Swift|23 iOS SDK顯示地圖和地圖標記的方法
Published in
4 min readJan 22, 2022
最近看到泰國大城新開了一家購物商場
從 Xcode 的 playground 練習
利用 MKMapView 顯示地圖帶我去線上遊覽吧!
好想出國(〒︿〒)
先查出地點的經緯度
在Playground裡要看到顯示controller的view
需要使用live view
在playground 加入 framework MapKit
import MapKit//為了在playground看到地圖import PlaygroundSupportlet mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))//顯示地圖經緯度和範圍mapView.region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 14.331622, longitude: 100.611817), latitudinalMeters: 1000, longitudinalMeters: 1000)
顯示地圖中心點的經緯度和範圍
用mapView的region(區域)顯示地圖中心點和經緯度,
型別為MKCoordinateRegion,要輸入以下三種參數:
latitude 是緯度,longitude 是經度
- latitudinalMeters — 緯度範圍,單位是公尺
因此我們寫入 1000, 表示地圖的最北邊和最南邊距離 1000 公尺 - longitudinalMeters — 經度範圍,單位是公尺
因此我們寫入 1000 表示地圖的最東邊和最西邊距離 1000 公尺
用 MKPointAnnotation加入地點標記
可以加入標題(title)和副標題(subtitle)
let AyutthayaShoppingMall = MKPointAnnotation()AyutthayaShoppingMall.title = "Central Ayutthaya"AyutthayaShoppingMall.coordinate = CLLocationCoordinate2D(latitude: 14.331622, longitude: 100.611817)AyutthayaShoppingMall.subtitle = "大城新開的百貨公司"mapView.addAnnotation(AyutthayaShoppingMall)PlaygroundPage.current.liveView = mapView
結果顯示如下
改變地圖顯示模式
mapView.mapType = .hybrid
mapView.mapType = .satellite