Detecting MapView finished changing region - ios

I have a MKMapView that has annotations. My goal is to hide the annotation, if one is selected, when the map finished scrolling.
When an annotation is called I assign the annotation into a variable to keep track of it.
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
lastSelectedAnnotation = view.annotation
}
I know of:
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool){ }
However, I cannot figure out (beginner here), how to detect that the map finished changing its region so I can call my function:
func hideSelectedAnnotation(_ mapView: MKMapView) {
DispatchQueue.main.async {
mapView.deselectAnnotation(self.lastSelectedAnnotation, animated: true)
self.lastSelectedAnnotation = nil
}
}
I hide the annotation also when an accessory button is tapped:
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl){
hideSelectedAnnotation(mapView)}
I have tried saving the coordinate of the region, and comparing them to the map but the map does not neccessarily center the annotation. I could also start a timer and when regionDidChangeAnimated is no longer called hide the annotation. But that seams like butchering it.
Thanks for any help!

I think you already figured it out...
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool){
// Call your function here
}
Should fire every time the map view region changes (unless the change was inflicted by the user's finger)
----- EDIT -----
Unfortunately, you have to detect user input using a UIPanGestureRecognizer.
I have used, with success, A UIPanGestureRecognizer like the following:
lazy var mapPanGestureRecognizer: UIPanGestureRecognizer = {
let gr = UIPanGestureRecognizer(target: self, action: #selector(draggedMap))
gr.delegate = self
return gr
}()
You will also have to add the UIPanGestureRecognizer to the map with
yourMap.addGestureRecognizer(mapPanGestureRecognizer)
You can then manage what happens in the #selector function by checking the state of the gesture, like so
#objc func draggedMap(panGestureRecognizer: UIPanGestureRecognizer) {
// Check to see the state of the passed panGestureRocognizer
if panGestureRecognizer.state == UIGestureRecognizer.State.began {
// Do something
}
}
The state is what allows you to determine if the user ended a gesture, is in the middle of a gesture, or began a gesture.
List of possible states

Related

Get the MKAnnotationView of user location

I'm trying to get the MKAnnotationView that displays the user location (blue dot) in MapKit to add a custom gesture recognizer. Is this possible?
I've tried via the delegate method but I don't know how to dequeue the view when I don't have the identifier string. If I had the identifier I could probably do something like the code below;
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
let userLocationAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "??", for: annotation)
userLocationAnnotationView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleStuff)))
return userLocationAnnotationView
}
}
EDIT
Ah, been stuck on this for hours and found the solution directly after I posted. I found two different ways of solving it with delegate methods. The first way could be via didSelect:
func mapView(_ mapView: MKMapView,
didSelect view: MKAnnotationView){
if view.annotation is MKUserLocation {
// User clicked on the blue dot
}
}
Or if a gesture recognizer is needed it could be done as below. Should probably add a check if the gesture recognizer already have been added since this function gets called every time an annotation view is added.
func mapView(_ mapView: MKMapView,
didAdd views: [MKAnnotationView]){
for view in views {
if view.annotation is MKUserLocation {
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleStuff)))
}
}
}

Swift Annotation Pin's Calloutbubble Gesture

I am searching an answer for adding gesture to the calloutbubble of annotation pin.
I tried different solutions, but they did not work for me.
Here is the latest one:
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView{
let rightButton = UIButton(type: UIButtonType.detailDisclosure)
let gesture = UITapGestureRecognizer(target: self, action: #selector(callout(gesture:)))
rightButton.addGestureRecognizer(gesture)
view.rightCalloutAccessoryView = rightButton
}
#objc func callout(gesture: UITapGestureRecognizer){
print("tapped")
}
Correct delegate method
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
///
}
plus
self.mapView.delegate = self

MapBox in Swift - Allowing a marker's annotation to have a button that links to a View

