我有这个文件通过地理位置返回地址:
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';
但是发生的变化是变量变空,因为它不执行接受地理定位的代码,我怎样才能使变量返回地址?
[编辑]
我试着按照地址返回变成函数的建议,我得到了这段代码:
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
答案 0 :(得分:0)
更简单的方法是导出getAddress函数,而不是导出实际变量。所以:
export function getAddress() { return address; }
(如果您更喜欢该语法,则为箭头函数等效。)