关于腾讯地图:腾讯位置服务教你快速实现距离测量小工具

以下内容转载自面糊的文章《腾讯地图SDK间隔测量小工具》

作者:面糊

链接:https://www.jianshu.com/p/6e5…

起源:简书

著作权归作者所有。商业转载请分割作者取得受权,非商业转载请注明出处。

前言

为了相熟腾讯地图SDK中的QGeometry几何类,以及点和线之间的配合,编写了这个能够在地图下面打点并获取直线间隔的小Demo。

应用场景

对于一些须要疾速晓得某段并不是很长的门路,并且须要本人来布局路线的场景,应用腾讯地图的路线布局性能可能并不是本人想要的后果,并且须要时刻联网。
该性能宗旨本人在地图下面布局路线,获取这条路线的间隔,并且能够将其保留为本人的路线。

然而因为只是通过经纬度来计算的直线间隔,在精度上会存在肯定的误差。

筹备

  • 腾讯地图3D SDK
  • 在地图上增加自定义手势
  • Poyline的绘制
  • 间隔计算

流程

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尝试一下。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理