Discover the nearest point on a polyline using Leaflet.js and showcase it

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]);
    };

Answer №1

When I initially retrieved the point, it was displayed incorrectly because I only retrieved it by its latlng. To display the correct point, you can use this onEventFunction:

 protected updateTrackTracingOnMouseMove = (event: L.LeafletMouseEvent): void => {
    const eventLayerPoint = this.map.latLngToLayerPoint(this.map.containerPointToLatLng(event.containerPoint));
    this.trackTracing.nearestPoint = this.map.layerPointToLatLng(
        this.trackLine.polyLine.closestLayerPoint(eventLayerPoint));
    this.trackTracing.dot.setLatLng(this.trackTracing.nearestPoint);
    this.trackTracing.trace.setLatLngs([event.latlng, this.trackTracing.nearestPoint]);
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Typescript: exploring the power of dynamic types

Can dynamic typing be implemented? The JSON structure I am working with looks like this: { "fieldName": "Some text", "type": String, "inputType": "text" }, { "fieldName": "Some bool&q ...

Tips for toggling the appearance of like and add to cart icons

I am attempting to create a simple functionality for liking and adding items to a cart by clicking on the icons, which should immediately change the icon's color when clicked. However, I am facing an issue where the parent div's link is also bein ...

Showing a div based on the selection of multiple options from a multiselect

I am having trouble implementing a show/hide functionality based on a multiselect dropdown in my Angular and Typescript project. Specifically, I want to display a div with another dropdown menu when the user selects a certain option from the multiselect ...

npm causing problems with babel-cli

While working on building a section of my library with Babel, I've encountered some issues when running Babel commands through npm. In my npm script named "build," the following commands are executed: { "prebuild": "rm -rf && mkdir dist", ...

Unable to fetch data from URL in Angular using the HttpClientModule

I have a goal in my application to retrieve data from the following URL and showcase it within the app: https://jsonplaceholder.typicode.com/posts/1 The issue I'm encountering is that the data is not being displayed in my app. The console is showing ...

Angular: Using ngrx for Nested HTTP Calls

Looking at my Angular code, I am trying to figure out how to convert nested HTTP calls into the ngrx pattern. My idea is to create separate actions for getUser and getPost, but I am struggling with passing the getUser response as a parameter to the getPo ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

Error: An identifier was unexpectedly encountered while using the Submit Handler

I am currently working on creating a validation script and an AJAX call. I have encountered a problem where the alert message is not working within the if condition. I can't seem to figure out what's causing this issue. When I execute the scri ...

Exploring the dynamic relationship between React's useEffect and useState functions

Currently, I am working on developing a table using React and Material UI's XGrid component. The table includes buttons that execute specific actions when clicked. One of the requirements is to set the row ID upon clicking the row itself using the use ...

Angular - personalized modal HTML

I am facing a challenge where I need to trigger a popup when a button is clicked. There can be multiple buttons, each with its own overlay popup, and these popups should close when clicking outside of them. Currently, I am using TemplateRef (#toggleButton ...

What is the best way to store and retrieve all the variable data from a .js file on a user's device?

I'm looking for a way to save and load multiple variables in JavaScript that determine a "save" state. These variables are stored in a file named "variables.js." Is there a simple method to easily save all the information in this file and then load i ...

The code seems to be malfunctioning in a separate JS file, but oddly enough, it functions properly when placed within a <script> tag

I am trying to create a loader, but I have encountered an issue where the script works when placed directly in the HTML file, but not when it is in a separate JavaScript file. Here is the script: var loader = document.getElementById("ld"); w ...

Encase the entire section following cloning with JQuery

Make sure to check out the jsfiddle demo linked below before proceeding: JSFIDDLE I need to transform the original structure as shown below: <div class="out"> <a>im here</a> <a>to save</a> <a>our</a> ...

Efficiently communicating updates to clients after executing multiple HTTP requests simultaneously in RxJS

Objective: Execute multiple asynchronous HTTP requests simultaneously with RxJS and trigger a callback after each request is completed. For instance: fetchData() { Observable.forkJoin( this.http.get('/somethingOne.json').map((res:Re ...

Organize the JSON data in a particular manner

I have a set of JSON data that looks like this: [ { "name": "Event 1", "sponsors": [ { "name": "Walmart", "location": "Seattle" }, { "name": "Target", "location": "Portland" }, { ...

What is the correct sequence of tags for an .aspx page?

I'm working on a test.aspx page. Here is the HTML code I have: <script type='text/javascript' language='javascript' src="scripts/test.js"></script> <script type="text/javascript" language='javascript' s ...

Interactive JQuery plugin for scrolling through thumbnails with customizable buttons

I am attempting to create a jQuery thumbnail scroller with buttons that respond to mousedown and mouseup events. I have successfully implemented the scrolling functionality, but I am facing issues when trying to refactor it into a reusable function. Below ...

Is there a way to create a clickable component for triggering an AJAX call without using a Submit button?

Just starting out with JS/JQuery programming, so please excuse any mistakes or unclear explanations. Any feedback is welcome, even if not requested specifically. I am working with multiple drop down lists that are populated dynamically by data from SQL Ta ...

What is the reason behind Google Plus loading CSS using XHR and then appending it to a <style> tag instead of simply using <link>?

I recently examined the Javascripts used in the new Google Plus platform and discovered an interesting approach to loading CSS. Instead of utilizing <link> tags to reference a CSS file, Google Plus employs XHR to retrieve the CSS content from a separ ...

Sharing a controller between directives in AngularJS

While trying to implement an angularjs directive, I encountered some difficulties in sharing a controller between directives I am unable to access the enterUser directive from the controller below app.directive('entires', [function () { retur ...