地圖的上上篇提到了如何顯示靜態地點:[iOS][Xcode][Swift]iPhone手機編程--在APP中加入地圖Map(MapKit)初級應用--靜態地點顯示
地圖的上一篇提到了如何顯示動態坐標:[iOS][Xcode][Swift]iPhone手機編程--在APP中加入地圖Map(MapKit)升級應用--動態追蹤用戶實時位置[含獲取用戶位置權限教程][CLLocationManager()]
在地圖中添加標記
為了追蹤實時位置,
地圖APP免不了有釘選功能(在特定位置添加標記),
因為是點選時再加入圖標的,
很明顯需要在StoryBoard中加入Tap的Gesture,
這次需要將Gesture拖曳到Map上,
@IBAction func respondToTap(_ sender: UITapGestureRecognizer) {
let tapLocation=sender.location(in: Map) //獲取Tap時所在的位置
print(tapLocation)
let tapMapCoordinate=Map.convert(tapLocation, toCoordinateFrom: Map) //將屏幕上的x,y轉換為地圖上的經緯度
print(tapMapCoordinate)
//MARK: SetAnnotation //在上述位置中加入圖標
let annotation=MKPointAnnotation()
annotation.title="I tap here"
annotation.coordinate=tapMapCoordinate
Map.addAnnotation(annotation)
}
要注意的是,convert的function有很多,
需要選擇的是convert(point: CGPoint, toCoordinateFrom: UIView)
用圖片替代默認圖標
為了與其他同類APP區分開來,
有不少APP都會加入自己的元素,
而地圖亦可以自定圖標,
就如同本篇一開始時的pokemon pin。
首先,需要加入Delegate,
然後,調用mapView function,
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier="default"
var annotationView=mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView==nil{
//如果無指定圖片的話,將圖標的設定為圖片"pokemon_pin",記得圖片需要事先放進Assets Folder
annotationView=MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.image=UIImage(named: "pokemon_pin")
}else{
annotationView?.annotation=annotation
}
return annotationView
}
地圖三步曲
地圖初級應用
[iOS][Xcode][Swift]iPhone手機編程--在APP中加入地圖Map(MapKit)初級應用--靜態地點顯示
地圖升級應用
地圖升升級應用 (中高級應用某君可不懂,只能一路升級下去好了)