Search code examples
iosswiftmapbox-iosmapbox-ios-maps

How to display Zip Code or Postal Code using MapBox iOS SDK


My goal is to display Zip Codes or Postal Codes using Mapbox's iOS SDK for USA only postal codes;

I am currently able to display the boundaries for Zip Codes and the international postal/zip code, for example "USP227518" when I actually want to display "27518"

I've tried using mapboxMap.queryRenderedFeatures() and was able to successfully display a modified string value as desired, however this doesn't solve my problem because I need to display the long zipcode with the prefix 'USP2' in order for it to find the Feature and display a map annotation without the prefix. This causes a visual overlap

I also tried 'mapboxMap.querySourceFeatures()' and was unable to retrieve any data at all from any of my sources

Here is the code I use to display the zip codes as given by MapBox

try mapboxMapView.mapboxMap.style.updateLayer(withId: MapConstants.symbolLayerIdentifier, type: SymbolLayer.self) { layer in

    layer.textField = .expression(Expression(.number) {
        Exp(.get) { "id" }
        zipCodes // Array of strings all with 'USP2' prefix
        Exp(.get) { "id" } 
        ""                  
    })
}

Is there some way to drop the prefixes or to query the source features for zip code points from the source points_postal_2?

I also have no idea where Exp(.get) { "id" } comes from. My best guess is it comes from here https://docs.mapbox.com/data/boundaries/reference/feature-lookup-tables/ . unit_code from that doc didn't work for me in place of "id" even when I removed the 'USP2' prefix from the zipCodes string array values

How do I display the zip codes on a map?


Solution

  • The undocumented MapBox iOS SDK is a tricky library.

    Slice is what I needed, and how does one use it, great question, it's not documented nor do any examples seem to exist!

    https://docs.mapbox.com/ios/maps/api/10.14.0/Structs/Expression/Operator.html#/s:10MapboxMaps10ExpressionV8OperatorO5sliceyA2EmF

    
     try mapView.mapboxMap.style.updateLayer(withId: MyMapLayerName, type: SymbolLayer.self) { layer in
         layer.textField = .expression(Expression(.match) {
              Exp(.get) { "id" }
              myZipCodeStringArray
              Exp(.slice) { // Drop first 4 characters, the prefix
                   Exp(.get) { "id" }
                   4
              }
              "" //not available
         })