React Native 地理定位权限回调
React Native geolocation permissions callback
我很难获得权限并在 RN 上正确获取当前位置。
我真正想做的是在权限被拒绝或授予时获得回调,这样我就可以分别请求我的当前位置。我请求权限使用:
geolocation.requestAuthorization();
这不是 return 承诺或接受回调所以我知道是否授予权限的唯一真实方法是重复调用
geolocation.getCurrentPosition();
并检查其内容
这感觉有点笨拙,因为 setInterval
几乎不是答案,所以我正在寻找更好的方法。
试试这样的东西,它对我有用。
(async () => {
{ try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Your App',
'message': 'Allow app to access your location '
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
Geocoder.geocodePosition({lat: position.coords.latitude, lng: position.coords.longitude})
.then(res => {
this.setState({
locationResult: res[0].formattedAddress
});
})
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
} else {
alert("Location permission denied");
}
} catch (err) {
console.log("No Access to location" + err);
}
}
})();
状态中的 locationResult 将包含地址详细信息。
我很难获得权限并在 RN 上正确获取当前位置。
我真正想做的是在权限被拒绝或授予时获得回调,这样我就可以分别请求我的当前位置。我请求权限使用:
geolocation.requestAuthorization();
这不是 return 承诺或接受回调所以我知道是否授予权限的唯一真实方法是重复调用
geolocation.getCurrentPosition();
并检查其内容
这感觉有点笨拙,因为 setInterval
几乎不是答案,所以我正在寻找更好的方法。
试试这样的东西,它对我有用。
(async () => {
{ try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Your App',
'message': 'Allow app to access your location '
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
Geocoder.geocodePosition({lat: position.coords.latitude, lng: position.coords.longitude})
.then(res => {
this.setState({
locationResult: res[0].formattedAddress
});
})
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
} else {
alert("Location permission denied");
}
} catch (err) {
console.log("No Access to location" + err);
}
}
})();
状态中的 locationResult 将包含地址详细信息。