Richard
Richard

Reputation: 65600

Mapbox GL JS: Control max zoom with geolocation control?

I am using Mapbox GL JS v0.32.1 and I have a geolocation control on my map.

I would like to make it so that the maximum zoom when the user geolocates is 8, so that the map zooms to the user's approximate location, not street location.

According to the documentation there should be a geolocate event available, but this isn't working for me:

var geoLocate = map.addControl(new mapboxgl.GeolocateControl());
geoLocate.on('geolocate', function(e) {
    console.log('geolocated');
    map.setZoom(8);
})

Geolocating (in Chrome at least) still zooms to the maximum zoom level available, and I don't see a console log message when it happens.

Upvotes: 3

Views: 2202

Answers (2)

Khurshid Ansari
Khurshid Ansari

Reputation: 5095

Try this way. smooth zoom to your location

var geoLocate = new mapboxgl.GeolocateControl();

map.addControl(geoLocate);

geoLocate.on('geolocate', function(e) {
   map.flyTo({
    center:[e.coords.longitude, e.coords.latitude], 
    zoom:16 //set zoom 
  });
});

Upvotes: 2

Lucas Wojciechowski
Lucas Wojciechowski

Reputation: 3802

Map#addControl returns Map. The geolocate event is fired on GeolocateControl. The following should work:

var geoLocate = new mapboxgl.GeolocateControl();
map.addControl(geoLocate);
geoLocate.on('geolocate', function(e) {
    console.log('geolocated');
    map.setZoom(8);
});

Upvotes: 1

Related Questions