PanTo多个标记

时间:2012-11-21 20:53:26

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

说我从外部源加载新标记,它看起来像这样:

var markersArray = [];

downloadUrl("eventsxml.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("id");
          var address = markers[i].getAttribute("id");
          var type = markers[i].getAttribute("venue_type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
          var html = "<b>" + name + "</b> <br/>" + address;
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon,
            shadow: icon.shadow

          });
          markersArray.push(marker);
          bindInfoWindow(marker, map, infoWindow, html);
        }
      });

我如何收集标记的边界,然后在加载后将它们全部平移到视图中?我在google上做了很多搜索,但这些解决方案都没有对我有用。

1 个答案:

答案 0 :(得分:4)

  1. 创建一个空的边界对象(google.maps.LatLngBounds
  2. 将所有标记添加到其中
  3. 使用它来居中和缩放地图
  4. 这样的事情:

    var markersArray = [];
    // create an empty bounds object
    var bounds = new google.maps.LatLngBounds();
    
    downloadUrl("eventsxml.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("id");
          var address = markers[i].getAttribute("id");
          var type = markers[i].getAttribute("venue_type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
    
          // add each marker's location to the bounds
          bounds.extend(point);
          var html = "<b>" + name + "</b> <br/>" + address;
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon,
            shadow: icon.shadow
    
          });
          markersArray.push(marker);
          bindInfoWindow(marker, map, infoWindow, html);
        }
        // center and zoom the map to fit the bounds
        map.fitBounds(bounds);
      });
    

    要平移边界的中心,而不是fitBounds,请使用:

    map.panTo(bounds.getCenter());
    

    请注意,这不会改变地图的缩放级别。