HTML5 Guidelines for Web Developers

(coco) #1
7.4 Display of Current Position on OpenStreetMap 195

Just as in section 7.1.2, Online Map Services, the data of the OpenStreetMap proj-
ect is represented using the OpenLayers library. After the two required JavaScript
files are loaded, the map is initialized in this example and the desired control
elements are added:


// Initialize map and add navigation
var map = new OpenLayers.Map ("map");
map.addControl(new OpenLayers.Control.Navigation());
map.addControl(new OpenLayers.Control.PanZoomBar());


In addition to the navigation element with the four arrows, we attach the zoom
bar to the map variable (map). We then create the selection element for the vari-
ous layers (Control.LayerSwitcher) and add several layers to the map. The func-
tion call of map.addLayers() receives an array of newly created map objects:


// Layer selection with four map types
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.addLayers([
new OpenLayers.Layer.OSM.Mapnik("Mapnik"),
new OpenLayers.Layer.OSM.Osmarender("Osmarender"),
new OpenLayers.Layer.OSM.CycleMap("CycleMap")
]);


To finish, the map gets a layer for the marker:


var markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);


The success callback after successfully determining the position looks like this:


function(pos) {
var ll = new OpenLayers.LonLat(
pos.coords.longitude,
pos.coords.latitude).transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
);
map.setCenter (ll,zoom);
markers.addMarker(
new OpenLayers.Marker(
ll,new OpenLayers.Icon(
'http://www.openstreetmap.org/openlayers/img/marker.png')
)
);
},

Free download pdf