Google Maps retain zoom and centre after refresh using local storage

Javascript
Jun 08 2017
1651 Views

Google Maps retain zoom and centre after refresh using local storage

Introduction
To retain Google Maps user's view (zoom level and centre point) after an HTTP refresh, we need to use HTML5 Local storage.

Google functions used
1. getZoom() - it will return current zoom level of google map.
2. getCenter() - it will returns the position displayed at the center of the map. We need to get lat, lng from this object.
3. setZoom()
4. setCenter()

Google events used
1. center_changed
2. zoom_changed

Define Local storage
Before using local storage, check browser support for localStorage

if (typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! No Web Storage support..
}

Other definitions for local storage

Define - localStorage.setItem("userZoomLevel", zoomLevel); 
using - localStorage.getItem("userZoomLevel", zoomLevel);

Working example

Html

< div id="map-canvas" >

Javascript

$(document).ready(function(){
    //Global Variables
    var mapCentre;
    var map;
    
    initialize();
    
    function initialize() {
        var mapOptions;
                
        if(localStorage.mapLat!=null && localStorage.mapLng!=null && localStorage.mapZoom!=null){
nbsp;           mapOpti />               center: new google.maps.LatLng(localStorage.mapLat,localStorage.mapLng),
              zoom: parseInt(localStorage.mapZoom),
              scaleControl: true
            };
        }else{
            //Choose some default options
nbsp;           mapOpti />               center: new google.maps.LatLng(0,0),
              zoom: 11,
              scaleControl: true
            };
        }
                
        //MAP
        map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
        
        mapCentre = map.getCenter();
        
        //Set local storage variables.
        localStorage.mapLat = mapCentre.lat();
        localStorage.mapLng = mapCentre.lng();
        localStorage.mapZoom = map.getZoom();
        
        google.maps.event.addListener(map,"center_changed", function() {
            //Set local storage variables.
            mapCentre = map.getCenter();
            
            localStorage.mapLat = mapCentre.lat();
            localStorage.mapLng = mapCentre.lng();
            localStorage.mapZoom = map.getZoom();    
        });
        
        google.maps.event.addListener(map,"zoom_changed", function() {
            //Set local storage variables.
            mapCentre = map.getCenter();
            
            localStorage.mapLat = mapCentre.lat();
            localStorage.mapLng = mapCentre.lng();
            localStorage.mapZoom = map.getZoom();     
        });
    }
});

Conclusion
Move around the map by zooming out and change center of the map and then refresh the page and it will load with new zoom level and center position.

Leave a Reply