2016-11-02 87 views
0

將現有地址作爲參數的地理編碼解碼器僅返回street_address。爲什麼?地址有效。它已經在https://google-developers.appspot.com/maps/documentation/utils/geocoder/帶地址的Google地址解析返回一個結果

我的電話進行了測試:

checkAddress(street, strNo, post_code, area, function (results) { 
     if (results) { 
    $.each(results, function (i, address) { 
    if (address.types[0] == "street_address") { 
     itemStreetNo = address.address_components[0].long_name; 
     itemStreet = address.address_components[1].long_name; 
    } 

    if (address.types[0] == "route") { 
     itemStreet = address.address_components[0].long_name; 
    } 

    if (address.types[0] == "postal_code") { 
     itemPostalCode = address.address_components[0].long_name; 
    } 

    if (address.types[0] == "country") { 
     itemCountry = address.address_components[0].long_name; 
    } 

    if (address.types[0] == "locality") { 
     itemRegion = address.address_components[0].long_name; 
    } 
    } 
}); 

我的功能是:

function checkAddress(address, number, zipcode, area, callback) { 

    var geocoder = new google.maps.Geocoder; 

    var addr = address + ' ' + number + ' ' + zipcode + ' ' + area; 

    geocoder.geocode({ 'address': addr }, function (results, status) { 

     if (status === google.maps.GeocoderStatus.OK) { 
      if (results[0]) { 
       callback(results); 
      } 
      else { 
       callback(null); 
      } 
     } 
     else { 
      callback(null); 
     } 
    }); 
} 

回答

2

你只在1個組件(address.address_components[0])搜索,所以你只能得到1個結果。

address.address_components[0]包含一個組件,例如「路由」。然後address.address_components[1]包含另一個組件,例如「locality」,然後address.address_components[2] ......據我記得,組件的順序是隨機的。

所以你需要的是迭代。對於每個組件你檢查類型,它可以讓你知道價值應該去的地方。

我爲不同堆棧溢出問題編寫了一個函數,它執行了這個迭代,它爲任何組件「釣魚」。

看看它是否適合你;讓我知道。

Google API Address Components

+0

感謝您的代碼。這是我需要獲取所有信息的內容。 –