I have a Google Maps V3 polyline. I can detect click events on the entire polyline, but can I do anything more advanced with the click event?
What I'd like to do is detect which section of the polyline has been clicked, and show this in an alert.
routePath = new google.maps.Polyline({
path: routeCoordinates,
strokeColor: "#CC33FF",
strokeWeight: 3
});
routePath.setMap(map);
google.maps.event.addListener(routePath, 'click', function() {
alert(routePath);
// TODO: display which section of the polyline has been clicked?
});
Does anyone know how to do this in Google Maps?
thanks!
On the click event you can receive a LatLng of the coordinate that was clicked. However, since that will probably not be an exact point that is creating the polyline you need to find the closest point. You can use the computeDistanceBetween in the Google Maps library or you can use Pythagoras theorem as it should give you a good enough accuracy in this case.
You can find more information on computeDistanceBetween here: https://developers.google.com/maps/documentation/javascript/reference#spherical
Here is a code example how you could do it with the computeDistanceBetween.
google.maps.event.addListener(routePath, 'click', function(h) {
var latlng=h.latLng;
alert(routePath);
var needle = {
minDistance: 9999999999, //silly high
index: -1,
latlng: null
};
routePath.getPath().forEach(function(routePoint, index){
var dist = google.maps.geometry.spherical.computeDistanceBetween(latlng, routePoint);
if (dist < needle.minDistance){
needle.minDistance = dist;
needle.index = index;
needle.latlng = routePoint;
}
});
// The closest point in the polyline
alert("Closest index: " + needle.index);
// The clicked point on the polyline
alert(latlng);
});