Nearest point on polyline
For the point 40.73, -74.01 and a three-vertex route, the closest spot on the line is 40.7227030704, -73.9972969296, on the second segment. You also learn how far along the route it sits and how far you are from it. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- Latitude
- 40.73
- Longitude
- -74.01
- Latitude
- 40.7227030704
- Longitude
- -73.9972969296
- Query lat
- 40.73
- Query lon
- -74.01
Finding the nearest point on a polyline to a free latitude and longitude is a core GIS and routing primitive: map apps snap a GPS fix onto a road centerline, logistics tools measure how far a vehicle is from a planned corridor, and survey scripts report how far along a path you already are. This nearest point on polyline tool accepts a query WGS84 coordinate and an ordered list of polyline vertices, projects them into a local equirectangular metre frame, and returns the closest location on any finite segment. You get the snapped latitude and longitude, the zero-based segment index, the fractional position on that segment, the distance along the line from the first vertex, the total polyline length, and the ground distance from the query to the snap point.
What nearest-point-on-polyline means for geographic routes
A polyline is an ordered chain of straight segments between vertices. In geographic space each vertex is a latitude and longitude on the WGS84 sphere, and each segment is the short chord between two consecutive vertices after a local map projection. Given a free query point that may sit off the route, the nearest point on the polyline is the location on any of those segments that minimizes ground distance to the query.
Segment index identifies which edge holds the snap, counting from zero at the first vertex. Distance along the line measures how far you have traveled from the first vertex to the snap if you walked the polyline itself, which is different from the straight-line distance from the query to the snap. Together those fields answer both “where on the route is closest to me?”
and “how far along the route is that place?” without requiring a full routing graph or a road network database.
Where snapping a point to a route pays off
Mobile and fleet products snap noisy GPS samples onto a planned corridor so the UI shows progress along a route rather than a jittery free fix. Field operations and utilities measure how far a crew or asset is from a pipeline, trail, or powerline without standing up a full network topology engine. Content and education sites that rank for nearest point on polyline benefit from a live free browser tool whose answers match the paid automation path on the same pure module.
Prefer dense enough vertices for curved roads so each segment stays short where the equirectangular approximation is strongest; for continental multi-thousand-kilometre polylines consider densifying or splitting if metre-level absolute accuracy matters at extreme extents.
What you can do with it
GPS snap to road or trail centerline
Project a free GPS fix onto an ordered route polyline and show the snapped lat/lon plus how far along the path the user has traveled.
Corridor offset and chainage reports
Measure ground distance from assets to a pipeline or trail alignment and report chainage (distance along) for maintenance tickets.
Track cleaning and map demos
Re-parameterize noisy track points as distance along a design polyline in ETL scripts or live educational map widgets.
FAQ
How do I find the nearest point on a polyline to a lat/lon?
Send query lat and lon plus a polyline array of at least two {lat, lon} vertices.
What if my polyline has only one point?
A polyline needs at least two vertices to define a segment. Out-of-range coordinates also fail without being billed.
What is the difference between distance along the route and distance to it?
Distance along the route is how far you would walk on the line itself from its first vertex to the snapped point. Distance to the route is the straight ground distance from your point to that snapped point.
Can the nearest point be a vertex or one end of the route?
Yes. The closest location may fall inside a segment, at a vertex where two segments meet, or at the start or finish of the whole route when your point lies beyond either end.
How accurate is it on very long routes?
Each segment is measured in a local flat frame, which works best when segments are short. Add enough vertices on curved roads, and split or densify routes thousands of kilometres long if metre-level accuracy matters.
Related tools
For developers — API access
Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.
API endpoint
Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.
Call it from your stack
curl -X POST https://api.kit.forhosting.com/geo/nearest-point-on-polyline \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"lat":40.7128,"lon":-74.006,"polyline":[{"lat":40.7,"lon":-74.02},{"lat":40.72,"lon":-74},{"lat":40.74,"lon":-73.98}]}'const res = await fetch("https://api.kit.forhosting.com/geo/nearest-point-on-polyline", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"lat": 40.7128,
"lon": -74.006,
"polyline": [
{
"lat": 40.7,
"lon": -74.02
},
{
"lat": 40.72,
"lon": -74
},
{
"lat": 40.74,
"lon": -73.98
}
]
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/geo/nearest-point-on-polyline",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"lat": 40.7128,
"lon": -74.006,
"polyline": [
{
"lat": 40.7,
"lon": -74.02
},
{
"lat": 40.72,
"lon": -74
},
{
"lat": 40.74,
"lon": -73.98
}
]
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/geo/nearest-point-on-polyline", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"lat":40.7128,"lon":-74.006,"polyline":[{"lat":40.7,"lon":-74.02},{"lat":40.72,"lon":-74},{"lat":40.74,"lon":-73.98}]}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"lat":40.7128,"lon":-74.006,"polyline":[{"lat":40.7,"lon":-74.02},{"lat":40.72,"lon":-74},{"lat":40.74,"lon":-73.98}]}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/geo/nearest-point-on-polyline", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"lat": 40.7128,
"lon": -74.006,
"polyline": [
{
"lat": 40.7,
"lon": -74.02
},
{
"lat": 40.72,
"lon": -74
},
{
"lat": 40.74,
"lon": -73.98
}
]
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "geo.nearest_point_on_polyline",
"status": "queued",
"_links": {
"result": "/tasks/tsk_…/result"
}
}The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.
Pricing
Published price — no tokens, no invented credits. A failed task is never charged.
Errors
| HTTP | Code | Meaning |
|---|---|---|
401 | unauthorized | Missing or invalid API key. |
402 | insufficient_balance | Your balance doesn't cover the task price. |
404 | unknown_type | That task type doesn't exist. |
429 | rate_limited | Too many requests. Use the webhook instead of polling. |
Technical notes
What nearest-point-on-polyline means for geographic routes
That location may fall in the interior of a segment, at a vertex where two segments meet, or at either endpoint of the whole path when the query lies beyond the start or finish.
Input contract, algorithm, response shape, and errors
Internally the solver takes the mean of the polyline vertices as the equirectangular origin, converts every vertex and the query into local east-north metres, then for each finite segment projects the query onto the infinite line and clamps the parameter t into the closed unit interval so the candidate stays on the segment. Among all segments it keeps the minimum squared distance, breaking exact ties by preferring the earlier segment for a stable contract. Zero-length consecutive duplicates are skipped once a real segment exists. POST a JSON body with lat and lon for the query point, both finite numbers in the usual WGS84 ranges of minus ninety to ninety and minus one hundred eighty to one hundred eighty, plus polyline as an ordered array of at least two vertices each carrying lat and lon. Optional radius_m defaults to six million three hundred seventy-one thousand metres for mean Earth scaling. Field aliases such as latitude, longitude, lng, vertices, points, and path are accepted so existing GIS payloads need less rewriting. Success returns lat and lon of the snap, echoed query_lat and query_lon, segment_index, t, distance_along_m and distance_along_km, distance_to_m and distance_to_km, polyline length in both units, vertex_count, segment_count, on_vertex, radius_m, and method equirectangular_polyline. Out-of-range coordinates, fewer than two vertices, non-finite numbers, and a missing polyline raise invalid_input and are not billed.
Where a nearest-point-on-polyline API earns its keep
Data pipelines that clean imported tracks use the snap plus distance_along_m to re-parameterize points as chainage along a design alignment. Pin the rounded response fields in tests and you get reproducible snaps for maps, LMS labs, and edge workers without hosting your own GIS stack.
Technical questions
What is segment_index?
A zero-based index of the polyline edge that holds the closest point. Segment 0 runs from the first vertex to the second, segment 1 from the second to the third, and so on.
How is distance along the line measured?
distance_along_m is the ground length from the first vertex to the snap point following the polyline segments, not the straight-line distance from the query to the snap.
What does the nearest point on polyline tool cost?
The browser tool is free. API requests use prepaid KIT balance at $0.002 per successful call; invalid input is not billed.