How many miles is it between Brussels and Dubai? What about from London to New York? Is San Francisco or Los Angeles closer to Hawaii? These are questions I’ve asked far more than I’d have thought I would ever need to. Luckily it can be answered in a few lines of code. The best part is, because this just uses standard math functions, it’ll work in ANY language from Swift to VBA. Sure names might vary from language to language (Math.PI in Java is M_PI in Objective-C) but the overall concept remains the same regardless.

Every point on Earth can be identified by a latitude and longitude. Brussels, for example, is 50.8503° N, 4.3517° E. Dubai is at 25.2048° N, 55.2708° E, and Honolulu is 21.3069° N, 157.8583° W. The first number in each pair is the latitude, noted as being in either the northern or southern hemisphere. The second number is the longitude, in either the western or eastern hemisphere. Since math can’t differentiate between N and S or between E and W, we use positive and negative numbers. For latitudes, anything in the southern hemisphere is negative, as are western longitudes. A latitude can have any value between -90 and +90, and a longitude anything between -180 and +180.

Brussels then, is at latitude 50.8503, longitude 4.3517. Honolulu at latitude 21.3069, longitude -157.8583.

To get the distance between two places, each latitude and longitude need to be converted from a decimal degree into a radian, using this formula.

//Converting from decimal degrees into radians radians = degrees * PI / 180.0

Once you have the radian version of each coordinate, you can calculate the distance between them.

//Get the radian distance from the two latitudes and longitudes d = 2 * asin(sqrt((pow(sin((lat1Rad - lat2Rad)/2),2) + cos(lat1Rad)*cos(lat2Rad) * (pow(sin((lon1Rad-lon2Rad)/2),2))))) //Multiply radian distance by the Earth's radius //Statute miles statute = d * 3,959 //Kilometers kilometer = d * 6371 //Nautical Miles nautical = d * 3440

The two coordinates below are for Honolulu and Los Angeles, but you can replace them with any two coordinates you want and the distance will automatically update. Go ahead and try it out!