Показать текущее местоположение и обновить местоположение в MKMapView в Swift
Я учусь использовать новый язык Swift (только Swift, без Objective-C). Для этого я хочу сделать простой вид с картой (MKMapView
). Я хочу найти и обновить местоположение пользователя (как в приложении Apple Map).
Я попробовал это, но ничего не произошло:
import MapKit
import CoreLocation
class MapView : UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
}
Не могли бы вы мне помочь?
Ответы
Ответ 1
CLLocationManager.didUpdateLocations
переопределить CLLocationManager.didUpdateLocations
(часть CLLocationManagerDelegate), чтобы получать уведомления, когда менеджер местоположений получает текущее местоположение:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last{
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
}
ПРИМЕЧАНИЕ. Если ваша цель - iOS 8 или выше, вы должны включить NSLocationAlwaysUsageDescription
или NSLocationWhenInUseUsageDescription
в свой Info.plist, чтобы заставить службы определения местоположения работать.
Ответ 2
100% работа, простые шаги и тестирование
Импортировать библиотеки:
import MapKit
import CoreLocation
установить делегатов:
CLLocationManagerDelegate,MKMapViewDelegate
Взять переменную:
let locationManager = CLLocationManager()
напишите этот код на viewDidLoad():
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
mapView.delegate = self
mapView.mapType = .standard
mapView.isZoomEnabled = true
mapView.isScrollEnabled = true
if let coor = mapView.userLocation.location?.coordinate{
mapView.setCenter(coor, animated: true)
}
Напишите метод делегата для местоположения:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
mapView.mapType = MKMapType.standard
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: locValue, span: span)
mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = locValue
annotation.title = "Javed Multani"
annotation.subtitle = "current location"
mapView.addAnnotation(annotation)
//centerMap(locValue)
}
Не забудьте установить разрешение в info.plist
<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>
Это выглядит как:
![enter image description here]()
Ответ 3
Для быстрого 3 и XCode 8 я нахожу этот ответ:
-
Сначала вам нужно установить конфиденциальность в info.plist. Вставьте строку NSLocationWhenInUseUsageDescription с вашим описанием, почему вы хотите получить местоположение пользователя. Например, установите строку "Для карты в приложении".
-
Во-вторых, используйте этот пример кода
@IBOutlet weak var mapView: MKMapView!
private var locationManager: CLLocationManager!
private var currentLocation: CLLocation?
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// Check for Location Services
if CLLocationManager.locationServicesEnabled() {
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
}
// MARK - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
defer { currentLocation = locations.last }
if currentLocation == nil {
// Zoom to user location
if let userLocation = locations.last {
let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
mapView.setRegion(viewRegion, animated: false)
}
}
}
-
В-третьих, установите флаг "Местоположение пользователя" в раскадровке для mapView.
Ответ 4
MyLocation - демоверсия Swift для iOS.
Вы можете использовать эту демонстрацию для следующего:
-
Показать текущее местоположение.
-
Выберите другое местоположение: в этом случае прекратите отслеживать местоположение.
-
Прикоснитесь к кнопке MKMapView (iOS), чтобы добавить кнопку.
Ответ 5
Для Swift 2 вы должны изменить его на следующее:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
Ответ 6
вам нужно переопределить CLLocationManager.didUpdateLocations
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
locationManager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion (center: location,span: span)
mapView.setRegion(region, animated: true)
}
вам также нужно добавить NSLocationWhenInUseUsageDescription
и NSLocationAlwaysUsageDescription
в настройку plist Result
как значение
Ответ 7
В Swift 4 я использовал функцию делегата locationManager, как указано выше.
func locationManager(manager: CLLocationManager!,
didUpdateLocations locations: [AnyObject]!) {
.. но это нужно было изменить на..
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
Это произошло из https://github.com/lotfyahmed/MyLocation/blob/master/MyLocation/ViewController.swift - спасибо!
Ответ 8
Привет. Иногда установка showUserLocation в коде не работает по какой-то странной причине.
Поэтому попробуйте комбинацию из следующего.
В viewDidLoad()
self.mapView.showsUserLocation = true
Перейдите к вашей раскадровке в XCode, в правой панели инспектора атрибутов установите флажок Местоположение пользователя, как на прикрепленном изображении. запустите ваше приложение, и вы сможете увидеть местоположение пользователя
![enter image description here]()