6

我正在制作一个应用程序,它将获取用户的当前位置或他的自定义地图标记来找出纬度和经度,然后使用这些值我想知道该区域的密码(邮政编码),以便我可以告诉用户货物是否可以交付在那个区域与否。

我试过这个:http ://www.geonames.org/export/ws-overview.html但它没有完整的数据,而且它所拥有的任何东西都不是很准确。是否有任何其他 API 可用于获取此类数据?

4

1 回答 1

16

如果您有位置(和 Google Maps API v3 地图),请对位置进行反向地理编码。处理返回的 postal_code 记录(有关示例,请参见此 SO 帖子)。

// assumes comma separated coordinates in a input element 
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);
  geocoder.geocode({'latLng': latlng}, processRevGeocode);
}

// process the results
function processRevGeocode(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
       var result;
       if (results.length > 1)
          result = results[1];
       else
          result = results[0];
       if (result.geometry.viewport)
          map.fitBounds(result.geometry.viewport);
       else if (result.geometry.bounds)
          map.fitBounds(result.geometry.bounds);  
       else { 
          map.setCenter(result.geometry.location);
          map.setZoom(11);
       }
       if (marker && marker.setMap) marker.setMap(null);
       marker = new google.maps.Marker({
           position: result.geometry.location,
           map: map
       });
       infowindow.setContent(results[1].formatted_address);
       infowindow.open(map, marker);
       displayPostcode(results[0].address_components);

    } else {
      alert('Geocoder failed due to: ' + status);
    }
}

// displays the resulting post code in a div
function displayPostcode(address) {
  for (p = address.length-1; p >= 0; p--) {
    if (address[p].types.indexOf("postal_code") != -1) {
       document.getElementById('postcode').innerHTML= address[p].long_name;
    }
  }
}

工作示例(显示来自地理编码地址的邮政编码、反向地理编码坐标或单击地图)

于 2013-05-23T02:59:24.967 回答