Swift GestureRecognizers with MKMapKit - Drop pin and drag - ios

I am trying to use a number of UIGestureReconizers with an MKMapView onto which the user can drop a pin and drag it around. It has a callout. I am implementing this in a TabbarController and also within a NavigationController. I currently have:
1) A PanGestureRecognizer animates the Tabbar and Navigation item off the screen. This works fine without interfering with panning the map.
2) A TapGestureRecognizer set to one tap animates the two items from 1) back onto the screen.
3) A TapGestureRecognizer set to two taps allows the underlying MKMapView zoom functionality to work. This GestureRecognizer's delegate has gestureRecognizer.shouldRecognizeSimultaneouslyWithGestureRecognizer set to true
These are setup in viewDidLoad as follows:
// This sets up the pan gesture recognizer to hide the bars from the UI.
let panRec: UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: "didDragMap:")
panRec.delegate = self
mapView.addGestureRecognizer(panRec)
// This sets up the tap gesture recognizer to un-hide the bars from the UI.
let singleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "didTapMap:")
singleTap.delegate = self
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
mapView.addGestureRecognizer(singleTap)
// This sets up the double tap gesture recognizer to enable the zoom facility.
// In order to pass double-taps to the underlying `MKMapView` the delegate for this recognizer (self) needs to return true from
// gestureRecognizer.shouldRecognizeSimultaneouslyWithGestureRecognizer
let doubleTap: UITapGestureRecognizer = UITapGestureRecognizer()
doubleTap.numberOfTapsRequired = 2
doubleTap.numberOfTouchesRequired = 1
doubleTap.delegate = self
mapView.addGestureRecognizer(doubleTap)
// This delays the single-tap recognizer slightly and ensures that it will NOT fire if there is a double-tap
singleTap.requireGestureRecognizerToFail(doubleTap)
My problem occurs when I try to implement a UILongPressGestureRecognizer to allow the dropping of a pin onto the map. I'm trying to use the following added to viewDidLoad:
// This sets up the long tap to drop the pin.
let longTap: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "didLongTapMap:")
longTap.delegate = self
longTap.numberOfTapsRequired = 0
longTap.minimumPressDuration = 0.5
mapView.addGestureRecognizer(longTap)
This is my action method:
func didLongTapMap(gestureRecognizer: UIGestureRecognizer) {
// Get the spot that was tapped.
let tapPoint: CGPoint = gestureRecognizer.locationInView(mapView)
let touchMapCoordinate: CLLocationCoordinate2D = mapView.convertPoint(tapPoint, toCoordinateFromView: mapView)
var viewAtBottomOfHierarchy: UIView = mapView.hitTest(tapPoint, withEvent: nil)
if let viewAtBottom = viewAtBottomOfHierarchy as? MKPinAnnotationView {
return
} else {
if .Began == gestureRecognizer.state {
// Delete any existing annotations.
if mapView.annotations.count != 0 {
mapView.removeAnnotations(mapView.annotations)
}
annotation = MKPointAnnotation()
annotation.coordinate = touchMapCoordinate
mapView.addAnnotation(annotation)
_isPinOnMap = true
findAddressFromCoordinate(annotation.coordinate)
updateLabels()
}
}
}
This does indeed allow a pin to be dropped on a long tap and a single tap will display the callout BUT a second tap to hold and drag causes a second pin to drop if the drag isn't started sufficiently quickly. This second pin drops into the space the previous pin was hovering in and can be dragged by the user, but the new pin dropping is awkward and wrong looking.
I'm trying to use the line:
if let viewAtBottom = viewAtBottomOfHierarchy as? MKPinAnnotationView {
to return the tap to the MKMapView and prevent another pin being dropped but the return never gets called even though a breakpoint on this line shows viewAtBottom is of type MapKit.MKPinAnnotationView. Any ideas where I'm going wrong?

I think I might have the answer to your problem if I understood it correctly.
Your having problems when one pin is dropped and then dragging the screen around without placing another pin, correct?
This is my code, I have been making something similar and this seems to work for me.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet var map: MKMapView!
var manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:)))
uilpgr.minimumPressDuration = 2
map.addGestureRecognizer(uilpgr)
if activePlace == -1 {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
self.map.showsUserLocation = true
} else {
//GET PLACE DETAILS TO DISPLAY ON MAP
if places.count > activePlace {
if let name = places[activePlace]["name"]{
if let lat = places[activePlace]["lat"]{
if let lon = places[activePlace]["lon"]{
if let latitude = Double(lat) {
if let longitude = Double(lon) {
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegionMake(coordinate, span)
self.map.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = name
self.map.addAnnotation(annotation)
}
}
}
}
}
}
}
}
func longpress(gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == UIGestureRecognizerState.began {
let touchPoint = gestureRecognizer.location(in: self.map)
let newCoordinate = self.map.convert(touchPoint, toCoordinateFrom: self.map)
let location = CLLocation(latitude: newCoordinate.latitude, longitude: newCoordinate.longitude)
var title = ""
CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
if error != nil {
print(error)
} else {
if let placemark = placemarks?[0] {
if placemark.subThoroughfare != nil {
title += placemark.subThoroughfare! + " "
}
if placemark.thoroughfare != nil {
title += placemark.thoroughfare! + " "
}
}
}
if title == "" {
title = "Added \(NSDate())"
}
let annotation = MKPointAnnotation()
annotation.coordinate = newCoordinate
annotation.title = title
self.map.addAnnotation(annotation)
places.append(["name": title, "lat":String(newCoordinate.latitude), "lon":String(newCoordinate.longitude)])
UserDefaults.standard.set(places, forKey: "places")
})
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = CLLocationCoordinate2D(latitude: locations[0].coordinate.latitude, longitude: locations[0].coordinate.longitude)
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let region = MKCoordinateRegion(center: location, span: span)
self.map.setRegion(region, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Hope it helps, the problem might also be that your minimum longpress duration is only 0.5.

Related

how to delete one overlay when another is added in Xcode swift 3

I'm trying to build a function in my app which allows the user to drop a pin in a location and show a radius around that location. I only want one pin and one radius to show at a time.
I have worked out how to drop a pin and add the radius, and to remove the old pin when the new one is dropped, but cannot work out how to delete the circle overlay so that only one is show, around the most recent dropped pin.
Code is below for my map view controller. help much appreciated!
import UIKit
import CoreLocation
import MapKit
class MapVC: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
//connect map
#IBOutlet weak var mapInterface: MKMapView!
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations[0] //all locations will be stored in CLLocation array, we request 0th element (the newest data which equals the most recent location)
print(location)
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.05, 0.05)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
print(location)
mapInterface.setRegion(region, animated: true)
self.mapInterface.showsUserLocation = true
}
//add pin drop
#IBAction func pinDrop(_ sender: UILongPressGestureRecognizer) {
//Pin drop annotation - get attributes of where to drop the pin
let location = sender.location(in: self.mapInterface)
let locCoord = self.mapInterface.convert(location, toCoordinateFrom: self.mapInterface)
let annotation = MKPointAnnotation()
//set pin characteristics
annotation.coordinate = locCoord
annotation.title = "Virtual location"
annotation.subtitle = "Dropped Pin"
//delete one pin once another is dropped
self.mapInterface.removeAnnotations(mapInterface.annotations)
//add pin annotation to map view
self.mapInterface.addAnnotation(annotation)
//print locCoord to console to check it worked
print(locCoord)
//create circle attributes
let cent = locCoord
let rad: Double = 500 //adjust radius to make circle bigger.
let circle = MKCircle(center: cent, radius: rad)
//print circle to console to check it worked
print(circle)
}
//add circle overlay
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay.isKind(of: MKCircle.self){
let circleRenderer = MKCircleRenderer(overlay: overlay)
circleRenderer.fillColor = UIColor.blue.withAlphaComponent(0.05)
circleRenderer.strokeColor = UIColor.blue
circleRenderer.lineWidth = 0.5
return circleRenderer
}
self.mapInterface.removeOverlays(overlay as! [MKOverlay])
return MKOverlayRenderer(overlay: overlay)
}
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
manager.stopUpdatingLocation()
}
}
Add the following code in pinDrop method.
self.mapInterface.removeOverlays(self.mapInterface.overlays)
mapView.removeOverlays(mapView.overlays) will do the trick
however, if i were you i'd rather update the annotation location instead of recreating a new one and remove the old one
to do that you will take that line
let annotation = MKPointAnnotation()
and put it above viewDidLoad method
and instead of :
//delete one pin once another is
self.mapInterface.removeAnnotations(mapInterface.annotations)
//add pin annotation to map view
self.mapInterface.addAnnotation(annotation)
it will be :
if self.mapInterface.annotations.count == 0 {
self.mapInterface.addAnnotation(annotation)
}

