You should use the map.flyTo() method coupled with map.on('load') from mapbox.
map.on('load', function () {
map.flyTo({
center: [
-74.5 + (Math.random() - 0.5) * 10, // Example data
40 + (Math.random() - 0.5) * 10 // Example data
],
essential: true // this animation is considered essential with respect to prefers-reduced-motion
});
}
As you notice you need the coordinates of the user in order to use the flyTo function.
You have two alernatives to get them:
1. User has authorized browser location -> use the browser location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
coordinates = [position.coords.latitude, position.coords.longitude];
});
}
2. User hasn't authorized browser location -> use an IP geolocation API
You could use an IP geolocation api like Abstract to get your visitors location:
$.getJSON("https://ipgeolocation.abstractapi.com/v1/?api_key=**********", function(data) {
console.log(data.longitude);
console.log(data.latitude);
coordinates = [data.longitude,data.latitude]
})
You could then load the map.on('load') function written above and pas the coordinates for the "center" key.