我有这段代码来返回地址:
const geo = {
getGeocode: (latitude, longitude) => {
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ latitude +','+ longitude + __API_KEY__)
.then(response => {
console.log(response);
return response.data.results[0].formatted_address
}).catch((error) => {
console.log( error.message )
});
return 'Error geocode'
},
getGeolocation: () => {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
return geo.getGeocode(position.coords.latitude,position.coords.longitude);
},
(error) => console.log( error.message ),
{ enableHighAccuracy: true, timeout: 20000 },
);
return 'Error geolocation';
},
};
export default geo;
但每次执行
import geolocation from './geolocation';
export default class App extends Component {
render() {
return (
<View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Address: {geolocation.getGeolocation()}</Text>
</View>
);
}
}
这将返回Error geolocation
它在控制台上返回地址正确的响应
我已经在很多方面尝试过了,在我所知道的内容应该正确地返回地址
[编辑]
我也尝试了这段代码:
export const geo = {
var: address = '...',
getGeocode: (latitude, longitude) => {
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ latitude +','+ longitude + __API_KEY__)
.then(response => {
console.log(response);
response.data.results[0].formatted_address;
}).catch((error) => {
console.log( error.message )
});
return 'Error geocode';
},
getGeolocation: () => {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
geo.getGeocode(position.coords.latitude, position.coords.longitude);
},
(error) => console.log( error.message ),
{ enableHighAccuracy: true, timeout: 20000 },
);
return address;
},
};
我正确地返回address
,但我无法将response.data.results[0].formatted_address
的值传递给变量address
我该怎么做?