Szukam, aby móc zapytać użytkownika aplikacji o jego bieżącą lokalizację i pinezkę, która zostanie automatycznie upuszczona w tym miejscu. Oto mój kod do przechwytywania bieżącej lokalizacji, ale mam problem ze zrozumieniem, w jaki sposób mogę usunąć pinezkę dla bieżącej lokalizacji.Swift MKMapView Upuść pinezkę do aktualnej lokalizacji
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.
}
}
Kiedy to zaimplementuję, daje mi błąd "Używanie nierozwiązanego identyfikatora" mapView "" – Kevin
'mapView' to nazwa zmiennej' MapView' zamienia ją na zmienną 'MapView' która jest' mapą ', także i zaktualizowałem to w mojej odpowiedzi – Rajat
Ah Widzę. Naprawiło to błąd. Jak mogę to przetestować? Po uruchomieniu go z mapą nie rozpoznaje bieżącej lokalizacji aplikacji. – Kevin