0

I have a fairy simple SwiftUI code block showing a map with a pin. This works so far.

I'd like to add a new pin by a list of draggable objects. Now, I am bit stuck at the following problems:

  1. Where to add a list of draggable items to create the pin?
  2. How to select the item and translate it to a marker object?
  3. How to determine the final location in MapKit where the pin is dragged?

I think it is solvable and I can do it in LeafletJS, but SwiftUI makes my head ache.

import MapKit
import CoreLocation

struct Marker: Identifiable {
    let id = UUID()
    var location: MapMarker
}

struct ContentView: View {
    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 47.8681, longitude: 8.205), span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.50))
    
    let markers = [Marker(location: MapMarker(coordinate: CLLocationCoordinate2D(latitude: 47.8681, longitude: 8.205), tint: .blue))]
    
    var body: some View {
        
        Map(coordinateRegion: $region, showsUserLocation: true, userTrackingMode: .constant(.follow),annotationItems: markers){ marker in
            marker.location
        }
            .frame(width: 1200, height: 600)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Benjamin Mewes
  • 89
  • 2
  • 10
  • https://stackoverflow.com/questions/67335607/how-to-convert-tap-gesture-to-coordinate-in-a-swiftui-map-view/71404041#71404041 – lorem ipsum Mar 10 '22 at 15:58
  • The first two parts sound like a Drag and Drop. There is a good [tutorial here](https://swiftui-lab.com/drag-drop-with-swiftui/). As to the third part, this is one of those areas where your best choice may be a `UIViewRepresentable` of an `MKMapView`. The trick above is interesting, but it is at the expense of draggability for your map itself. – Yrb Mar 10 '22 at 16:09
  • The response in the link I posted above may be a little more applicable in your use case because you want to drag and drop, therefore you have a point where you can toggle from the map's gestures to the custom gesture and vice versa. `MKMapKit` is probably a better solution but the pure SwiftUI option is viable here. – lorem ipsum Mar 10 '22 at 17:14

0 Answers0