[OpenLayers-Users] Using cookies to remember the map state
Mapmaker
bmcbride at cha-llp.com
Fri Feb 26 10:06:46 EST 2010
Hi all,
I recently ported the following Google Maps API tutorial (using cookies to
remember the map state when the user leaves the page and comes back) to
OpenLayers.
http://econym.org.uk/gmap/cookies.htm http://econym.org.uk/gmap/cookies.htm
Here's the code..
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet"
href="http://openlayers.org/dev/theme/default/style.css" type="text/css" />
<link rel="stylesheet"
href="http://openlayers.org/dev/examples/style.css" type="text/css" />
<script src="http://openlayers.org/dev/OpenLayers.js"></script>
<script type="text/javascript">
var lon = 5;
var lat = 40;
var zoom = 5;
var map, layer;
// === Some cookie parameters ===
var cookiename = "mapinfo"; // name for this cookie
var expiredays = 7; // number of days before cookie expiry
// === Look for the cookie ===
if (document.cookie.length>0) {
cookieStart = document.cookie.indexOf(cookiename + "=");
if (cookieStart!=-1) {
cookieStart += cookiename.length+1;
cookieEnd=document.cookie.indexOf(";",cookieStart);
if (cookieEnd==-1) {
cookieEnd=document.cookie.length;
}
cookietext = document.cookie.substring(cookieStart,cookieEnd);
// == split the cookie text and create the variables ==
bits = cookietext.split("|");
lat = parseFloat(bits[0]);
lon = parseFloat(bits[1]);
zoom = parseInt(bits[2]);
}
}
function init(){
map = new OpenLayers.Map( 'map' );
layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0", {layers: 'basic'}
);
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);
map.addControl( new OpenLayers.Control.LayerSwitcher() );
}
// === Set the cookie before exiting ===
function setCookie() {
mapcenter = new OpenLayers.LonLat(map.getCenter().lon,
map.getCenter().lat);
var cookietext =
cookiename+"="+mapcenter.lat+"|"+mapcenter.lon+"|"+map.getZoom();
if (expiredays) {
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
cookietext += ";expires="+exdate.toGMTString();
}
// == write the cookie ==
document.cookie=cookietext;
}
</script>
</head>
<body onload="init()" onunload="setCookie()">
<h1 id="title">WMS Example</h1>
<div id="tags">
</div>
<div id="map" class="smallmap"></div>
</body>
</html>
--
View this message in context: http://n2.nabble.com/Using-cookies-to-remember-the-map-state-tp4639597p4639597.html
Sent from the OpenLayers Users mailing list archive at Nabble.com.
More information about the Users
mailing list