65.9K
CodeProject is changing. Read more.
Home

Latitude and longitude

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2 votes)

Aug 31, 2012

CPOL
viewsIcon

17789

This is an alternative for "Latitude and longitude"

Introduction

The simple code allows you to measure the distance between two places on earth with latitude and longitude pairs in meters.

Background 

Finding proximity between two points is important. In day to day life we speak about distances in Meters and KM. But mathematically how to convert the distance between two {latitude,longitude} pairs?

Using the code 

The logic is simple. Convert the values to radians. Than calculate d=sine(latitude distance)^2+cosine(longitude distance). distance=2* tan2(sqrt(d),sqrt(1-d)). Multiply the distance with earth radius to get geographical distance in radians. All you have to do is get it converted to meters.  

public class DistanceInMeter
{
	
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
    double earthRadius = 3958.75;
    double dLat = toRadians(lat2-lat1);
    double dLng = toRadians(lng2-lng1);
    double a = Math.Sin(dLat/2) * Math.Sin(dLat/2) +
               Math.Cos(Math.toRadians(lat1)) * Math.Cos(Math.toRadians(lat2)) *
               Math.Sin(dLng/2) * Math.Sin(dLng/2);
    double c = 2 * Math.Atan2(Math.sqrt(a), Math.sqrt(1-a));
    double dist = earthRadius * c;

    int meterConversion = 1609;

    return (dist * meterConversion);
    }

	static double  toRadians(double degree)
	{
		return (degree*0.0174532925 );
	}
}  

Points of Interest

You can import Google map in you application and find all places within some distance. This function is typically helpful for spatial data mining.