Mapkit with LongPressGestureRecognizer working intermittently - ios

I have a very simple setup, where I have a MapKit, and I'd like to be able to drop pin to it everytime the user do a long press on the map.
It works ok for the first pin. But if the user tried another long press (on another location), then the gesture is not recognized. The third time will work, the fourth time doesnt work, etc (every odd attempt will get recognized).
I have a sample project that demonstrate this:
https://github.com/alexwibowo/SimpleLocationMarker
Basically, my view controller looks like below:
class ViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView! {
didSet{
let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.addNewAnnotation(recognizer:)))
gestureRecognizer.minimumPressDuration = 0.5
mapView.addGestureRecognizer(gestureRecognizer)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
#objc func addNewAnnotation(recognizer: UILongPressGestureRecognizer){
if (recognizer.state != .began) {
return
}
let touchPoint = recognizer.location(in: mapView)
let wayCoords = mapView.convert(touchPoint, toCoordinateFrom: mapView)
let annotation = MKPointAnnotation()
annotation.title = "New"
annotation.coordinate = wayCoords
mapView.addAnnotation(annotation)
}
}
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "locationMarkerIdentifier"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.annotation = annotation
view.canShowCallout = true
view.isDraggable = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
return view
}
}
I'm sure it is a very simple mistake I've done!

First, set its delegate to self.
#IBOutlet weak var mapView: MKMapView! {
didSet{
let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.addNewAnnotation(recognizer:)))
gestureRecognizer.minimumPressDuration = 0.5
mapView.addGestureRecognizer(gestureRecognizer)
gestureRecognizer.delegate = self
}
}
Second,
extension ViewController : UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}

Related

Detect longpress in MapView for SwiftUI

I have a MapView in SwiftUi and I am trying to add a pin annotation to it when a user long presses a location on the map. I see this can easily be accomplished in swift however I am using SwiftUI. I do not know how to add the long-press detector. A code example would be great.
My MapView
struct MapView: UIViewRepresentable {
#Binding
var annotations: [PinAnnotation]
let addAnnotationListener: (PinAnnotation) -> Void
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
return mapView
}
func updateUIView(_ view: MKMapView, context: Context) {
view.delegate = context.coordinator
view.addAnnotations(annotations)
if annotations.count == 1 {
let coords = annotations.first!.coordinate
let region = MKCoordinateRegion(center: coords, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
view.setRegion(region, animated: true)
}
}
func makeCoordinator() -> MapViewCoordinator {
MapViewCoordinator(self)
}
}
MapViewCoordinator
class MapViewCoordinator: NSObject, MKMapViewDelegate {
var mapViewController: MapView
init(_ control: MapView) {
self.mapViewController = control
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let annotation = view.annotation
guard let placemark = annotation as? MKPointAnnotation else { return }
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{
//Custom View for Annotation
let identifier = "Placemark"
if let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) {
annotationView.annotation = annotation
return annotationView
} else {
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView.isEnabled = true
annotationView.canShowCallout = true
let button = UIButton(type: .infoDark)
annotationView.rightCalloutAccessoryView = button
return annotationView
}
}
}
The method to add a pin to a MapView
func addPinBasedOnGesture(gestureRecognizer:UIGestureRecognizer){
var touchPoint = gestureRecognizer.locationInView(mapView)
var newCoordinates = self.convertPoint(touchPoint, toCoordinateFromView: mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = newCoordinates
mapView.addAnnotation(annotation)
}
Below solution adds a pin at the point where user long presses on the Map.
Add below method in MapViewCoordinator
#objc func addPinBasedOnGesture(_ gestureRecognizer:UIGestureRecognizer) {
let touchPoint = gestureRecognizer.location(in: gestureRecognizer.view)
let newCoordinates = (gestureRecognizer.view as? MKMapView)?.convert(touchPoint, toCoordinateFrom: gestureRecognizer.view)
let annotation = PinAnnotation()
guard let _newCoordinates = newCoordinates else { return }
annotation.coordinate = _newCoordinates
mapViewController.annotations.append(annotation)
}
and longPress gesture code in func makeUIView(context: Context) -> MKMapView {}
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
let longPressed = UILongPressGestureRecognizer(target: context.coordinator,
action: #selector(context.coordinator.addPinBasedOnGesture(_:)))
mapView.addGestureRecognizer(longPressed)
return mapView
}
Find below modified parts of provided code to get required behaviour:
struct SUMapView: UIViewRepresentable {
// ... other your code here
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
let longPressed = UILongPressGestureRecognizer(target:
context.coordinator, action: #selector(addPin(gesture:)))
mapView.addGestureRecognizer(longPressed)
return mapView
}
// ... other your code here
}
class MapViewCoordinator: NSObject, MKMapViewDelegate {
// ... other your code here
#objc func addPin(gesture: UILongPressGestureRecognizer) {
// do whatever needed here
}
// ... other your code here
}

