Java tutorial
//package com.java2s; /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { /** The Earth's radius, in kilometers. */ private static final double EARTH_RADIUS_KM = 6371.0; /** * Gets the great circle distance in kilometers between two geographical points, using * the <a href="http://en.wikipedia.org/wiki/Haversine_formula">haversine formula</a>. * * @param latitude1 the latitude of the first point * @param longitude1 the longitude of the first point * @param latitude2 the latitude of the second point * @param longitude2 the longitude of the second point * @return the distance, in kilometers, between the two points */ public static float getDistance(double latitude1, double longitude1, double latitude2, double longitude2) { double dLat = Math.toRadians(latitude2 - latitude1); double dLon = Math.toRadians(longitude2 - longitude1); double lat1 = Math.toRadians(latitude1); double lat2 = Math.toRadians(latitude2); double sqrtHaversineLat = Math.sin(dLat / 2); double sqrtHaversineLon = Math.sin(dLon / 2); double a = sqrtHaversineLat * sqrtHaversineLat + sqrtHaversineLon * sqrtHaversineLon * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return (float) (EARTH_RADIUS_KM * c); } }