Marker layers in OpenLayers.

Posted by – Tuesday 2012-12-11

The most usual way of creating a markers layer in OpenLayers is by adding to the map an instance of the class OpenLayers.Layer.Markers. However, this method is no longer encouraged. As said in the OpenLayers documentation [1]:

Markers support only point geometries. They are styled only using the OpenLayers.Icon class. They do not support lines, polygons, or other complex features. Their interaction method differs significantly from vector layers.

In general, Markers are the ‘older’ way to interact with geographic data in the browser. Most new code should, where possible, use vector layers in place of marker layers.

The following JavaScript code snippet shows a world map – taken from OpenStreetMap – with a marker placed on the city of Lugo (lon = 43.016667, lat = -7.55), in Spain.

var map;

function init() {
	var mapOptions = {
              	projection: 'EPSG:900913',
	      	controls: [
                    new OpenLayers.Control.Navigation(), 
                    new OpenLayers.Control.PanZoomBar()
                ]
	    };
        map = new OpenLayers.Map('map', mapOptions);

        var baseLayer = new OpenLayers.Layer.OSM('OpenStreetMap');

	var sm = new OpenLayers.StyleMap({
		externalGraphic: 'http://openlayers.org/dev/img/marker.png',
		graphicWidth: 20, 
		graphicHeight: 24, 
		graphicYOffset: -24
	});
	var markersLayer = new OpenLayers.Layer.Vector('markers', {
                styleMap: sm
	});

	var pt = new OpenLayers.Geometry.Point(-7.55, 43.016667)
                 .transform('EPSG:4326', 'EPSG:900913');
	markersLayer.addFeatures([new OpenLayers.Feature.Vector(pt)]);

	map.addLayers([baseLayer, markersLayer]);
	map.setCenter(map.getCenter(), 1);
}

A vector layer – class OpenLayers.Layer.Vector – has been used instead a marker one. The HTML div element in which the map is shown has the id “map”.


notes

[1] OpenLayers Library Documentation, Marker Overlays: http://goo.gl/yBGRA

0 Comments on Marker layers in OpenLayers.

Respond

Respond

Comments

Comments