iOS 原生地圖框架 MapKit 提供 MKMapView、標註、覆蓋層、地理編碼、路徑規劃等完整能力,無需引入第三方 SDK 即可構建豐富 LBS 應用。
import MapKit
let mapView = MKMapView(frame: view.bounds)
mapView.delegate = self
mapView.showsUserLocation = true
mapView.mapType = .standard // .satellite, .hybrid
view.addSubview(mapView)
NSLocationWhenInUseUsageDescription。CLLocationManager().requestWhenInUseAuthorization()。MKMapViewDelegate 監聽 didUpdate userLocation。class CustomAnnotation: NSObject, MKAnnotation {
let coordinate: CLLocationCoordinate2D
let title: String?
let subtitle: String?
let imageName: String
// ...
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let custom = annotation as? CustomAnnotation else { return nil }
let id = "customPin"
var view = mapView.dequeueReusableAnnotationView(withIdentifier: id)
if view == nil {
view = MKAnnotationView(annotation: custom, reuseIdentifier: id)
view?.canShowCallout = true
}
view?.image = UIImage(named: custom.imageName)
view?.annotation = custom
return view
}
let polyline = MKPolyline(coordinates: coords, count: coords.count)
mapView.addOverlay(polyline)
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let line = overlay as? MKPolyline {
let renderer = MKPolylineRenderer(polyline: line)
renderer.strokeColor = .systemBlue
renderer.lineWidth = 3
return renderer
}
return MKOverlayRenderer(overlay: overlay)
}
let geocoder = CLGeocoder()
// 地址 -> 坐標
geocoder.geocodeAddressString("北京市朝陽區") { placemarks, error in
guard let loc = placemarks?.first?.location else { return }
// 移動地圖至 loc.coordinate
}
// 坐標 -> 地址
geocoder.reverseGeocodeLocation(location) { placemarks, error in
print(placemarks?.first?.name ?? "未知")
}
let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: start))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: end))
request.transportType = .automobile
MKDirections(request: request).calculate { response, error in
guard let route = response?.routes.first else { return }
self.mapView.addOverlay(route.polyline)
self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
}
osm2pgsql 導入 PostGIS。| 資源 | 特點 |
|---|---|
| Apple 官方文檔 | 權威、最新、含 Swift/ObjC 範例 |
| RayWenderlich MapKit 教程 | 項目制實戰,適合入門到精通 |
| Mapbox iOS SDK | 進階樣式、離線、3D,超越 MapKit |
| CSDN/掘金/簡書搜 "MapKit 實戰" | 中文社區大量踩坑筆記、demo |
MKAnnotationView 復用、分級聚類。MapKit 是 iOS 原生地圖開發的首選,API 現代、性能優異、隱私合規。結合 CoreLocation、Contacts、SiriKit 可構建完整位置服務閉環。建議從官方文檔入手,配合 RayWenderlich 實戰教程,再根據業務決定是否引入第三方 SDK。