Java tutorial
//package com.java2s; //License from project: Apache License public class Main { private static final double RAD_PER_DEG = Math.PI / 180.0; private static final double EARTH_RADIUS_METERS = 6367000.0; public static double fastDistanceMeters(double latRad1, double lngRad1, double latRad2, double lngRad2) { if ((Math.abs(latRad1 - latRad2) > RAD_PER_DEG) || (Math.abs(lngRad1 - lngRad2) > RAD_PER_DEG)) { return accurateDistanceMeters(latRad1, lngRad1, latRad2, lngRad2); } // Approximate sin(x) = x. double sineLat = (latRad1 - latRad2); // Approximate sin(x) = x. double sineLng = (lngRad1 - lngRad2); // Approximate cos(lat1) * cos(lat2) using // cos((lat1 + lat2)/2) ^ 2 double cosTerms = Math.cos((latRad1 + latRad2) / 2.0); cosTerms = cosTerms * cosTerms; double trigTerm = sineLat * sineLat + cosTerms * sineLng * sineLng; trigTerm = Math.sqrt(trigTerm); // Approximate arcsin(x) = x return EARTH_RADIUS_METERS * trigTerm; } public static double accurateDistanceMeters(double lat1, double lng1, double lat2, double lng2) { double dlat = Math.sin(0.5 * (lat2 - lat1)); double dlng = Math.sin(0.5 * (lng2 - lng1)); double x = dlat * dlat + dlng * dlng * Math.cos(lat1) * Math.cos(lat2); return (2 * Math.atan2(Math.sqrt(x), Math.sqrt(Math.max(0.0, 1.0 - x)))) * EARTH_RADIUS_METERS; } }