PanTo multiple markers

时光怂恿深爱的人放手 提交于 2019-12-18 09:41:37

问题


say I load new markers from an external source, it looks like this:

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);
        }
      });

How would I go about gathering the bounds for the markers and then panning them all into view once they're loaded? I did so much searching on google but none of those solutions have worked for me.


回答1:


  1. create an empty bounds object (a google.maps.LatLngBounds)
  2. add all your markers to it
  3. use it to center and zoom your map

Something like this:

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);
  });

To panTo the center of that bounds, instead of fitBounds, use:

map.panTo(bounds.getCenter());

Note that that will not change the zoom level of the map.



来源:https://stackoverflow.com/questions/13501915/panto-multiple-markers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!