How do I dynamically scale my Google map?

I work with google map. In accordance with the requirements, I need to set a different level of scaling, which depends on my search query. If there are several places on the map on the map, then the map should focus the country. Another scenario: if the city has different locations, then the map should be focused at the city level.

+3
source share
3 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);
+4
source

I found the following article very helpful. Using code code code, I can achieve to enter a link description here .

I tried the code in drupal and it works.

0

, , , , bounds.extend map.fitBounds, , , , :

    //places is an array that contains the search result
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0, place; place = places[i]; i++) {
      //pass the location of each place to bounds.extend
      bounds.extend(place.geometry.location);
    }
    //tell your map to sets the viewport to contain all the places.
    map.fitBounds(bounds);

, , , , , map.fitBounds, , , :

//response is the geocoder response
map.fitBounds(response[0].geometry.viewport);

https://codepen.io/jaireina/pen/gLjEqY

0

Source: https://habr.com/ru/post/1736478/


All Articles