Skip to content

Instantly share code, notes, and snippets.

@bamnet
Last active October 20, 2018 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bamnet/0d5b91e9e08e4bfce721c608b5cd24da to your computer and use it in GitHub Desktop.
Save bamnet/0d5b91e9e08e4bfce721c608b5cd24da to your computer and use it in GitHub Desktop.
Helper functions for use with the Google Maps JavaScript API to find points along a polyline.

Point Along Polyline

The percentAlongPath and distanceAlongPath functions below use the Geometry library of the Google Maps API to interpolate points a percentage or distance along a polyline. This can be useful to plot points along a polyline at regular intervals.

Note: The Geometry library must be loaded by appending &libraries=geometry to the <script> tag used to load the Google Maps API. For more information, check out the Library documentation.

analytics

/**
* percentAlongPath finds the location of a point a percentage along the path.
*
* 0 (0%) = start, 0.5 (50%) = midpoint, 1 (100%) = end, etc.
*
* @param {Array<LatLng>} path List of latlngs that make up the polyline.
* @param {number} percent Fractional amount of path to travel.
* @returns {LatLng}
*/
function percentAlongPath(path, percent) {
const length = google.maps.geometry.spherical.computeLength(path);
return distanceAlongPath(path, percent * length);
}
/**
* distanceAlongPath finds the location of a point along a polyline a distance from the start.
*
* Supplying a distance longer than the path will just return the end of the path.
*
* @param {Array<LatLng>} path List of latlngs that make up the polyline.
* @param {number} targetDistance Distance from the start of the path, in meters.
* @returns {LatLng}
*/
function distanceAlongPath(path, targetDistance) {
let traveled = 0;
for (let i = 1; i < path.length; i++) {
const legDistance = google.maps.geometry.spherical.computeDistanceBetween(path[i-1], path[i]);
if (targetDistance < traveled + legDistance) {
// We don't need to go the full length, time to interpolate.
const distanceLeft = targetDistance - traveled;
return google.maps.geometry.spherical.interpolate(path[i-1], path[i], distanceLeft / legDistance);
}
traveled = traveled + legDistance;
}
return path[path.length - 1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment