Java calculates distances based on latitude and longitude

preface

Recently, there is a requirement to obtain the distance between users according to the longitude and latitude. At first, GEO in Redis was used, but the calculated distance deviated greatly from the expected distance, so another way was sought to calculate the distance between two longitude and latitude through geodesy. If anyone uses redis method to calculate successfully welcome to comment to me, let me learn.

First introduce dependencies

<dependency>
  <groupId>org.gavaghan</groupId>
  <artifactId>geodesy</artifactId>
  <version>1.1.3</version>
</dependency>
Copy the code

Distance calculation utility class

import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class DistanceUtils {
    /** * Calculate the distance according to latitude and longitude **@paramLon1 longitude 1 star@paramLat1 latitude 1 *@paramLon2 is 2 times longitude@paramLat2 latitude 2 *@returnDistance (km) */
    public static String getDistance(String lon1, String lat1, String lon2, String lat2) {
        GlobalCoordinates source = new GlobalCoordinates(Double.parseDouble(lat1), Double.parseDouble(lon1));
        GlobalCoordinates target = new GlobalCoordinates(Double.parseDouble(lat2), Double.parseDouble(lon2));
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere, source, target);
        double distance = geoCurve.getEllipsoidalDistance();
        BigDecimal distanceBig = new BigDecimal(distance).setScale(2, RoundingMode.UP);
        distanceBig = distanceBig.multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.UP);
        return distanceBig.toString().concat("km");
    }

    public static void main(String[] args) {
        String lon1 = "119.6438888888889";
        String lat1 = "37.966944444444444";
        String lon2 = "119.63916666666667";
        String lat2 = "37.9675"; System.out.println(getDistance(lon1, lat1, lon2, lat2)); }}Copy the code

test

Run the main method

The results of

0.42km
Copy the code