OpenLayers 101

Here’s a simple one-file way to get an OpenLayers map on a website. This is all the code you need, including the HTML, Javascript and CSS.

This particular example pulls in some custom tiles from a URL and overlays them on the “standard” OpenstreetMap map. You will need to change the URL (and attribution text) to point to the overlay you are interested in.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <title>NPE Scotland</title> <script type="text/javascript" src="http://www.openlayers.org/api/OpenLayers.js"> </script> <script type="text/javascript"> var map; var EPSG4326 = new OpenLayers.Projection("EPSG:4326"); var EPSG900913 = new OpenLayers.Projection("EPSG:900913"); var b = 20037508.34; function init() { map = new OpenLayers.Map ("map", { controls:[ new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar(), new OpenLayers.Control.Attribution(), new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.MouseDefaults(), new OpenLayers.Control.KeyboardDefaults()], maxExtent: new OpenLayers.Bounds(-1*b, -1*b, b, b), maxResolution: 156543.0399, units: 'm', projection: EPSG900913, displayProjection: EPSG4326 }); layerMapnik = new OpenLayers.Layer.OSM( null, null, { numZoomLevels: 15 }); layerOverlay = new OpenLayers.Layer.OSM( "NPE Scotland", "tiles/${z}/${x}/${y}.jpg", { transitionEffect: "none", isBaseLayer: false, attribution: "Imagery CC-By-NC-SA NPEMap.org.uk" } ); map.addLayer(layerMapnik); map.addLayer(layerOverlay); var start = new OpenLayers.LonLat(-3.5, 56.5); map.setCenter(start.transform(EPSG4326, EPSG900913), 7); } </script> </head> <body onload="init();" style="margin: 0;"> <div id="map" style="position: absolute; width: 100%; height: 100%;"> </div> </body> </html>  

Here’s what it looks like: