SMPLGRP
SMPLGRP

Reputation: 261

Center Map based on Route

I would like to center a Google Map based on the center-point of the route, but I cannot use fitbounds because it doesn't allow me to use a custom zoom (it zooms to the bounds of the route).

The following is my current attempt. I wonder if it is possible to use map.setCenter? I have commented out the line that I think I need help with.

google.maps.event.addListener(dr, 'directions_changed', function() {
  var route = dr.getDirections().routes[0];
  var path = route.overview_path;
  es.getElevationAlongPath({
    path: path,
    samples: Math.max(50, path.length * 2)
  }, function(result, status) {
    if (status == google.maps.ElevationStatus.OK) {
      drawElevation(result);
      recalcHeight();
      if (fitBounds) {
        map.setZoom(route.bounds);
       //map.setCenter();
        fitBounds = false;

      }
    }
    else {
      $('#error').text(status).show();
    }
    recalcHeight();
  });
});

Update: this simple change solved my problem - custom zoom followed by correct centering:

map.setZoom(13);
map.setCenter(route.bounds.getCenter());

Second Update: Please remove the the vote downs. This was a legitimate question that had an easy answer.

Upvotes: 1

Views: 2685

Answers (2)

Krishan Kant Sharma
Krishan Kant Sharma

Reputation: 361

If you display a Google Map on your site using the Google JS API, here is how you can have it auto-centered and auto-zoomed depending on the markers it contains.

Before adding markers:

bounds = new google.maps.LatLngBounds();

Everytime you add a new marker:

loc = new google.maps.LatLng(marker.position.lat(),marker.position.lng()); bounds.extend(loc);

After all markers have been added:

map.fitBounds(bounds); # auto-zoom map.panToBounds(bounds); # auto-center

That's it, cheers.

I found it from here: Link

Upvotes: 2

Dr.Molle
Dr.Molle

Reputation: 117334

A DirectionsRoute has a bounds-property(a LatLngBounds-object). LatLngBounds have a center-property, so all you need to do is to set the center of the map to the center of the bounds of route:

map.setCenter(route.bounds.getCenter());

Upvotes: 2

Related Questions