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">
<meta charset="utf-8" />
<title>My OpenStreetMap Map</title>
<script type="text/javascript" src="">
<script type="text/javascript">
var map;

function init() 
    map = new OpenLayers.Map ("map", 
            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 });
    var start = new OpenLayers.LonLat(-3.5, 56.5);
    map.setCenter(start.transform("EPSG:4326", "EPSG:900913"), 7);
<body onload="init();" style="margin: 0;">
<div id="map" 
    style="position: absolute; width: 100%; height: 100%;">

Here’s what it looks like:

Leave a Reply

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

Solve this * Time limit is exhausted. Please reload CAPTCHA.