I was working on a project this week that required me to zoom in to a marker on a Google map. That’s easy, I thought, there must be a method for doing that within the V3 API.
I was wrong.
panTo()
method for smoothly panning to a marker, but the setZoom()
method re-draws the map canvas and jumps straight to the zoom level you set.“
There are a few StackOverflow answers lying around on ways to do this, but they’re all pretty awkwardly implemented. Therefore, I thought I’d write something up that I can re-use. Since it’s written up, I may as well share it.
Therefore, without further ado, here’s my Google Maps Smooth Scroll JavaScript class.
The class is Promise based, so you can easily run something once the zoom has completed and you can use it as follows:
// Create a new instance of our smooth zoom class.
// Pass in an instance of Google Maps in order to use.
const zoomer = new GoogleMapSmoothZoom( map )
// Zoom in to a level of 12.
zoomer.in( 12 )
// Zoom out to a level of 4 and then run something when it's finished.
zoomer.out( 4 )
.then( () => {
console.log( 'Zoom finished' )
} )
There you have it. Zoom in or out of a google map smoothly.
Enjoy!
Thanks for sharing!
You repeat a lot of code so you can cut it in half by doing this.
_zoomTo( level, cnt ) {
if ( cnt === level ) {
if ( this.resolve ) {
this.resolve( this );
}
return;
}
const nextZoom = level - cnt > 0 ? cnt + 1 : cnt - 1;
const z = google.maps.event.addListener( this.map, 'zoom_changed', event => {
google.maps.event.removeListener( z );
this._zoomTo( level, nextZoom );
} )
this._doZoom( cnt );
}
Hi Nolan,
Thanks for the heads up!
I’ll take a look at that and see if I can consolidate the code down a bit!