我正在尝试测量地图上两个坐标(经度,纬度)之间的距离。第一个坐标是我的当前位置,这是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
我想以公制单位找到这两个坐标之间的距离,我知道这些类型不匹配,但是如何转换它们以便我可以找到这两个节点之间的距离?
答案 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)
}
}