ios - iOS Mapbox SDK - 如何将 MGLPointAnnotation 标记添加到地图图层中
问题描述
例如,我需要找到一种将标记从 转换MGLPointAnnotation
为MGLShapeSource
或类似的方法,以便将标记添加到地图图层并完全控制如何在地图上显示和聚类它们。
我正在使用MapBox SDK v5.2
. 该应用程序在内部生成标记(标题、副标题、坐标和图标图像名称),并且在点击时标记会显示在地图上并带有标注。标记是使用 创建的,MGLPointAnnotation()
并使用 添加到地图中mapView.addAnnotation()
。
但是为了完全控制标记的显示方式,例如根据缩放级别对它们进行聚类或打开/关闭它们,我需要将标记添加到地图图层,例如使用,MGLShapeSource
然后style.addSource()
和style.addLayer()
。
问题是我找不到从MGLPointAnnotation
toMGLShapeSource
或类似的转换器的方法。我对此进行了调查,但我能想到的唯一解决方案是将标记信息包含在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)
解决方案
您可以MGLShapeSource
使用一组MGLPointAnnotation
或MGLPointFeature
对象创建一个。从那里,您可以添加类似于此集群示例的集群层。
如果您还想为每个点分配文本或其他数据,请使用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 数据创建形状源。
推荐阅读
- python - 使用 matplotlib 编写两个或三个 x 刻度标签,以 UT 和 MLT(磁本地时间)显示小时
- c++ - 不能包含 mainwindow.h
- android - 调用 Vidyo Connection disable() 函数时应用程序崩溃
- javascript - 有什么方法可以优化这个反应应用程序,可能呈现数百万个组件
- c++ - 乘以 std::complex
通过模板化运算符重载加倍 - asp.net-core - 最大索赔数量
- java - 将在同步语句之前在另一个同步诺克之前?
- bit-manipulation - 给定并行中多个整数的索引,AVX或其他可以提取特定位的设置指令?
- c++ - 为什么 std::mutex 需要很长时间才能共享?
- mysql - MYSQL - FK存在和不存在时的SubSelect