我在使用redux的react-native中使用geolocation,但是我遇到了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>
);
}
您是否尝试过高精度?
navigator.geolocation.getCurrentPosition(
(position) => {
dispatch({
type: GET_LOCATION,
lat: position.coords.latitude,
lng: position.coords.longitude
});
},
(error) => {},
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
以下代码适用于我获取我当前的国家/地区名称。
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));
}