我有这个文件可以通过地理位置返回地址:
import React, { Component } from 'react';
import axios from 'axios';
const __API_KEY__ = '&key=...';
export var address = '';
const getGeocode = () => {
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ this.state.latitude +','+ this.state.longitude + __API_KEY__)
.then(response => {
console.log(response);
this.setState({
place: response.data.results[0].formatted_address
})
address = response.data.results[0].formatted_address
}).catch((error) => {
this.setState({ error: error.message })
});
};
export const getGeolocation = () => (
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
}, () => this.getGeocode());
},
address = position.coords.latitude,
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000 },
)
);
我可以在另一个文件中返回地址变量,我需要以下地址:
import { Address } from './services/geolocation';
但是发生的是变量是空的,因为它不执行采用地理位置的代码,我该如何使变量返回地址?
[edit]
我试图遵循地址返回的函数的建议,我在此代码中得到了:
import React, { Component } from 'react';
import axios from 'axios';
const __API_KEY__ = '&key=...';
function getGeocode( latitude, longitude ) {
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ latitude +','+ longitude + __API_KEY__)
.then(response => {
console.log(response);
var address = response.data.results[0].formatted_address
}).catch((error) => {
this.setState({ error: error.message })
});
return address;
};
export function getGeolocation() {
navigator.geolocation.getCurrentPosition(
(position) => {
var address = getGeocode(position.coords.latitude, position.coords.longitude);
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000 },
)
console.log(address);
return address;
};
,另一个我试图这样导入:
import { getGeolocation } from './services/geolocation';
const address = getGeolocation();
,但我收回了这个错误:
(0,_geolocation.getGeolocation) is not a function
这样做的更简单的方法是导出getAddress函数,而不是导出实际变量。所以:
export function getAddress() { return address; }
(如果您喜欢该语法,则箭头函数等效)。