4

我正在使用 Javascript API 的 Google Maps Version 2 的地理编码服务。 https://developers.google.com/maps/documentation/javascript/v2/reference 但是谷歌决定不再支持他。

注意:Google Maps JavaScript API 版本 2 已于 2010 年 5 月 19 日正式弃用。V2 API 将继续工作到 2013 年 5 月 19 日。我们鼓励您将代码迁移到 Maps JavaScript API 版本 3。

那么如何在谷歌地图版本 3 javascript api 中使用缩放进行地理编码?

4

2 回答 2

20

要缩放地图以最好地显示地理编码操作的结果,您可以使用google.maps.Map fitBounds方法和结果的 viewport 属性:

function codeAddress() {
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map, 
                position: results[0].geometry.location
            });
        if (results[0].geometry.viewport) 
          map.fitBounds(results[0].geometry.viewport);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

代码片段:

var geocoder, map, marker;

function codeAddress() {
  var address = document.getElementById("address").value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      if (marker && marker.setMap) marker.setMap(null);
      marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      if (results[0].geometry.viewport)
        map.fitBounds(results[0].geometry.viewport);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

function initialize() {
  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  google.maps.event.addDomListener(document.getElementById('btn'), 'click', codeAddress);
  codeAddress();

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="address" value="Palo Alto, CA" />
<input id="btn" value="Geocode" type="button" />
<div id="map_canvas"></div>

于 2012-12-03T18:35:56.243 回答
3
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': zipcode }, function(results, status)
{
    if (status == google.maps.GeocoderStatus.OK)
    {
        map.setCenter(results[0].geometry.location);
        map.setZoom(12);
    }
    else
    {
       alert(zipcode + " not found");
       console.log("status : ", status);
    }
});
于 2012-12-03T18:17:19.830 回答