Skip to content

Instantly share code, notes, and snippets.

@andrewharvey
Created February 3, 2024 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewharvey/4793283aaed4d6704b1346b2d22923bb to your computer and use it in GitHub Desktop.
Save andrewharvey/4793283aaed4d6704b1346b2d22923bb to your computer and use it in GitHub Desktop.
Suggested workaround for https://github.com/mapbox/mapbox-gl-js/issues/13067#issuecomment-1925291846 Mapbox GL JS GeolocateControl place marker without initial camera update
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Locate the user</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v3.1.2/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v3.1.2/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
mapboxgl.accessToken = localStorage.getItem('MapboxAccessToken';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12',
center: [-24, 42],
zoom: 1
});
// Add geolocate control to the map.
const geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: false,
showUserHeading: true,
showUserLocation: true
});
// store the original _updateCamera implementation to restore later
const updateCamera = geolocate._updateCamera;
// replace updateCamera method with noop operation
geolocate._updateCamera = function () {};
map.addControl(geolocate);
map.on('load', () => {
// after first geolocate...
geolocate.once('geolocate', () => {
// restore update camera for future use
geolocate._updateCamera = updateCamera;
});
// trigger to get the dot on the map
geolocate.trigger();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment