Finding nearest locations using Google Maps API
Asked Answered
M

4

21

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?

Megass answered 15/5, 2013 at 9:22 Comment(0)
H
27

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:

$sql = "SELECT *, ( 6371 * acos( cos( radians(" . $db->real_escape_string($lat) . ") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(" . $db->real_escape_string($lng) . ") ) + sin( radians(" . $db->real_escape_string($lat) . ") ) * sin( radians( lat ) ) ) ) AS distance FROM your_table_name HAVING distance < 15";

$lat and $lng being your center coordinates

lat and lng being your MySQL column names

15 being the radius (in km) around your coordinates

This 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!

Hypophosphite answered 15/5, 2013 at 11:17 Comment(3)
Thanks for that sql query. I have all bike station locations and their latitude and longitude, I pull from a service and can store that in an sql table. I'm going to give your solution a try. Saw somewhere that, you can put all lat-long in an array and use Haversine formula. I have like nearly 3000 records, and don't want to load all that in an array and search for the nearest one. I think I'm going to try your second solution and update here on what worked. Cheers.Megass
If I had 3K records, I would use that approach. It would be fine. I am dealing with over 150K records and it runs just fine. Use AJAX! And you will have a great app! :-)Hypophosphite
It helped me too :)Acquiesce
U
15

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:

  • Get all bike stations location.
  • Store them in array.
  • Find the user current location.
  • Loop your array, and convert locations to distances using the mentioned method.
  • Sort you array to get smallest distance.

Distance results are expressed in meters.

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.

Undershoot answered 30/7, 2016 at 4:53 Comment(3)
You should also think in terms of performance and API calls / quota. I don't think this is an appropriate answer when OP mentioned that he's dealing with a few thousand locations, especially when you can do all that with one single database query.Hypophosphite
@Hypophosphite I hope you read the answer well before you comment :)Undershoot
Which part of it? Both methods need an API call for every point. Am I wrong?Hypophosphite
D
5

I have the same task and i solved using the haversine formula. Here is my example in PHP

private function distance($latA, $lngA,$latB, $lngB) {
    $R = 6371000;
    $radiansLAT_A = deg2rad($latA);
    $radiansLAT_B = deg2rad($latB);
    $variationLAT = deg2rad($latB - $latA);
    $variationLNG = deg2rad($lngB - $lngA);

    $a = sin($variationLAT/2) * sin($variationLAT/2) 
                + cos($radiansLAT_A) * cos($radiansLAT_B) * sin($variationLNG/2) * sin($variationLNG/2);

    $c = 2 * atan2(sqrt($a), sqrt(1-$a));

    $d = $R * $c;

    return $d;
}  

And for test i used these coords

$distance = $this->distance(-12.0972,-77.0267,-13.160616,-74.227440);

The result should be 325932.546518 in meters. If u want in km just divide 325932.546518/1000 = 325.932546518km

The same formula could be translated to javascript following the guide haversine

Diaphragm answered 27/9, 2017 at 23:22 Comment(3)
What is the function of this data $R = 6371000; ? Is that static?Scyphozoan
@DimasAdiAndrea $R is earth’s radius ;)Diaphragm
i have compared this formula with google maps computeDistanceBetween function with setting both to 6378137 earth radius, the result from this formula is :812.3261185522 and from google maps function is 812.3261185526761 which is acceptable precision for me. so finally i choose to use this formula in my project. thank youJacinto
I
4

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.

Inamorato answered 15/5, 2013 at 10:5 Comment(2)
Thanks for the answer. Seems like I need another api key for google places. I'm already using Android Maps key for Maps api access, this is a bit confusing to me, got to read more.Megass
Yes you are right. While Google can provide you with a lot of useful data, if you can use other trusted sources (your own data, other providers, etc.), just do use them! Then you won't rely on Google for the data updates (which can be a struggle) and in many cases you can't anyway.Hypophosphite

© 2022 - 2024 — McMap. All rights reserved.