Categories
OpenLayers

OpenLayers 101

[Updated] 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 simply shows an OpenStreetMap map. It is up to you to add additional layers, be them from raster sources, or vector data. It’s been updated for the simpler syntax used for OpenLayers 2.13.1, and also HTML 5.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My OpenStreetMap Map</title>
<script type="text/javascript" src="http://www.openlayers.org/api/OpenLayers.js">
</script>
<script type="text/javascript">
var map;

function init() 
{
    map = new OpenLayers.Map ("map", 
    {
        controls:[
            new OpenLayers.Control.Navigation(),
            new OpenLayers.Control.PanZoomBar(),
            new OpenLayers.Control.Attribution(),
        new OpenLayers.Control.LayerSwitcher()],
        projection: "EPSG:900913",
        displayProjection: "EPSG:4326"
    });
    
    layerMapnik = new OpenLayers.Layer.OSM(
    	null, null, { numZoomLevels: 15 });
    map.addLayer(layerMapnik);
    var start = new OpenLayers.LonLat(-3.5, 56.5);
    map.setCenter(start.transform("EPSG:4326", "EPSG:900913"), 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:
ol101v2

Leave a Reply

Your email address will not be published. Required fields are marked *