我需要承诺这行代码:
navigator.geolocation.getCurrentPosition(setPosition);
因为它的结果是异步的。
我试过这个:
await new Promise (resolve => navigator.geolocation.getCurrentPosition(
() => setPosition().then(resolve))
)
但是不工作...
我之前的代码是这样的:
const setPosition = async (position) => {
const lat = await position.coords.latitude
const lng = await position.coords.longitude
mapOptions.center = {
lat: lng,
lng: lat
}
}
navigator.geolocation.getCurrentPosition(setPosition);
有什么想法吗?
使用Typescript,一种可能的解决方案是
const getLocation = (options: GeoOptions) => {
return new Promise((resolve, reject) => {
Geolocation.getCurrentPosition(resolve, reject, options);
});
}
type GeoOptions = {
timeout?: number;
maximumAge?: number;
enableHighAccuracy?: boolean;
distanceFilter?: number;
useSignificantChanges?: boolean;
};