首页 > 解决方案 > iOS Mapbox SDK - 如何将 MGLPointAnnotation 标记添加到地图图层中

问题描述

例如,我需要找到一种将标记从 转换MGLPointAnnotationMGLShapeSource或类似的方法,以便将标记添加到地图图层并完全控制如何在地图上显示和聚类它们。

我正在使用MapBox SDK v5.2. 该应用程序在内部生成标记(标题、副标题、坐标和图标图像名称),并且在点击时标记会显示在地图上并带有标注。标记是使用 创建的,MGLPointAnnotation()并使用 添加到地图中mapView.addAnnotation()

但是为了完全控制标记的显示方式,例如根据缩放级别对它们进行聚类或打开/关闭它们,我需要将标记添加到地图图层,例如使用,MGLShapeSource然后style.addSource()style.addLayer()

问题是我找不到从MGLPointAnnotationtoMGLShapeSource或类似的转换器的方法。我对此进行了调查,但我能想到的唯一解决方案是将标记信息包含在GeoJSON文件中。但我想避免这种情况,因为标记是在应用程序运行时生成的,而不是来自外部只读 GeoJSON 文件。

如何创建单个 poi 的示例:

let poi1 = MGLPointAnnotation()
         poi1.coordinate = CLLocationCoordinate2D(latitude: 38.788534, longitude: -9.494489)
         poi1.title = "poi1"
         poi1.subtitle = "This is the text for poi1"
         poiTitleImage[poi1.title!] = "icon1"

mapView.addAnnotation(poi1)

标签: iosmapbox-ios

解决方案


您可以MGLShapeSource使用一MGLPointAnnotationMGLPointFeature对象创建一个。从那里,您可以添加类似于此集群示例的集群层。

如果您还想为每个点分配文本或其他数据,请使用MGLPointFeature对象,然后将文本分配为属性值。

例如:

        var features = [MGLPointFeature]()
        for _ in 1...100 {
            let point = MGLPointFeature()

            let lat = Double(arc4random_uniform(180) / 2)
            let lon = Double(arc4random_uniform(360) / 2)

            point.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
            point.attributes["title"] = "\(lat) \(lon)"
            features.append(point)
        }
        let source = MGLShapeSource(identifier: "clusteredFeatures",
                                    features: features,
                                    options: [.clustered: true, .clusterRadius: 20])
        style.addSource(source)

可以在Mapbox 网站上找到如何呈现包含信息的标注的示例。似乎该handleMapTap方法可能包含您要查找的内容。

本质上,您将查询用户点击的地图。访问所选要素的属性,然后显示包含该信息的标注。上面的示例使用 aUILabel来显示信息。

如果您想使用默认标注,请参阅动态样式交互点示例中的handleMapTap方法。此示例还从运行时加载的 JSON 数据创建形状源。


推荐阅读