CLLocation的distanceFromLocation方法计算地图上距离 (汇总)

来源:互联网 发布:宜家椅子 知乎 编辑:程序博客网 时间:2024/04/30 05:46

http://www.cnblogs.com/pengyingh/articles/2373246.html


准备两个CLLocation的对象,比如要计算某个位置与使用者当前位置的距离,
则其 中一个CLLocation是userLocation = [locationManager location],locationManager是CLLocationManager的实例,
并已执行[locationManager startUpdatingLocation];
然后计算这两个CLLocation的距离(已格式化成12.34 km
[NSString stringWithFormat:@"%0.2f km",[userLocation distanceFromLocation :location]/1000]

 

根据经纬度计算两点之间距离的Obcective-C代码  

根据经纬度计算两点之间距离的Obcective-C代码,转自一位CocoaChina会员的博客(Link),其中其中er 就是地球椭球半径,对于google map使用 6378137 就可以了。 函数的调用非常简单, 几乎适用任何平台:)

#define PI 3.1415926double LantitudeLongitudeDist(double lon1,double lat1,         double lon2,double lat2){ double er = 6378137; // 6378700.0f; //ave. radius = 6371.315 (someone said more accurate is 6366.707) //equatorial radius = 6378.388 //nautical mile = 1.15078 double radlat1 = PI*lat1/180.0f; double radlat2 = PI*lat2/180.0f; //now long. double radlong1 = PI*lon1/180.0f; double radlong2 = PI*lon2/180.0f; if( radlat1 < 0 ) radlat1 = PI/2 + fabs(radlat1);// south if( radlat1 > 0 ) radlat1 = PI/2 - fabs(radlat1);// north if( radlong1 < 0 ) radlong1 = PI*2 - fabs(radlong1);//west if( radlat2 < 0 ) radlat2 = PI/2 + fabs(radlat2);// south if( radlat2 > 0 ) radlat2 = PI/2 - fabs(radlat2);// north if( radlong2 < 0 ) radlong2 = PI*2 - fabs(radlong2);// west //spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at) //zero ag is up so reverse lat double x1 = er * cos(radlong1) * sin(radlat1); double y1 = er * sin(radlong1) * sin(radlat1); double z1 = er * cos(radlat1); double x2 = er * cos(radlong2) * sin(radlat2); double y2 = er * sin(radlong2) * sin(radlat2); double z2 = er * cos(radlat2); double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2)); //side, side, side, law of cosines and arccos double theta = acos((er*er+er*er-d*d)/(2*er*er)); double dist  = theta*er; return dist;}
复制代码
1:获取当前手机经纬度@implementation CurrentLocation@synthesize locationManager;@synthesize target,callBack;#pragma mark --#pragma mark Public-(void) startUpdatingLocation{    [[self locationManager] startUpdatingLocation];}#pragma mark --#pragma mark Memory management-(void) dealloc{    [super dealloc];    [locationManager release];}#pragma mark --#pragma mark Location manager/* Return a location manager -- create one if necessary. */- (CLLocationManager *)locationManager {    if (locationManager != nil) {return locationManager;}    locationManager = [[CLLocationManager alloc] init];    [locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];    [locationManager setDelegate:self];    return locationManager;}#pragma mark --#pragma mark CLLocationManagerDelegate methods/* Conditionally enable the Add button: If the location manager is generating updates, then enable the button; If the location manager is failing, then disable the button. */- (void)locationManager:(CLLocationManager *)manager    didUpdateToLocation:(CLLocation *)newLocation           fromLocation:(CLLocation *)oldLocation {    NSLog(@"获取到经纬度!");}- (void)locationManager:(CLLocationManager *)manager       didFailWithError:(NSError *)error {        NSLog(@"获取失败!"); }@end2:  获取当前手机经纬度的详细地址@implementation AddressReverseGeoder#pragma mark --#pragma mark Public
//根据经纬度开始获取详细地址信息- (void)startedReverseGeoderWithLatitude:(double)latitude longitude:(double)longitude{    CLLocationCoordinate2D coordinate2D;    coordinate2D.longitude = longitude;    coordinate2D.latitude = latitude;    //    MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:coordinate2D];    geoCoder.delegate = self;    [geoCoder start];}#pragma mark --#pragma mark MKReverseGeocoderDelegate methods//获得地址信息- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {    NSString *address = [NSString stringWithFormat:@"%@ %@ %@ %@ %@%@",                                      placemark.country,                                      placemark.administrativeArea,                                      placemark.locality,                                      placemark.subLocality,                                      placemark.thoroughfare,                                      placemark.subThoroughfare];    NSLog(@"经纬度所对应的详细:%@", address);    geocoder = nil;}//错误处理- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {    NSLog(@"error %@" , error);}#pragma mark --#pragma mark Memory management- (void)dealloc {    [super dealloc];}@end
复制代码

