I would like to extend/ alter a mapbox geolocation control with some features, e.g.:
- I would like to flyTo instead of jumpTo the current location
- I would like to add some behavior (e.g. prevent dragging) when the geocontrol button is toggled on.
How do I do that? I tried making a wrapper but then I get some problems:
- the color of button should turn blue when toggled on but that does not work anymore
- I do not know how to add features to the clicking of the button.
I have a fiddle showing how I tried to make a wrapper. As you can see the flyTo works.
mapboxgl.accessToken = 'pk.eyJ1IjoidG1jdyIsImEiOiJIZmRUQjRBIn0.lRARalfaGHnPdRcc-7QZYQ'
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v9', //stylesheet location
center: [-74.50, 40], // starting position
zoom: 9 // starting zoom
})
class GeolocateControlWrapper extends mapboxgl.GeolocateControl {
constructor() {
super()
}
_onSuccess(position) {
this._map.flyTo({
center: [position.coords.longitude, position.coords.latitude],
zoom: 17,
bearing: 0,
pitch: 0
})
this.fire('geolocate', position)
this._finish()
}
}
map.addControl(new GeolocateControlWrapper({
positionOptions: {
enableHighAccuracy: true,
timeout: 300
},
watchPosition: true
}), 'top-left')
EDIT, update: I am still having trouble with part 2 of my question. I managed to get the fiddle with 'a wrapper' working though, see this. However in my 'real-life' environment I get following error when clicking the geocontrol button:
Uncaught TypeError: Cannot read property 'extend' of undefined
at GeolocateControlWrapper._onClickGeolocate (eval at <anonymous> (0.b708727….js:485), <anonymous>:192:48)
_onClickGeolocate @ Maplayout.vue?f994:154
VM2654:1 Uncaught SyntaxError: Unexpected identifier
which references this line:
mapboxgl.util.extend(defaultGeoPositionOptions, this.options && this.options.positionOptions || {})
Any idea why?
EDIT, update: Got it working using following code:
class GeolocateControlWrapper extends mapboxgl.GeolocateControl {
_onSuccess (position) {
this._map.flyTo({
center: [position.coords.longitude, position.coords.latitude],
zoom: 17,
bearing: 0,
pitch: 0
})
this.fire('geolocate', position)
this._finish()
}
_setupUI (supported) {
super._setupUI(supported)
if (supported === false) return
this._geolocateButton.className += ' needsclick'
}
_onClickGeolocate () {
super._onClickGeolocate()
// toggle watching the device location
if (this.options.watchPosition) {
if (this._geolocationWatchID !== undefined) { // clear watchPosition
console.log('looks good in if....')
}
else {
// enable watchPosition
console.log('looks good in else....')
}
}
}
}