How to let user to add custom annotation? - swift

I could not found any document, video or stackoverflow answer.
Here is my problem. I created map and add into my custom MKAnnotation and MKAnnotationView.
I want to let user to create custom pin and save to it's local via CoreData
MyCustomAnnotation has same attributes which is title, subtitle, and coordinate.
The first solution that I come up with put a button which creates a draggable pin to user location.
But I need to get less complex, more sophistication solution.
private func addPins() {
let list = PrivateLocations.shared.initLocations()
for pin in list {
map.addAnnotation(pin)
}
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if view.annotation is MKUserLocation { return }
let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil)
let customView = views?[0] as! CustomCalloutView
customView.delegate = self
customView.isUserInteractionEnabled = true
customView.titleLabel.text = view.annotation?.title!
customView.desc.text = view.annotation?.subtitle!
customView.center = CGPoint(x: view.bounds.size.width / 2, y: -customView.bounds.size.height*0.52)
view.addSubview(customView)
map.setCenter((view.annotation?.coordinate)!, animated: true)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
} else {
let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "CustomAnnotationView")
annotationView.image = UIImage(named: "myImage")
annotationView.canShowCallout = false
return annotationView
}
}
And finally here is my CustomPin class :
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(_ title: String, _ subtitle: String, _ coordinate: CLLocationCoordinate2D) {
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
}

That's how I solve this problem,
1) Create a UIView for user show where he wants to add an annotation.
2) Add a pan gesture recognizer in it.
func addPanGesture(view: UIView) {
let pan = UIPanGestureRecognizer(target: self, action: #selector (self.handlePan(sender:)))
view.addGestureRecognizer(pan)
}
3) In my selector func, I call pinDropped() func
#objc func handlePan(sender: UIPanGestureRecognizer) {
let view = sender.view!
let translation = sender.translation(in: self.mapView)
switch sender.state {
case .began, .changed:
pinImage.center = CGPoint(x: dropPinImage.center.x + translation.x, y: dropPinImage.center.y + translation.y)
sender.setTranslation(CGPoint.zero, in: view)
break
default:
pinDropped()
break
}
}
4) I write what will be happening in my pinDropped func
func pinDropped() {
DispatchQueue.main.async {
let pin = CustomPin(self.lastOrigin, "pin")
self.mapView.addAnnotation(pin)
}
self.saveButton.alpha = 1
pinImage.alpha = 0
}

Related

Swift - How to update observed data in a (custom or not) MKAnnotation callout WITHOUT deselecting the annotation

