3 :: Geolocation on an OpenStreetMap

So I made the mistake of searching for Geolocation for OpenStreetMap and found ready-bake code, which made it very very difficult to force myself to make it all from scratch using the OpenLayers JavaScript library.  Today’s demo can be found online here.

    <title>HTML5 Geolocation with Openstreetmap and OpenLayers</title>
    <style type="text/css">
      html, body, #basicMap {
          width: 640;
          height: 520;
          margin: 10;

    <script src="http://openlayers.org/api/OpenLayers.js"></script>
      function init() {
        map = new OpenLayers.Map("basicMap");
        var mapnik = new OpenLayers.Layer.OSM();

    navigator.geolocation.getCurrentPosition(function(position) {
     document.getElementById('anzeige').innerHTML="Latitude: " + position.coords.latitude + 
              " Longitude: " +
            position.coords.longitude + "<p>";
            var lonLat = new OpenLayers.LonLat(position.coords.longitude,
                         new OpenLayers.Projection("EPSG:4326"), //transform from WGS 1984
                             map.getProjectionObject() //to Spherical Mercator Projection

            markers.addMarker(new OpenLayers.Marker(lonLat));

            map.setCenter(lonLat, 16 // Zoom level

        //map = new OpenLayers.Map("basicMap");
        //var mapnik = new OpenLayers.Layer.OSM();
        OpenLayers.LonLat(3,3) // Center of the map
            new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
            new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
          ), 15 // Zoom level
        var markers = new OpenLayers.Layer.Markers( "Markers" );



  <body onload="init();">
HTML5 geolocation:
    <div id="basicMap"></div>
<br>HTML5 geolocation<br>
<br>with Openstreetmap and OpenLayers<br>
Your position estimated by browser geolocation API:<p>

<div id="anzeige">(will be displayed here)<p></div>

Leave a Reply

Your email address will not be published. Required fields are marked *