# How to correctly select a edge of a polygon in Google Maps?

by The.Wolfgang.Grimmer   Last Updated April 16, 2019 01:22 AM

How to correctly select a edge of a polygon in Google Maps?

So far, I was able to create a simple demo here

You can try the code to see that there's a bug wherein it doesn't select the last edge of the polygon. Any idea how to deal with this correctly?

``````var markerDist;
var startPointMarker = new google.maps.Marker();
var endPointMarker = new google.maps.Marker();
var map;

var clickedPolylineLatLng = new google.maps.MVCArray();
var clickedPolylineArray = [];
var clickedPolyline = new google.maps.Polyline({
path: clickedPolylineLatLng,
strokeColor: 'blue',
strokeWidth: 10
});

function distanceBetween(point1, point2) {
return google.maps.geometry.spherical.computeDistanceBetween(point1, point2);
}

function initialize() {
var myLatLng = new google.maps.LatLng(0, -180);
var myOptions = {
zoom: 2,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

var flightPlanCoordinates = [new google.maps.LatLng(-27.46758, 153.027892), new google.maps.LatLng(37.772323, -122.214897), new google.maps.LatLng(29.46758, 88.027892), new google.maps.LatLng(20.46758, 97.027892), new google.maps.LatLng(17.772323, 78.214897)];
var flightPath = new google.maps.Polygon({
paths: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 10
});

google.maps.event.addListener(flightPath, 'click', function(el) {
markerDist = {
p1: '',
p2: '',
d: -1
};

startPointMarker.setMap(null);
endPointMarker.setMap(null);

clickedPolyline.setMap(null);
//clickedPolylineLatLng.clear();

var latLng = el.latLng;

console.log('getPath array');
console.table(this.getPath().getArray());
console.log('getPaths array');
console.log(this.getPath().getArray().length);
console.log(this.getPath().getLength());

var allPoints = this.getPath().getArray();
for (var i = 0; i < allPoints.length - 1; i++) {
var ab = distanceBetween(allPoints[i], latLng);
var bc = distanceBetween(latLng, allPoints[i + 1]);
var ac = distanceBetween(allPoints[i], allPoints[i + 1]);

if ((parseFloat(markerDist.d) == -1) || parseFloat(markerDist.d) > parseFloat(Math.abs(ab + bc - ac))) {
markerDist.p1 = allPoints[i];
markerDist.p2 = allPoints[i + 1];
markerDist.d = Math.abs(ab + bc - ac);

clickedPolylineLatLng.clear();
clickedPolylineLatLng.push(allPoints[i]);
clickedPolylineLatLng.push(allPoints[i + 1]);

}
}
startPointMarker.setPosition(markerDist.p1);
endPointMarker.setPosition(markerDist.p2);
startPointMarker.setMap(map);
endPointMarker.setMap(map);
clickedPolyline.setMap(map);
});
flightPath.setMap(map);
}

window.onload = initialize;
``````
Tags :

## Related Questions

Updated April 13, 2015 20:09 PM

Updated December 31, 2016 08:09 AM

Updated April 25, 2017 11:22 AM

Updated July 21, 2017 01:22 AM

Updated January 12, 2019 20:22 PM