Using OpenLayers

Published 2013-05-17

Getting the map canvas

Make a div element with an identifier and make it fill the entire canvas. Also for good measure put a style in for the proper attribution.

<style type="text/css">
div#map { width:100%; height:100% }
div#map div.olControlAttribution { top: 0; bottom: auto }
</style>
...
<div id="map"></map>

Pull in the OpenLayers library.

<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>

Now declare an initialization function that will spawn the canvas, a base layer for the map, and a few controls. This function can be called from the body element's onload attribute.

map = new OpenLayers.Map ("map", {
        controls:[
                new OpenLayers.Control.Navigation(),
                new OpenLayers.Control.PanZoomBar(),
                new OpenLayers.Control.LayerSwitcher(),
                new OpenLayers.Control.Attribution(),
                new OpenLayers.Control.MousePosition(),
        ],
        maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
        maxResolution: 156543.0399,
        numZoomLevels: 19,
        units: 'm',
        projection: new OpenLayers.Projection("EPSG:900913"),
        displayProjection: new OpenLayers.Projection("EPSG:4326")
} );

layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
map.addLayers([layerMapnik]);

I've chosen the OpenStreetMap Mapnik layer which comes as built-in layer-type. Further I've enabled five controls:

  • Navigation - the drag-able map feature
  • PanZoomBar - the zoombar on the left with navigation arrows
  • LayerSwitcher - the plus on the right which gives a menu with available layers
  • Attribution - provides automatic attribution where available (legal stuff)
  • MousePosition - gives coordinates of the pointer position

Lastly we'll position the map canvas at our desired coordinates

var lonLat = new OpenLayers.LonLat(12.57147, 55.68368).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.setCenter(lonLat, 14);

The result should be something like demo1.

Putting GPX files on the canvas

To draw GPX data on the canvas put the GPX file next to the html file on the webserver. Some browsers have protective rules regarding javascript run from the file:// domain - a real webserver may be required.

var lonLat = new OpenLayers.LonLat(12.47000, 56.00000).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.setCenter(lonLat, 15);

var vectorLayer = new OpenLayers.Layer.Vector("GPX Track", {
    strategies: [new OpenLayers.Strategy.Fixed()],
    protocol: new OpenLayers.Protocol.HTTP({
        url: "demo2.gpx",
        format: new OpenLayers.Format.GPX(),
    }),
    projection: new OpenLayers.Projection("EPSG:4326"),
    style: {
        strokeColor: "magenta",
        strokeWidth: 6,
        strokeOpacity: 0.4
    },
    visibility: true
});
map.addLayer(vectorLayer);

The result should be something like demo2. This particular GPX track should not match up with the roads in the forrest.

If there are many tracks this could of course be done programmatically.

var database = [
    ["route-N-10km.gpx", "#008", true],
    ["route-NE-8km.gpx", "#008", true],
    ["route-E-8km.gpx", "#008", true],
    ["route-SE-9km.gpx", "#008", true]];

var lgpx;
for (var i=0; i<database.length; i=i+1) {
    var filename = database[i][0]
    var color = database[i][1]
    var visibility = database[i][2]
    lgpx = new OpenLayers.Layer.Vector(filename, {
        strategies: [new OpenLayers.Strategy.Fixed()],
        protocol: new OpenLayers.Protocol.HTTP({
            url: filename,
            format: new OpenLayers.Format.GPX(),
        }),
        projection: new OpenLayers.Projection("EPSG:4326"),
        style: {
            strokeColor: color,
            strokeWidth: 6,
            strokeOpacity: 0.4,
        },
        visibility: visibility
    });
    map.addLayer(lgpx);
}