Here you can find the source of distance(double lat1, double lng1, double lat2, double lng2)
public static double distance(double lat1, double lng1, double lat2, double lng2)
//package com.java2s; //License from project: Open Source License public class Main { public static final double LATITUDE_MAX = 90.0; public static final double LONGITUDE_MAX = 180.0; /**/* w ww.j a v a2s . c om*/ * Calculate distance (in meters) between two points in (latitude, longitude). * <p> * Uses Haversine method to compute the distances. * If (lat, long) combination are invalid it returns a negative distance (invalid value) * </p> * Taken from : http://stackoverflow.com/a/27943 */ public static double distance(double lat1, double lng1, double lat2, double lng2) { if (Math.abs(lat1) == LATITUDE_MAX || Math.abs(lat2) == LATITUDE_MAX || Math.abs(lng1) == LONGITUDE_MAX || Math.abs(lng2) == LONGITUDE_MAX) { return Double.MAX_VALUE; } final int R = 6371;// Radius of the earth Double dLat = Math.toRadians(lat2 - lat1); Double dLon = Math.toRadians(lng2 - lng1); double sinLatDist = Math.sin(dLat / 2); double cosLat1 = Math.cos(Math.toRadians(lat1)); double cosLat2 = Math.cos(Math.toRadians(lat2)); double sinLonDist = Math.sin(dLon / 2); Double a = (sinLatDist * sinLatDist) + (cosLat1 * cosLat2 * sinLonDist * sinLonDist); Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c * 1000;// convert to meters } }