I'm struggling to get KVO updates within a callout already displayed.
My use case: I want to display on an open callout the real time distance between user location and the annotation I add to the map. Annotation does not change its position.
I add annotations to mapView, using a custom annotation I have defined. No issue here.
On each annotation selected, the callout displays all the information defined in the custom annotation
However, the distance is refreshed in the callout ONLY if I unselect the annotation and reselect it
The distance property is declared as #objc dynamic so it can be observed.
I compute the distance each time the user location change. This part works too.
I cannot figure out what I'm missing to have the callout updated without closing and reopening it.
The code I'm using is what is described here by Rob: Swift -How to Update Data in Custom MKAnnotation Callout?
So my question: is it possible to change realtime a value (observed) in a notificationView callout ? If yes is KVO the best approach ?
In the link below, how would be implemented the mapView viewFor method ?
Any example would be very helpful.
It's my first post here, so please if I did it wrong, let me know and I will provide more information and details.
But my situation is trivial: the standard callout performs Key-Value Observation (KVO) on title and subtitle. (And the annotation view observes changes to coordinate.). But how to display change of values in the current open callout ? That is the think I do not get.
CustomAnnotation class:
class CustomAnnotation: NSObject, MKAnnotation {
#objc dynamic var title: String?
#objc dynamic var subtitle: String?
#objc dynamic var coordinate: CLLocationCoordinate2D
#objc dynamic var distance: CLLocationDistance
var poiColor: String?
var poiPhone: String?
init(title: String, subtitle: String, coordinate: CLLocationCoordinate2D, poiColor: String, poiPhone: String, distance: CLLocationDistance) {
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
self.poiColor = poiColor
self.poiPhone = poiPhone
self.distance = distance
super.init()
}
}
CustomAnnotationView class:
class CustomAnnotationView: MKMarkerAnnotationView {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
displayPriority = .required
canShowCallout = true
detailCalloutAccessoryView = createCallOutWithDataFrom(customAnnotation: annotation as? CustomAnnotation)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
removeAnyObservers()
}
override var annotation: MKAnnotation? {
didSet {
removeAnyObservers()
if let customAnnotation = annotation as? CustomAnnotation {
updateAndAddObservers(for: customAnnotation)
}
}
}
private var subtitleObserver: NSKeyValueObservation?
private var distanceObserver: NSKeyValueObservation?
private let subtitleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let distanceLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
}
private extension CustomAnnotationView {
func updateAndAddObservers(for customAnnotation: CustomAnnotation) {
subtitleLabel.text = customAnnotation.subtitle
subtitleObserver = customAnnotation.observe(\.subtitle) { [weak self] customAnnotation, _ in
self?.subtitleLabel.text = customAnnotation.subtitle
}
let locationManager = CLLocationManager()
let theLatitude:CLLocationDegrees = (locationManager.location?.coordinate.latitude)!
let theLongitude:CLLocationDegrees = (locationManager.location?.coordinate.longitude)!
// Get pin location
let pointLocation = CLLocation(latitude: customAnnotation.coordinate.latitude, longitude: customAnnotation.coordinate.longitude)
//Get user location
let userLocation = CLLocation(latitude: theLatitude, longitude: theLongitude)
// Return distance en meters
let distanceFromUser = pointLocation.distance(from: userLocation)
customAnnotation.distance = distanceFromUser*100
distanceLabel.text = String(format: "%.03f", customAnnotation.distance)+" cm"
distanceObserver = customAnnotation.observe(\.distance) { [weak self] customAnnotation, _ in
self?.distanceLabel.text = "\(customAnnotation.distance) cm"
}
}
func removeAnyObservers() {
subtitleObserver = nil
distanceObserver = nil
}
func createCallOutWithDataFrom(customAnnotation: CustomAnnotation?) -> UIView {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = true
view.addSubview(subtitleLabel)
view.addSubview(distanceLabel)
NSLayoutConstraint.activate([
subtitleLabel.topAnchor.constraint(equalTo: view.topAnchor),
subtitleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
subtitleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
subtitleLabel.bottomAnchor.constraint(equalTo: distanceLabel.topAnchor),
distanceLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
distanceLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
distanceLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
if let customAnnotation = customAnnotation {
updateAndAddObservers(for: customAnnotation)
}
return view
}
}
And to finish:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation { return nil }
let annotation = annotation as? CustomAnnotation
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "CustomAnnotation") as? CustomAnnotationView
if annotationView == nil {
annotationView = CustomAnnotationView(annotation: annotation, reuseIdentifier: "CustomAnnotation")
annotationView?.canShowCallout = true
} else {
annotationView?.annotation = annotation
}
return annotationView
}
Thank you.
You would appear to have correctly configured the observers for the subtitle and distance. The problem is that a change in location is not triggering an update to distance. Thus, there is nothing triggering the KVO.
You have an observer for distance, which will trigger an update of the label. But you are not changing distance. You should remove the CLLocationManager code from that routine where you add the observers, and instead create a location manager (not within the annotation view, though) which uses its delegate to update all of the annotation distances, e.g.:
class ViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.distanceFilter = 5
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let currentLocation = locations.last(where: { $0.horizontalAccuracy >= 0 }) else { return }
mapView.annotations
.compactMap { $0 as? CustomAnnotation }
.forEach {
$0.distance = CLLocation(latitude: $0.coordinate.latitude, longitude: $0.coordinate.longitude)
.distance(from: currentLocation)
}
}
}
Obviously, you would remove the CLLocationManager code from updateAndAddObservers.

How to add polylines and annotations from user taps in SwiftUI

