Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

google maps - PanTo multiple markers

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  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.

proof of concept fiddle

code snippet:

// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. 
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 10,
    center: {
      lat: -33.9,
      lng: 151.2
    },
  });
  const infoWindow = new google.maps.InfoWindow();
  var markersArray = [];
  // create an empty bounds object
  var bounds = new google.maps.LatLngBounds();

  // downloadUrl("eventsxml.php", function(data) {
  // var xml = data.responseXML;
  var xml = parseXml(xmlString);
  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,
      title: name
    });
    markersArray.push(marker);
    bindInfoWindow(marker, map, infoWindow, html);
  }
  // center and zoom the map to fit the bounds
  map.fitBounds(bounds);
  // });
}
// Data for the markers consisting of a name, a LatLng and a venue_type.
const xmlString = '<markers><marker id="Bondi Beach" lat="-33.890542" lng="151.274856" venue_type="beach"/><marker id="Coogee Beach" lat="-33.923036" lng="151.259052" venue_type="beach"/><marker id="Cronulla Beach" lat="-34.028249" lng="151.157507" venue_type="beach"/><marker id="Manly Beach" lat="-33.80010128657071" lng="151.28747820854187" venue_type="beach"/><marker id="Maroubra Beach" lat="-33.950198" lng="151.259302" venue_type="beach"/><marker id="Sydney" lat="-33.8688197" lng="151.2092955" venue_type="town"/><marker id="Wagga Wagga" lat="-35.1081689" lng="147.3598323" venue_type="town"/></markers>';

var customIcons = {
  beach: {
    icon: "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png",
  },
  town: {
    icon: "http://maps.google.com/mapfiles/ms/micons/blue.png",
  }
};

function parseXml(str) {
  if (window.ActiveXObject) {
    var doc = new ActiveXObject('MicrosoftXMLDOM');
    doc.loadXML(str);
    return doc;
  } else if (window.DOMParser) {
    return (new DOMParser).parseFromString(str, 'text/xml');
  }
}

function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
  });
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Complex Marker Icons</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>
</body>

</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...