使用腾讯位置服务地图SDK快速实现距离测量小工具

以下内容转载自面糊的文章《腾讯地图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尝试一下。

猜你喜欢

转载自www.cnblogs.com/Yi-Xiu/p/13390328.html