The Java implementation calculates the distance between geographical coordinates

  • 2020-04-01 03:44:55
  • OfStack

Java to calculate the distance between two latitude and longitude points, directly on the code, please refer to the comments for specific explanation


package com.jttx.poi.utils;
import com.jttx.poi.entity.Point;
/**
 * Created by louis on 2014/9/2.
 */
public class GeoUtils {
    /**
     * Calculate the distance between two longitude and latitude points (in meters)
     * @param lng1  longitude
     * @param lat1  latitude
     * @param lng2
     * @param lat2
     * @return
     */
    public static double getDistance(double lng1,double lat1,double lng2,double lat2){
        double radLat1 = Math.toRadians(lat1);
        double radLat2 = Math.toRadians(lat2);
        double a = radLat1 - radLat2;
        double b = Math.toRadians(lng1) - Math.toRadians(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1)
                * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378137.0;//Take the length radius of the earth in WGS84 standard reference ellipsoid (unit :m)
        s = Math.round(s * 10000) / 10000;
        return s;
    }
    /**
     * To calculate TP value
     * @param curPoint      The current point
     * @param relatedPoint  Offset point
     * @param isGeography   Is it a geographic coordinate false for 2d coordinates
     * @return              tp value
     */
    public static double getDirAngle(Point curPoint,Point relatedPoint,boolean isGeography){
        double result = 0;
        if(isGeography){
            double y2 = Math.toRadians(relatedPoint.getLat());
            double y1 = Math.toRadians(curPoint.getLat());
            double alpha = Math.atan2(relatedPoint.getLat() - curPoint.getLat(), (relatedPoint.getLng() - curPoint.getLng()) * Math.cos((y2 - y1) / 2));//The latitude times the cosine of y2 minus y1/2 is less than br over >             double delta =alpha<0?(2*Math.PI+alpha):alpha;
            result = Math.toDegrees(delta);
        }else {
            double alpha = Math.atan2(relatedPoint.getLat() - curPoint.getLat(), relatedPoint.getLng() - curPoint.getLng());
            double delta=alpha<0?(2*Math.PI+alpha):alpha;
            result = Math.toDegrees(delta);
        }
        return result;
    }
    public static void main(String[] args) {
        System.out.println(getDistance(121.446014,31.215937,121.446028464238,31.2158502442799  ));
    }
}

That's all for this article, I hope you enjoy it.


Related articles: