2010-06-07 98 views
1

iam嘗試使用gmaps V3中提供的地址組件類型獲取國家/地區名稱。gmaps地址組件類型獲取國家名稱

我不知道我能得到正確的方式.. http://code.google.com/apis/maps/documentation/javascript/services.html#GeocodingAddressTypes

IAM試圖在這裏提醒國名鏈接纔可:

alert(results[1].address_component[country]); 

和here`s代碼..任何幫助真的appreciated..thanks

function codeLatLng() { 
    var input = document.getElementById("latlng").value; 
    var latlngStr = input.split(",",2); 
    var lat = parseFloat(latlngStr[0]); 
    var lng = parseFloat(latlngStr[1]); 
    var latlng = new google.maps.LatLng(lat, lng); 
    if (geocoder) { 
     geocoder.geocode({'latLng': latlng}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      if (results[1]) { 
      alert(results[1].address_component[country]); 
      } else { 
      alert("No results found"); 
      } 
     } else { 
      alert("Geocoder failed due to: " + status); 
     } 
     }); 
    } 
    } 

回答

0

alert(results[1].address_component['country']); //國家是一個字符串

10

首先,address_components應該是複數。 Google文檔由於錯字導致誤導。

address_components數組有一個地址的每個組件的項目。每個項目中的類型數組告訴你所有適用於每個地址組件的類型(例如:國家,地區等) - 所以你真正想要做的是找到具有「國家」作爲其中之一的address_components數組項目它的類型,然後爲該數組項目選擇short_name或long_name。

此外,您可能並不總是有結果值[1]。這將假定至少有2個搜索結果返回。結果[0]將是第一個。

這裏有一個例子:

var country; 

for (i=0;i<results[0].address_components.length;i++){ 
    for (j=0;j<results[0].address_components[i].types.length;j++){ 
     if(results[0].address_components[i].types[j]=="country") 
      country = results[0].address_components[i].long_name 
    } 
} 
-1

Google's documentation,結果總是以最具體的順序返回到最具體:

一般來說,地址是從最具體到最不退還具體;更確切的地址是最顯着的結果,就像在這種情況下一樣。請注意,我們會返回不同類型的地址,從最具體的街道地址到不太具體的政治實體,如社區,城市,縣,州等。如果您希望匹配更一般的地址,則可能需要檢查"types"字段返還的Placemark s。

鑑於這個事實,我們甚至不必循環遍歷結果。只需選擇的那些底:

alert(results.slice(-1)[0].address_components.slice(-1)[0].long_name); 

如果事實證明,「結果」或「address_components」可以丟失或長度爲0一些簡單的錯誤檢查可以添加。

+0

不正確,postal_code也可能是最後的 – Christoffer 2014-05-22 09:24:54

+0

@Christoffer:你是什麼意思?只有郵政編碼,沒有其他信息的條目? – hippietrail 2014-05-25 00:29:31

+0

沒有我的意思是,你認爲國家總是最後的地址組件?但事實並非如此。你可以相信這個位置,所以你必須遍歷它們。 – Christoffer 2014-05-26 12:30:49

相關問題