检索屏幕区域的城市名称 [Mapbox]

Retrieving city name for onscreen region [Mapbox]

我对 iOS 和 Mapbox 开发比较陌生。我正在开发一款应用程序,用户可以在其中自由操作一张满是他们保存的地点的地图。

当他们达到完全由城市地理填充的缩放级别时,我想在横幅样式视图中显示他们正在查看的城市名称,即使城市标签是不在地图上的视野范围内(放大时通常会出现这种情况)。

Here's a screenshot of the UI for context.

我正在尝试使用以下代码在 Mapbox tileset 中查询城市名称:

func mapViewRegionIsChanging(_ mapView: MGLMapView) {

    let zoomLevel = mapView.zoomLevel

    if zoomLevel >= 14.0 {

            // layer identifier taken from layer name in Mapbox Studio
            let layerIdentifier = "place-city-lg-n"

            let screenRect = UIScreen.main.bounds

            let cityName = mapView.visibleFeatures(in: screenRect, styleLayerIdentifiers: Set([layerIdentifier]))

            print(cityName)
    }

我认为此代码不起作用,因为标签不在指定缩放级别的屏幕上。

我想知道使用 visibleFeaturesInRect 是否是满足我需要的最佳方法——是否有更好的方法来检索城市名称而不考虑可见元素和缩放级别?

对于此任务,我建议使用 Mapbox 中的 MapboxGeocoder。它用于获取有关 city/village 的信息。 你可以安装 pod:

pod 'MapboxGeocoder.swift', '~> 0.12'

并使用此代码:

let geocoder = Geocoder.shared

func mapViewRegionIsChanging(_ mapView: MGLMapView) {

    let geocodeOptions = ReverseGeocodeOptions(coordinate: mapView.centerCoordinate)
    geocodeOptions.allowedScopes = [.place]

    let _ = geocoder.geocode(geocodeOptions) { (placemarks, attribution, error) in
        guard let placemark = placemarks?.first else { return }
        print(placemark.name)
        print(placemark.qualifiedName)
    }
}

您可以添加您的条件,它确实有助于解决您的任务