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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8372223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:43:46  来源:igfitidea点击:

Get zip code based on lat & long?

javascriptgeolocationmaps

提问by Connor

Is there a service or API I can ping, and pass in the lat/long as parameters, where it returns the zip code that lat/long pair is within? This is US-only, so I don't have to worry about international codes, etc.

是否有我可以 ping 的服务或 API,并将纬度/经度作为参数传递,它返回纬度/经度对所在的邮政编码?这是仅限美国的,所以我不必担心国际代码等。

I feel like Google Maps' reverse-geocoding is too heavy for me. I'd prefer something lighter, if possible. This will be done in javascript.

我觉得谷歌地图的反向地理编码对我来说太重了。如果可能的话,我更喜欢更轻的东西。这将在 javascript 中完成。

回答by Micha? Powaga

It is called Reverse Geocoding (Address Lookup). To get address for lat: 40.714224, lng: -73.961452 query http://maps.googleapis.com/maps/api/geocode/jsonwith parameters latlng=40.714224,-73.961452&sensor=true(example) and it returns JSON object or use http://maps.googleapis.com/maps/api/geocode/xmlto return XML response (example). It's from Google and it's free.

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

回答by Data Pro

For the Google API, you need to use it within a Google map, according to their site:

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

Note: the Geocoding API may only be used in conjunction with a Google map; geocoding results without displaying them on a map is prohibited.

注意:Geocoding API 只能与谷歌地图结合使用;禁止地理编码结果而不在地图上显示。

回答by kubetz

Please have a look on http://geonames.org. There is a webservice findNearbyPostalCodes(international).

请查看http://geonames.org。有一个网络服务findNearbyPostalCodes(国际)。

Example: findNearbyPostalCodesJSON?lat=47&lng=9&username=demo

示例findNearbyPostalCodesJSON?lat=47&lng=9&username=demo

Shortened output:

缩短输出

{
  "postalCodes": [{
    "adminCode3": "1631",
    "distance": "2.2072",
    "postalCode": "8775",
    "countryCode": "CH",
    "lng": 8.998679778165283,
    "placeName": "Luchsingen",
    "lat": 46.980169648620375
  }]
}

Limit of the demo account is 2000 queries per hour.

模拟账户的限制是每小时 2000 次查询。

回答by Hitesh Sahu

Google Maps API can get zip code associated with a geolocation. However if you are somewhere in middle of jungle then this API will not return anything as postal code are mapped to postal addresses. In that case you need to get zip code of nearby city.

Google Maps API 可以获取与地理位置相关联的邮政编码。但是,如果您在丛林中的某个地方,那么此 API 将不会返回任何内容,因为邮政编码已映射到邮政地址。在这种情况下,您需要获取附近城市的邮政编码。

You can use this method to do so

您可以使用此方法来执行此操作

  //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>

Working example

工作示例

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

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

enter image description here

在此处输入图片说明

回答by Nicolas Giszpenc

The answer from kubetz is great, but since we have to use https to get geolocation to work(Geolocation API Removed from Unsecured Origins in Chrome 50), the call to http://api.geonames.orgfails because it is not over https. A local php script, called over https, that gets from geonames.org solves the problem.

kubetz 的回答很好,但是由于我们必须使用 https 才能使地理定位工作从 Chrome 50 中的不安全来源中删除 Geolocation API),对http://api.geonames.org的调用失败,因为它没有通过 https . 从 geonames.org 获取的通过 https 调用的本地 php 脚本解决了这个问题。

//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);
?>