I am trying to drop annotations/pins wherever a user touches a certain location on the map. Whenever a user drops more 2 or more pins, it creates a polyline that connects the points. I got it to work in regular Swift 5, but I am trying to make it work in SwiftUI. I am using Mapbox. I am having trouble figuring out how to make it work with the coordinator. Can anyone help me figure this out? Thanks!
import SwiftUI
import Mapbox
// Creates an annotation using title & coordinate
extension MGLPointAnnotation {
convenience init(title: String, coordinate: CLLocationCoordinate2D) {
self.init()
self.title = title
self.coordinate = coordinate
}
}
// Represents & Displays an MGLMapView in SwiftUI
struct MapView: UIViewRepresentable {
// Property binding to add annotations
#Binding var annotations: [MGLPointAnnotation]
//var mapView: MGLMapView!
//var coordinates = [CLLocationCoordinate2D]()
// Creates a mapView with MGLMapView type
private let mapView: MGLMapView = MGLMapView(frame: .zero, styleURL: MGLStyle.streetsStyleURL)
// Needed function for UIViewRepresentable
func makeUIView(context: UIViewRepresentableContext<MapView>) -> MGLMapView {
mapView.delegate = context.coordinator
// Add a single tap gesture recognizer. This gesture requires the built-in MGLMapView tap gestures (such as those for zoom and annotation selection) to fail.
let singleTap = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.handleMapTap(sender:)))
for recognizer in mapView.gestureRecognizers! where recognizer is UITapGestureRecognizer {
singleTap.require(toFail: recognizer)
}
mapView.addGestureRecognizer(singleTap)
// Convert `mapView.centerCoordinate` (CLLocationCoordinate2D) to screen location (CGPoint).
let centerScreenPoint: CGPoint = mapView.convert(mapView.centerCoordinate, toPointTo: nil)
print("Screen center: \(centerScreenPoint) = \(mapView.center)")
return mapView
}
// Needed function for UIViewRepresentable
func updateUIView(_ uiView: MGLMapView, context: UIViewRepresentableContext<MapView>) {
updateAnnotations()
uiView.addAnnotations(annotations)
}
// Styles the map with a MapBox Studio URL
func styleURL(_ styleURL: URL) -> MapView {
mapView.styleURL = styleURL
return self
}
// Specifies where the map is centered
func centerCoordinate(_ centerCoordinate: CLLocationCoordinate2D) -> MapView {
mapView.centerCoordinate = centerCoordinate
return self
}
// Specifies the zoom level of the initial view
func zoomLevel(_ zoomLevel: Double) -> MapView {
mapView.zoomLevel = zoomLevel
return self
}
// Updates the annotations in the view
private func updateAnnotations() {
if let currentAnnotations = mapView.annotations {
mapView.removeAnnotations(currentAnnotations)
}
mapView.addAnnotations(annotations)
}
// Makes the coordinater (coordinator class below)
func makeCoordinator() -> MapView.Coordinator {
Coordinator(self, mapView)
}
// A coordinator used with a delegate to add the annotation view to the map
// A coordinator class is declared to implement and view MGLMapViewDelegate in SwiftUI
final class Coordinator: NSObject, MGLMapViewDelegate {
var control: MapView
var mapView: MGLMapView!
var coordinates = [CLLocationCoordinate2D]()
var pointAnnotations = [MGLPointAnnotation]()
init(_ control: MapView, _ mapView: MGLMapView) {
self.control = control
self.mapView = mapView
}
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
return nil
}
#objc func handleMapTap(sender: UITapGestureRecognizer) {
// Convert tap location (CGPoint) to geographic coordinate (CLLocationCoordinate2D).
let tapPoint: CGPoint = sender.location(in: mapView)
let tapCoordinate: CLLocationCoordinate2D = mapView.convert(tapPoint, toCoordinateFrom: mapView)
print("You tapped at: \(tapCoordinate.latitude), \(tapCoordinate.longitude)")
// Create an array of coordinates for our polyline, starting at the center of the map and ending at the tap coordinate.
//var coordinates: [CLLocationCoordinate2D] = [mapView.centerCoordinate]
coordinates.append(tapCoordinate)
print("Coordinates list: \(coordinates)")
//var pointAnnotations = [MGLPointAnnotation]()
for coordinate in coordinates {
let point = MGLPointAnnotation()
point.coordinate = coordinate
point.title = "\(coordinate.latitude), \(coordinate.longitude)"
pointAnnotations.append(point)
print("Annotations: \(pointAnnotations)")
let polyline = MGLPolyline(coordinates: &coordinates, count: UInt(coordinates.count))
mapView.addAnnotation(polyline)
}
mapView.addAnnotations(pointAnnotations)
// Remove any existing polyline(s) from the map.
//if mapView.annotations?.count != nil, let existingAnnotations = mapView.annotations {
//mapView.removeAnnotations(existingAnnotations)
//}
// Add a polyline with the new coordinates.
//let polyline = MGLPolyline(coordinates: &coordinates, count: UInt(coordinates.count))
//mapView.addAnnotation(polyline)
}
}
}
First of all, the single tap cannot work if making it 'to fail' for other recognisers, (I don't know why that happened in SwiftUI). Removing the for loop makes it work, but also disables other single tap features on the map, for example, annotations will not be clickable.
Therefore, I suggest using some other gesture instead, the following example is based on long press.
func makeUIView(context: UIViewRepresentableContext<MapView>) -> MGLMapView {
mapView.delegate = context.coordinator
let longTap = UILongPressGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.handleMapTap(sender:)))
mapView.addGestureRecognizer(longTap)
return mapView
}
Second, the 'mapView' in the handler function should be 'control.mapView' according to the first line of your 'Coordinator' class.
#objc func handleMapTap(sender: UILongPressGestureRecognizer) {
// Run the code unless user end the long press (Long press handler keep calling during press)
//guard sender.state == .ended else { return }
// Convert tap location (CGPoint) to geographic coordinate (CLLocationCoordinate2D).
let locationInMap = sender.location(in: control.mapView)
let coordinateSet = control.mapView.convert(locationInMap, toCoordinateFrom: nil)
print("You tapped at: \(coordinateSet.latitude)")
if sender.state == UIGestureRecognizer.State.ended {
print("You final tapped at: \(coordinateSet.latitude)")
}
}
I faced with the same issue with you.
I updated my library to the newest version and every thing worked!

