Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set google map custom zoom level dynamically?

Tags:

google-maps

I am working with google map. According to requirements i need to set different zoom level that is dependent to my search query.If there are multiple location on the map in country then map should focus the country. Other scenario is , if there are different locations marked in a city then map should be focused to city level.

like image 527
Rana Imtiaz Avatar asked Jan 24 '26 04:01

Rana Imtiaz


1 Answers

var geoCoder = new GClientGeocoder();
geoCoder.setViewport(map.getBounds());
geoCoder.getLocations('searchquery', function(latlng) {
  if( latlng.Placemark.length > 0 ) {
    var box = latlng.Placemark[0].ExtendedData.LatLonBox;
    var bounds = new GLatLngBounds(new GLatLng(box.south, box.west), new GLatLng(box.north, box.east));
    var center = new GLatLng(box.Placemark[0].Point.coordinates[1], latlng.Placemark[0].Point.coordinates[0]);
    var zoom = oMap.getBoundsZoomLevel(bounds);
    map.setCenter(center, zoom);
  }
});

I think the key part of this for you is

//box is a LatLonBox with the size of your resultquery. You can create this yourself as well
var box = latlng.Placemark[0].ExtendedData.LatLonBox;

//bounds are the bounds of the box
var bounds = new GLatLngBounds(new GLatLng(box.south, box.west), new GLatLng(box.north, box.east));

//center is the center of the box, you want this as the center of your screen
var center = new GLatLng(box.Placemark[0].Point.coordinates[1], latlng.Placemark[0].Point.coordinates[0]);

//zoom is the zoomlevel you need for all this
var zoom = oMap.getBoundsZoomLevel(bounds);

//the actual action
map.setCenter(center, zoom);
like image 183
douwe Avatar answered Jan 25 '26 20:01

douwe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!