It really depends if the Nearby things you are looking for are in the Google database as places of interest, or if they are arbitrary addresses / locations.
If they are addresses / locations, something similar to what you specify is correct.
- Geocode all the places you want to include and store them in a DB (with Lat/Lon)
- Geocode the place you are at (where you want information for)
- Use a maths routine for distance on a sphere to list the places within a specified distance
The Maths is:
- Get the current latitude and longitude in Radians (LatOrLon * PI / 180)
- Get the target latitude and longitude in Radians (LatOrLon * PI / 180)
- Get the Radius of your sphere (in this case earth = 3963.1 Miles)
- Use the long complex and confusing forumla
Below (where Lat1 and Lon1 are your current location in Radians and Lat2 and Lon2 are your target in Radians):
Acos(
Cos(Lat1) * Cos(Lon1) * Cos(Lat2) * Cos(Lon2) +
Cos(Lat1) * Sin(Lon1) * Cos(Lat2) * Sin(Lon2) +
Sin(Lat1) * Sin(Lat2)
) * EarthRadiusInMiles
This can be done using an SQL Function (MSSQL, but you can easily code this logic into most other languages).
CREATE FUNCTION [dbo].[CoordinateDistanceMiles](
@Latitude1 float,
@Longitude1 float,
@Latitude2 float,
@Longitude2 float
)
RETURNS float
AS
BEGIN
-- SAME LOCATION, RETURN 0
IF @Latitude1 = @Latitude2 AND @Longitude1 = @Longitude2 RETURN 0.00
-- CONSTANTS
DECLARE @EarthRadiusInMiles float;
SET @EarthRadiusInMiles = 3963.1
DECLARE @PI float;
SET @PI = PI();
-- RADIANS conversion
DECLARE @lat1Radians float;
DECLARE @long1Radians float;
DECLARE @lat2Radians float;
DECLARE @long2Radians float;
SET @lat1Radians = @Latitude1 * @PI / 180;
SET @long1Radians = @Longitude1 * @PI / 180;
SET @lat2Radians = @Latitude2 * @PI / 180;
SET @long2Radians = @Longitude2 * @PI / 180;
RETURN Acos(
Cos(@lat1Radians) * Cos(@long1Radians) * Cos(@lat2Radians) * Cos(@long2Radians) +
Cos(@lat1Radians) * Sin(@long1Radians) * Cos(@lat2Radians) * Sin(@long2Radians) +
Sin(@lat1Radians) * Sin(@lat2Radians)
) * @EarthRadiusInMiles;
END
Then from any calling query you can sort by the distance, for example:
CREATE PROCEDURE [dbo].[NearbyThings]
(
@Lat float,
@Lon float,
@Num int = 10
)
AS
SET NOCOUNT ON
Select Top (@Num)
'Distance' = Round(dbo.CoordinateDistanceMiles(@Lat, @Lon, Lat, Lon), 1),
ThingId,
Postcode,
Lat,
Lon
From
Things
Order by
dbo.CoordinateDistanceMiles(@Lat, @Lon, Lat, Lon) ASC
GO