I have a bus route as DB table where Lat/Long of each Bus stop is stored.

Now, I get live GPS cordinates and when the bus reaches a particular point, I want to know whether its close to Stop S2 or S3 - The key is that least distance should be measured along the bus route , not the shortest linear distance ignoring say a curve.

I am using Google maps API.

Can you suggest which path to take?

Note that its not a nearest place from current location using google places API.

Diagram showing 4 Bus stops and current GPS (star

2 Answers 2


Not sure if you're going to be able to use the Google Maps api to do this. You more likely need a bespoke gis solution, by which I mean probably a spatial database which stores the bus routes and then works out firstly the nearest point on the route (which probably involves firstly finding the nearest route, then the nearest node on that route), otherwise with a large network you would have to iterate through thousands of route points.

The next task is to work out whether it is nearer along the line to one stop than the other stop. This is fairly easily done, so long as you have access to the underlying line geometry.

If you can get the route geometry in Gmaps there may be a way of iterating through the line segments and doing various "nearest" calculations on them, but the Google Maps API is quite a long way from real spatial database functionality, ad would probably involve a lot of API calls, unless you can implement your own solution for things like converting lat/long to distances on the ground.

Otherwise, you're stuck using the less accurate method.


My approach would be to first check which vertex of the polyline lies the closest to the actual position. If you have that, you can grab the vertices of the polyline from vertex 0 till that vertex and create a new google maps polyline from those. Note, that you will not plot that new polyline on the map, but will only use it for determining the distance to the next stop. If your polyline is not segmented i.e. it is not made up of separate polylines between bus stops, you can do the following: Determine the closest polyline vertex to the bus' location and determine the closest polyline vertices to the stations. Then all those points will be one of the vertices of the big polyline. Then you can use the getAt method of the polyline object to determine which point of the polyline is the bus stop and the bus location is, and then you can do the same that I have explained in my first paragraph.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.