ForEach loop in a Map doesn't work

Hi all,

here's a tiny litte demo app

import SwiftUI
import MapKit

struct MarkerData: Identifiable {
  var id = UUID()
  var coordinate: CLLocationCoordinate2D
}

struct MapView2: View {
  @State private var markers: [MarkerData] = []
  
  var body: some View {
    ForEach(markers) { marker in
      Text("\(marker.coordinate)")
    }
    Map {
      ForEach(markers) { marker in
        MapMarker(coordinate: marker.coordinate)
      }
    }
  }
}

The ForEach loop inside the Map gives the error:
"Generic parameter 'V' could not be inferred"

The one above seems to be fine.

What is wrong with the loop inside the map?

(I'm working with XCode Version 16.2)

Best!

Welcome to the forum

MapMarker is deprecated and required extra parmateres in Map:

Deprecated: Use Marker along with Map initializers that take a MapContentBuilder instead.

Here is the example from Xcode doc:

struct IdentifiablePlace: Identifiable {
    let id: UUID 
    let location: CLLocationCoordinate2D
    init(id: UUID = UUID(), lat: Double, long: Double) {
        self.id = id
        self.location = CLLocationCoordinate2D(
            latitude: lat,
            longitude: long)
    }
}

struct PinAnnotationMapView: View { 
    let place: IdentifiablePlace = IdentifiablePlace(lat: 0, long: 0)
    @State var region: MKCoordinateRegion = MKCoordinateRegion()

    var body: some View {
        Map(coordinateRegion: $region, annotationItems: [place])
        { place in
            MapMarker(coordinate: place.location)
        }
    }
}

I tested your code replacing MapMarker by Marker, it works (with a String as first parameter.

    Map {
      ForEach(markers) { marker in
        Marker("test", coordinate: marker.coordinate)  // MapMarker
      }
    }

Oh, wow, thank you!

I thought the error was about the ForEach statement:

Generic parameter 'V' could not be inferred.
In call to initializer (SwiftUI.ForEach)

What a misleading error message.

You might want to checkout Interacting with nearby points of interest sample code if you haven't already. It's a great starting point to learn about some of the new APIs in MapKit.

ForEach loop in a Map doesn't work
 
 
Q