Make Google Maps retain zoom and center after refr

2020-07-09 06:45发布

问题:

How do I make Google Maps retain the user's view (zoom level and center point) after an HTTP refresh?

Right now, it resets the view after each refresh. Can I tweak the code below to say "zoom: current zoom level" and "center: current center location" somehow?

function initialize() {  
  var myLatLng = new google.maps.LatLng(0,0);  
  var myOptions = {  
    zoom: 2,  
    center: myLatLng,  
    mapTypeId: google.maps.MapTypeId.TERRAIN  
  };  

I have figured out some other ways to do this for http://test.barrycarter.info/sunstuff.html but they're all considerably harder.

回答1:

Try this:

// you could use the event listener to load the state at a certain point
 loadMapState();

// as a suggestion you could use the event listener to save the state when zoom changes or drag ends
google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);
function tilesLoaded() {
    google.maps.event.clearListeners(map, 'tilesloaded');
    google.maps.event.addListener(map, 'zoom_changed', saveMapState);
    google.maps.event.addListener(map, 'dragend', saveMapState);
}   


// functions below

function saveMapState() { 
    var mapZoom=map.getZoom(); 
    var mapCentre=map.getCenter(); 
    var mapLat=mapCentre.lat(); 
    var mapLng=mapCentre.lng(); 
    var cookiestring=mapLat+"_"+mapLng+"_"+mapZoom; 
    setCookie("myMapCookie",cookiestring, 30); 
} 

function loadMapState() { 
    var gotCookieString=getCookie("myMapCookie"); 
    var splitStr = gotCookieString.split("_");
    var savedMapLat = parseFloat(splitStr[0]);
    var savedMapLng = parseFloat(splitStr[1]);
    var savedMapZoom = parseFloat(splitStr[2]);
    if ((!isNaN(savedMapLat)) && (!isNaN(savedMapLng)) && (!isNaN(savedMapZoom))) {
        map.setCenter(new google.maps.LatLng(savedMapLat,savedMapLng));
        map.setZoom(savedMapZoom);
    }
}

function setCookie(c_name,value,exdays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
      x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
      y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x=x.replace(/^\s+|\s+$/g,"");
      if (x==c_name)
        {
        return unescape(y);
        }
      }
    return "";
}


回答2:

I didn't want to use Cookies so I created another method using localStorage.

HTML

<div id="map-canvas" style="width:100%;height:500px;"></div>

JS

$(document).ready(function(){
    //Global Variables
    var mapCentre;
    var map;

    initialize();

    function initialize() {
        var mapOptions;

        if(localStorage.mapLat!=null && localStorage.mapLng!=null && localStorage.mapZoom!=null){
            mapOptions = {
              center: new google.maps.LatLng(localStorage.mapLat,localStorage.mapLng),
              zoom: parseInt(localStorage.mapZoom),
              scaleControl: true
            };
        }else{
            //Choose some default options
            mapOptions = {
              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();     
        });
    }
});

Link to JSFiddle: http://jsfiddle.net/x11joex11/G4rdm/10/

Just move around the map by zooming out since it starts in the middle of the ocean and then hit run again or refresh the page and you will see it remembers the position and zoom.

It stores to localStorage every time the user pans the screen or zooms thanks to the event messages "center_changed" and "zoom_changed"



回答3:

You'd need to store this data in a cookie, then read from the cookie to get the values, or use default values if the cookie doesn't exist. Have an event listener on zoom_changed, and use map.getZoom(), then save the zoom level to the cookie. And likewise have an event listener on center_changed and use map.getCenter() to save the center point coordinates to the cookie. Or possibly could wrap them both up into bounds_changed.



标签: google-maps