web-dev-qa-db-fra.com

Swift MKMapView Drop a Pin Annotation to Current Location)

Je cherche à pouvoir demander à l'utilisateur de l'application son emplacement actuel et une épingle à déposer automatiquement à cet emplacement. Voici mon code pour récupérer l'emplacement actuel, mais j'ai du mal à comprendre comment je peux déposer une épingle pour l'emplacement actuel.

import UIKit
import MapKit
import CoreLocation


class MapVC: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {



@IBOutlet weak var map: MKMapView!

let locationManager =  CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    // User's location

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    if #available(iOS 8.0, *) {
        locationManager.requestAlwaysAuthorization()
    } else {
        // Fallback on earlier versions
    }
    locationManager.startUpdatingLocation()

    // add gesture recognizer
    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(MapVC.mapLongPress(_:))) // colon needs to pass through info
    longPress.minimumPressDuration = 1.5 // in seconds
    //add gesture recognition
    map.addGestureRecognizer(longPress)
}

// func called when gesture recognizer detects a long press

func mapLongPress(_ recognizer: UIGestureRecognizer) {

    print("A long press has been detected.")

    let touchedAt = recognizer.location(in: self.map) // adds the location on the view it was pressed
    let touchedAtCoordinate : CLLocationCoordinate2D = map.convert(touchedAt, toCoordinateFrom: self.map) // will get coordinates

    let newPin = MKPointAnnotation()
    newPin.coordinate = touchedAtCoordinate
    map.addAnnotation(newPin)


}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location = locations.last! as CLLocation

    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))




    //set region on the map
    self.map.setRegion(region, animated: true)



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}
12
Kevin

Si vous souhaitez ajouter une épingle à l'emplacement de l'utilisateur, vous pouvez le faire dans la méthode déléguée didUpdateLocations comme celle-ci

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    mapView.removeAnnotation(newPin)

    let location = locations.last! as CLLocation

    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))        

    //set region on the map
    map.setRegion(region, animated: true)

    newPin.coordinate = location.coordinate
    map.addAnnotation(newPin)

}

Créez une variable globale pour votre épingle

let newPin = MKPointAnnotation()

Ainsi, chaque fois que l'utilisateur se déplace vers un nouvel emplacement, la broche précédente sera supprimée et une nouvelle broche sera ajoutée à l'emplacement mis à jour.

19
Rajat

Vous devez d'abord ajouter une annotation dans la méthode didUpdateLocations, puis chaque fois qu'une annotation est ajoutée, viewForAnnotation est appelé. Voici donc le code et la méthode correspondante pour ajouter une broche à l'emplacement actuel de l'utilisateur:

// Ajout d'annotation sur l'emplacement actuel

 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //Get Current Location
        let location = locations.last! as CLLocation
        let userLocation:CLLocation = locations[0] as CLLocation
        let myAnnotation: MKPointAnnotation = MKPointAnnotation()
        myAnnotation.coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude)
        myAnnotation.title = "Current location"
        map.addAnnotation(myAnnotation)
}

// Ajout d'une image à la broche de l'emplacement actuel de l'utilisateur

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

   guard !(annotation is MKUserLocation) else {
            let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "userLocation")
            annotationView.image = UIImage(named:"anyimage.png")
            return annotationView
        }
return nil
}

N'hésitez pas à demander s'il y a un autre problème.

3
Shobhakar Tiwari