Swift: MapView calloutAccessoryControlTapped index

class MapViewController: UIViewController, MKMapViewDelegate, HomeModelProtocol {
var feedItems: NSArray = NSArray()
var selectedLocation : LocationModel = LocationModel()
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let initialLocation = CLLocation(latitude: 45.444958, longitude: 12.328463)
centerMapLocation(location: initialLocation)
mapView.delegate = self
let homeModel = HomeModel()
homeModel.delegate = self
homeModel.downloadItems()
}
func itemsDownloaded(items: NSArray) {
feedItems = items
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
let regionRadus: CLLocationDistance = 1000
func centerMapLocation(location: CLLocation){
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadus, regionRadus)
mapView.setRegion(coordinateRegion, animated: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//checkLocationAuthorizationStatus()
displayLocations()
}
func displayLocations(){
let i = feedItems.count
var x = 0
while x<i{
let item: LocationModel = feedItems[x] as! LocationModel
var poiCoodinates = CLLocationCoordinate2D()
poiCoodinates.latitude = CDouble(item.latitude!)!
poiCoodinates.longitude = CDouble(item.longitude!)!
let pin: MKPointAnnotation = MKPointAnnotation()
pin.coordinate = poiCoodinates
self.mapView.addAnnotation(pin)
pin.title = item.name
pin.subtitle = item.address
x = x+1
}
//return loc
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let view = MKMarkerAnnotationView(annotation: selectedLocation as? MKAnnotation, reuseIdentifier: "pin")
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.leftCalloutAccessoryView = UIButton(type: .detailDisclosure)
return view
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
print(control.tag)
selectedLocation = feedItems[0] as! LocationModel
performSegue(withIdentifier: "InformationSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get reference to the destination view controller
let detailVC = segue.destination as! InformationViewController
// Set the property to the selected location so when the view for
// detail view controller loads, it can access that property to get the feeditem obj
detailVC.selectedLocation = selectedLocation
}
}
This is my code.
I want to display the Location in the next Viewcontroller.
I need to get the index at feeditems[].
How can i get the index in:
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl)
So how do i get the index, which Button is tapped. There are many objects that are placed in the map.
Thank you for help and sorry for my bad english, hope you guys understand me.
1.Define Sublass MKPointAnnotation.
class MyPointAnnotation: MKPointAnnotation {
var feedItem: LocationModel
}
2.Set MyPointAnnotation.feedItem to feedItem.
let item: LocationModel = feedItems[x] as! LocationModel
var poiCoodinates = CLLocationCoordinate2D()
poiCoodinates.latitude = CDouble(item.latitude!)!
poiCoodinates.longitude = CDouble(item.longitude!)!
let pin: MyPointAnnotation = MyPointAnnotation()
pin.coordinate = poiCoodinates
pin.feedItem = item // Important!
self.mapView.addAnnotation(pin)
3.Get feedItem in calloutAccessoryControlTapped delegate method.
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if let pin = view.annotation as? MyPointAnnotation {
print(pin.feedItem)
}
}
Sublass MKAnnotation add index property / object from feedItems array to the class and
see custom class MyAnnotation implemented there in swift customPinAnnotationButton
this idea but now i have only objective -c version
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
NSLog(#"wqwqwqwqwqw . . .");
MyAnnotation*ann = view.annotation;
NSLog(#"nammemmeme : %#",ann.weatherItem);
[self performSegueWithIdentifier:#"showDetails" sender:ann.weatherItem];
}
1.Define subclasses for Annotation
class PointAnnotation: MKPointAnnotation {
var indexAnnotation = 0
}
2.Mapview Delegate
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation.isMember(of: MKUserLocation.self) {
return nil
}
let identifier = "myAnnotation"
var annotationView: MKAnnotationView?
annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.image = UIImage(named:"Golf Courses.png")
annotationView?.canShowCallout = true
let callButton = UIButton(type: .detailDisclosure)
annotationView?.rightCalloutAccessoryView = callButton
annotationView?.sizeToFit()
} else {
annotationView!.annotation = annotation
}
}
3.Callaccessory button taped go to next view contoller
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
let obj = kStoryboardShops.instantiateViewController(withIdentifier: "ShopDetailsViewController") as! ShopDetailsViewController
if let annotation = view.annotation as? PointAnnotation {
obj.dicDetails = arrayOfItems[annotation.indexAnnotation]
}
let nav = UINavigationController(rootViewController: obj)
self.present(nav, animated: true, completion: nil)
}
}

