簡體   English   中英

在JavaScript中從經緯度獲取郵政編碼

[英]get zipcode from latitude and longitude in javascript

想要從該位置的經度和緯度顯示該位置的郵政編碼。 下面是我的代碼。

function markerLocation() { 
  var currentLocation = marker.getPosition();
  var geocoder  = new google.maps.Geocoder();        
  var location  = new google.maps.LatLng(currentLocation.lat(), currentLocation.lng());

  geocoder.geocode({ 'latLng': location , function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) { 
      var add = results[0].address_components[1][1];
      document.getElementById('lat').value = add;
    }
  });

在這里,我想顯示緯度的郵政編碼。 但是當我使用address_components時,它顯示為undefined。 請幫助。

嘗試這個:

<input id="postal_code"/>
<input id="street"/>
...

腳本

if (status == google.maps.GeocoderStatus.OK) {
for(var i in results[0].address_components) {
  // skip items with no types 
  if(typeof results[0].address_components[i].types == 'undefined') {
    continue;
  }

  if(results[0].address_components[i].types.indexOf('postal_code') > -1) {
    document.getElementById('postal_code').value = results[0].address_components[i].long_name;
  }
  if(results[0].address_components[i].types.indexOf('street') > -1) {
    document.getElementById('street').value = results[0].address_components[i].long_name;
  }
  ...
}
}

暫無
暫無

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

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