如何根据纬度和经度获取邮政编码?

15
有没有一种服务或API,可以传入经度/纬度作为参数进行ping,并返回该经纬度所在的邮政编码?这仅适用于美国,因此我不必担心国际代码等问题。
我觉得Google Maps的反向地理编码对我来说太繁重了。如果可能的话,我更喜欢轻量级的东西。这将在javascript中完成。

可能是邮政编码数据库的重复问题。 - Wouter Dorgelo
5个回答

23

它被称为反向地理编码(地址查找)。要获取纬度为40.714224,经度为-73.961452的地址,请使用参数latlng=40.714224,-73.961452&sensor=true例子)查询http://maps.googleapis.com/maps/api/geocode/json,它会返回JSON对象或使用http://maps.googleapis.com/maps/api/geocode/xml返回XML响应(例子)。这来自于谷歌且免费。


7
请注意,谷歌明确禁止在不将Geocoding放在地图上的情况下使用它,根据他们的TOS - eighteyes
1
以上链接返回404错误..所以这里是地理编码API的最新链接 - https://developers.google.com/maps/documentation/geocoding/start#ReverseGeocoding - Arman Ortega
1
目前它不是免费的。请在此处查看 https://developers.google.com/maps/documentation/geocoding/usage-and-billing - oracleruiz

8

对于Google API,根据他们的网站,您需要在Google地图中使用它:

注意:Geocoding API只能与Google地图一起使用;禁止在不显示地图的情况下使用地理编码结果。


不确定为什么一开始就被投票否决了,但它提出了一个关于Google API的TOS的好问题。 - icecreamman
3
这不是真的。"您可以在Google地图上显示地理编码API的结果,也可以不使用地图。如果您想在地图上显示地理编码API的结果,则这些结果必须在Google地图上显示。禁止在非Google地图上使用地理编码API数据。" https://developers.google.com/maps/documentation/geocoding/policies - Scott Decker

7

对我来说运行得很好。虽然我还没有实现它,但我将你的jsfiddle代码粘贴到我的视图中,它在加载时告诉了我我的邮政编码。 - JustJohn
嘿kubetz,我怎样能够获得最近的城市和所属州?这个可行吗?你的jsfiddle代码在我的项目中运转得非常好。 - JustJohn

1
谷歌地图API可以获取与地理位置相关联的邮政编码。但是,如果您在丛林中间的某个地方,则此API将不返回任何内容,因为邮政编码被映射到邮政地址。在这种情况下,您需要获取附近城市的邮政编码。
您可以使用以下方法来实现。
  //Reverse GeoCode position into Address and ZipCOde
  function getZipCodeFromPosition(geocoder, map,latlng,userLocationInfoWindow) {

   geocoder.geocode({'location': latlng}, function(result, status) {
     if (status === 'OK') {
       if (result[0]) {

            console.log("GeoCode Results Found:"+JSON.stringify(result));

            //Display Address
            document.getElementById("address").textContent  = "Address: " +result[0].formatted_address;

           //Update Info Window on Server Map
           userLocationInfoWindow.setPosition(latlng);
           userLocationInfoWindow.setContent('<IMG BORDER="0" ALIGN="Left" SRC="https://media3.giphy.com/media/IkwH4WZWgdfpu/giphy.gif" style ="width:50px; height:50px"><h6 class ="pink-text">You Are Here</h4> <p class = "purple-text" style ="margin-left:30px;">'+result[0].formatted_address+'</p>');
           userLocationInfoWindow.open(map);
           map.setCenter(latlng);

            //Try to Get Postal Code
            var postal = null;
            var city = null;
            var state = null;
            var country = null;

          for(var i=0;i<result.length;++i){
              if(result[i].types[0]=="postal_code"){
                  postal = result[i].long_name;
              }
              if(result[i].types[0]=="administrative_area_level_1"){
                  state = result[i].long_name;
              }
              if(result[i].types[0]=="locality"){
                  city = result[i].long_name;
              }
              if(result[i].types[0]=="country"){
                  country = result[i].long_name;
              }
          }
          if (!postal) {
            geocoder.geocode({ 'location': result[0].geometry.location }, function (results, status) {
              if (status == google.maps.GeocoderStatus.OK) {

                //Postal Code Not found, Try to get Postal code for City
                var result=results[0].address_components;

                for(var i=0;i<result.length;++i){
                 if(result[i].types[0]=="postal_code"){
                    postal = result[i].long_name;
                 }
                }
                  if (!postal) {

                    //Postal Code Not found
                     document.getElementById("postal").textContent  = "No Postal Code Found  for this location";
                  }else
                  {
                     //Postal Code found
                      document.getElementById("postal").textContent  = "Zip Code: "+postal;
                  }
              }
          });
          } else
              {
              //Postal Code found
              document.getElementById("postal").textContent  = "Zip Code: "+postal;
              }
          console.log("STATE: " + state);
          console.log("CITY: " + city);
          console.log("COUNTRY: " + country);

             } else {
           window.alert('No results found');
         }
       } else {
         window.alert('Geocoder failed due to: ' + status);
       }
     });
 }
</script>

工作示例

https://codepen.io/hiteshsahu/pen/gxQyQE?editors=1010

enter image description here


0
kubetz的回答很好,但是由于我们必须使用https才能使地理定位工作(Chrome 50中从不安全来源中删除了地理定位API),所以对http://api.geonames.org的调用失败了,因为它没有使用https。通过一个本地的php脚本,通过https获取geonames.org的数据可以解决这个问题。
//javascript function
function getZipFromLatLong() {
    var url = "getzip.php";
    var formData = new FormData();
    formData.append("lat", current_lat);
    formData.append("long", current_long);

    var r = new XMLHttpRequest();
    r.open("POST", url, true);
    r.onreadystatechange = function () {
        if (r.readyState != 4 || r.status != 200) {
            return;
        } else {
            data = r.responseText;
            var jdata = JSON.parse(data);
            document.getElementById("zip").value = jdata.postalCodes[0].postalCode;
        }
    }
    r.send(formData);
}

//getzip.php script
<?php

$lat = $_POST["lat"];
$long = $_POST["long"];

$url = "http://api.geonames.org/findNearbyPostalCodesJSON?username=demo&lat=" . $lat .  "&lng=" . $long;

$content = file_get_contents($url);

//the output is json, so just return it as-is
die($content);
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接