首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Google反向地理代码API -不返回一致的数据

Google反向地理代码API -不返回一致的数据
EN

Stack Overflow用户
提问于 2017-09-20 01:50:14
回答 2查看 430关注 0票数 1

我正在开发一个在React中的应用程序,我正在使用谷歌反向地理代码API来查找用户的城市、州、县、县&邮政编码(必须包括县、州和国家)。我的问题是,我无法找到一种一致的方法来收集数据,因为Google每次都会返回一个JSON文件,根据位置的不同,顺序不同。

我现在的代码是:

代码语言:javascript
运行
复制
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末尾的锁和键。

我试图通过结果,并选择不同的类型,但这仍然不起作用。我也想让这个在整个北美发挥作用..。

非常感谢您的反馈!谢谢!

EN

回答 2

Stack Overflow用户

发布于 2017-09-21 04:11:17

最后我想不出来了。最后,我切换到了https://locationiq.org/ API,它做的正是我想要做的。

票数 0
EN

Stack Overflow用户

发布于 2018-01-03 11:31:38

你可以这样做:

代码语言:javascript
运行
复制
 _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://medium.com/@eesh.t/auto-detect-location-react-component-using-google-geocoding-and-reverse-geocoding-in-autocomplete-66a269c59315

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46312056

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档