标记丢失后如何平移标记(Google Maps API)?

时间:2016-05-24 03:54:39

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

我想在标记放到Google地图上时放大每个标记。

我尝试在drop函数和addMarkerWithTimeout函数中使用panTo和setZoom方法,但它似乎不起作用。我花了几个小时试图解决这个问题。有没有人有任何想法?

var neighbors = [
    {lat: 41.081445, lng: -81.519005},
    {lat: 42.652579, lng: -73.756232},
    {lat: 61.218056, lng: -149.900278},
    {lat: 32.735687, lng: -97.108066},
    ];


var markers = [];
var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('googlemapsbackground'), {
    zoom: 4,
    center: {lat: 39.8282, lng: -98.5795}
  });
}

window.onload = function drop() {
  clearMarkers();
  for (var j = 0; j < neighbors.length; j++) {
    addMarkerWithTimeout(neighbors[j], j * 1000);
  }
}

function addMarkerWithTimeout(position, timeout) {
  window.setTimeout(function() {
    markers.push(new google.maps.Marker({
      position: position,
      map: map,
      animation: google.maps.Animation.DROP
    }));
  }, timeout);
}

function clearMarkers() {
  for (var j = 0; j < markers.length; j++) {
    markers[j].setMap(null);
  }
  markers = [];
}

1 个答案:

答案 0 :(得分:0)

您可以尝试使用LatLngBounds对象。

function addMarkerWithTimeout(position, timeout) {
  window.setTimeout(function() {
    var bounds = new google.maps.LatLngBounds(),
        marker = new google.maps.Marker({
          position: position,
          map: map,
          animation: google.maps.Animation.DROP
        });

    bounds.extend(marker.getPosition());
    markers.push(marker);
    map.fitBounds(bounds);
  }, timeout);
}