sql server
--[dbo].[sp_DuAnGetKhoangCach] 10.7756587, 106.70042379999995, 0.5
CREATE PROCEDURE [dbo].[sp_DuAnGetKhoangCach]
@ZipLatitude float,
@ZipLongitude float,
@Radius float
AS
SELECT * FROM DuAn
WHERE dbo.TinhKhoanCach2Diem(lat, lng, @ZipLatitude, @ZipLongitude) < @Radius
CREATE FUNCTION TinhKhoanCach2Diem(
@Latitude1 float,
@Longitude1 float,
@Latitude2 float,
@Longitude2 float
)
RETURNS float
AS
BEGIN
-- CONSTANTS
DECLARE @EarthRadiusInMiles float;
SET @EarthRadiusInMiles = 6371 -- 3959 for miles, 6371 for KM
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
C#
/// <summary>
/// Specifies a Latitude / Longitude point.
/// </summary>
public class LatLng
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public LatLng(){
}
public LatLng(double lat, double lng)
{
this.Latitude = lat;
this.Longitude = lng;
}
}
/// <summary>
/// Returns the distance in miles or kilometers of any two
/// latitude / longitude points.
/// </summary>
/// <param name="pos1">Location 1</param>
/// <param name="pos2">Location 2</param>
/// <param name="unit">Miles or Kilometers</param>
/// <returns>Distance in the requested unit</returns>
public double HaversineDistance(LatLng pos1, LatLng pos2, DistanceUnit unit)
{
double R = (unit == DistanceUnit.Miles) ? 3960 : 6371;
var lat = (pos2.Latitude - pos1.Latitude).ToRadians();
var lng = (pos2.Longitude - pos1.Longitude).ToRadians();
var h1 = Math.Sin(lat / 2) * Math.Sin(lat / 2) +
Math.Cos(pos1.Latitude.ToRadians()) * Math.Cos(pos2.Latitude.ToRadians()) *
Math.Sin(lng / 2) * Math.Sin(lng / 2);
var h2 = 2 * Math.Asin(Math.Min(1, Math.Sqrt(h1)));
return R * h2;
}
public enum DistanceUnit { Miles, Kilometers };
var Offices = GetMyOfficeList();
for(int i = 0; i< Offices.Count; i++)
{
Offices[i].Distance = HaversineDistance(
coord,
new LatLng(Offices[i].Lat, Offices[i].Lng),
DistanceUnit.Miles);
}
var closestOffice = Offices.OrderBy(x => x.Distance).Take(1).Single();