0

I want to detect a user tap on the map so i can add a marker and get the coordinates of that point. I was able to do that on android and with react but it seems impossible in swiftui because i can't find new ways to do that. Currently i have my mapview like this.

import SwiftUI
import UIKit
import MapboxMaps

struct MapBoxMapView: UIViewControllerRepresentable {
    
    func makeUIViewController(context: Context) -> MapViewController {
        return MapViewController()
    }
    
    func updateUIViewController(_ uiViewController: MapViewController, context: Context) {
    }
}

class MapViewController: UIViewController {
    internal var mapView: MapView!

    
    override func viewDidLoad() {
        super.viewDidLoad()
        let myResourceOptions = ResourceOptions(accessToken: "MY_TOKEN")
        let myCameraOptions = CameraOptions(center: CLLocationCoordinate2D(latitude: 0, longitude: 0), zoom: 10)
        
        let initOptions = MapInitOptions(
            resourceOptions: myResourceOptions,
            cameraOptions: myCameraOptions,
            styleURI: StyleURI(rawValue: StyleURI.satellite.rawValue)
        )
        
        mapView = MapView(frame: view.bounds, mapInitOptions: initOptions)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        
        self.view.addSubview(mapView)
    }
}

What can i do to make it possible? I searched on v10 documentation but found nothing.

  • For v10, this example demonstrates how to identify features near a click. While the overall example is to a different end, the `onMapClick` functions shows the method to find a feature and then build an annotation. https://docs.mapbox.com/ios/maps/examples/view-annotation-marker/ – darshilsakhiya Dec 30 '22 at 11:22

1 Answers1

1
    // Implement the action method for the tap gesture recognizer
    @objc func handleMapTap(sender: UITapGestureRecognizer) {
    // Get the coordinates of the point on the map that was tapped
    let point = sender.location(in: mapView)
    let coordinate = mapView.mapboxMap.coordinate(for: point)
    
    // Convert the point to geographic coordinates
    // Make a `PointAnnotationManager` which will be responsible for 
    //managing a collection of `PointAnnotation`s.
    
    
    
    let pointAnnotationManager = 
    mapView.annotations.makePointAnnotationManager()
    // Initialize a point annotation with a single coordinate
    // and configure it with a custom image (sourced from the asset 
    catalogue)
    var customPointAnnotation = PointAnnotation(coordinate: coordinate)
    // Make the annotation show a red pin
    customPointAnnotation.image = .init(image: UIImage(named: 
    "red")!, name: "red_pin")
    
    // Add the annotation to the manager in order to render it on the 
    map.
    pointAnnotationManager.annotations = [customPointAnnotation]
    
    }// end func

i use this code block in my code.

Observer23
  • 29
  • 6