How to detect the mapView was moved in Swift and update zoom

I'm trying to set a minimum zoom level on my map in Swift 2. I can't find any documentation on how to restrict a map from being zoomed too far in. What I've decided to try is to monitor for map movement (such as drag or zoom) and then set MKZoomScaleback to a minimum.
Most of the answers I've found for regionDidChangeAnimated are in Objective C, which I don't know and I'm having trouble converting them to Swift.
I tried implementing #hEADcRASH's answer: https://stackoverflow.com/a/30924768/4106552, but it doesn't trigger and print anything to the console when the map is moved in the simulator.
Can anyone tell me what I'm doing wrong? I'm new to Swift, so it could be a small error. Also, let me know if there is a lightweight way to solve for restricting the zoom level on a map. I'm worried that the monitor for movement will slow down the map animation a bit. Thanks for the help.
Here is my view controller.
import UIKit
import Parse
import MapKit
class SearchRadiusViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var map: MKMapView!
#IBOutlet weak var menuBtn: UIBarButtonItem!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
//menu button control
if self.revealViewController() != nil {
menuBtn.target = self.revealViewController()
menuBtn.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
//user location
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//set map
let location:CLLocationCoordinate2D = manager.location!.coordinate
let latitude = location.latitude
let longitude = location.longitude
let latDelta:CLLocationDegrees = 0.1
let longDelta:CLLocationDegrees = 0.1
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
let maplocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(maplocation, span)
map.setRegion(region, animated: true)
//stop updating location, only need user location once to position map.
manager.stopUpdatingLocation()
}
//Attempt to monitor for map movement based on hEADcRASH's answer.
private var mapChangedFromUserInteraction = false
private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
let view = self.map.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) {
print("yes")
mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction()
if (mapChangedFromUserInteraction) {
// user changed map region
print("user changed map in WILL")
}
}
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
print("yes ddd")
if (mapChangedFromUserInteraction) {
// user changed map region
print("user changed map in Did")
}
}
}
After reviewing and combining a number of other questions/answers and the help of #lorenzoliveto I've got it working in Swift. Please leave a comment if there a better/more lightweight way to achieve the same thing.
I added self.map.delegate = self to the viewDidLoad function.
Below is the code for how I'm monitoring for map movement and then once a user has zoomed in "too far" and the width of the map goes below 2 miles I then zoom out the map using mapView.setRegion.
private var mapChangedFromUserInteraction = false
private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
let view = self.map.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 will change map region
print("user WILL change map.")
// calculate the width of the map in miles.
let mRect: MKMapRect = mapView.visibleMapRect
let eastMapPoint = MKMapPointMake(MKMapRectGetMinX(mRect), MKMapRectGetMidY(mRect))
let westMapPoint = MKMapPointMake(MKMapRectGetMaxX(mRect), MKMapRectGetMidY(mRect))
let currentDistWideInMeters = MKMetersBetweenMapPoints(eastMapPoint, westMapPoint)
let milesWide = currentDistWideInMeters / 1609.34 // number of meters in a mile
print(milesWide)
print("^miles wide")
// check if user zoomed in too far and zoom them out.
if milesWide < 2.0 {
var region:MKCoordinateRegion = mapView.region
var span:MKCoordinateSpan = mapView.region.span
span.latitudeDelta = 0.04
span.longitudeDelta = 0.04
region.span = span;
mapView.setRegion(region, animated: true)
print("map zoomed back out")
}
}
}
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if (mapChangedFromUserInteraction) {
// user changed map region
print("user CHANGED map.")
print(mapView.region.span.latitudeDelta)
print(mapView.region.span.longitudeDelta)
// calculate the width of the map in miles.
let mRect: MKMapRect = mapView.visibleMapRect
let eastMapPoint = MKMapPointMake(MKMapRectGetMinX(mRect), MKMapRectGetMidY(mRect))
let westMapPoint = MKMapPointMake(MKMapRectGetMaxX(mRect), MKMapRectGetMidY(mRect))
let currentDistWideInMeters = MKMetersBetweenMapPoints(eastMapPoint, westMapPoint)
let milesWide = currentDistWideInMeters / 1609.34 // number of meters in a mile
print(milesWide)
print("^miles wide")
// check if user zoomed in too far and zoom them out.
if milesWide < 2.0 {
var region:MKCoordinateRegion = mapView.region
var span:MKCoordinateSpan = mapView.region.span
span.latitudeDelta = 0.04
span.longitudeDelta = 0.04
region.span = span;
mapView.setRegion(region, animated: true)
print("map zoomed back out")
}
}
UPDATE: 3/7, I discovered an interesting bug in the implementation above. On the simulator it works fine when clicking to zoom, but when you use the pinch to zoom (option + click) the simulator stops allowing you to drag the map around after it animates the zoom back out. This also happened on the beta version on my iphone. I added dispatch_async around the blocks that animate that map back to their position and it appears to be working on the simulator. It no longer appears frozen after it animates and I can continue to drag around the map and try to zoom in.
dispatch_async(dispatch_get_main_queue(), {
var region:MKCoordinateRegion = mapView.region
var span:MKCoordinateSpan = mapView.region.span
span.latitudeDelta = 0.04
span.longitudeDelta = 0.04
region.span = span;
mapView.setRegion(region, animated: true)
print("map zoomed back out")
})
The solution that works for me is one where I set the zoom range. This approach may not have been available at the time the question was asked.
The code fragment below is what I use. I'm not entirely sure what the distance units are, but I believe they are meters. Figuring out what range works in a given instance may be a matter of trial and error.
let mapView = MKMapView(frame: .zero)
let zoomRange = MKMapView.CameraZoomRange(
minCenterCoordinateDistance: 120000,
maxCenterCoordinateDistance: 1600000
)
mapView.cameraZoomRange = zoomRange

