当我们使用google api v3输入zipcode时搜索位置

时间:2014-03-11 11:08:05

标签: javascript google-maps google-maps-api-3

这是我的代码但不起作用:

  var geocoder;
  var map;

  function initialize() {
     geocoder = new google.maps.Geocoder();

     var latlng = new google.maps.LatLng(-28.397, 189.644);

     var mapOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
     };

     map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);

  }

  google.maps.event.addDomListener(window, 'load', initialize);

  //Call this wherever needed to actually handle the display
  function codeAddress() {
     var zipCode = document.getElementById("address").value;
     alert("zipCode" +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 个答案:

答案 0 :(得分:0)

zipCode在全球范围内并不是唯一的。当你想把结果限制在一个给定的国家时,正如AntoJurković所说,componentRestrictions:

{ 'address': zipCode,componentRestrictions:{country:'in'}}

结果:(30.7332254,76.78702899999996)