开发者

how to calculate two coordinates distance in objective c?

as title how to? i have tried the code from google earth, but seem like the result is different with the google map calculation result. below provided the code i did

-(double)GetDistance:(double)lat1 long1:(double)lng1 la2:(double)lat2 long2:(double)lng2 {
    //NSLog(@"latitude 1:%.7f,longitude1:%.7f,latitude2:%.7f,longtitude2:%.7f",lat1,lng1,lat2,lng2);
    double radLat1 = [self rad:lat1];
    double radLat2 = [self rad:lat2];
    double a = radLat1 - radLat2;
    double b = [self rad:lng1] -[self rad:lng2];
    double s = 2 * asin(sqrt(pow(sin(a/2),2) + cos(radLat1)*cos(radLat2)*pow(sin(b/2),2)));
    s = s * EARTH_RADIUS;
    s = round(s * 10000) / 10000;
    return开发者_Go百科 s;
}

-(double)rad:(double)d
{
    return d *3.14159265 / 180.0;
}

the EARTH_RADIUS value is 6378.138

by using this function by provided two coordinates the result come out is 4.5kM but when i use google map get direction between two same coordinates, it show me the distance is about 8km

can anyone help to point out the problem of my code?


Since this is tagged iPhone, why not use the built-in distance function rather than rolling your own? location1 and location2 are CLLocation objects.

CLLocationDistance distance = [location1 getDistanceFrom:location2];


Here is a simple code (supposing you just have latitude and longitude of the two points)

CLLocation *startLocation = [[CLLocation alloc] initWithLatitude:startLatitude longitude:startLongitude];
CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:endLatitude longitude:endLongitude];
CLLocationDistance distance = [startLocation distanceFromLocation:endLocation]; // aka double

Don't forget to add MapKit Framework to your project, and import MapKit in your file :

#import <MapKit/MapKit.h>


Google Maps is likely to be giving you the driving distance, whereas the great circle equation you have listed is going to be the straight line surface distance. If there was a straight line surface road directly from point A to point B, Google Maps would likely give you the same distance as the equation you have there.


Since

getDistanceFrom:

isDeprecated Try use the

[newLocation distanceFromLocation:oldLocation


You should be able to use the google API directly to calculate either great circle distance or driving distance depending on your application needs.

See GLatLong::distanceFrom and GDirections::getDistance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