我们有一个要求,我们必须为标记/点提供拖放设施。示例https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/适用于1个标记。因为它是硬编码到geojson.features [0] .geometry.coordinates = [coords.lng,coords.lat];
但是,在多点场景中,如何为拖动的各个特征设置geojson?
如果需要进一步的细节,请告知。
Thankx
您可以通过存储当前标记并在onMove期间对其应用更改来实现此目的。
我已经为每个对象添加了一个属性来定义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
}
}
]
};
在点图层上的onmousedown
事件中,存储当前要素ID
这里
features[0]
是可用的,因为事件在点上发射,所以第一个特征是点击的特征
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);
});
之后,在onMove
方法中,您可以使用它来移动正确的功能:
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);
}
请参阅此处的工作示例:https://codepen.io/tmacpolo/pen/moxmpZ