SWIFT 2 : Problems with the first swipe gesture on a MapView

I have a issue with my swipe gesture on a MapView, to be more accurate I have issues with the first swipe gesture on a MapView because it does not does a function & moves the screen at the same time.
The code recognize my location, put an annotation on me, and runs a 5 sec timer that allows the app to add new annotations only every 5 secs. The MapView follows my path as usually. All good so far. Check the pic of my simulator at the end.
Then it occurred to me that it would be a good idea to allow the user to scape from that region and explore the rest of the map. The user can do that only swiping in any direction. And when the user is at any other location he can press the "getBack" button to center the map on his current location. All works good too.
The issue is that when the gesture Swipe is detected , that first swipe does not move the screen. It is only the second swift which does it.
I think that may be the first swipe only stops the map from following my path, and then the second one is the one that moves the screen.
Is there a way for the first swipe to stop following my path and move the map at the same time ?
I hope I made myself clear :(
The Code of the ViewController:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet var map: MKMapView!
var locationManager = CLLocationManager()
let latDelta:CLLocationDegrees = 0.05
let longDelta:CLLocationDegrees = 0.05
var reStartCountClock = true
var getBackInPlace = true
var timer = NSTimer()
#IBAction func getBack(sender: AnyObject) {
getBackInPlace = true
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
let uilpgr = UILongPressGestureRecognizer(target: self, action: "actionWhenPressed:")
uilpgr.minimumPressDuration = 1
map.addGestureRecognizer(uilpgr)
let uilpgrD = UISwipeGestureRecognizer(target: self, action:Selector("handleSwipe:"))
uilpgrD.direction = .Down
let uilpgrU = UISwipeGestureRecognizer(target: self, action:Selector("handleSwipe:"))
uilpgrU.direction = .Up
let uilpgrR = UISwipeGestureRecognizer(target: self, action:Selector("handleSwipe:"))
uilpgrR.direction = .Right
let uilpgrL = UISwipeGestureRecognizer(target: self, action:Selector("handleSwipe:"))
uilpgrL.direction = .Left
map.addGestureRecognizer(uilpgrD)
map.addGestureRecognizer(uilpgrR)
map.addGestureRecognizer(uilpgrL)
map.addGestureRecognizer(uilpgrU)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locationOnline:CLLocation = locations[0]
let spanOnline:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
let centerOnline:CLLocationCoordinate2D = CLLocationCoordinate2DMake(locationOnline.coordinate.latitude, locationOnline.coordinate.longitude)
let regionOnline:MKCoordinateRegion = MKCoordinateRegionMake(centerOnline, spanOnline)
if getBackInPlace == true {
self.map.setRegion(regionOnline, animated: true)
}
if reStartCountClock == true {
timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "Anota", userInfo: nil, repeats: true)
reStartCountClock = false
let annotationOnline = MKPointAnnotation()
annotationOnline.title = "Updated Location"
annotationOnline.subtitle = "Pin Pam Pum"
annotationOnline.coordinate = centerOnline
self.map.addAnnotation(annotationOnline)
}
}
func handleSwipe (gestureRecognizer: UIGestureRecognizer)
{
getBackInPlace = false
print("Entra en el gesto")
}
func Anota (){
reStartCountClock = true
timer.invalidate()
}
func actionWhenPressed (gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == UIGestureRecognizerState.Began
{
getBackInPlace = false
print("Gesture Recognized")
let touch = gestureRecognizer.locationInView(self.map)
let touchCoordinate:CLLocationCoordinate2D = map.convertPoint(touch, toCoordinateFromView: self.map)
let touchAnnotation = MKPointAnnotation()
touchAnnotation.coordinate = touchCoordinate
touchAnnotation.title = "You tapped here"
touchAnnotation.subtitle = "It is a recommended place"
self.map.addAnnotation(touchAnnotation)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The Simulator:

Keep the pin (MKAnnotation) on the center when user scroll the map

I would like keep the MKAnnotaion on the centre of the screen when the user scoll the map like Careem app:
So far I managed to show the pin, update the pin position but when I scroll the map, the annotation in my code initially moves and then gets back to the centre. I would like the pin to remain on the centre.
#IBOutlet var mapView: MKMapView!
var centerAnnotation = MKPointAnnotation()
var manager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
manager = CLLocationManager() //instantiate
manager.delegate = self // set the delegate
manager.desiredAccuracy = kCLLocationAccuracyBest // required accurancy
manager.requestWhenInUseAuthorization() // request authorization
manager.startUpdatingLocation() //update location
var lat = manager.location.coordinate.latitude // get lat
var long = manager.location.coordinate.longitude // get long
var coordinate = CLLocationCoordinate2DMake(lat, long)// set coordinate
var latDelta:CLLocationDegrees = 0.01 // set delta
var longDelta:CLLocationDegrees = 0.01 // set long
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
var region:MKCoordinateRegion = MKCoordinateRegionMake(coordinate, span)
self.mapView.setRegion(region, animated: true)
centerAnnotation.coordinate = mapView.centerCoordinate
self.mapView.addAnnotation(centerAnnotation)
}
func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) {
centerAnnotation.coordinate = mapView.centerCoordinate;
}
****UPDATE****
As suggested by Anna I have added a view to the map. Here the code:
var newPoint = self.mapView.convertCoordinate(mapView.centerCoordinate, toPointToView: self.view)
var pinImage = UIImage(named: "yoga_pins.png")
var imageView = UIImageView(image: pinImage) // set as you want
imageView.image = pinImage
imageView.backgroundColor = UIColor.clearColor()
imageView.contentMode = UIViewContentMode.Center
imageView.center.y = newPoint.y
imageView.center.x = newPoint.x
self.view.addSubview(imageView)
the only problem is that when the map is loaded the first time, the annotation which is located on the mapView.centerCoordinate and I am gonna use to get the latitude and longitude:
when I then scroll the map, the pin moves in the correct position (under the image):
func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) {
centerAnnotation.coordinate = mapView.centerCoordinate;
}
I recommend you DSCenterPinMapView
It is a custom MapView with an animated and customizable center pin useful for selecting locations in map.
You should install the Pod and then, as a solution to your question you should implement the delegate so that you can get the location where pin drops.
pinMapView.delegate = self
extension MyViewController: DSCenterPinMapViewDelegate {
func didStartDragging() {
// My custom actions
}
func didEndDragging() {
// My custom actions
selectedLocation = pinMapView.mapview.centerCoordinate
}
}
You can use custom button. Add that button on centre of the map. Just show and hide that button according to your conditions.
So when you move map that button stay on same position that is centre of the map.

