Mapbox GL JS:在多点地图中拖动1个点
Mapbox GL JS : Drag 1 point in many points map
我们有一个要求,我们必须为标记/点提供拖放功能。 https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/ 示例非常适合 1 个标记。 因为它被硬编码为 geojson.features[0].geometry.coordinates = [coords.lng, coords.lat];
但是,在多点场景中,如何为被拖动的各个要素设置 geojson?
如果需要任何进一步的详细信息,请告知。
谢谢
您可以通过存储当前标记并在 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
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);
});
之后,在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
我们有一个要求,我们必须为标记/点提供拖放功能。 https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/ 示例非常适合 1 个标记。 因为它被硬编码为 geojson.features[0].geometry.coordinates = [coords.lng, coords.lat];
但是,在多点场景中,如何为被拖动的各个要素设置 geojson?
如果需要任何进一步的详细信息,请告知。
谢谢
您可以通过存储当前标记并在 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
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);
});
之后,在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