Skip to content Skip to sidebar Skip to footer

Right Click On Google Map Polyline Isn't Actually "on" The Polyline

Both of these markers were placed on a Google map by handling the right click method on a polyline, ie: google.maps.event.addListener(polyline, 'rightclick', myMethodThatHandlesIt)

Solution 1:

Because it provides a better user experience, the hit box for markers, lines and shapes is somewhat larger than the actual item. So if you click close, it counts. That doesn't help with precision.

For polylines, you'd need to implement a snap-to-line functionality to find the closes point on the actual polyline. This answer provides some guidance: Find a point in a polyline which is closest to a latlng


Solution 2:

For anyone else who runs into this, I couldn't figure out a clean way of doing it in Javascript and ultimately I didn't need to. The maker can be a little off but I need to persist it as a point that intersects the line. So the following method is in place to change the marker location before I store it.

I opted to use Microsoft.SqlServer.Types.SqlGeography which has a method of

Geography.ShortestLineTo(OtherGeography)

That gives a new line with two points, one at the user's marker location, the other at the closest intersection to the route/polyline/linestring.

The end of the new line is the closest point on the route to where the user right clicked on the polyline.

        public static System.Data.Spatial.DbGeography GetClosestPointOnRoute(System.Data.Spatial.DbGeography line, System.Data.Spatial.DbGeography point)
    {
        SqlGeography sqlLine = SqlGeography.Parse(line.AsText()).MakeValid(); //the linestring
        SqlGeography sqlPoint = SqlGeography.Parse(point.AsText()).MakeValid(); //the point i want on the line

        SqlGeography shortestLine = sqlPoint.ShortestLineTo(sqlLine); //find the shortest line from the linestring to point

        //lines have a start, and an end
        SqlGeography start = shortestLine.STStartPoint();
        SqlGeography end = shortestLine.STEndPoint();

        DbGeography newGeography = DbGeography.FromText(end.ToString(), 4326);

        var distance = newGeography.Distance(line);

        return newGeography;
    }

Additionally Issue 5887 was created over in Googleland to hopefully address.


Post a Comment for "Right Click On Google Map Polyline Isn't Actually "on" The Polyline"