Jannik
Jannik

Reputation: 427

Java: How to calculate exact center of multiple coordinates?

I want to calculate the exact center of multiple coordinates (latitude / longitude pairs). For example:

New York: 40.730610, -73.935242
Chicago: 41.881832, -87.623177
Atlanta: 33.753746, -84.386330

=> Center: lat, long (probably around here 39, -82)

How would you implement this using Java? Thank you

Upvotes: 1

Views: 597

Answers (2)

Tutai Kumar Dalal
Tutai Kumar Dalal

Reputation: 114

As already answered, please create a polygon using the points then calculate calculateCentroid() from the polygon

Upvotes: 1

AllMightyGoat
AllMightyGoat

Reputation: 49

This might help

import java.util.ArrayList;
import java.util.List;

public class coordinate_check {
    List<coordinate> places = new ArrayList<>();
    public coordinate centre(){
        if(places.size() == 1) return  places.get(0);
        final int size = places.size();
        double x=0,y=0,z=0,lati,longi;
       for(coordinate alpha : places){
            lati = Math.toRadians(alpha.lat); 
            longi = Math.toRadians(alpha.lon); 
           double a = Math.cos(lati) * Math.cos(longi);
           double b = Math.cos(lati) * Math.sin(longi);
           double c = Math.sin(lati);
           x+=a;
           y+=b;
           z+=c;
       }
       x/=size;
       y/=size;
       z/=size;
        longi = Math.atan2(y,x);
        double hyp = Math.sqrt(x*x+y*y);
        lati = Math.atan2(z,hyp);
        return  new coordinate(Math.toDegrees(lati), Math.toDegrees(longi))
    }
}




class coordinate{
     static double lat;
     static double lon;
     public coordinate(double x, double y){
         lat = x;
         lon = y;
     }
}

Upvotes: 0

Related Questions