Calculate the center point of multiple latitude/longitude coordinate pairs

后端 未结 21 1578
暖寄归人
暖寄归人 2020-11-27 09:27

Given a set of latitude and longitude points, how can I calculate the latitude and longitude of the center point of that set (aka a point that would center a view on all poi

21条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 09:33

    In the interest of possibly saving someone a minute or two, here is the solution that was used in Objective-C instead of python. This version takes an NSArray of NSValues that contain MKMapCoordinates, which was called for in my implementation:

    #import 
    
    + (CLLocationCoordinate2D)centerCoordinateForCoordinates:(NSArray *)coordinateArray {
        double x = 0;
        double y = 0;
        double z = 0;
    
        for(NSValue *coordinateValue in coordinateArray) {
            CLLocationCoordinate2D coordinate = [coordinateValue MKCoordinateValue];
    
            double lat = GLKMathDegreesToRadians(coordinate.latitude);
            double lon = GLKMathDegreesToRadians(coordinate.longitude);
            x += cos(lat) * cos(lon);
            y += cos(lat) * sin(lon);
            z += sin(lat);
        }
    
        x = x / (double)coordinateArray.count;
        y = y / (double)coordinateArray.count;
        z = z / (double)coordinateArray.count;
    
        double resultLon = atan2(y, x);
        double resultHyp = sqrt(x * x + y * y);
        double resultLat = atan2(z, resultHyp);
    
        CLLocationCoordinate2D result = CLLocationCoordinate2DMake(GLKMathRadiansToDegrees(resultLat), GLKMathRadiansToDegrees(resultLon));
        return result;
    }
    

提交回复
热议问题