Sometimes, we want to limit panning in Google maps API V3 and JavaScript.
In this article, we’ll look at how to limit panning in Google maps API V3 and JavaScript.
How to limit panning in Google maps API V3 and JavaScript?
To limit panning in Google maps API V3 and JavaScript, we can create a bounds object and check against it.
For instance, we write
const allowedBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(70.33956792419954, 178.01171875),
new google.maps.LatLng(83.86483689701898, -88.033203125)
);
const lastValidCenter = map.getCenter();
google.maps.event.addListener(map, "center_changed", () => {
if (allowedBounds.contains(map.getCenter())) {
lastValidCenter = map.getCenter();
return;
}
map.panTo(lastValidCenter);
});
to call addListener
to listen to the center_changed
event.
Then event handler is run when we pan the map.
In the event handler, we check if the center is in the bounds with allowedBounds.contains(map.getCenter())
.
If it is, we pan with panTo
.
Otherwise, we move back to lastValidCenter
.
We create the allowedBounds
object with the LatLngBounds
constructor called with 2 LatLng
objects.
Conclusion
To limit panning in Google maps API V3 and JavaScript, we can create a bounds object and check against it.