I'm quite new with the Google Maps API and I was wondering if there is a way to force the zoom in to a specific location, for example: the US.
What I'm looking for is a way to simulate the kind of zooming in effect of the mouse scrolling wheel, if the cursor is in the US, when you zoom in with the scrolling wheel, the center will start moving towards the cursor.
I tried using the 'zoom_changed' event and changing the center dynamically, but since it is not running in a desktop (device mode), the event is only triggered at the end (source).
Here is my code:
var map;
var centerUS;
var currentCenter;
var currentZoom;
function initMap() {
//define Map
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 0, lng: 0},
zoom: 3,
disableDefaultUI: true
});
//limit the zoom
map.setOptions({ minZoom: 3, maxZoom: 10 });
//initialization of variables
currentZoom = map.getZoom();
currentCenter = map.getCenter();
centerUS = new google.maps.LatLng(40, -100);
//add the listener for zooming in
map.addListener('zoom_changed', function () {
zoomInTheUS();
});
}
function zoomInTheUS() {
//get new values
var newZoom = map.getZoom();
currentCenter = map.getCenter();
//if the user is zooming in
if (newZoom > currentZoom) {
//difference between the current center and the center of the US
var changeLat = centerUS.lat() - currentCenter.lat();
var changeLng = centerUS.lng() - currentCenter.lng();
//approach the center of the US by a factor of 10% of the distance
var newLat = currentCenter.lat() + changeLat * 0.1;
var newLng = currentCenter.lng() + changeLng * 0.1;
//define new center and pan to it
var newCenter = new google.maps.LatLng(newLat, newLng);
map.panTo(newCenter);
}
//actualize the value of currentZoom
currentZoom = newZoom;
}
I tried to do it during the 'drag' event because it is triggered repeatedly, but it doesn't work. I think it may be because the event is triggered very quickly and the newZoom and currentZoom variable almost always have the same value. Or maybe, on device mode, the zoom variable from the Google Maps API is refreshed at the end of an event. I am only assuming, I do not know.
Is there a way to achieve what I want? I thought of disabling the panning when 2 fingers are detected or maybe changing from device mode to non-device mode, but I haven't found anything about it.
Thank you in advance.