React Native Geolocation 等待功能不起作用
React Native Geolocation await function not working
我正在尝试从 react-native 包“@react-native-community/geolocation”获取地理定位。单击按钮我想获得纬度和经度,为此,我正在创建一个名为 getUserCurrentLocation() 的单独函数,但我想将此函数设置为异步等待类型。
const getUserCurrentLocation = () async => {
await Geolocation.getCurrentPosition(
info => {
setGeo({
lat: info.coords.latitude,
long: info.coords.longitude,
});
console.log(info.coords.latitude + '#' + info.coords.longitude);
},
error => console.log(error),
{
enableHighAccuracy: false,
timeout: 20000,
maximumAge: 10,
distanceFilter: 0,
},
);
};
您需要将 async 移到括号后面。这就是如何使用 async 和 await with try and catch block
const getUserCurrentLocation = async () => {
try {
const info = await Geolocation.getCurrentPosition();
setGeo({
lat: info.coords.latitude,
long: info.coords.longitude,
});
console.log(info.coords.latitude + '#' + info.coords.longitude);
} catch(error) {
console.log(error);
}
};
但我在 Documents 上看到您不需要使用承诺,这是一个示例,它应该可以正常工作:
访问 https://github.com/react-native-geolocation/react-native-geolocation/blob/master/example/GeolocationExample.js#:~:text=componentDidMount()%20%7B-,Geolocation.getCurrentPosition(,)%3B,-this.watchID%20%3D%20Geolocation
Geolocation.getCurrentPosition(
position => {
const initialPosition = JSON.stringify(position);
this.setState({initialPosition});
},
error => Alert.alert('Error', JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
);
我正在尝试从 react-native 包“@react-native-community/geolocation”获取地理定位。单击按钮我想获得纬度和经度,为此,我正在创建一个名为 getUserCurrentLocation() 的单独函数,但我想将此函数设置为异步等待类型。
const getUserCurrentLocation = () async => {
await Geolocation.getCurrentPosition(
info => {
setGeo({
lat: info.coords.latitude,
long: info.coords.longitude,
});
console.log(info.coords.latitude + '#' + info.coords.longitude);
},
error => console.log(error),
{
enableHighAccuracy: false,
timeout: 20000,
maximumAge: 10,
distanceFilter: 0,
},
);
};
您需要将 async 移到括号后面。这就是如何使用 async 和 await with try and catch block
const getUserCurrentLocation = async () => {
try {
const info = await Geolocation.getCurrentPosition();
setGeo({
lat: info.coords.latitude,
long: info.coords.longitude,
});
console.log(info.coords.latitude + '#' + info.coords.longitude);
} catch(error) {
console.log(error);
}
};
但我在 Documents 上看到您不需要使用承诺,这是一个示例,它应该可以正常工作: 访问 https://github.com/react-native-geolocation/react-native-geolocation/blob/master/example/GeolocationExample.js#:~:text=componentDidMount()%20%7B-,Geolocation.getCurrentPosition(,)%3B,-this.watchID%20%3D%20Geolocation
Geolocation.getCurrentPosition(
position => {
const initialPosition = JSON.stringify(position);
this.setState({initialPosition});
},
error => Alert.alert('Error', JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
);