我正在运行此基本的反应本机代码,以在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',
}
})
请提出其他更好的选择。
答案 0 :(得分:0)
出于某种原因,navigator.geolocation在Android设备上无法稳定运行,我将getCurrentPosition更改为watchPosition,并且未使用third(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();
}
答案 1 :(得分:0)
Fisrt,检查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 },
);
}