Google地图搜索问题与地标

时间:2012-05-28 19:34:40

标签: javascript html google-maps geocoding

我正在开发一个带有Google地图应用程序的网页,我遇到了一些问题。目前,网页上有一个功能图(没有任何图层)和一个搜索栏。我是编程的新手,所以希望有一个我很想念的快速解决方案。 当我搜索地址时,地图上会放置一个地标。但是,地图不会放大地标。如何让地图放大每个搜索到的地址?

  <script type="text/javascript">
    var geocoder;
    var map; 
  function initialize() {
    geocoder = new google.maps.Geocoder ();
    var latlng = new google.maps.LatLng (55.1667, -114.4000);
    var myOptions = {
      zoom: 5,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
     map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
        }
    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
            });
            } 
        else {
            alert("Geocode was not successful for the following reason: " + status);
                }
    }); 
                            }
</script>

谢谢

1 个答案:

答案 0 :(得分:0)

我会调用两个函数:

(1)将地图置于标记

的中心

您已经拥有LatLng,或者从marker.getPosition()获取,并拨打map.setCenter(myLatLng)

(2)设置地图的缩放

map.setZoom(zoomLevel),可以固定在12到16左右,或根据它的标记类型(街道地址或城市概览?)变化。此信息可以存储在标记变量marker.zoomLevel中。

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 });
      map.setZoom(16);
    } 
    else { 
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}