如下内容转载自面糊的文章《腾讯地图SDK距离测量小工具》做者:面糊git
连接:https://www.jianshu.com/p/6e5...ide
来源:简书工具
著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。ui
为了熟悉腾讯地图SDK中的QGeometry几何类,以及点和线之间的配合,编写了这个能够在地图上面打点并获取直线距离的小Demo。spa
对于一些须要快速知道某段并非很长的路径,而且须要本身来规划路线的场景,使用腾讯地图的路线规划功能可能并非本身想要的结果,而且须要时刻联网。
该功能主旨本身在地图上面规划路线,获取这条路线的距离,而且能够将其保存为本身的路线。code
可是因为只是经过经纬度来计算的直线距离,在精度上会存在必定的偏差。blog
一、在MapView上添加自定义长按手势,并将手势在屏幕上的点转为地图坐标,添加Marker:rem
- (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]; } }
- (CLLocationCoordinate2D)convertPoint: toCoordinateFromView
:二、使用添加的Marker的坐标点,绘制Polyline:get
- (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]; }
三、计算距离:QGeometry是SDK提供的有关几何计算的类,在该类中提供了众多工具方法,如"坐标转换、判断相交、外接矩形"等方便的功能it
- (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尝试一下。