1

I've managed to to add a geolocation marker to an OpenLayers 3 map that reflects the actual position and accuracy of geolocation.

I got a custom button on the map to start the geolocation, but how can I stop geolocation and remove the marker from the map? That means use the same button to toggle my function on and off.

Here my code until now:

// new Position Control

    var button = document.createElement('button');
    button.innerHTML = 'P';

    var handleGetPosition = function(e) {
        getPosition();
    };

    button.addEventListener('click', handleGetPosition, false);
    button.addEventListener('touchstart', handleGetPosition, false);

    var element = document.createElement('div');
    element.className = 'get-position ol-unselectable ol-control';
    element.appendChild(button);

    var GetPositionControl = new ol.control.Control({
        element: element
    });

    map.addControl(GetPositionControl);


// set up the geolocation api to track our position
function getPosition() {
      var geolocation = new ol.Geolocation({
        projection: map.getView().getProjection(),
        tracking: true,
        trackingOptions: {
          enableHighAccuracy: true,
          maximumAge: 5000  
        }
      });

     var accuracyFeature = new ol.Feature();
      geolocation.on('change:accuracyGeometry', function() {
        accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
      });

      var positionFeature = new ol.Feature();
      positionFeature.setStyle(new ol.style.Style({
        image: new ol.style.Circle({
          radius: 4,
          fill: new ol.style.Fill({
            color: '#3399CC'
          }),
          stroke: new ol.style.Stroke({
            color: '#fff',
            width: 1
          })
        })
      }));

      geolocation.on('change:position', function() {
        var pos = geolocation.getPosition();
        positionFeature.setGeometry(pos ?
            new ol.geom.Point(pos) : null);
        view.setCenter(pos);
        view.setZoom(19);    
      });

      new ol.layer.Vector({
        map: map,
        source: new ol.source.Vector({
          features: [accuracyFeature, positionFeature]
        })
      });     
};  
2
  • 1
    in your onclick event geolocation.setTracking(!geolocation.getTracking())
    – ScottH
    Oct 18, 2016 at 21:13
  • I've tried several ways to integrate this code, but I did not get it to run. I've included it at the beginning of my getPosition-function. Now I've tried to include a if-clause to check if the geolocation is tracking. if (geolocation.getTracking() = true) { map.removeLayer(geolocationLayer); geolocation.setTracking(false);} but this also doesn't work since geolocation isn't defined yet. How did You think to integrate the code?
    – geom
    Oct 19, 2016 at 18:16

1 Answer 1

2
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <link rel="stylesheet" href="http://openlayers.org/en/master/css/ol.css" type="text/css">
    <style type="text/css">
    #map {
      width: 100%;
      height: 100%;
    }
    </style>
    <title>Google Maps integration example</title>
  </head>
  <body>
    <div id="map" class="map"></div>
    <button id='buttonx' text='click'></button>
    <script src="http://openlayers.org/en/master/build/ol.js" type="text/javascript"></script>
    <script type="text/javascript">
    var view = new ol.View({
            projection: 'EPSG:4326',
            center: [-90, 45],
            zoom: 14
        });
    var map = new ol.Map(
    {
        target: document.getElementById('map'),
        projection: 'EPSG:4326',
        view: view,
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],

    });
  var geolocation = new ol.Geolocation({
        projection: map.getView().getProjection(),
        tracking: false,
        trackingOptions: {
          enableHighAccuracy: true,
          maximumAge: 5000  
        }
      });
    var button = document.getElementById('buttonx');
    var handleGetPosition = function(e) {
    var trackingwasalreadyon = geolocation.getTracking(); 
    console.log(trackingwasalreadyon);
    if(trackingwasalreadyon){ 
        geolocation.setTracking(false);
            //******************************
            //**                          **
            //** CODE HERE TO REMOVE THE  **
            //** GEOLOCATION LAYERS       **
            //**                          **
            //******************************
        } else 
        { geolocation.setTracking(true); getPosition(); 
        } 
    };
    button.addEventListener('click', handleGetPosition, false);
    button.addEventListener('touchstart', handleGetPosition, false);
function getPosition() {
     var accuracyFeature = new ol.Feature();
      geolocation.on('change:accuracyGeometry', function() {
        accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
      });
      var positionFeature = new ol.Feature();
      positionFeature.setStyle(new ol.style.Style({
        image: new ol.style.Circle({
          radius: 4,
          fill: new ol.style.Fill({
            color: '#3399CC'
          }),
          stroke: new ol.style.Stroke({
            color: '#fff',
            width: 1
          })
        })
      }));
      geolocation.on('change:position', function() {
        var pos = geolocation.getPosition();
        positionFeature.setGeometry(pos ?
            new ol.geom.Point(pos) : null);
        view.setCenter(pos);
        view.setZoom(19);    
      });

      new ol.layer.Vector({
        map: map,
        source: new ol.source.Vector({
          features: [accuracyFeature, positionFeature]
        })
      });     
};  
</script>    </script>
  </body>
</html>
1
  • Welcome to GIS SE! As a new user please take the Tour to learn about our focused Question and Answer format. Please edit your answer to include some explanation on how to use your answer and what it does to solve the question.
    – Midavalo
    Oct 19, 2016 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.