0

I'm relatively new to iOS and Mapbox development. I'm working on an app where a user can freely manipulate a map full of places they have saved.

When they reach a zoom-level that is completely filled by the geography of a city, I would like to display the name of the city which they are viewing in a banner-style view, even if a city label is not within view on the map (as is often the case when zoomed in).

Here's a screenshot of the UI for context.

I'm trying to query the Mapbox tileset for the city name using the following code:

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)
    }

I think this code doesn't work because the label is not onscreen at the specified zoom level.

I'm wondering if using visibleFeaturesInRect is the best approach for my need—is there a better way to retrieve city name regardless of visible elements and zoom level?

1 Answers1

0

For this task I'd recommend using MapboxGeocoder from Mapbox. It is for getting information about the city/village. you can install pod:

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

and use this code:

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)
    }
}

you can add your conditions and it really helps to solve your task

Vadim Nikolaev
  • 2,132
  • 17
  • 34