Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

java - How to calculate distance between two point over a path

I am having a list of co-ordinates that represent the path, and source and destination coordinates. So, using spatial4j,JTS,GeoTools or any other library how to calculate the distance between two points(source & destination) over a predefined path(list of coordinates).

Below is the sample which I have tried using spatail4j which is a straight line distance. But the same thing how we can achieve over a path I have used spatial4j but using different libraries like JTS,GeoTools etc.,

public static void main(String[] args) {
        SpatialContext ctx = SpatialContext.GEO;
        Point p1= ctx.getShapeFactory().pointXY( 77.610099,12.91502);
        Point p2= ctx.getShapeFactory().pointXY( 77.59038,12.917055);
        System.out.println(ctx.getDistCalc().distance(p1, p2) * DistanceUtils.DEG_TO_KM);
    }
// output: 2.149124512680105

Below are the route/path geopoints:

12.91502 , 77.610099
12.91502 , 77.610092
12.913957 , 77.610069
12.913954 , 77.610033
12.91644 , 77.610048
12.916573 , 77.605512
12.916618 , 77.603053
12.916622 , 77.601803
12.916652 , 77.600092
12.916735 , 77.597653
12.916896 , 77.590946
12.916927 , 77.590242
12.916936 , 77.589467
12.917083 , 77.589466
12.917055 , 77.59038

According to the google map the value should be 2.8Km. Is there any other java library using which we achieve the same thing as the resource for spatial4j is very less.

question from:https://stackoverflow.com/questions/65913433/how-to-calculate-distance-between-two-point-over-a-path

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want precision, then you should probably go to Haversine Formula, luckily enough, you can always find a useful solution browsing the web

public static Double getDistance(Double lat1, Double lon1, Double lat2, Double lon2) {
    final int R = 6371; // Earth Radius in km, use 3959 if you want in miles
    Double latDistance = toRad(lat2-lat1);
    Double lonDistance = toRad(lon2-lon1);
    Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + 
    Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * 
    Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
    Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    return R * c;
}

I've actually just adapted this to your use-case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...