papyruscs icon indicating copy to clipboard operation
papyruscs copied to clipboard

Save map location as cookie

Open jmartin657 opened this issue 3 years ago • 0 comments

Not an issue, just a little something I added if you guys want it, it saves the current position and zoom level of the map to restore it on page refresh (useful in my case because I will have the page auto-refresh to update player positions). There is a limitation however it uses cookies so only works if the map page is hosted locally or externally but not if opened in a file viewer like windows explorer.

So changed this view at line 208 of map.html

      const view = new ol.View({
        projection: projection,
        center: getStartingCenter(),
        zoom: getStartingZoom(),
        minZoom: 0,
        maxZoom: config.globalMaxZoom - config.globalMinZoom
      });

Added this after the end of bracket of line 414 of map.html

    // On map move
map.on("moveend", function(e){
	// Get the current map location
	var currentCenter = map.getView().getCenter();
	var currentZoom = map.getView().getZoom();
	// Save the position in a cookie
	setCookie('currentX',currentCenter[0],7);
	setCookie('currentZ',currentCenter[1],7);
	setCookie('currentZoom',currentZoom,7);
});

// Get starting position
function getStartingCenter(){
	// Get cookie with current position
	var savedX = getCookie('currentX');
	var savedZ = getCookie('currentZ');
	if(savedX && savedZ){
		return [parseFloat(savedX), parseFloat(savedZ)];
	}else{
		return [0,0];
	}
}

function getStartingZoom(){
	// Get cookie with current zoom
	var savedZoom = getCookie('currentZoom');
	if(savedZoom){
		return parseFloat(savedZoom);
	}else{
		return 7;
	}
}

// Cookie functions
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);
		}
	}
}

jmartin657 avatar Mar 03 '21 22:03 jmartin657