如何使用Mapkit访问用户位置(Swift)
问题描述:
我是新开发的应用程序,我一直在尝试创建一个应用程序,它将使用核心位置管理器来查找用户位置,然后使用mapkit进行显示。以下是我提出的代码。我一直无法解决它,有人知道我在做什么错了吗?谢谢。如何使用Mapkit访问用户位置(Swift)
//
// ViewController.swift
// MapKit Test
//
// Created by TMT on 7/11/15.
// Copyright (c) 2015 TMT Inc. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.showsUserLocation = true
mapView.showsPointsOfInterest = true
mapView.delegate = self
let locationManager = CLLocationManager()
// Ask for Authorisation from the User.
locationManager.requestAlwaysAuthorization()
// For use in foreground
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
@NSCopying var location: CLLocation! { get }
var span = MKCoordinateSpanMake(0.2
, 0.2)
var region = MKCoordinateRegion(center: location, span: span)
mapView.setRegion(region, animated: true)
var request = MKLocalSearchRequest()
request.naturalLanguageQuery = "library"
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答
您没有处理location/map的委托方法。您的代码正在设置地图和位置框架以及委托方法。你已经初始化了它们,并告诉编译器你想用mapkit/corelocation做些什么。所以,现在你需要处理你已经包含了委托方法MKMapViewDelegate, CLLocationManagerDelegate
,并委托除处理设置为self
的地方,你的代码某处
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
//Get map location
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))
self.mapView.setRegion(region, animated: true)
//Get co ordinates
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
println("Error: " + error.localizedDescription)
return
}
if placemarks.count > 0 {
let pm = placemarks[0] as! CLPlacemark
self.displayLocationInfo(pm)
} else {
println("Error with the data.")
}
})
}
func displayLocationInfo(placemark: CLPlacemark) {
//Remove observer
self.locationManager.stopUpdatingLocation()
println(placemark.locality)
println(placemark.postalCode)
println(placemark.administrativeArea)
println(placemark.country)
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error: " + error.localizedDescription)
}
+0
我需要把这个放在哪里?我尝试将其粘贴到我的代码中,并且只是遇到了一堆错误。 – TMT
看看这个样本的https:// github上。 com/talhaqamar/Map-demo-swift –
谢谢Johnny,这对我帮助很大。 – TMT