Daryll Doyle WordPress Development and Consultancy in Cornwall

Google Maps Smooth Zoom

G

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.

Apparently Google are fine with adding a 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!

About the author

Daryll Doyle

Daryll is a Staff Engineer at 10up.

With a deep passion for web development and open-source technology, Daryll is the original author of the SVG sanitization plugin Safe SVG, which boasts over 900,000 installs from the WordPress.org plugin directory and is now proudly maintained by 10up.

Throughout his career, Daryll has demonstrated expertise in SVGs and WordPress, sharing his knowledge through public speaking engagements, including a notable talk at WordCamp London 2018.

Beyond his professional life, Daryll enjoys spending quality time with his family and diving into research on Developer Experience, constantly seeking ways to improve the workflow and productivity of fellow developers.

3 comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • 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!

Daryll Doyle WordPress Development and Consultancy in Cornwall