Attach a marker to a designated street

Currently, I am working on a project that involves tracking user feedback for a long stretch of construction area. The challenge lies in ensuring that the marker placed by the user snaps to the road between two specific points - Point A and Point B.

I have previously snapped markers to roads generally, but never to a particular road like this. This leads me to believe that either Google Maps does not currently offer this feature, or I have yet to discover how to implement it.

One potential solution I am considering is generating a polyline by creating directions from Point A to Point B, and then finding a way to snap the marker to that polyline. However, the exact method to achieve this remains unclear to me at this point.

Answer №1

After exploring various sources, I developed a unique solution by combining different ideas. While the suggestion to pad the points was helpful, it didn't quite achieve the level of accuracy I desired. Drawing upon my distant math class memories, I recalled a method that could potentially solve this problem. In the end, I created a script that iterates through the path's points and calculates the closest point based on user input.

The drawback of this approach is its inefficiency as it requires looping through all points each time. Unfortunately, due to the unpredictable nature of paths with multiple points moving in any direction, determining the closest point remains challenging until the full set is processed. Nonetheless, the advantage lies in pinpointing the absolute closest point without snapping to any specific location.

The function takes two parameters: the marker point (a single lat/lng pair) and an array of lat/lng points representing your path. It returns the lat/lng coordinates on the path closest to the specified marker point. While this function can be customized for additional information retrieval, it perfectly serves my current needs.

function find_closest_point_on_path(marker_pt,path_pts){

    var lowest = 9999999999999999;
    var theLat = 0;
    var theLng = 0;

    $.each(path_pts,function(key, path_pt){
        if(typeof path_pts[key+1] != "undefined"){
            var test = point_to_line_segment_distance(path_pt.lat(),path_pt.lng(), path_pts[key+1].lat(),path_pts[key+1].lng(), marker_pt.lat(),marker_pt.lng());
            if(test[0] < lowest){
                lowest = test[0];
                theLat = test[1];
                theLng = test[2];
            }
        }
    });

    return new google.maps.LatLng(theLat, theLng);
}

function point_to_line_segment_distance(startX,startY, endX,endY, pointX,pointY) {

    // Adapted from Philip Nicoletti's function, found here: http://www.codeguru.com/forum/printthread.php?t=194400

    r_numerator = (pointX - startX) * (endX - startX) + (pointY - startY) * (endY - startY);
    r_denominator = (endX - startX) * (endX - startX) + (endY - startY) * (endY - startY);
    r = r_numerator / r_denominator;

    px = startX + r * (endX - startX);
    py = startY + r * (endY - startY);

    s = ((startY-pointY) * (endX - startX) - (startX - pointX) * (endY - startY) ) / r_denominator;

    distanceLine = Math.abs(s) * Math.sqrt(r_denominator);

    closest_point_on_segment_X = px;
    closest_point_on_segment_Y = py;

    if ( (r >= 0) && (r <= 1) ) {
       distanceSegment = distanceLine;
    }
    else {
       dist1 = (pointX - startX) * (pointX - startX) + (pointY - startY) * (pointY - startY);
       dist2 = (pointX - endX) * (pointX - endX) + (pointY - endY) * (pointY - endY);
       if (dist1 < dist2) {
          closest_point_on_segment_X = startX;
          closest_point_on_segment_Y = startY;
          distanceSegment = Math.sqrt(dist1);
       }
       else {
          closest_point_on_segment_X = endX;
          closest_point_on_segment_Y = endY;
          distanceSegment = Math.sqrt(dist2);
       }
    }

    return [distanceSegment, closest_point_on_segment_X, closest_point_on_segment_Y];
}

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

The close icon in the ReactStrap modal is not being displayed properly, and I need to know how to utilize the header with a different tag

I recently started working with React JS and I am currently utilizing the Modal component from reactStrap. <Modal isOpen={props.isOpen} centered='true'> <ModalHeader> Change this Question? <button type= ...

Using jQuery and AJAX to fetch the string value being returned by my function

