首先获取当前位置 运行
get current location in first run
我有一个使用位置服务的应用程序,但是当我请求当前位置并在用户允许后,应用程序无法找到位置。
用户要找到它的位置必须关闭并重新打开应用程序,直到找到正确的位置。
这是我的代码:
componentWillMount() {
this.getCurrentLocation();
}
getCurrentLocation = () => {
const locationConfig = {
timeout: 20000,
maximumAge: 1000,
enableHighAccuracy: false
};
navigator.geolocation.getCurrentPosition(
this.iGetLocation,
(error) => {
console.log(error);
},
locationConfig
);
};
我认为问题出在您的位置回调:this.iGetPosition
。尝试使用回调函数,如下所示。
这对我有用(检查 getCurrentPosition
函数):
componentDidMount() {
this.requestAccess();
}
requestAccess = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Location permission',
'message': 'App needs access to your location ' +
'so we can show your location.'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 },
);
} else {
console.log("Location permission denied")
}
} catch (err) {
console.warn(err)
}
}
我有一个使用位置服务的应用程序,但是当我请求当前位置并在用户允许后,应用程序无法找到位置。 用户要找到它的位置必须关闭并重新打开应用程序,直到找到正确的位置。 这是我的代码:
componentWillMount() {
this.getCurrentLocation();
}
getCurrentLocation = () => {
const locationConfig = {
timeout: 20000,
maximumAge: 1000,
enableHighAccuracy: false
};
navigator.geolocation.getCurrentPosition(
this.iGetLocation,
(error) => {
console.log(error);
},
locationConfig
);
};
我认为问题出在您的位置回调:this.iGetPosition
。尝试使用回调函数,如下所示。
这对我有用(检查 getCurrentPosition
函数):
componentDidMount() {
this.requestAccess();
}
requestAccess = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Location permission',
'message': 'App needs access to your location ' +
'so we can show your location.'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 },
);
} else {
console.log("Location permission denied")
}
} catch (err) {
console.warn(err)
}
}