I have the following code to catch the polyline click
localPolyLine.addListener('click', (e) => {
});
Let's say the localPolyline has many points in it's path.
How can I get the index of the path that is clicked?
If your polyline is editable, the click will return more information. If it isn't editable, you can iterate through the segments of the polyline using the geometry library poly.isLocationOnEdge method to determine which segment of the polyline the click segment is:
// returns the lowest index, first vertex of the clicked segment
for (var i=0; i<localPolyLine.getPath().getLength()-1; i++) {
var tempPoly = new google.maps.Polyline({
path:[localPolyLine.getPath().getAt(i),localPolyLine.getPath().getAt(i+1)]
});
if (google.maps.geometry.poly.isLocationOnEdge(e.latLng, tempPoly, 1e-1)) {
console.log(i);
document.getElementById("info").innerHTML = "poly index="+i;
}
}
working code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 0,
lng: -180
},
mapTypeId: 'terrain'
});
var flightPlanCoordinates = [{lat: 37.772,lng: -122.214},{lat: 21.291,lng: -157.821},{lat: -18.142,lng: 178.431},{lat: -27.467,lng: 153.027}];
var localPolyLine = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: false,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
localPolyLine.setMap(map);
localPolyLine.addListener('click', (e) => {
for (var i=0; i<localPolyLine.getPath().getLength()-1; i++) {
var tempPoly = new google.maps.Polyline({
path:[localPolyLine.getPath().getAt(i),localPolyLine.getPath().getAt(i+1)]
});
if (google.maps.geometry.poly.isLocationOnEdge(e.latLng, tempPoly, 1e-1)) {
console.log(i);
document.getElementById("info").innerHTML = "poly index="+i;
}
}
});
}
#map {
height: 90%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Polylines</title>
</head>
<body>
<div id="info">poly index=</div>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&loading=async">
</script>
</body>
</html>