我正在尝试使用这个库:
@react-native-community/geolocation
const requestLocationPermission = async (success, failure) => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
)
if( granted === PermissionsAndroid.RESULTS.GRANTED ) {
console.log("You can use the location")
Geolocation.getCurrentPosition(
({ coords }) => {
console.log("coords: ", coords)
},
(errObject) => {
console.log("message: ", errObject) // it gets thrown here
}
)
} else {
console.log("You cannot use the location")
}
} catch (err) {
}
}
它会提示用户允许或拒绝应用程序访问其位置。允许后我得到这个:
{"PERMISSION_DENIED": 1, "POSITION_UNAVAILABLE": 2, "TIMEOUT": 3, "code": 2, "message": "No location provider available."}
在
AndroidMenufest.xml
:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
不需要做更多的事情,就像这样 useState(0) 对于 lat 和 lang 不提供任何字符串写入此 Geolocation.getCurrentPosition((data)=>(console.log(data) //这里可以设置状态 ))
只需打开设备定位即可解决。