Reputation: 6316
How can I get the X and Y of GeolocateControl after it geolocated on the map?
I tried to this like
setTimeout(function(){
var userlocation = geolocate.Position;
var lat = userlocation.latitude;
var lng = userlocation.longitude;
console.log(lat);
}, 3000);
but it is not returning anything. and I am getting this error
Uncaught TypeError: Cannot read property 'coords' of undefined
Code:
let geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true,
watchPosition: true
}
});
map.addControl(geolocate);
map.on('load', function(){
geolocate.trigger();
});
setTimeout(function(){
var userlocation = geolocate.Position;
var lat = userlocation.coords.latitude;
var lng = userlocation.coords.longitude;
console.log(lat);
}, 3000);
Upvotes: 0
Views: 809
Reputation: 2029
The Geolocate Control has a geolocate
event which fires each time the Geolocation API position update returns successfully. Assuming that geolocate
is the variable containing your control instance, your code would look like this:
geolocate.on('geolocate', function (position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log('lat, lng', latitude, longitude);
});
Upvotes: 1