Reputation: 565
We have a requirement where-in we have to provide drag drop facility for markers / points. The example https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/ works perfect for 1 marker. Because it is hardcoded to geojson.features[0].geometry.coordinates = [coords.lng, coords.lat];
However, in a multi point scenario how to set the geojson for respective feature which was dragged?
Kindly let know if any further details required.
Thankx
Upvotes: 1
Views: 1792
Reputation: 662
You can achieve that by storing the current marker and applying the change on it during onMove.
I have added a property to each object to define an id
:
var geojson = {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [0, 0]
},
properties: {
id: 1
}
},
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [0, 1]
},
properties: {
id: 2
}
}
]
};
On the onmousedown
event on point layer, store the current feature id
Here
features[0]
is usable because the event fired on point so the first feature is ever the clicked one
map.on("mousedown", "point", function(e) {
currentFeatureId = e.features[0].properties.id;
// Prevent the default map drag behavior.
e.preventDefault();
canvas.style.cursor = "grab";
map.on("mousemove", onMove);
map.once("mouseup", onUp);
});
After that, in the onMove
method you can use it to move the right feature :
function onMove(e) {
var 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.
var currentMarker = geojson.features.find(obj => {
return obj.properties.id === currentFeatureId
})
currentMarker.geometry.coordinates = [coords.lng, coords.lat];
map.getSource("point").setData(geojson);
}
See working exemple here : https://codepen.io/tmacpolo/pen/moxmpZ
Upvotes: 4