UILongPressGestureRecognizer getting fired twice

UILongPressGestureRecognizer is getting fired twice when user long presses on a map for over 2-4 seconds. How can I ensure it will only be fired once?
func action(gestureRecognizer:UIGestureRecognizer) {
println("long pressed on map")
override func viewDidLoad() {
super.viewDidLoad()
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
if activePlace == -1 {
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
} else {
var uilpgr = UILongPressGestureRecognizer(target: self, action: "action:")
uilpgr.minimumPressDuration = 2.0
myMap.addGestureRecognizer(uilpgr)
}
}
func action(gestureRecognizer:UIGestureRecognizer) {
println("long pressed on map")
var touchPoint = gestureRecognizer.locationInView(self.myMap)
var newCoordinate = myMap.convertPoint(touchPoint, toCoordinateFromView: self.myMap)
var annotation = MKPointAnnotation()
annotation.coordinate = newCoordinate
//annotation.title = "New Place"
myMap.addAnnotation(annotation)
var loc = CLLocation(latitude: newCoordinate.latitude, longitude: newCoordinate.longitude)
}
You have to check the gesture recognizer´s state for the begin of the gesture:
func action(gestureRecognizer:UIGestureRecognizer) {
if gestureRecognizer.state == UIGestureRecognizerState.Began {
// ...
}
}
Long-press gestures are continuous. The gesture begins (UIGestureRecognizerStateBegan) when the number of allowable fingers (numberOfTouchesRequired) have been pressed for the specified period (minimumPressDuration) and the touches do not move beyond the allowable range of movement (allowableMovement). The gesture recognizer transitions to the Change state whenever a finger moves, and it ends (UIGestureRecognizerStateEnded) when any of the fingers are lifted.
try something like this:
let longGesture = UILongPressGestureRecognizer(target : self,
action : #selector(someFunc(gestureRecognizer:)))
func someFunc(gestureRecognizer: UILongPressGestureRecognizer){
if gestureRecognizer.state == .began {
//do something
}

Resources