Skip to content

Instantly share code, notes, and snippets.

@andrewharvey
Last active June 27, 2017 00:50
Show Gist options
  • Save andrewharvey/6c6282db4a7c9b316ebd51421160c5e4 to your computer and use it in GitHub Desktop.
Save andrewharvey/6c6282db4a7c9b316ebd51421160c5e4 to your computer and use it in GitHub Desktop.
Mapbox GL JS 0.39.0 check geolocation within maxBounds
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox-gl-js/v0.39.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v0.39.0/mapbox-gl.css' rel='stylesheet' />
<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 = 'pk.eyJ1IjoiYWxhbnRnZW8tcHJlc2FsZXMiLCJhIjoiNkRKcXdVdyJ9.XVLiu2tRo5f2P__oBfdqsw';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-74, 41],
zoom: 13,
maxBounds: [[-75, 40], [-68, 42]]
});
var geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
map.addControl(geolocate);
(function() {
var proxied = geolocate._updateCamera;
geolocate._updateCamera = function() {
// get geolocation
var location = new mapboxgl.LngLat(arguments[0].coords.longitude, arguments[0].coords.latitude);
var bounds = map.getMaxBounds();
if (bounds) {
// if geolocation is within maxBounds
if (location.longitude >= bounds.getWest() && location.longitude <= bounds.getEast() &&
location.latitude >= bounds.getSouth && location.latitude <= bounds.getNorth) {
return proxied.apply( this, arguments );
} else {
console.log('geolocate is outside bounds');
return null;
}
}
return proxied.apply( this, arguments );
};
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment