[GIS] How to toggle custom geolocation marker in OpenLayers 3

geolocationopenlayers

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]
        })
      });     
};  

Best Answer

<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>
Related Question