我在与redux的react-native中使用地理位置,但是遇到了2个问题。
有人可以帮助我吗?
这是我的代码..
Reducer.js
let initialState = {
lng: null,
lat: null,
}
export default function prayerTimes(state = initialState, action) {
switch (action.type) {
case GET_LOCATION:
return {
...state,
lat: action.lat,
lng: action.lng
}
}
}
Action.js
export function getLocation() {
return dispatch => {
navigator.geolocation.getCurrentPosition((position) => {
dispatch({
type: GET_LOCATION,
lat: position.coords.latitude,
lng: position.coords.longitude
});
});
};
}
App.js
componentDidMount() {
const { getLocation } = this.props;
getLocation();
}
render() {
const { lng, lat } = this.props;
return (
<View style={{justifyContent: 'center'}}>
<Text style={{color: 'white'}}>Latitude: {lat}</Text>
<Text style={{color: 'white'}}>Latitude: {lng}</Text>
</View>
);
}
答案 0 :(得分:0)
您是否尝试过启用高精度?
navigator.geolocation.getCurrentPosition(
(position) => {
dispatch({
type: GET_LOCATION,
lat: position.coords.latitude,
lng: position.coords.longitude
});
},
(error) => {},
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
答案 1 :(得分:0)
下面的代码对我有用,以获取当前的国家名称。
constructor(props) {
super(props);
this.state = {
lat: null,
long: null,
};
}
componentDidMount () {
navigator.geolocation.getCurrentPosition(
(position) => {
var lat = parseFloat(position.coords.latitude);
var long = parseFloat(position.coords.longitude);
this.setState({ lat: lat, long: long });
},
(error) => { },
);
}
componentDidUpdate () {
var pos = {
lat: this.state.lat,
lng: this.state.long,
};
Geocoder.geocodePosition(pos).then(res => { // import Geocoder from 'react-native-geocoder';
AsyncStorage.setItem('location',res[0].country); // res[0].country gives you the country name of your location
})
.catch(error => alert(error));
}