user1883212
user1883212

Reputation: 7859

Google Map V3: fitbounds and center not working together

The following code show on a map a church and a priest:

    var churchLatLng = new google.maps.LatLng(53.4, 0.14);

    var mapOptions = {
        center: churchLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    myMap = new google.maps.Map(document.getElementById('myDiv'), mapOptions);

    var bounds = new google.maps.LatLngBounds();

    // Setting church marker
    new google.maps.Marker({
        position: churchLatLng,
        map: myMap,
    });

    bounds.extend(churchLatLng);

    var priestLatLng = new google.maps.LatLng(51.2,0.13);                               

    new google.maps.Marker({
       position: priestLatLng, 
       map: myMap
    });

    bounds.extend(priestLatLng);    

    myMap.fitBounds(bounds);    

The code use both the option "center" to center the church at the center of the map, and the function "fitBounds" to fit all the markers (church and priest only in this case).

The result is that the map border is set to encompass the two markers, but the option "center" doesn't work anymore and is ignored.

What I want is setting the bounds, but at the same time showing the church at the centre of the map.

How can I accomplish this?

Upvotes: 0

Views: 2419

Answers (2)

geocodezip
geocodezip

Reputation: 161404

  1. call myMap.fitBounds to set the bounds to show all the markers.
  2. change the map to center where you like (on the church)
  3. add a listener to the bounds_changed event, when that fires, check to see if the map bounds contains the priest marker, if it does, you are done.
  4. if the priest marker is not contained by the map bounds, zoom out one level (map.setZoom(map.getZoom()-1)).

    myMap.fitBounds(bounds);
    google.maps.event.addListenerOnce(myMap,'bounds_changed',function() {
      google.maps.event.addListenerOnce(myMap, 'center_changed', function() {
        if (!myMap.getBounds().contains(priestLatLng)) {
          myMap.setZoom(myMap.getZoom()-1);
        }
      });
      myMap.setCenter(churchLatLng);
    });
    

Upvotes: 4

putvande
putvande

Reputation: 15213

Try to use an eventlistener and wait for the bounds to change (it works asynchronous).
Something like:

google.maps.event.addListenerOnce(myMap, 'bounds_changed', function(event) {
    myMap.setCenter(churchLatLng);
});

Upvotes: 0

Related Questions