步骤:1 -导入
import MapKit
import CoreLocation
步骤:2 -添加代表
MKMapViewDelegate,CLLocationManagerDelegate
步骤:3 -声明
@IBOutlet var mapView: MKMapView!
var locationManager = CLLocationManager()
var myLocation = CLLocation()
步骤:4 -内部 ViewDidLoad
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled()
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
//MARK: - MapView and Location Manager -
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
self.myLocation = locations.last!
print("NewLocation \(locations[0].coordinate.latitude) \(locations[0].coordinate.longitude)")
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
let annotationIdentifier = "AnnotationIdentifier"
var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
}
else
{
let av = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
av.rightCalloutAccessoryView = UIButton(type: .roundedRect)
annotationView = av
}
if let annotationView = annotationView
{
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "Location")
}
return annotationView
}
self.mapView.showsUserLocation = true
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(address!) { (placemarks, error) in
guard
let placemarks = placemarks,
let location = placemarks.first?.location
else
{
return
}
let newPin = MKPointAnnotation()
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)
newPin.title = address
newPin.coordinate = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
self.mapView.addAnnotation(newPin)
}
@IBAction func btnDirection(_ sender: Any)
{
let address = self.dictEventDetails.object(forKey: "address") as? String
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(address!) { (placemarks, error) in
guard
let placemarks = placemarks,
let location = placemarks.first?.location
else
{
return
}
let coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary:nil))
mapItem.name = address
mapItem.openInMaps(launchOptions:nil)
}
}