ic3
ic3

Reputation: 7690

Google Maps - synchronize zoom/position of multiple maps

Is there a standard way to synchronize the position and zoom of two Google maps in the same page.

The idea is too have both besides, two maps. It should work with mouse zoom and recenter.

Upvotes: 2

Views: 1215

Answers (1)

Mervin Samy
Mervin Samy

Reputation: 396

I would try this, on your drag event set the 2nd maps' center by taking it from the first map

map2.setCenter(map1.getCenter());

you can do the same with zoom

map2.setZoom(map1.getZoom());

working fiddle here: https://jsfiddle.net/mervinsamy/w076uaL4/

var map1, map2;
var listener1;
var listener2;

function initMap() {
  var mapOptions = {
    zoom: 15,
    center: new google.maps.LatLng(33.8120918, -117.9211629),
    mapTypeId: 'terrain'
  };
  var mapOptions2 = {
    zoom: 15,
    center: new google.maps.LatLng(33.8120918, -117.9211629),
    mapTypeId: 'hybrid'
  };

  map1 = new google.maps.Map(document.getElementById('map1'), mapOptions);
  map2 = new google.maps.Map(document.getElementById('map2'), mapOptions2);


  map1.addListener('mouseover', function() {
    google.maps.event.removeListener(listener2);
    listener1 = google.maps.event.addListener(map1, 'bounds_changed', (function() {
      map2.setCenter(map1.getCenter());
      map2.setZoom(map1.getZoom());
    }));
  });


  map2.addListener('mouseover', function() {
    google.maps.event.removeListener(listener1);
    listener2 = google.maps.event.addListener(map2, 'bounds_changed', (function() {
      map1.setCenter(map2.getCenter());
      map1.setZoom(map2.getZoom());
    }));
  });


}
#map1,
#map2 {
  width: 450px;
  height: 400px;
}
<div id="map1">
</div>


<div id="map2"></div>

<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAmj6gxqgx_9AUOSJoXY6f7q2WrsexIlqE&callback=initMap">
</script>

Upvotes: 5

Related Questions