Mapbox gl playground
A mapbox gl js playground for quick tryouts
by Benderlio
HTML
<script src=" https://npmcdn.com/@turf/turf/turf.min.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.css">
<script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.2.0/mapbox-gl-draw.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.2.0/mapbox-gl-draw.css">
<div id="map"></div>
CSS
#map {
height: 500px;
}
JavaScript
mapboxgl.accessToken = 'pk.eyJ1IjoiZmFyYWRheTIiLCJhIjoiTUVHbDl5OCJ9.buFaqIdaIM3iXr1BOYKpsQ';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/satellite-v9',
center: [-120.2180599383928, 55.94864965239703],
zoom: 5
});
function isEventAtCoordinates(event, coordinates) {
if (!event.lngLat) return false;
return event.lngLat.lng === coordinates[0] && event.lngLat.lat === coordinates[1];
}
function distance(a, b) {
var dist = Math.sqrt(Math.pow((a.x - b.x), 2) + Math.pow((a.y - b.y), 2));
return dist;
}
MapboxDraw.modes.draw_line_string.clickAnywhere = function (state, e) {
if (e.originalEvent.shiftKey) {
//erase a coordinate near this click
console.warn('state', state);
console.warn('SHIFT', state.line);
const line = state.line.coordinates;
const lastClick = line[line.length - 1]
const a = map.project(lastClick)
const res = line.map((i, index) => {
const b = map.project(i)
const d = distance(a, b)
return {
index,
distance: d
};
}).find(i => i.distance < 5)
console.log('res', res);
if (res) {
//state.line.removeCoordinate(res.index)
state.line.coordinates = state.line.coordinates.filter((i, index) => index !== res.index)
}
} else {
console.log('NO SHiFT');
if (state.currentVertexPosition > 0 && isEventAtCoordinates(e, state.line.coordinates[state.currentVertexPosition - 1]) ||
state.direction === 'backwards' && isEventAtCoordinates(e, state.line.coordinates[state.currentVertexPosition + 1])) {
return this.changeMode('simple_select', { featureIds: [state.line.id] });
}
this.updateUIClasses({ mouse: 'add' });
...