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