CLLocationCoordinate2D与2点之间的距离

时间:2013-12-10 10:59:17

标签: ios ios7 core-location cllocationmanager

详细

我正在尝试测量地图上两个坐标(经度,纬度)之间的距离。第一个坐标是我的当前位置,这是CLLocation,另一个坐标是地图上的CLLocationCoordinate2D类型的图钉。

问题

我致电distanceFromLocation以获取CLLocation中的当前位置,但它显示来自CLLocationCoordinate2D的收件人类型不正确。

CLLocationCoordinate2D locationCoordinate;

// Set the latitude and longitude
locationCoordinate.latitude  = [[item objectForKey:@"lat"] doubleValue];
locationCoordinate.longitude = [[item objectForKey:@"lng"] doubleValue];

CLLocationDistance dist = [locationCoordinate distanceFromLocation:locationManager.location.coordinate]; // bad receiver type from CLLocationCoordinate2D

问题

我想以公制单位找到这两个坐标之间的距离,我知道这些类型不匹配,但是如何转换它们以便我可以找到这两个节点之间的距离?

4 个答案:

答案 0 :(得分:10)

使用以下方法查找两个位置之间的距离

-(float)kilometersfromPlace:(CLLocationCoordinate2D)from andToPlace:(CLLocationCoordinate2D)to  {

    CLLocation *userloc = [[CLLocation alloc]initWithLatitude:from.latitude longitude:from.longitude];
    CLLocation *dest = [[CLLocation alloc]initWithLatitude:to.latitude longitude:to.longitude];

    CLLocationDistance dist = [userloc distanceFromLocation:dest]/1000;

    //NSLog(@"%f",dist);
    NSString *distance = [NSString stringWithFormat:@"%f",dist];

    return [distance floatValue];

}

答案 1 :(得分:6)

例如:

   +(double)distanceFromPoint:(double)lat lng:(double)lng
   {

      CLLocation *placeLocation = [[CLLocation alloc] initWithLatitude:lat longitude:lng];
      CLLocationCoordinate2D usrLocation = locationManager.location;
      CLLocation * userLocation = [[CLLocation alloc] initWithLatitude:usrLocation.latitude longitude:usrLocation.longitude];

      double meters = [userLocation distanceFromLocation:placeLocation];

      return meters;
   }

答案 2 :(得分:3)

尝试将CLLocationCoordinate2D转换为CLLocation

使用

创建CLLocation对象
-(id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude

答案 3 :(得分:1)

基于@ manujmv上面的回答,这是一个Swift扩展(返回米):

import Foundation
import CoreLocation

extension CLLocationCoordinate2D {
    func distanceTo(coordinate: CLLocationCoordinate2D) -> CLLocationDistance {
        let thisLocation = CLLocation(latitude: self.latitude, longitude: self.longitude)
        let otherLocation = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)

        return thisLocation.distanceFromLocation(otherLocation)
    }
}