API串接練習咖啡店&&Mapkit應用 導航 (2) Mapkit應用 地圖與導航
Published in
7 min readAug 12, 2020
成果
地圖顯示
import MapKit
設置大頭針
- 生成大頭針
let studioAnnotation = MKPointAnnotation()
2.設置位置與大頭針細節
studioAnnotation.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)// 設置大頭針標題studioAnnotation.title = cafeData?.name// 設置大頭針副標題,點選後可以看見studioAnnotation.subtitle = cafeData?.address
3.修改顯示的範圍
關於修改 latitudinalMeters , longitudinalMeters 是map距離邊界的距離
所以數值越大 所涵蓋的東西會越多 反之越少
mapView.setCenter(studioAnnotation.coordinate, animated: true)// 更改當前可見區域,並且根據指定的坐標和距離值創建新的MKCoordinateRegionmapView.setRegion(MKCoordinateRegion(center: studioAnnotation.coordinate, latitudinalMeters: 200, longitudinalMeters: 200), animated: true)
可參考Peter的MapKit文章
4.加入到mapview
mapView.addAnnotation(studioAnnotation)
func settingcafeAnnotation() {if let cafeData=cafeData{latitude=Double(cafeData.latitude)!longitude=Double(cafeData.longitude)!
cafeName.text=cafeData.namecafeAddress.text=cafeData.addressopenTime.text="\(cafeData.open_time)"}let studioAnnotation = MKPointAnnotation()studioAnnotation.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)// 設置大頭針標題studioAnnotation.title = cafeData?.name// 設置大頭針副標題,點選後可以看見studioAnnotation.subtitle = cafeData?.address
mapView.setCenter(studioAnnotation.coordinate, animated: true)// 更改當前可見區域,並且根據指定的坐標和距離值創建新的MKCoordinateRegionmapView.setRegion(MKCoordinateRegion(center: studioAnnotation.coordinate, latitudinalMeters: 200, longitudinalMeters: 200), animated: true)mapView.addAnnotation(studioAnnotation)}
導航實現
1.設置目標經維度
//目標經維度let targetLocation=CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
2. 導航目的地建立一個MKMapItem
//透過地targetLocation建立一個MKMapItemlet targetPlacemark=MKPlacemark(coordinate: targetLocation)
3.建立目標地圖項目
// 目標地圖項目let targetItem=MKMapItem(placemark: targetPlacemark)
4.建立使用者目前位置的地圖項目
這邊的MKMapItem.forCurrentLocation() 依照蘋果官方的文件
他是顯示裝置的目前位置並起建立的項目
所以這個回傳並不是坐標數據,而是蘋果的MKMapItem
如果要精準座標數據那要使用CLLocation
let userMapItem=MKMapItem.forCurrentLocation()
5.建立路徑
//建構路徑let routes=[userMapItem,targetItem]
6.呼叫openMaps方法開啟系統地圖
//呼叫openMaps方法開啟系統地圖 這邊設定開車MKMapItem.openMaps(with: routes, launchOptions: [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving])
參考
程式碼
希望這篇文章能夠幫助到你(妳)
如有錯誤指正
I hope you found this guide helpful. If not, then please let me know either in the comments below, I’m AlberLee
Swift#19