I have the following code-behind implementation: [WebMethod] [ScriptMethod(UseHttpGet=true)] public string GetMessage() { XmlTextReader reader = new XmlTextReader (Global.sAppPath + "/alt/importantMsg.xml"); string message = ...

Verify if the input text field meets the minimum value requirement upon submission

I have a basic HTML form on my website... After collecting the user input, I convert it into JSON data (intending to send it elsewhere later on. Currently, just using console.log for testing). Once the user fills out the form and clicks submit, I want to ...

The tubular.js Youtube video background is overlapping my other components on the site, instead of displaying behind them as intended

I recently implemented the tubular.js script on my webpage to display a YouTube video as the background. On the tubular page, there is a statement that reads: First, it assumes you have a single wrapper element under the body tag that envelops all of ...

Can JavaScript/JQuery be used to dynamically alter the color of a dropdown menu or change the color of list items when a radio option is selected?

Is it possible to enhance the functionality of my code that currently selects a radio option and automatically changes the dropdown box? Can I also make the selected dropdown item change color, such as blue for 'Work', green for 'Grocery&apo ...

Utilize React Material UI to elegantly envelop your TableRows

Currently, I am faced with a challenge involving a table that utilizes Material UI and React-table. My goal is to wrap text within the TableRow element, but all my attempts have not been successful so far. Is there anyone who knows the best approach to a ...

Patience is key when waiting for the outcome of an async Javascript function in order to obtain a result (Could it be

Hey there, I've been searching for a solution to my problem even though it's been discussed before. I'm trying to achieve something simple: creating a string like distance is : " + CalculateDistance(position);. The desired result should look ...

Can the text value be read and its strings changed?

I need to modify the message inside an H2 element with the code provided below. I want to change the text from No results were found for this query: <em class="querytext"> to "No results were found by hello world!, but the catch is that I cannot di ...

Transcluding content inside a table cell with Angular

Recently, I came across a peculiar issue with an attribute directive in Angular. This directive simply adds a class name to the element where it is applied, specifically to a table cell <td>. Oddly enough, when I set transclude: true in the directive ...

A step-by-step guide on resolving the issue "Error: listen EADDRINUSE: address already in use :::5000" in the event of an error

node:events:495 throw er; // Unhandled 'error' event ^ Error: listen EADDRINUSE: address already in use :::5000 at Server.setupListenHandle [as _listen2] (node:net:1817:16) at listenInCluster (node:net:1865:12) at Server. ...

Sharing data between app.js and client-side files in Node.js: How to do it effectively?

I have a question about passing a value from my Node.js app.js file to my client-side JavaScript file. Here is my app.js file: var express = require('express'); var app = express(); var port = process.en ...

JavaScript - memory heap exhausted

Recently, I encountered an issue with my API written in Node.js. The purpose of this API is to read data from a MySQL database, write it into a CSV file, and allow users to download the file once the writing process is complete. Initially, everything was f ...

There seems to be an issue with the next function's functionality within a Nodejs middleware

Currently, I am delving into the world of Nodejs with expressjs. My focus is on understanding middleware functions and specifically, the role of "next". In the middleware concept, "next" simply moves on to the next middleware in line. So, what exactly is ...

The appearance of all input forms in MaterializeCSS when used in an electron environment appears to

After following the instructions here on how to get started with Materialize CSS, I am having issues with my input form appearing strange: https://i.sstatic.net/lveS2.png The contents of my current index.html file are as follows: <!DOCTYPE html> &l ...

Viewing a Google Charts graph upon the loading of a web page

Utilizing the Google Charts library, I have incorporated a graphic on my web page that is dynamically added using AJAX into a <div> element. To display the graph when the page loads, I have written the following code: <script type="text/ ...

Locate the element within the specified parameters using [protractor]

Here's my query: element.all(by.repeater('user in users')).then(function(rows) { // looking to locate an element in rows using CSS selector, for example } UPDATE : I want to clarify that I am trying to find an element using rows[rows.len ...

Create a Vue application that is built on modules which could potentially be absent

I am currently developing a Vue+Vite app with module-based architecture. I have several Vue components and some parts of the app are functioning correctly. However, I want to ensure that the missing components are not imported or used in the application. H ...

Use CSS to position the SVG element to the bottom right corner of the screen

I have a <div> on the page with the CSS class .svgImage applied to it. Whenever I resize the browser window, the svg image resizes correctly but keeps shifting its position on the page. When I make the browser window vertically smaller, the svg imag ...

Converting PHP variables into JavaScript

I am looking for a way to add the value of a PHP variable to a jQuery variable and perform addition on them. Specifically, I have a form on page one that will take a value inputted by the user and post it to a second page. The second page contains a div ...

The Javafx WebEngine's executescript() function is unable to send a multiline string

Issue: I'm struggling to make the JavaFX WebEngine trigger a JavaScript function when using a Java String object with multiple lines. If I input the following example in HTML: "asd" ENTER "qwe" into the textArea, and then click the send button, the f ...