Using isLocationOnEdge to determine if a point is close to a route, I am getting weird results. As shown in the image, figure 1 contains the route (the green polyline) and is surrounded by boundaries (the black lines), that outside it, isLocationOnEdge() returns false, except for that region in figure 2.
The tolerance used is 0.001 which is supposed to allow up to 111 meters. But the straight line distance from that region in figure 2 to the closest point on the route is around 190 meters.
Here is the jsfiddle (requires maps api key).
function initMap() {
const directionsService = new google.maps.DirectionsService();
var polys = {}
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: { lat: 30.0318444756445, lng: 31.25973456250148 }, // cairo
});
directionsService
.route({
origin: new google.maps.LatLng(30.001896865282045, 31.27506692156426),
destination: new google.maps.LatLng(30.00456579847159, 31.27285809204621),
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives: true
})
.then((response) => {
var paths = response.routes[0].overview_path;
var polyline = new google.maps.Polyline({
path: paths,
strokeWeight: 7,
strokeColor: "green"
});
polys.polyline = polyline
polyline.setMap(map);
// zoom into the polyline
var bounds = new google.maps.LatLngBounds();
polyline.getPath().forEach(function(e) {
bounds.extend(e);
})
map.fitBounds(bounds);
})
.catch((e) => {
window.alert("Directions request failed due to " + e)
console.log(e)
});
google.maps.event.addListener(map, 'click', function(event) {
// place a marker where we clicked at, only if isLocationOnEdge returned true
point = new google.maps.Marker({
position: event.latLng,
map
});
const isCloseToPolyline = google.maps.geometry.poly.isLocationOnEdge(event.latLng, polys.polyline, 0.001)
console.log("point is close to polyline: ", isCloseToPolyline)
if (isCloseToPolyline === false) {
point.setMap(null)
}
});
}
window.onload = function() {
if (typeof(google) == "undefined") {
var mapsAPI = prompt("Please enter your API key ", "");
$.getScript('https://maps.google.com/maps/api/js?key=' + mapsAPI).done(function(){initMap()});
} else {
console.log("google api already loaded");
}
};