如何在Google地图API中使用邮政编码代替经纬度

22

我想知道是否有一种方法可以使用邮政编码而不是经纬度,可以使用此代码片段或使用地理编码请求。

    <script type="text/javascript">
        function initialize() {
            var latlng = new google.maps.LatLng(22.1482635,-100.9100755);
            // var latlang = new google.maps.zipcode(7845); <- Is there a way to do that?
            var myOptions = {
                zoom: 8,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                title:"zipcode"
            });

        }
    </script>
1个回答

33

您可以使用Google GeoCode API请求邮政编码的纬度和经度,然后从那里开始。

如果您想直接或通过其他媒介进行操作,则API请求URL将如下所示:

http://maps.googleapis.com/maps/api/geocode/json?address=50323&sensor=false

其中50323是您的邮政编码。

或者您可以使用Google Javascript API通过jQuery完成所有操作。

var geocoder; //To use later
var map; //Your map
function initialize() {
  geocoder = new google.maps.Geocoder();
  //Default setup
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

//Call this wherever needed to actually handle the display
function codeAddress(zipCode) {
    geocoder.geocode( { 'address': zipCode}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        //Got result, center the map and put it out there
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

1
出现错误:未捕获的nf:在属性地址中:不是字符串。 - Umar Sid
2
这里有同样的问题,如果我将邮政编码作为字符串传递,它会跳转到南非(尝试来自比利时的8790邮政编码),如果我将邮政编码作为整数传递,则返回与@Mohd.Umar所说相同的错误。 - AlvaroAV
3
自从有人在这里发布帖子已经三年了,但我想提醒一下。您希望谷歌将其视为邮政编码。例如,http://maps.googleapis.com/maps/api/geocode/json?address=31158+usa,它会将31158视为街道名称。如果我不添加USA,它会带我去法国。 - user763410

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