Hi I'm writing an app that shows the bike stations near an address. I have the list of latitude and longitude locations of each bike station from a service.
I can mark my current location, or any address so far. How do I show all the bike stations near my location on map. Do I first get nearest Google places from the current location and then access the database for bike location and make markers on the map? What is the best approach?
Just In case someone is looking for a correct answer in 2016.
There is a very useful library created by google, The Geometry library has many different method which might help solving this problem:
computeDistanceBetween()
This answer explains exactly how to use it.
This will typically calculate distance between two passed LatLng objects.
So you can simply:
The previous algorithm may not be optimized, because some of us may have an array of thousands of coordinates, this where the method containsLocation() becomes handy, as you can narrow your searching region by specifying a polygon you can search within.
This might not be the most optimum method to find nearest location, but I believe it will do the job if you have a reasonable number of stations in your database.
I have the same task and i solved using the haversine formula. Here is my example in PHP
And for test i used these coords
The result should be
325932.546518
in meters. If u want in km just divide325932.546518/1000
=325.932546518km
The same formula could be translated to javascript following the guide haversine
If you already have the coordinates of your bike stations and if you trust this data, then just use it to draw your markers. Now you have to define what "near" means.
You have different solutions for this. Either you choose to draw the markers for all the bike stations within the map bounds (but that could be many markers to draw depending on the zoom level, or you have to prevent your script from drawing the markers before a certain zoom level is reached) or you can draw the markers within n kilometers around a location (can be the user location, the map center coordinates, etc.).
For the second solution, and if you are storing your bike stations in a MySQL database, you could do a query like that:
$lat
and$lng
being your center coordinateslat
andlng
being your MySQL column names15
being the radius (in km) around your coordinatesThis uses the Haversine formula. Good information can be found here.
Hope this helps, but we don't really know how you organized your data in your app. Give us more info if you need more help on this!
Google might already have these results, But if you already have your coordinates for the places it seems like it might be more straightforward to just plot your points.