OL3: Setting map view center to geolocation.getCurrentPosition doesn't work

Anders Finn Jørgensen picture Anders Finn Jørgensen · Nov 5, 2014 · Viewed 8.7k times · Source

When the application starts, I want to center the map view on the users current position. I have tried two different approaches and can't get them work. The first one worked properly in leaflet, but in the development process I have decided to use OL3 instead.

First approach (worked in leaflet):

  var myProjectionName = "EPSG:25832";
  proj4.defs(myProjectionName,
             "+proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs");

 var centerPosition;

 if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        function (pos) {
                 centerPosition =             
                            ol.proj.transform(
                                     [position.coords.longitude,
                                      position.coords.latitude],
                                     'EPSG:4326', 
                                      myProjectionName);
        },
        function (err) {centerPosition = [724844,6178000];},
        {
            enableHighAccuracy: false,
            timeout: 5000,
            maximumAge: 1000  
        });
}

My second approach was using the ol.Geolocation class:

 var proj1 = ol.proj.get(myProjectionName);
 var geolocation = new ol.Geolocation({
                             projection: proj1
                       });
 var centerPosition= geolocation.getPosition();

The center position is used in creating the view/map object:

var map = new ol.Map({
   target: 'map',
   logo : false,
   layers: [ GSTGroup, OVLGroup, SheatLayer],
   view: new ol.View({
      projection: myProjectionName,
      center: centerPosition,
      resolutions : AVLresolutions,
      resolution : 2
     })
});

I have some suspecions that the cause of the problem is the projection, but on the other hand the projection works properly in transforming layers (WMTS, Vector), source from Geojson in different coordinatesystem and in ol.control.MousePosition.

I am using Firefox 32.0.3 and the geolocator plugin to development/test

Working example in http://jsfiddle.net/AndersFinn/ak4zotn8/

Answer

Thomas Gratier picture Thomas Gratier · Nov 7, 2014

Add after the map declaration the following (tested):

var proj1 = ol.proj.get(myProjectionName);
var geolocation = new ol.Geolocation({
    projection: myProjectionName,
    tracking: true
});

geolocation.on('change', function(evt) {
  console.log(geolocation.getPosition());
  map.getView().setCenter(geolocation.getPosition());
});

The most important part is tracking: true in the code: it means you check regularly the position to center.

The second important part is to bind event on geolocation object (an instance of ol.Geolocation)

See in the official examples the geolocation samples and the API docs to make some changes depending of your requirements