class extension not being called - unable to configure annotations on map

I'm on Swift 5 and Xcode 11, currently trying to create a map with predefined annotations using custom images instead of the default markers. I've been playing around with Apple's sample code for AnnotatingMapWithCustomData and could tailor it to what I needed. But once I tried to copy the code into my own project, the annotations showed up as default markers instead of the custom annotationViews I configured.
import UIKit
import MapKit
class MapViewController: UIViewController {
#IBOutlet private weak var mapView: MKMapView!
private var allAnnotations: [MKAnnotation]?
private var displayedAnnotations: [MKAnnotation]? {
willSet {
if let currentAnnotations = displayedAnnotations {
mapView.removeAnnotations(currentAnnotations)
}
}
didSet {
if let newAnnotations = displayedAnnotations {
mapView.addAnnotations(newAnnotations)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
registerMapAnnotationViews()
// Create the array of annotations and the specific annotations for the points of interest.
allAnnotations = [ShrekAnnotation(), CoffeeAnnotation()]
// Dispaly all annotations on the map.
displayedAnnotations = allAnnotations
centerMapOnLondon()
}
/// - Tag: RegisterAnnotationViews
private func registerMapAnnotationViews() {
mapView.register(MKAnnotationView.self, forAnnotationViewWithReuseIdentifier: NSStringFromClass(ShrekAnnotation.self))
mapView.register(MKAnnotationView.self, forAnnotationViewWithReuseIdentifier: NSStringFromClass(CoffeeAnnotation.self))
}
private func centerMapOnLondon() {
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let center = CLLocationCoordinate2D(latitude: 51.507911, longitude: -0.132222)
mapView.setRegion(MKCoordinateRegion(center: center, span: span), animated: true)
}
}
extension MapViewController: MKMapViewDelegate {
/// - Tag: CreateAnnotationViews
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !annotation.isKind(of: MKUserLocation.self) else {
// Make a fast exit if the annotation is the `MKUserLocation`, as it's not an annotation view we wish to customize.
return nil
}
var annotationView: MKAnnotationView?
if let annotation = annotation as? ShrekAnnotation {
annotationView = setupShrekAnnotationView(for: annotation, on: mapView)
} else if let annotation = annotation as? CoffeeAnnotation {
annotationView = setupCoffeeAnnotationView(for: annotation, on: mapView)
}
return annotationView
}
/// - Tag: ConfigureAnnotationViews
private func setupShrekAnnotationView(for annotation: ShrekAnnotation, on mapView: MKMapView) -> MKAnnotationView {
let reuseIdentifier = NSStringFromClass(ShrekAnnotation.self)
let view = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier, for: annotation)
view.canShowCallout = true
// Provide the annotation view's image.
let image = #imageLiteral(resourceName: "map-shrek1")
view.image = image
return view
}
/// - Tag: ConfigureAnnotationViews
private func setupCoffeeAnnotationView(for annotation: CoffeeAnnotation, on mapView: MKMapView) -> MKAnnotationView {
let reuseIdentifier = NSStringFromClass(CoffeeAnnotation.self)
let view = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier, for: annotation)
view.canShowCallout = true
// Provide the annotation view's image.
let image = #imageLiteral(resourceName: "map-cof1")
view.image = image
return view
}
}
Apparently the class extension is not being called but I don't know how to fix this. The code that worked before I tried implementing it in my own project is identical. Could I have missed something I should've copied too or can you find the reason for the bug in the code?
Thanks for any help.
I think you are not setting the mapView delegate hence viewFor annotation is not being triggered and your custom annotation view is not appearing on map. Set
mapView.delegate = self
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
registerMapAnnotationViews()
// Create the array of annotations and the specific annotations for the points of interest.
allAnnotations = [ShrekAnnotation(), CoffeeAnnotation()]
// Dispaly all annotations on the map.
displayedAnnotations = allAnnotations
centerMapOnLondon()
}
Hope this helps

