Create a draggable point
Drag the point to a new location on a map and populate its coordinates in a display.
See the example: https://docs.mapbox.com//mapbox-gl-js/example/drag-a-point/
HTML
<script src="https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.css">
<div id="map"></div>
<pre id="coordinates" class="coordinates"></pre>
CSS
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
.coordinates {
background: rgba(0, 0, 0, 0.5);
color: #fff;
position: absolute;
bottom: 40px;
left: 10px;
padding: 5px 10px;
margin: 0;
font-size: 11px;
line-height: 18px;
border-radius: 3px;
display: none;
}
JavaScript
// TO MAKE THE MAP APPEAR YOU MUST
// ADD YOUR ACCESS TOKEN FROM
// https://account.mapbox.com
mapboxgl.accessToken = 'pk.eyJ1IjoibHN0aXoiLCJhIjoiY2s5dGtnNTZ2MWVybzNobjEyam0yd2E3MyJ9.6dCvGbS93SKGMbOqZA4Qag';
const coordinates = document.getElementById('coordinates');
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [2.20, 41.90],
zoom: 6
});
const canvas = map.getCanvasContainer();
const geojson = {
'type': 'FeatureCollection',
'features': [{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
// These coordinates outline Maine.
'coordinates': [
[
[1.85, 42.10],
[1.85, 41.75],
[2.50, 41.75],
[2.50, 42.10],
[1.85, 42.10]
]
]
}
}]
};
function onMove(e) {
const coords = e.lngLat;
// Set a UI indicator for dragging.
canvas.style.cursor = 'grabbing';
// Update the Point feature in `geojson` coordinates
// and call setData to the source layer `point` on it.
//geojson.features[0].geometry.coordinates = [coords.lng, coords.lat];
console.log(`${coords.lat} - ${coords.lng}`);
let north = coords.lat + 0.17;
let west = coords.lng - 0.32;
let south = coords.lat - 0.17;
let east = coords.lng + 0.32;
geojson.features[0].geometry.coordinates = [[
[west, north],
[west, south],
[east, south],
[east, north],
[west, north]
]];
map.getSource('pol').setData(geojson);
}
function onUp(e) {
const coords = e.lngLat;
// Print the coordinates of where the point had
// finished being dragged to on the map.
coordinates.style.display = 'block';
coordinates.innerHTML = `Longitude: ${coords.lng}<br />Latitude: ${coords.lat}`;
canvas.style.cursor = '';
// Unbind mouse/touch events
map.off('mousemove', onMove);
map.off('touchmove', onMove);
}
map.on('load', () => {
// Add a single point to the map.
map.addSource('pol', {
'type': 'geojson',
...