navigator.geolocation.getcurrentPosition() 未获取纬度和经度值
Posted
技术标签:
【中文标题】navigator.geolocation.getcurrentPosition() 未获取纬度和经度值【英文标题】:navigator.geolocation.getcurrentPosition() not fetching latitude and longitude values 【发布时间】:2018-09-25 10:54:03 【问题描述】:我正在运行这个基本的 react 本机代码,用于在 android 设备和模拟器上获取纬度和经度值,但没有返回当前的纬度/经度值。
在模拟器上运行时会返回一些值,但它不是正确的纬度/经度值,而在设备上甚至没有返回值。这里是代码
import React, Component from 'react'
import View, Text, Switch, StyleSheet, Button from 'react-native'
import createStackNavigator from 'react-navigation';
class HomeScreen extends Component
render()
return (
<View style = styles.container>
<Button
title="Add New Outlet"
onPress=() => this.props.navigation.navigate('Details')
/>
</View>
)
class DetailsScreen extends React.Component
constructor(props)
super(props);
this.state =
latitude: null,
longitude: null,
error: null,
;
componentDidMount()
navigator.geolocation.getCurrentPosition(
(position) =>
this.setState(
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
);
,
(error) => this.setState( error: error.message ),
enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 ,
);
render()
return(
<View style = styles.container>
<Text style = styles.boldText>
Latitude:
</Text>
<Text>
this.state.latitude
</Text>
<Text style = styles.boldText>
Longitude:
</Text>
<Text>
this.state.longitude
</Text>
</View>
)
const RootStack = createStackNavigator(
Home: HomeScreen,
Details: DetailsScreen,
,
initialRouteName: 'Home',
);
export default class App extends React.Component
render()
return <RootStack />;
const styles = StyleSheet.create (
container:
flex: 1,
alignItems: 'center',
marginTop: 50
,
boldText:
fontSize: 30,
color: 'red',
)
请提出更好的替代方案..
【问题讨论】:
【参考方案1】:由于某种原因 navigator.geolocation 在 Android 设备上运行不稳定,我将 getCurrentPosition 更改为 watchPosition 并且没有使用第三个(geo_options)参数。它对我有用。
componentDidMount()
this.state.watchId = navigator.geolocation.watchPosition(
(position) => console.log(position),
(error) => console.log(error),
);
另外,当组件卸载时,您必须清除监视和停止位置观察。
componentWillUnmount()
navigator.geolocation.clearWatch(this.state.watchId);
navigator.geolocation.stopObserving();
【讨论】:
【参考方案2】:首先,检查android权限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
下一步:
componentDidMount()
if (Platform.OS === "android")
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
).then(granted =>
if (granted) this._getCurrentLocation();
);
else
this._getCurrentLocation();
然后:
_getCurrentLocation = () =>
navigator.geolocation.getCurrentPosition(
(position) =>
this.setState(
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
);
,
(error) => this.setState( error: error.message ),
enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 ,
);
【讨论】:
以上是关于navigator.geolocation.getcurrentPosition() 未获取纬度和经度值的主要内容,如果未能解决你的问题,请参考以下文章