Save map annotation using UserDefaults

I have been searching relentlessly for this solution and left with no choice except to rely on the expertise here on Stackoverflow. I am working on saving a map annotation if the app closes and I have been using the UserDefault to save the annotation.
This is the Objective C code that I found and I tried converting it into Swift and I think there is an error with it. I am not too sure. I place this code at viewDidLoad()
This is the save annotation
var pinnedAnnotation: CLLocationCoordinate2D = (parkedCarAnnotation?.coordinate)!
var coordinateData: NSData = NSData(bytesNoCopy: pinnedAnnotation, length: sizeof(pinnedAnnotation), freeWhenDone: false)
UserDefaults.standard.set(coordinateData, forKey: pinnedAnnotation)
UserDefaults.standard.synchronize()
And I needed a load annotation when the app open.
I dont know if viewDidLoad is the right place to put. Previously I put it in a mapView function of updatingLocation
Edited: Added code for further clarification of what I have done that needed to be corrected
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self as MKMapViewDelegate
checkLocationAuthorizationStatus()
tabBar.delegate = self
if UserDefaults.standard.object(forKey: "pinnedAnnotation") != nil {
let annotation = MKPointAnnotation()
self.mapView.addAnnotation(annotation)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let pinnedAnnotation: CLLocationCoordinate2D = (parkedCarAnnotation?.coordinate)!
let locationData = ["latitude": parkedCarAnnotation?.coordinate.latitude, "longitude": parkedCarAnnotation?.coordinate.longitude]
UserDefaults.standard.set(locationData, forKey: "pinnedAnnotation")
UserDefaults.standard.synchronize()
print("Saving data ", UserDefaults.standard.set(locationData, forKey: "pinnedAnnotation"))
}
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
if(item.tag == 0){
if mapView.annotations.count == 1{
mapView.addAnnotation(parkedCarAnnotation!)
} else {
mapView.removeAnnotation(mapView.annotations as! MKAnnotation)
}
}
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? ParkingSpot{
let identifier = "pin"
var view: MKPinAnnotationView
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.animatesDrop = true
view.pinTintColor = UIColor.orange
view.calloutOffset = CGPoint(x: -8, y: -3)
view.rightCalloutAccessoryView = UIButton.init(type:.detailDisclosure) as UIView
return view
} else {
return nil
}
}
extension ViewController: CLLocationManagerDelegate{
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
centerMapOnLocation(location: CLLocation(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude))
let locationServiceCoordinate = LocationService.instance.locationManager.location!.coordinate
parkedCarAnnotation = ParkingSpot(title: "My Parking Spot", locationName: "Find your way back to your car location", coordinate: CLLocationCoordinate2D(latitude: locationServiceCoordinate.latitude, longitude: locationServiceCoordinate.longitude))
}
}
I'm not entirely sure what you're asking...
For starters when you're saving data to UserDefaults the key needs to be a string, I also believe you'll need to save you data in UserDefaults as a Dictionary
let locationData = ["lat": parkedCarAnnotation?.coordinate?.latitude, "long": parkedCarAnnotation?.coordinate.longitude]
UserDefaults.standard.set(locationData, forKey: "pinned_annotation")
And then to retrieve the data you would call
if let annotationData = UserDefaults.standard.object(forKey: "pinned_annotation") as? Dictionary {
guard let lat = annotationData["lat"], let long = annotationData["long"] else { return }
let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
}
Now you should hopefully be able to set your annotation with the coordinate

