OpenLayers Simple Example

From OpenStreetMap Wiki
Jump to navigation Jump to search

Deploy an OpenStreetMap slippymap on my own website. For a more up to date example use leaflet instead.

This simple example may help if you are Deploying your own Slippy Map. This DHTML snippit will bring in the OpenLayers javascript library and use it to show an OSM map!

Note: OpenStreetMap is serving the tile images

Please note that tile images are coming from the OpenStreetMap servers. Although OSM are supporting this kind of usage at the moment, we offer no guarantees. There may be downtime (planned or unplanned), and tile URLs may change.

If you are expecting heavy user load, then you should discuss with everyone first (Contact). You should consider following the other instructions on creating your own tiles, or set up your own squid cache for tiles. This will reduce the dependency for you, and will ease bandwidth usage for the OSM servers.

Of course the images themselves (our maps) change over time too, not necessarily for the better.


First, create a folder to work in. Download a stable release of OpenLayers from (note: this is a link to the older version 2 which those examples are based on), and uncompress it. Copy the `OpenLayers.js` file and the `theme` directory to the base of the folder. Then, copy one of the following into a new HTML file, and view it in a browser.

The smallest example

<title>OpenLayers Simplest Example</title>
<div id="demoMap" style="height:250px"></div>
<script src="OpenLayers.js"></script>
    map = new OpenLayers.Map("demoMap");
    map.addLayer(new OpenLayers.Layer.OSM());

The code shows how you

  • initialise a Map object with a DIVs id
  • add a OpenStreetMap Layer
  • force the tiles to show by calling zoomToMaxExtent, you could also call zoomToExtent, but for that you need a bounds object in the correct projection...

A little more extensive example

    <title>OpenLayers Demo</title>
    <style type="text/css">
      html, body, #basicMap {
          width: 100%;
          height: 100%;
          margin: 0;
    <script src="OpenLayers.js"></script>
      function init() {
        map = new OpenLayers.Map("basicMap");
        var mapnik         = new OpenLayers.Layer.OSM();
        var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
        var toProjection   = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
        var position       = new OpenLayers.LonLat(13.41,52.52).transform( fromProjection, toProjection);
        var zoom           = 15; 

        map.setCenter(position, zoom );
  <body onload="init();">
    <div id="basicMap"></div>


Other tile sets

If you are deploying your own tile images (for example, with Mapnik), just use the layer definition below:

 var newLayer = new OpenLayers.Layer.OSM("New Layer", "URL_TO_TILES/${z}/${x}/${y}.png", {numZoomLevels: 19});

The addition of /${z}/${x}/${y}.png URL template has been required since the 27th June 2009.

Change the url and numZoomLevels as appropriate.

Restricting the bounds & zoom levels

This restricts the map to showing the area around Oxford, and zoom levels 13-16. To add lower zooms, add new numbers in the resolutions array (each one is double the next).

      var fromProjection = new OpenLayers.Projection("EPSG:4326"); // transform from WGS 1984
      var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
      var extent = new OpenLayers.Bounds(-1.32,51.71,-1.18,51.80).transform(fromProjection,toProjection);
      function init() {
        var options = {
          restrictedExtent : extent,
          controls: [
            new OpenLayers.Control.Navigation(),
            new OpenLayers.Control.PanZoomBar(),
            new OpenLayers.Control.Attribution()
        map = new OpenLayers.Map("Map", options);
        var newLayer = new OpenLayers.Layer.OSM(
          "New Layer", 
          {zoomOffset: 13, resolutions: [19.1092570678711,9.55462853393555,4.77731426696777,2.38865713348389]}
        map.setCenter(new OpenLayers.LonLat(-1.25,51.75).transform(fromProjection,toProjection), 0); // 0=relative zoom level

Altering the location of the attribution text and scale line

You can override the location of the attribution text and scale line, and the font used, by adding the following lines in the style section

      div.olControlAttribution, div.olControlScaleLine {
          font-family: Verdana;
          font-size: 0.7em;
          bottom: 3px;

Add Markers

<title>OpenLayers Simplest Example</title>
<div id="Map" style="height:250px"></div>
<script src="OpenLayers.js"></script>
    var lat            = 47.35387;
    var lon            = 8.43609;
    var zoom           = 18;

    var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
    var toProjection   = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
    var position       = new OpenLayers.LonLat(lon, lat).transform( fromProjection, toProjection);

    map = new OpenLayers.Map("Map");
    var mapnik         = new OpenLayers.Layer.OSM();

    var markers = new OpenLayers.Layer.Markers( "Markers" );
    markers.addMarker(new OpenLayers.Marker(position));

    map.setCenter(position, zoom);

Use Proj4js for other transformations

The example lets you use WGS84 coordinates to navigate in a sphericalMercator projected OSM map. If your coordinates are in a different projection, you can add Proj4js to perform reprojections.

Add the proj4js.js script from to your page (after the OpenLayers lib!)

Add your projection defintion (these are obtainable from the Proj4 project, you need the a record from \proj\nad\epsg

See for examples

Example for EPSG:28992 (new RD)

Proj4js.defs["EPSG:28992"] = "+title=Amersfoort / RD New +proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs";

Then, you can use EPSG:28992 coordinates and this epsg code in the transformfunction instead of WGS84

like so:

    new OpenLayers.LonLat(155000,465000) // Center of the map
            new OpenLayers.Projection("EPSG:28992"), // transform from new RD 
            new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
    15); // Zoom level

Develop this example?

Feel free to edit this page with improvements.

This example was originally created by Harry Wood (and anyone else who edits this page). It is intentionally more basic, with only one layer defined, and no support for URL params (permalink) etc. So adding these features is not necessarily an improvement. In fact, if you have ideas for making this even more simple, that would be good.