didSelect for MKAnnotationView not firing

I have troubles to make a custom annotation at a MapView selectable. I was trying several ways, without success:
Using didSelect of MKMapViewDelegate
Using a UIButton which is added to the AnnotationView
Using UITapGestureRecognizer for the ImageView, which should be used for the annotation
You can find all these approaches commented in the code below:
override func viewDidLoad() {
super.viewDidLoad()
// some more initialization code
for item in items {
let annotation = IdentifiedMKPointAnnotation() // has only one additional property named "id"
annotation.coordinate = CLLocationCoordinate2D(latitude: item.spots[0].latitude!, longitude: item.spots[0].longitude!)
annotation.id = i
self.mapView.addAnnotation(annotation)
i += 1
}
}
// MARK: - MapViewDelegate
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let item = self.items[(annotation as! IdentifiedMKPointAnnotation).id!]
let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "")
//annotationView.canShowCallout = false
//annotationView.isEnabled = false
let imageView = UIImageView()
imageView.frame.size = CGSize(width: 40, height: 40)
imageView.layer.cornerRadius = 20
imageView.layer.masksToBounds = true
imageView.af_setImage(withURL: URL(string: item.images.count > 0 ? item.images[0] : item.image!)!)
imageView.contentMode = .scaleAspectFill
//let gr = UIGestureRecognizer(target: self, action: #selector(annotationSelected(_:)))
//imageView.addGestureRecognizer(gr)
//imageView.isUserInteractionEnabled = true
//let button = UIButton()
//button.frame.size = CGSize(width: 40, height: 40)
//button.setImage(#imageLiteral(resourceName: "play_arrow"), for: .normal)
//button.addTarget(self, action: #selector(annotationSelected(_:)), for: .touchUpInside)
annotationView.addSubview(imageView)
//annotationView.addSubview(button)
return annotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
performSegue(withIdentifier: "showDetail", sender: self.items[(view.annotation as! IdentifiedMKPointAnnotation).id!])
view.setSelected(false, animated: false)
}
func annotationSelected(_ sender: UIImageView) {
performSegue(withIdentifier: "showDetail", sender: self.items[((sender.superview as! MKAnnotationView).annotation as! IdentifiedMKPointAnnotation).id!])
}
Any ideas why the action(s) isn't/aren't firing?
If the annotation's title is blank, didSelect delegate is not called. Try the following code.
let annotation = IdentifiedMKPointAnnotation()
annotation.title = "title"
Just found the solution based on the following post: https://stackoverflow.com/a/28671680/6010489
It's enough to set height and width of the annotationview:
annotationView.frame.size.height = 40
annotationView.frame.size.width = 40
For some reason I had the same problem when mapView's delegate was set in Storyboard (Xcode 10.2, Swift 5.0). So this was not working:
However, when I removed the connection and did it in code instead it worked fine:
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
}
A Swift 5 bug maybe? Storyboard solution works with Objective-C.

MKMapView does call didSelect callback only once

