Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center coordinate of a set of CLLocationsCoordinate2D

Is there any way to get center coordinate of a set of CLLocationsCoordinate2D in iOS?

enter image description here

like image 503
dispatchMain Avatar asked Jan 17 '13 07:01

dispatchMain


2 Answers

Hmm... it depends how you define the centre of the points. Does it depend on the distribution etc...

An easy way to do it is as follows...

//find rect that encloses all coords

float maxLat = -200;
float maxLong = -200;
float minLat = MAXFLOAT;
float minLong = MAXFLOAT;

for (int i=0 ; i<[locations count] ; i++) {
    CLLocationCoordinate2D location = [locations objectAtIndex:i];

    if (location.latitude < minLat) {
        minLat = location.latitude;
    }

    if (location.longitude < minLong) {
        minLong = location.longitude;
    }

    if (location.latitude > maxLat) {
        maxLat = location.latitude;
    }

    if (location.longitude > maxLong) {
        maxLong = location.longitude;
    }
}

//Center point

CLLocationCoordinate2D center = CLLocationCoordinate2DMake((maxLat + minLat) * 0.5, (maxLong + minLong) * 0.5);

This will give the center of the rect covering all the points. However it does not take the spread into account.

i.e.

. = point
X = centre

.....               X                   .

EDIT

Corrected some of the maths.

like image 131
Fogmeister Avatar answered Sep 27 '22 19:09

Fogmeister


I know it's really late but someone could read this and help himself Using Fogmeister answer you could create a MKCoordinateRegion

CLLocationDegrees minLat,minLng,maxLat,maxLng;
for(CLLocationCoordinate2D coordinate in coordinates) {
    minLat = MIN(minLat, coordinate.latitude);
    minLng = MIN(minLng, coordinate.longitude);

    maxLat = MAX(maxLat, coordinate.latitude);
    maxLng = MAX(maxLng, coordinate.longitude);
}

CLLocationCoordinate2D coordinateOrigin = CLLocationCoordinate2DMake(minLat, minLng);
CLLocationCoordinate2D coordinateMax = CLLocationCoordinate2DMake(maxLat, maxLng);

MKMapPoint upperLeft = MKMapPointForCoordinate(coordinateOrigin);
MKMapPoint lowerRight = MKMapPointForCoordinate(coordinateMax);

//Create the map rect
MKMapRect mapRect = MKMapRectMake(upperLeft.x,
                                  upperLeft.y,
                                  lowerRight.x - upperLeft.x,
                                  lowerRight.y - upperLeft.y);

//Create the region
MKCoordinateRegion region = MKCoordinateRegionForMapRect(mapRect);

//THIS HAS THE CENTER, it should include spread
CLLocationCoordinate2D centerCoordinate = region.center;

Greetings!!!

like image 45
Heavy_Bullets Avatar answered Sep 27 '22 18:09

Heavy_Bullets