A simple map
HTML
<link rel="stylesheet" href="https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.css">
<script src="https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>title</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.45.0/mapbox-gl.css' rel='stylesheet' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.45.0/mapbox-gl.js'></script>
<script src='https://api.mapbox.com/mapbox.js/plugins/turf/v3.0.11/turf.min.js'></script>
</head>
<body>
<div id='map'></div>
</body>
</html>
CSS
body {
margin:0;
padding:0;
}
#map {
position:absolute;
top:0;
bottom:0;
width:100%;
}
JavaScript
mapboxgl.accessToken = 'pk.eyJ1IjoicHJpY2Vyb2JvdCIsImEiOiJjaXNyZzdoMXcwMDRkMnpwYmVpc2wyaDB6In0.I544EVAxja9rja2pO0cZLw';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [0, 0],
zoom: 2
});
map.on('load', function() {
drawBounds(map, 'white')
});
map.on('click', function() {
drawBounds(map, 'red')
})
function drawBounds (map) {
const currentBound = map.getBounds()
let bounds = new mapboxgl.LngLatBounds(currentBound._sw, currentBound._ne)
const sw = currentBound._sw
const ne = currentBound._ne
const nw = {
lng: ne.lng,
lat: sw.lat,
}
const se = {
lng: sw.lng,
lat: ne.lat,
}
let polygon = turf.polygon([[
[nw.lng, nw.lat],
[ne.lng, ne.lat],
[se.lng, se.lat],
[sw.lng, sw.lat],
[nw.lng, nw.lat],
]])
addDebugPoint (map, nw, 'black')
addDebugPoint (map, ne, 'green')
addDebugPoint (map, se, 'red')
addDebugPoint (map, sw, 'orange')
addDebugPoint (map, nw, 'black')
let polygon2 = turf.polygon([[
[bounds.getNorthWest().lng, bounds.getNorthWest().lat],
[bounds.getNorthEast().lng, bounds.getNorthEast().lat],
[bounds.getSouthEast().lng, bounds.getSouthEast().lat],
[bounds.getSouthWest().lng, bounds.getSouthWest().lat],
[bounds.getNorthWest().lng, bounds.getNorthWest().lat],
]])
addDebugPoint (map, bounds.getNorthWest(), 'black')
addDebugPoint (map, bounds.getNorthEast(), 'green')
addDebugPoint (map, bounds.getSouthEast(), 'red')
addDebugPoint (map, bounds.getSouthWest(), 'orange')
addDebugPoint (map, bounds.getNorthWest(), 'black')
addDebugRectangle(map, polygon, 'red')
...