Skip to content

technologyOpenLayers

Rene Pickhardt edited this page Aug 14, 2013 · 1 revision

Overview

We want to use OpenLayers, a API for querying data from Open Streetmaps to display geodata for our users, for example to show Metalheads in your proximity. There is already a good wiki out there but I try to boil it down to some important informations on how to use it and get started. As addition to that, there is a documentation of the Javascript file available that is the base of the whole API.

Getting started

First of all, some basic use-cases of the API. To create a simple map you can take a look at this example:

  1 <!DOCTYPE HTML>
  2 <title>OpenLayers Simplest Example</title>
  3 <div id="demoMap" style="height:250px"></div>
  4 <script src="OpenLayers.js"></script>
  5 <script>
  6     map = new OpenLayers.Map("demoMap");
  7     map.addLayer(new OpenLayers.Layer.OSM());
  8     map.zoomToMaxExtent();
 9 </script>

I will go over the lines in detail. The concept of OpenLayers are as the name might give away the Layers. You can create a new layer when you want to show more informations, for examples put markers on the map. And the Map itself is also a layer. So to start you create a new map object from the constructor with map = new OpenLayers.Map("demoMap") This invokes the constructor and creates a new blank map object, that is put on the position of the div, in this case named "demoMap" Then the concept of the layers comes to show. We add a layer to the blank map object, in this case the map itself. map.addLayer(new OpenLayers.Layer.OSM()); If you leave the brakes empty it uses the default map set supplied by OpenStreetMaps, but you can also use your own map, details here. The last line of this example just shows one of the ways to manipulate the displayed default parameters for the map, in this case it starts at the maximum zooming level.

Fun with POIs

In the next example, we try to work with an external source to bind a list of POIs into our map. First of all the complete working example to copy-paste again.

<html><body>
  <div id="mapdiv"></div>
  <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
  <script>
    map = new OpenLayers.Map("mapdiv");
    map.addLayer(new OpenLayers.Layer.OSM());
 
    var markers = new OpenLayers.Layer.Markers( "Markers" );
    map.addLayer(markers);
 
    var venues = [{name: 'Musikbunker Aachen', adress:'Rehmanstr. 12', lon: 50.7579, lat: 6.10804, website:'http://www.musikbunker-aachen.de',image:'bunker.jpg'}, 
		     {name: 'K17', adress:'Pettenkoferstraße 17a', lon: 52.5184, lat: 13.468, website:'http://www.k17-berlin.de'}, 
		     {name: 'Access', adress:'Greifswalder Allee 33', lon: 52.5368, lat: 13.4268, website:'http://www.myspace.com/accessberlin'},
		     {name: 'Hof 23', adress:'Langhansstr. 23', lon: 52.557, lat: 13.4504, website:'http://www.hof23.de'},
	 	     {name: 'Matrix', adress:'Hauptstrasse 200', lon: 51.4701, lat: 7.31927, website:'http://www.matrix-bochum.de/'},
       		     {name: 'Steinbruch Theater', adress:'Odenwaldstraße 26', lon: 49.809, lat: 8.69412, website:'http://www.steinbruch-theater.de'}];
    
    var lonlat;
    //Set start centrepoint and zoom    
    var lonLat = new OpenLayers.LonLat(9.0000, 51.0000 )
          .transform(
            new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
            map.getProjectionObject() // to Spherical Mercator Projection
          );
    var zoom=5;
    map.setCenter (lonLat, zoom); 
 
    
    // The overlay layer for our marker, with a simple diamond as symbol
    var overlay = new OpenLayers.Layer.Vector('Overlay', {
        styleMap: new OpenLayers.StyleMap({
            externalGraphic: 'file:///home/tobi/metalcon/metalcon/mapsClient/marker.png',
            graphicWidth: 20, graphicHeight: 24, graphicYOffset: -24,
            title: '${tooltip}'
        })
    });

    //looping over all venues from the JSON we defined earlier, the local venues can be replaced with a feed from an external source
    for (i in venues) {


    // Here we define our default map position and zoom level
    // The location of our marker and popup. We usually think in geographic
    // coordinates ('EPSG:4326'), but the map is projected ('EPSG:3857').
    var myLocation = new OpenLayers.Geometry.Point(venues[i].lat, venues[i].lon)
        .transform('EPSG:4326', 'EPSG:3857');

    // We add the marker with a tooltip text to the overlay
    overlay.addFeatures([
        new OpenLayers.Feature.Vector(myLocation, {tooltip: 'OpenLayers'})
    ]);
    // A popup with some information about our location
    var popup = new OpenLayers.Popup.FramedCloud("Popup", 
        myLocation.getBounds().getCenterLonLat(), null,
        '<a target="_blank" href="'+(venues[i].website)+'">'+(venues[i].name)+'</a> '+'</br> Ihr findet uns: '+venues[i].adress, null,
        true // <-- true if we want a close (X) button, false otherwise
    );
    map.addPopup(popup);
    map.addControl(new OpenLayers.Control.LayerSwitcher());
	    
}
    
  </script>
</body></html>

A bit of the code stays the same as before, we create a empty map and add the default OSM map. Next we create a new empty layer for the markes and try to fill it with markers. For that we have a object in JSON that has all the informations we need for the marker, first of all the lotitude and longitude so we know where to place them. The other informations can be displayed in Popups, since we have HTML-Boxes. But before we start iterating over our object we set the default coordinates for our map, in our case a map of germany. Next step is to walk over our JSON with for (i in venues) and give every entry a position on our map.

Clone this wiki locally