Swift Custom Annotation does not get select

I have a custom annotationView on my map, when I select the custom annotation i want to create a action and pass the annotation data to another view. The best way for it to work I would have to use the built in func didSelect. When i do select the custom annotation nothing thing happen. Im not show why the didSelect function did not get called thank you in advance.
class RquestCustomPointAnnotation:MKPointAnnotation {
var image: String!
}
func placeRquestByUsersOnMap(){
//retrieve item from firebase
var markerArray = [MKPointAnnotation]()
let path = "rquest/frontEnd/posts/userCreatedPost"
self.childRef(path).observe(.childAdded, andPreviousSiblingKeyWith: {snapshot, _ in
//get status
if let status = snapshot.childSnapshot(forPath: "status").value as? String {
if status == "pending"{
let indentifier = "rquest"
if let coordinate = snapshot.childSnapshot(forPath: "coordinate").value as? NSDictionary {
let lat = coordinate["lat"] as! Double
let long = coordinate["long"] as! Double
let location = CLLocationCoordinate2D(latitude: lat, longitude: long)
let point = RquestCustomPointAnnotation()
let rquestView = MKAnnotationView(annotation: point, reuseIdentifier: indentifier)
point.image = "22"
let key = snapshot.key
point.coordinate = location
point.accessibilityValue = key
point.accessibilityLabel = "Rquest"
markerArray.append(point)
self.mapView.addAnnotation(rquestView.annotation!)
//create an obserarver to check if it is
let paths = "rquest/frontEnd/posts/userCreatedPost/\(key)/"
self.childRef(paths).observe(.childChanged, andPreviousSiblingKeyWith: { (snap, _) in
if snap.key == "status" {
if let status = snap.value as? String {
if status != "pending" {
for i in markerArray {
if i.accessibilityValue == key {
self.mapView.removeAnnotation(i)
}
}
}
}
}
})
}
}
}
})
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is RquestCustomPointAnnotation {
let reuseIdentifier = "rquest"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
annotationView?.canShowCallout = true
} else {
annotationView?.annotation = annotation
}
let customPointAnnotation = annotation as! RquestCustomPointAnnotation
annotationView?.image = UIImage(named: customPointAnnotation.image)
return annotationView
}
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
print("did select")
}
You have canShowCallout set to true. So, when you tap on it, do you want callout or have it call didSelect? (Usually you'd do one or the other, but not both.) And are you seeing your callout?
I notice a curious behavior that if (a) the annotation doesn't have a title, and (b) the annotation view's canShowCallout is true, then not only can it not show the callout, but it also prevents the didSelect from being called.
You may either want to turn canShowCallout to false, or make sure your annotation has a title.