I have set up a simple app with a tabbed map view (map on tab 1) that reads info from a json file on a server (point info is stored in MySQL) with SwiftyJSON and Alamofire. The points are loaded into the map. What I would like to do is add a button to the annotation, which outlets to a different view tab and passes along the point's ID.
I have not tried anything yet as I have no idea where to get started and the documentation doesn't mention anything similar.
How does one go about adding an outlet to a map point annotation?
When you tap your pin the callout appears with a title and/or a subtitle. You need to add left and right callout accessory views to this callout. You do this by conforming to the MGLMapViewDelegate and implementing the following methods:
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}
func mapView(_ mapView: MGLMapView, leftCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? {
...your code here...
let deleteButton = UIButton(type: .custom)
deleteButton.tag = 100
}
func mapView(_ mapView: MGLMapView, rightCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? {
...your code here...
let infoButton = UIButton(type: .custom)
infoButton.tag = 101
}
func mapView(_ mapView: MGLMapView, annotation: MGLAnnotation, calloutAccessoryControlTapped control: UIControl) {
...your code here...
switch control.tag {
case 100:
// do some delete stuff
case 101:
// do some info stuff
default:
break
}
The MapBox example showing actual usage is here:
MapBox example. This example doesn't segue but you would just trigger a segue with the button tap instead of the UIAlert.
For future reference:
func mapView(_ mapView: MGLMapView, annotation: MGLAnnotation, calloutAccessoryControlTapped control: UIControl) {
// Hide the callout view.
// mapView.deselectAnnotation(annotation, animated: true)
performSegue(withIdentifier: "toDetail", sender: view)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("Seque toDetail")
// do stuff
}

Update lat and long when the mapview camera is being moved?

Here's my code, that works but it doesn't get updated and it's not accurate. I simply want to apply the camera lat and lng to another variable.
let cameraLat = self.mapView.camera.centerCoordinate.latitude
let cameraLng = self.mapView.camera.centerCoordinate.longitude
for google maps:
if you have set the mapView.delegate = self and you have implemented the GMSMapViewDelegate it's pretty easy to get the an event everytime the camera changes, so you mapView view changes.
you could either implement the func mapView(mapView: GMSMapView, didChangeCameraPosition position: GMSCameraPosition) or func mapView(mapView: GMSMapView, idleAtCameraPosition position: GMSCameraPosition) method.
and then access the new camera values (lat/lng) like you did before, so just reassign your variables to the new values.
or MapKit:
add delegate to class like
class ViewController: UIViewController, MKMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
...
mapView.delegate = self
}
}
This method is called whenever the currently displayed map region changes. During scrolling, this method may be called many times to report updates to the map position. Therefore, your implementation of this method should be as lightweight as possible to avoid affecting scrolling performance.
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let lat = mapView.camera.centerCoordinate.latitude
let lng = mapView.camera.centerCoordinate.longitude
}

determine if MKMapView was dragged/moved

