在两个主要的ways to add overlays 到MGLMapView 中,运行时样式API 更适合文本标签,也更适合根据缩放级别改变外观。在此过程中,您也可以使用相同的 API 创建多边形。
首先为您想要着色的区域创建多边形特征:
var cards: [MGLPolygonFeature] = []
var coordinates: [CLLocationCoordinate2D] = […]
let card = MGLPolygonFeature(coordinates: &coordinates, count: UInt(coordinates.count))
card.attributes = ["address": 123]
// …
cards.append(card)
在地图加载完成后运行的任何方法中,例如MGLMapViewDelegate.mapView(_:didFinishLoading:),将包含这些特征的形状源添加到当前样式:
let cardSource = MGLShapeSource(identifier: "cards", features: cards, options: [:])
mapView.style?.addSource(cardSource)
使用适当的形状源,创建一个样式层,将多边形特征呈现为淡紫色填充:
let fillLayer = MGLFillStyleLayer(identifier: "card-fills", source: cardSource)
fillLayer.fillColor = NSExpression(forConstantValue: #colorLiteral(red: 0.9098039216, green: 0.8235294118, blue: 0.9647058824, alpha: 1))
mapView.style?.addLayer(fillLayer)
然后创建另一个样式层,在每个多边形要素的质心处呈现标签。 (MGLSymbolStyleLayer 自动计算质心,考虑不规则形状的多边形。)
// Same source as the fillLayer.
let labelLayer = MGLSymbolStyleLayer(identifier: "card-labels", source: cardSource)
// Each feature’s address is an integer, but text has to be a string.
labelLayer.text = NSExpression(format: "CAST(address, 'NSString')")
// Smoothly interpolate from transparent at z16 to opaque at z17.
labelLayer.textOpacity = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)",
[16: 0, 17: 1])
mapView.style?.addLayer(labelLayer)
当您自定义这些样式层时,请特别注意MGLSymbolStyleLayer 上控制附近符号是否因碰撞而自动隐藏的选项。您可能会发现自动碰撞检测使得无需指定textOpacity 属性。
创建源时,可以传递给MGLShapeSource 初始化程序的选项之一是MGLShapeSourceOption.clustered。但是,为了使用该选项,您必须创建 MGLPointFeatures,而不是 MGLPolygonFeatures。幸运的是,MGLPolygonFeature 有一个 coordinate 属性,让您无需手动计算即可找到质心:
var cardCentroids: [MGLPointFeature] = []
var coordinates: [CLLocationCoordinate2D] = […]
let card = MGLPolygonFeature(coordinates: &coordinates, count: UInt(coordinates.count))
let cardCentroid = MGLPointFeature()
cardCentroid.coordinate = card.coordinate
cardCentroid.attributes = ["address": 123]
cardCentroids.append(cardCentroid)
// …
let cardCentroidSource = MGLShapeSource(identifier: "card-centroids", features: cardCentroids, options: [.clustered: true])
mapView.style?.addSource(cardCentroidSource)
此集群源只能与MGLSymbolStyleLayer 或MGLCircleStyleLayer 一起使用,而不是MGLFillStyleLayer。 This example 更详细地展示了如何使用聚类点。