I'm using a custom annotation in my mapkit project (in swift 3) to show multiple annotations on the map. It's showing and I can click on annotationn but only the first time. For openning the annotation again I need to click everywhere on the map and click again the annotation. Could anybody help me ? Thank you in advance.
Here are the functions I'm using:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation
{
return nil
}
var annotationView = self.map.dequeueReusableAnnotationView(withIdentifier: "Pin")
if annotationView == nil{
annotationView = AnnotationView(annotation: annotation, reuseIdentifier: "Pin")
annotationView?.canShowCallout = false
}else{
annotationView?.annotation = annotation
}
if (indexPin > 0) {
indexPin = indexPin - 1
let pin : PinAnnotation = pinAnotationList[indexPin]
annotationView?.image = UIImage(named: pin.imageName)
}
return annotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)
{
if view.annotation is MKUserLocation
{
return
}
let pin = view.annotation as! PinAnnotation
if pin.userType == "O" {
if (currentLatitude == 0 || currentLatitude2 == 0) {
self.showAlert(self, message: "It's necessary to set origin and destiny addresses")
return
}
AppVars.DriverId = pin.userId
AppVars.VehicleId = pin.vehicleId
AppVars.LatitudeDriver = pin.coordinate.latitude
AppVars.LongitudeDriver = pin.coordinate.longitude
performSegue(withIdentifier: "callDriverPopupSegue", sender: self)
}
else {
let customView = (Bundle.main.loadNibNamed("AnnotationView", owner: self, options: nil))?[0] as! CustomCalloutView
var calloutViewFrame = customView.frame;
let point = CGPoint(x: calloutViewFrame.size.width/2 + 15,y :calloutViewFrame.size.height - 10)
calloutViewFrame.origin = point
customView.frame = calloutViewFrame;
customView.titleLabel.text = pin.title
view.addSubview(customView)
}
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
if (view.isKind(of: PinAnnotation.self))
{
for subview in view.subviews
{
subview.removeFromSuperview()
}
}
if (view.isKind(of: AnnotationView.self))
{
for subview in view.subviews
{
subview.removeFromSuperview()
}
}
}
Class PinAnnotation
import MapKit
class PinAnnotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var userId: Int!
var vehicleId:Int!
var userType: String!
var imageName: String!
var title: String!
init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
}
}
Class AnnotationView
import MapKit
class AnnotationView: MKAnnotationView
{
}
I've found a solution ! The situation occurred when called performSegue(withIdentifier: "callDriverPopupSegue", sender: self) in didSelect because the annotation that was clicked keeped selected. So I add the code bellow in mapview controller to deselect the annotation and after that I was able to click for the second time.
override func viewWillAppear(_ animated: Bool) {
DispatchQueue.main.async {
for item in self.map.selectedAnnotations {
self.map.deselectAnnotation(item, animated: false)
}
}
}

Transfer of Description and Image using Segue

I am currently trying to create a map app that has around 20 pins. I have made a segue so that the Pin's Annotation's Title is transferred. However now I need to implement it so that a description is correctly selected from a series of 20 .txt file descriptions and 20 images. But I believe I am able to do it with one Segue.
Here is my current code
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate,CLLocationManagerDelegate {
#IBOutlet weak var MapView: MKMapView!
let manager = CLLocationManager()
var artworkPin:Artwork!
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//let location = locations[0]
//let span:MKCoordinateSpan = MKCoordinateSpanMake(0.02, 0.02)
//let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
}
override func viewDidLoad() {
super.viewDidLoad()
// tracking user's location
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
// Setting up Map
let distanceSpan:CLLocationDegrees = 2000
MapView.setRegion(MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(-39.0556253, 174.0752278), distanceSpan, distanceSpan), animated: true)
MapView.showsUserLocation = true
MapView.delegate = self
// artwork on map
let windwandcoord: CLLocationCoordinate2D = CLLocationCoordinate2DMake(-39.055961,174.072288)
artworkPin = Artwork(title:"Wind Wand",locationName:"Majestic",discipline:"Statue",
coordinate:windwandcoord)
MapView.addAnnotation(artworkPin)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
if annotation is MKUserLocation {return nil}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
pinView!.calloutOffset = CGPoint(x: -5, y: 5)
let calloutButton = UIButton(type: .detailDisclosure)
pinView!.rightCalloutAccessoryView = calloutButton
pinView!.sizeToFit()
}
else {
pinView!.annotation = annotation
}
return pinView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
performSegue(withIdentifier: "no", sender:self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let ViewTwo = segue.destination as! ViewTwo
ViewTwo.artworkPin = self.artworkPin
}
}
I also don't think this will give the correct title if I add another pin am I correct? Because it will simply take the name of artworkPin rather than of any variable pin added.
Thanks for any help.

Resources