传单-如何在拖放时匹配标记和折线 [英] Leaflet - How to match marker and polyline on drag and drop
问题描述
我有一个使用leafletJS的项目. 例如,我在地图上有2个点(A,B).我将其显示为2个标记 我必须从A到B绘制一条折线. 我移动了标记A,然后将其移动到标记A的折线的开头,使其与标记A匹配(移动后跟随标记A). 我怎样才能做到这一点? 对不起,我的英语不好. 非常感谢.
I have a project with leafletJS. For example, I have 2 points (A, B) in map. I display it as 2 Markers I must draw a polyline from A to B. I moved marker A and I want to the head of polyline of marker A match to marker A (moved follow marker A). How can I do this? Sorry for my bad English. Thanks all very much.
Truong M.
推荐答案
给出以下L.Latlng
,L.Marker
和L.Polyline
:
var a = new L.LatLng(-45, -90),
b = new L.LatLng(45, 0),
c = new L.LatLng(-45, 90);
var marker_a = new L.Marker(a, {draggable: true}).addTo(map),
marker_b = new L.Marker(b, {draggable: true}).addTo(map),
marker_c = new L.Marker(c, {draggable: true}).addTo(map);
var polyline = new L.Polyline([a, b, c]).addTo(map);
您需要将事件监听器和回调附加到您的L.Marker
上.您可以自动执行此操作,但现在我将使其保持简单:
You'll need to attach eventlisteners and callbacks to your L.Marker
's. You could automate this, but i'll keep it simple for now:
marker_a
.on('dragstart', dragStartHandler)
.on('drag', dragHandler)
.on('dragend', dragEndHandler);
marker_b
.on('dragstart', dragStartHandler)
.on('drag', dragHandler)
.on('dragend', dragEndHandler);
marker_c
.on('dragstart', dragStartHandler)
.on('drag', dragHandler)
.on('dragend', dragEndHandler);
现在,在dragstart上,您需要从折线中找到与标记的latlng相对应的latlng,并将其键存储在标记实例中,以便以后在以下位置使用它:
Now on dragstart you'll need to find the latlng from the polyline which corresponds with your marker's latlng and store it's key in your marker instance so you can use it later on:
function dragStartHandler (e) {
// Get the polyline's latlngs
var latlngs = polyline.getLatLngs(),
// Get the marker's start latlng
latlng = this.getLatLng();
// Iterate the polyline's latlngs
for (var i = 0; i < latlngs.length; i++) {
// Compare each to the marker's latlng
if (latlng.equals(latlngs[i])) {
// If equals store key in marker instance
this.polylineLatlng = i;
}
}
}
现在您知道折线的latlng的键,可以在拖动事件上的标记时进行更改:
Now you know the key of the polyline's latlng you can change it when dragging the marker on the dragevent:
function dragHandler (e) {
// Get the polyline's latlngs
var latlngs = polyline.getLatLngs(),
// Get the marker's current latlng
latlng = this.getLatLng();
// Replace the old latlng with the new
latlngs.splice(this.polylineLatlng, 1, latlng);
// Update the polyline with the new latlngs
polyline.setLatLngs(latlngs);
}
要干净整洁,请删除dragend上存储的密钥:
Just to be clean and tidy remove the stored key on dragend:
function dragEndHandler (e) {
// Delete key from marker instance
delete this.polylineLatlng;
}
就是这样.这是有关Plunker的一个工作示例: http://embed.plnkr.co/SJRec3/preview
That's it. Here's a working example on Plunker: http://embed.plnkr.co/SJRec3/preview
这篇关于传单-如何在拖放时匹配标记和折线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!