Skip to content

Instantly share code, notes, and snippets.

@jeffreycrow
Last active August 17, 2019 07:12
Show Gist options
  • Select an option

  • Save jeffreycrow/7723486 to your computer and use it in GitHub Desktop.

Select an option

Save jeffreycrow/7723486 to your computer and use it in GitHub Desktop.
Function for the Google Maps API V3 that returns a LatLng object representing the midpoint of a complex polyline (taken in as an array of points). Also requires midpoint distance, but this is easily calculable from the array of points.
getMidpoint: function(points, midpointDistance) {
var tempDistance = midpointDistance;
var midpointLatLng;
// We go through each segment of the line
for (var i = 0; i < points.length - 1; i++) {
var segment = points.slice(i, i + 2);
var length = google.maps.geometry.spherical.computeLength(segment);
tempDistance = tempDistance - length;
// If we're at zero or below, we've found the line where our midpoint exists
if (tempDistance <= 0) {
// We've gone past the midpoint so we need to back up.
var midpointLength = tempDistance + length;
// The proportion of the current segment where our midpoint exists
var percentage = midpointLength / length;
midpointLatLng = google.maps.geometry.spherical.interpolate(segment[0], segment[1], percentage);
break;
}
}
if (typeof midpointLatLng === 'undefined') {
// we don't have a midpoint for this polyline, something went very wrong
return false;
} else {
return midpointLatLng;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment