以下內容轉載自面糊的文章《騰訊地圖SDK距離測量小工具》
作者:面糊
鏈接:https://www.jianshu.com/p/6e507ebcdd93
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
前言
為了熟悉騰訊地圖SDK中的QGeometry幾何類,以及點和線之間的配合,編寫了這個可以在地圖上面打點並獲取直線距離的小Demo。
使用場景
對於一些需要快速知道某段並不是很長的路徑,並且需要自己來規划路線的場景,使用騰訊地圖的路線規划功能可能並不是自己想要的結果,並且需要時刻聯網。
該功能主旨自己在地圖上面規划路線,獲取這條路線的距離,並且可以將其保存為自己的路線。
但是由於只是通過經緯度來計算的直線距離,在精度上會存在一定的誤差。
准備
流程
1、在MapView上添加自定義長按手勢,並將手勢在屏幕上的點轉為地圖坐標,添加Marker:
- (void)setupLongPressGesture {
self.addMarkerGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(addMarker:)];
[self.mapView addGestureRecognizer:self.addMarkerGesture];
}
- (void)addMarker:(UILongPressGestureRecognizer *)gesture {
if (gesture.state == UIGestureRecognizerStateBegan) {
// 取點
CLLocationCoordinate2D location = [self.mapView convertPoint:[gesture locationInView:self.mapView] toCoordinateFromView:self.mapView];
QPointAnnotation *annotation = [[QPointAnnotation alloc] init];
annotation.coordinate = location;
// 添加到路線中
[self.annotationArray addObject:annotation];
[self.mapView addAnnotation:annotation];
[self handlePoyline];
}
}
- 騰訊地圖的QMapView類中,提供了可以將屏幕坐標直接轉為地圖坐標的便利方法:
- (CLLocationCoordinate2D)convertPoint: toCoordinateFromView:
2、使用添加的Marker的坐標點,繪制Polyline:
- (void)handlePoyline {
[self.mapView removeOverlays:self.mapView.overlays];
// 判斷是否有兩個點以上
if (self.annotationArray.count > 1) {
NSInteger count = self.annotationArray.count;
CLLocationCoordinate2D coords[count];
for (int i = 0; i < count; i++) {
QPointAnnotation *annotation = self.annotationArray[i];
coords[i] = annotation.coordinate;
}
QPolyline *polyline = [[QPolyline alloc] initWithCoordinates:coords count:count];
[self.mapView addOverlay:polyline];
}
// 計算距離
[self countDistance];
}
- 這里需要注意的是,每次重新添加Overlay的時候,需要將之前的Overlay刪除掉。目前騰訊地圖還不支持在同一條Polyline中繼續修改。
3、計算距離:QGeometry是SDK提供的有關幾何計算的類,在該類中提供了眾多工具方法,如"坐標轉換、判斷相交、外接矩形"等方便的功能
- (void)countDistance {
_distance = 0;
NSInteger count = self.annotationArray.count;
for (int i = 0; i < count - 1; i++) {
QPointAnnotation *annotation1 = self.annotationArray[i];
QPointAnnotation *annotation2 = self.annotationArray[i + 1];
_distance += QMetersBetweenCoordinates(annotation1.coordinate, annotation2.coordinate);
}
[self updateDistanceLabel];
}
QMetersBetweenCoordinates()方法接收兩個CLLocationCoordinate2D參數,並計算這兩個坐標之間的直線距離
示例:通過打點連線的方式獲取路線的總距離

鏈接
感興趣的同學可以在碼雲中下載Demo嘗試一下。
