Currently, I am working on a feature that involves finding the closest point on a trackline based on the position of the mouse. The user should be able to create markers that align with the track.
To achieve this, I have implemented a circle marker to display the closest point on the track and a dashed polyline connecting the mouse position to the circle marker. Using Leaflet's "closestLayerPoint" function and GPS conversion (LatLng to x,y and vice versa), I update the positions of the circle marker and polyline during the Mousemove event.
Everything functions correctly until I move the map (zoom in/out or drag). It seems like the old track position is being used to calculate the nearest point, resulting in incorrect positions.
Prior to moving the map: view image here
After moving the map: view image here
p.S.: The mouse position is not visible due to the Windows snipping tool obstruction, but it is accurate.
protected initTraceOptions(): void {
this.trackTracing = {
dot: L.circleMarker([0, 0], { radius: 10 }),
trace: L.polyline([[0, 0], [0, 0]], {
color: 'black',
dashArray: '20, 20', dashOffset: '20',
}),
active: false,
nearestPoint: null,
};
}
public activateTrackTracing(): void {
if (this.trackTracing.active) {
return;
}
this.map.off('mousemove');
this.trackTracing.dot.addTo(this.map);
this.trackTracing.trace.addTo(this.map);
this.map.on('mousemove', this.updateTrackTracingOnMouseMove);
this.trackTracing.active = true;
}
protected updateTrackTracingOnMouseMove = (event: L.LeafletMouseEvent): void => {
this.trackTracing.nearestPoint = this.map.containerPointToLatLng(
this.trackLine.polyLine.closestLayerPoint(event.containerPoint));
this.trackTracing.dot.setLatLng(this.trackTracing.nearestPoint);
this.trackTracing.trace.setLatLngs([event.latlng, this.trackTracing.nearestPoint]);
};