我正在开发一个在React中的应用程序,我正在使用谷歌反向地理代码API来查找用户的城市、州、县、县&邮政编码(必须包括县、州和国家)。我的问题是,我无法找到一种一致的方法来收集数据,因为Google每次都会返回一个JSON文件,根据位置的不同,顺序不同。
我现在的代码是:
fetch(`https://maps.googleapis.com/maps/api/geocode/json?${qs}`).then((res) => res.json()).then((json) => {
//success!
var city=false,state=false,county=false,country=false,zip=false;
for (var i = 0; i < json.results.length; i++) {
if ((!city || !state) && json.results[i].types[0] === "locality") {
city = json.results[i].address_components[0].short_name,
state = json.results[i].address_components[2].short_name;
} else if (!county && json.results[i].types[0] === "administrative_area_level_2") {
county = json.results[i].address_components[0].short_name;
} else if (!state && json.results[i].types[0] === "administrative_area_level_1") {
state = json.results[i].address_components[0].short_name;
} else if (!county && json.results[i].types[0] === "county") {
county = json.results[i].address_components[0].short_name;
} else if (!country && json.results[i].types[0] === "country") {
country = json.results[i].address_components[0].short_name;
}
}${qs}是URL末尾的锁和键。
我试图通过结果,并选择不同的类型,但这仍然不起作用。我也想让这个在整个北美发挥作用..。
非常感谢您的反馈!谢谢!
发布于 2017-09-21 04:11:17
最后我想不出来了。最后,我切换到了https://locationiq.org/ API,它做的正是我想要做的。
发布于 2018-01-03 11:31:38
你可以这样做:
_geoCodeCallback = (results, status, event) => {
const google = window.google; // eslint-disable-line
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]) {
const add = results[0].formatted_address;
const value = add.split(",");
const count = value.length;
const city = value[count - 3];
// here we can dispatch action to search by city name and autofill the autocomplete
} else {
console.log("address not found");
}
} else {
console.log(status);
}
}
_geocodeAddress = (geocoder, latlng) => {
geocoder.geocode({ location: latlng }, this._geoCodeCallback);
}
if (navigator.geolocation) {
this._displayLocation = (latitude, longitude) => {
const geocoder = new google.maps.Geocoder();
const latlng = new google.maps.LatLng(latitude, longitude);
this._geocodeAddress(geocoder, latlng);
};有关使用google反向geo编码获取城市和其他细节的整个实现,请参阅
https://stackoverflow.com/questions/46312056
复制相似问题