Is there a way to determine if a MKMapView was dragged around?
I want to get the center location every time a user drags the map using CLLocationCoordinate2D centre = [locationMap centerCoordinate]; but I'd need a delegate method or something that fires as soon as the user navigates around with the map.
The code in the accepted answer fires when the region is changed for any reason. To properly detect a map drag you have to add a UIPanGestureRecognizer. Btw, this is the drag gesture recognizer (panning = dragging).
Step 1: Add the gesture recognizer in viewDidLoad:
-(void) viewDidLoad {
[super viewDidLoad];
UIPanGestureRecognizer* panRec = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(didDragMap:)];
[panRec setDelegate:self];
[self.mapView addGestureRecognizer:panRec];
}
Step 2: Add the protocol UIGestureRecognizerDelegate to the view controller so it works as delegate.
#interface MapVC : UIViewController <UIGestureRecognizerDelegate, ...>
Step 3: And add the following code for the UIPanGestureRecognizer to work with the already existing gesture recognizers in MKMapView:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
Step 4: In case you want to call your method once instead 50 times per drag, detect that "drag ended" state in your selector:
- (void)didDragMap:(UIGestureRecognizer*)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateEnded){
NSLog(#"drag ended");
}
}
This is the only way that worked for me that detects pan as well as zoom changes initiated by user:
- (BOOL)mapViewRegionDidChangeFromUserInteraction
{
UIView *view = self.mapView.subviews.firstObject;
// Look through gesture recognizers to determine whether this region change is from user interaction
for(UIGestureRecognizer *recognizer in view.gestureRecognizers) {
if(recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateEnded) {
return YES;
}
}
return NO;
}
static BOOL mapChangedFromUserInteraction = NO;
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
mapChangedFromUserInteraction = [self mapViewRegionDidChangeFromUserInteraction];
if (mapChangedFromUserInteraction) {
// user changed map region
}
}
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
if (mapChangedFromUserInteraction) {
// user changed map region
}
}
(Just the) Swift version of #mobi's excellent solution:
private var mapChangedFromUserInteraction = false
private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
let view = self.mapView.subviews[0]
// Look through gesture recognizers to determine whether this region change is from user interaction
if let gestureRecognizers = view.gestureRecognizers {
for recognizer in gestureRecognizers {
if( recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Ended ) {
return true
}
}
}
return false
}
func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction()
if (mapChangedFromUserInteraction) {
// user changed map region
}
}
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if (mapChangedFromUserInteraction) {
// user changed map region
}
}
Swift 3 solution to Jano's answer above:
Add the Protocol UIGestureRecognizerDelegate to your ViewController
class MyViewController: UIViewController, UIGestureRecognizerDelegate
Create the UIPanGestureRecognizer in viewDidLoad and set delegate to self
viewDidLoad() {
// add pan gesture to detect when the map moves
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.didDragMap(_:)))
// make your class the delegate of the pan gesture
panGesture.delegate = self
// add the gesture to the mapView
mapView.addGestureRecognizer(panGesture)
}
Add a Protocol method so your gesture recognizer will work with the existing MKMapView gestures
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
Add the method that will be called by the selector in your pan gesture
func didDragMap(_ sender: UIGestureRecognizer) {
if sender.state == .ended {
// do something here
}
}
Look at the MKMapViewDelegate reference.
Specifically, these methods may be useful:
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
Make sure your map view's delegate property is set so those methods get called.
In my experience, similar to "search while typing", I found a timer is the most reliable solution. It removes the need for adding additional gesture recognizers for panning, pinching, rotating, tapping, double tapping, etc.
The solution is simple:
When the map region changes, set/reset the timer
When the timer fires, load markers for the new region
import MapKit
class MyViewController: MKMapViewDelegate {
#IBOutlet var mapView: MKMapView!
var mapRegionTimer: NSTimer?
// MARK: MapView delegate
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
setMapRegionTimer()
}
func setMapRegionTimer() {
mapRegionTimer?.invalidate()
// Configure delay as bet fits your application
mapRegionTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "mapRegionTimerFired:", userInfo: nil, repeats: false)
}
func mapRegionTimerFired(sender: AnyObject) {
// Load markers for current region:
// mapView.centerCoordinate or mapView.region
}
}
Another possible solution is to implement touchesMoved: (or touchesEnded:, etc.) in the view controller that holds your map view, like so:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
for (UITouch * touch in touches) {
CGPoint loc = [touch locationInView:self.mapView];
if ([self.mapView pointInside:loc withEvent:event]) {
#do whatever you need to do
break;
}
}
}
This might be simpler than using gesture recognizers, in some cases.
A lot of these solutions are on the hacky / not what Swift intended side, so I opted for a cleaner solution.
I simply subclass MKMapView and override touchesMoved. While this snippet does not include it, I would recommend creating a delegate or notification to pass on whatever information you want regarding the movement.
import MapKit
class MapView: MKMapView {
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
print("Something moved")
}
}
You will need to update the class on your storyboard files to point to this subclass, as well as modify any maps you create through other means.
As noted in the comments, Apple discourages the use of subclassing MKMapView. While this falls to the discretion of the developer, this particular usage does not modify the behavior of the map & has worked for me without incident for over three years. However, past performance does not indicate future compatibility, so caveat emptor.
You can also add a gesture recognizer to your map in Interface Builder. Link it up to an outlet for its action in your viewController, I called mine "mapDrag"...
Then you'll do something like this in your viewController's .m:
- (IBAction)mapDrag:(UIPanGestureRecognizer *)sender {
if(sender.state == UIGestureRecognizerStateBegan){
NSLog(#"drag started");
}
}
Make sure you have this there too:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
Of course you'll have to make your viewController a UIGestureRecognizerDelegate in your .h file in order for that to work.
Otherwise the map's responder is the only one who hears the gesture event.
I know this is an old post but here my Swift 4/5 code of Jano's answer whit Pan and Pinch gestures.
class MapViewController: UIViewController, MapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.didDragMap(_:)))
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(self.didPinchMap(_:)))
panGesture.delegate = self
pinchGesture.delegate = self
mapView.addGestureRecognizer(panGesture)
mapView.addGestureRecognizer(pinchGesture)
}
}
extension MapViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
#objc func didDragMap(_ sender: UIGestureRecognizer) {
if sender.state == .ended {
//code here
}
}
#objc func didPinchMap(_ sender: UIGestureRecognizer) {
if sender.state == .ended {
//code here
}
}
}
Enjoy!
To recognize when any gesture ended on the mapview:
[https://web.archive.org/web/20150215221143/http://b2cloud.com.au/tutorial/mkmapview-determining-whether-region-change-is-from-user-interaction/)
This is very useful for only performing a database query after the user is done zooming/rotating/dragging the map around.
For me, the regionDidChangeAnimated method only was called after the gesture was done, and didn't get called many times while dragging/zooming/rotating, but it's useful to know if it was due to a gesture or not.
You can check for animated property
if false then user dragged map
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if animated == false {
//user dragged map
}
}
Jano's answer worked for me, so I thought I'd leave an updated version for Swift 4 / XCode 9 as I'm not particularly proficient in Objective C and I'm sure there are a few others that aren't either.
Step 1: Add this code in viewDidLoad:
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(didDragMap(_:)))
panGesture.delegate = self
Step 2: Make sure your class conforms to the UIGestureRecognizerDelegate:
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UIGestureRecognizerDelegate {
Step 3: Add the following function to make sure your panGesture will work simultaneously with other gestures:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
Step 4: And ensuring your method isn't called "50 times per drag" as Jano rightly points out:
#objc func didDragMap(_ gestureRecognizer: UIPanGestureRecognizer) {
if (gestureRecognizer.state == UIGestureRecognizerState.ended) {
redoSearchButton.isHidden = false
resetLocationButton.isHidden = false
}
}
*Note the addition of #objc in the last step. XCode will force this prefix on your function in order for it compile.
I was trying to have an annotation in the center of the map that is always at the center of the map no matter what the uses does. I tried several of the approaches mentioned above, and none of them were good enough. I eventually found a very simple way of solving this, borrowing from the Anna's answer and combining with Eneko's answer. It basically treats the regionWillChangeAnimated as the start of a drag, and regionDidChangeAnimated as the end of one, and uses a timer to update the pin in real-time:
var mapRegionTimer: Timer?
public func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
mapRegionTimer?.invalidate()
mapRegionTimer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { (t) in
self.myAnnotation.coordinate = CLLocationCoordinate2DMake(mapView.centerCoordinate.latitude, mapView.centerCoordinate.longitude);
self.myAnnotation.title = "Current location"
self.mapView.addAnnotation(self.myAnnotation)
})
}
public func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
mapRegionTimer?.invalidate()
}
enter code hereI managed to do implement this in easiest way, which handles all interaction with map (tapping/double/N tapping with 1/2/N fingers, pan with 1/2/N fingers, pinch and rotations
Create gesture recognizer and add to map view's container
Set gesture recognizer's delegate to some object implementing UIGestureRecognizerDelegate
Implement gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) method
private func setupGestureRecognizers()
{
let gestureRecognizer = UITapGestureRecognizer(target: nil, action: nil)
gestureRecognizer.delegate = self
self.addGestureRecognizer(gestureRecognizer)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool
{
self.delegate?.mapCollectionViewBackgroundTouched(self)
return false
}
this worked for me with swift 5
let manager = CLLocationManager()
#IBOutlet weak var map: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
manager.delegate = self
manager.requestWhenInUseAuthorization()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.startUpdatingLocation()
map.delegate = self
}
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if mapView.userLocation.isEqual(annotation) {
return nil;
}
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "AnnotationView")
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "AnnotationView")
}
annotationView?.isDraggable = true
annotationView?.canShowCallout = true
return annotationView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationView.DragState, fromOldState oldState: MKAnnotationView.DragState) {
switch newState {
case .starting:
print(".starting")
case .dragging:
print(".dragging")
case .ending:
print(".ending")
case .canceling:
print(".canceling")
case .none:
print(".none")
default: break
}
}
}
Updated 2023 version of the accepted answer, except it checks all mapView subviews and not just the first subview (to prevent future complications with OS updates). It also doesn't check for the .began state of the gesture, which I found unneeded for my use-case, so feel free to add it within the .contains(where:) block if your use-case requires.
/// Obtains all gestures within the mapView subviews to see if any
/// of the gestures changed state to began or ended.
/// - Returns: True if any gesture within the mapView changed state to ended, false otherwise.
private var regionDidChangeFromUserInteraction: Bool {
self.map.subviews // Look at all mapView subviews
.compactMap { $0.gestureRecognizers } // look at all subview gesture recognizers
.reduce([], +) // Reduces an Array of Arrays of gestures to an Array of gestures
.contains(where: { $0.state == .ended }) // if ended returns true else false
}
/// The framework calls this method at the beginning of a change to the map’s visible region.
func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
guard regionDidChangeFromUserInteraction else {
print("mapView:regionWillChangeAnimated - No Interaction detected.")
return
}
print("mapView:regionWillChangeAnimated - User Interaction detected.")
}
/// The map view calls this method at the end of a change to the map’s visible region.
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
guard regionDidChangeFromUserInteraction else {
print("mapView:regionDidChangeAnimated - No Interaction detected.")
return
}
print("mapView:regionDidChangeAnimated - User Interaction detected.")
}
First, make sure your current view controller is a delegate of the map. So set your Map View delegate to self and add MKMapViewDelegate to your view controller. Example below.
class Location_Popup_ViewController: UIViewController, MKMapViewDelegate {
// Your view controller stuff
}
And add this to your map view
var myMapView: MKMapView = MKMapView()
myMapView.delegate = self
Second, add this function which is fired when the map is moved. It will filter out any animations and only fire if interacted with.
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if !animated {
// User must have dragged this, filters out all animations
// PUT YOUR CODE HERE
}
}

Resources