FitBounds doesnt work in googlemaps javascript

1.1k Views Asked by At

I have a map and a list of markers, each of which has a position in LatLng object. The position is valid because i can see the markers on the map. However i want to fit the map to the markers so i use the proper syntax as below. However the map never zooms and centers in those two positions. Instead it load in the initial center,zoom that i config in the initMap. Can anybody identify the problem please???

var bounds = new google.maps.LatLngBounds();
var location = new google.maps.LatLng(25.36234, 15.3623);
var location2 = new google.maps.LatLng(38.2352, 12.36435);
bounds.extend(location2);
bounds.extend(location);
window.parent.map.fitBounds(bounds);
window.parent.map.setCenter(bounds.getCenter());
1

There are 1 best solutions below

5
oividiosCaeremos On

window.parent.map seems a bit odd of a solution for your problem.
This should solve your problem.

var map;

  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: new google.maps.LatLng(39.5473234, 35.3796685),
    mapTypeId: 'roadmap'
  });


  var bounds = new google.maps.LatLngBounds();
  var location = new google.maps.LatLng(25.36234, 15.3623);
  var location2 = new google.maps.LatLng(38.2352, 12.36435);
  bounds.extend(location2);
  bounds.extend(location);
  map.fitBounds(bounds);
  map.setCenter(bounds.getCenter());