使用CLLocationCoordinate2D计算两点之间的距离

4

详细信息

我正在尝试测量地图上两个坐标(经度,纬度)之间的距离。第一个坐标是我的当前位置,它是一个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

问题

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


1
distanceFromLocation方法位于_CLLocation类_中,它以一个_CLLocation对象_作为参数(而不是_CLLocationCoordinate2D struct_)。这就是错误的含义。 - user467105
是的,我知道为什么会出现这个错误,但我不知道如何转换它使其正常工作! - E-Riddie
4个回答

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];

}

实际上最好返回一个double,因为distanceFromLocation的结果是CLLocationDistance,它确实是一个double。 - Javier Cadiz

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;
   }

3

尝试将CLLocationCoordinate2D转换为CLLocation

使用以下方式创建一个CLLocation对象,

-(id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude

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)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接