The distance is calculated between 2 CLLocations and not between to coordinates.

You need to use these coordinates to get the CLLocations for the respective coordinates using the following line of code

CLLocation*newLocation =[[CLLocation alloc] initWithCoordinate: newCoordinate altitude:1 horizontalAccuracy:1 verticalAccuracy:-1 timestamp:nil];

Similarly for the other coordinate and then you can calculate the distance between these two locations using the following line of code

CLLocationDistance kilometers =[newLocation distanceFromLocation:oldLocation]/1000;

In MkMapview calculate distance between two points

问:

Hi in iPhone App How to calculate distance between two points in MKMapView as shown in image

first point would be center point of visible map in mapview

2nd point would be any of corner of visible rect of mapview in mapview(here for example i have taken top left point)

答:

You can get lat/lon of the center with:

convertPoint:toCoordinateFromView:

loc1 and loc2 are both CLLocation objs.

CLLocationDistance dist =[loc1 distanceFromLocation:loc2];

So these two tips should help you. if you need some code, let me know :-)

 

答:

Here is how you can calculate the wanted distance :

// You first have to get the corner point and convert it to a coordinateMKMapRect mapRect = self.mapView.visibleMapRect;MKMapPoint cornerPointNW =MKMapPointMake(mapRect.origin.x, mapRect.origin.y);CLLocationCoordinate2D cornerCoordinate =MKCoordinateForMapPoint(cornerPointNW);// Then get the center coordinate of the mapView (just a shortcut for convenience)CLLocationCoordinate2D centerCoordinate = self.mapView.centerCoordinate// And then calculate the distanceCLLocationDistance distance =[cornerCoordinate distanceFromLocation:centerCoordinate];
计算走过的距离,并显示出来
问:

I trying to calculate the total distance travelled and output it to the View Controller, but the results are not as expected. Code is as follows:

MyCLController.m

-(void)locationManager:(CLLocationManager*)manager    didUpdateToLocation:(CLLocation*)newLocation           fromLocation:(CLLocation*)oldLocation{           validLocation = YES;    if(!newLocation)     {        validLocation = NO;    }    if(newLocation.horizontalAccuracy <0)    {        validLocation = NO;    }    // Filter out points that are out of order    NSTimeInterval secondsSinceLastPoint =-[newLocation.timestamp timeIntervalSinceNow];    if(secondsSinceLastPoint <0)    {        validLocation = NO;    }    if(validLocation == YES)    {        [self.delegate locationChange:newLocation :oldLocation];    }

NewWorkoutViewController.m

-(void)locationChange:(CLLocation*)newLocation:(CLLocation*)oldLocation{           CLLocationDistance meters =[newLocation distanceFromLocation:oldLocation];    currentSpeed =([newLocation speed]*3600)/1000;    totalDistance =(totalDistance + meters)/1000;    totalDistanceMeters =  totalDistanceMeters + meters;    avgSpeed = totalDistance / counterInt;    [speedLbl1 setText:[NSString stringWithFormat:@"%.3f", currentSpeed]];    [distanceLbl1 setText:[NSString stringWithFormat:@"%.3f", totalDistance]];

}

The problem is with my totalDistance, it doesn't appear to be adding to it each time, its as if its overwriting it, when I test in the car I can see values of 10 / 20 meters between coordinates, so this indicates that distanceFromLocation appears to be working.

Anyone any thoughts ?

答:

Try this :

totalDistance = totalDistance +(meters /1000);

instead of this

totalDistance =(totalDistance + meters)/1000;

The way you had it, totalDistance was being divided by 1000 each time i.e. if you're travelling 10m each time :

totalDistance =(0+10)/1000=0.01;totalDistance =(0.01+10)/1000=0.01001//!< You expected this to be 0.02!totalDistance =(0.01001+10)/1000=0.01001001//!< You expected this to be 0.03!
原创粉丝点击