簡體   English   中英

Google Reverse Geocode API-不返回一致的數據

[英]Google Reverse Geocode API - not returning consistent data

我正在使用React Native JS開發一個應用,並且正在使用Google的反向地理編碼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末尾的latlng和鍵。
我試圖查看結果,並選擇了不同的類型,但這仍然行不通。 我也想讓它在整個北美運作。

所有反饋非常感謝!!! 謝謝!

好吧,我最終無法弄清楚。 我最終切換到https://locationiq.org/ API,它完全符合我的嘗試。

您可以執行以下操作:

 _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反向地理編碼在React中獲取城市和其他詳細信息的完整實現,請參見

https://medium.com/@eesh.t/auto-detect-location-react-component-using-google-geocoding-and-reverse-geocoding-in-autocomplete-66a269c59315

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM