我已經有一些使用MKMapView
和MKPointAnnotation
的經驗,我曾經在地圖上放置了一些別針。 這次我想更進一步,使用MKPinAnnotationView
來寫一個標籤和一些引腳。MKPinAnnotationView不顯示標題
不幸的是,它並不像我預期的那樣工作。
這是我想做的事:
我有一個圖表(的MKMapView對象),當我觸摸它,我把一根鋼釘在觸摸點,然後進行一些計算,這給了我一個地圖上的第二個點。我把第二個引腳(位於第二個點)放在最後一個引腳上,我想放一個標籤,說「Hello Second!」。
下面是相關代碼:
class ViewController: UIViewController, MKMapViewDelegate {
var mapView:MKMapView!, touchPoint,secondPoint:MKPointAnnotation!
override func viewDidLoad() {
super.viewDidLoad()
mapView = MKMapView()
...........
let mapTap = UITapGestureRecognizer(target: self,
action: #selector(ViewController.mapTouchHandler))
mapView.addGestureRecognizer(mapTap)
}
func mapTouchHandler(gesture:UITapGestureRecognizer) {
...........
// Compute map coordinates for the touch point (tapGeoPoint).
if touchPoint == nil {
touchPoint = MKPointAnnotation()
mapView.addAnnotation(touchPoint);
}
touchPoint.coordinate = CLLocationCoordinate2D(latitude: tapGeoPoint.latitude,
longitude: tapGeoPoint.longitude)
...........
computeSecondPoint(url: someComputedURL)
}
func computeSecondPoint(url searchURL:String) {
let reqURL = NSURL(string: searchURL)!, session = URLSession.shared,
task = session.dataTask(with: reqURL as URL) {
(data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
do {let allData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
.................
// Compute map coordinates for the second point (secondPointCoord).
if self.secondPoint == nil {
self.secondPoint = MKPointAnnotation()
self.mapView.addAnnotation(self.secondPoint)
}
DispatchQueue.main.async {
() -> Void in
self.secondPoint.coordinate = CLLocationCoordinate2D(latitude: secondPointCoord.latitude,
longitude: secondPointCoord.longitude)
self.secondPoint.title = "Hello Second!"
}
} catch let error as NSError {print(error.localizedDescription)}
} else {
print("Error inside \(#function):\n\(error)")
}
}
task.resume()
}
func mapView(_ mapView: MKMapView,
viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "pin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 0)
}
return view
}
}
現在,這裏是什麼情況,如預期的引腳放置,但我沒有看到第二個的任何標籤。 我還注意到,如果我點擊第二個引腳碰巧的地方(在這種情況下,第二個引腳將停留在同一個地方),那麼標籤就會出現(因爲它應該總是這樣做)。如果我再次點擊(不是那麼近),那麼標籤會再次消失(儘管它不應該)。
有沒有在我的代碼(上面)是不正確的? 任何相關的提示將不勝感激。
那麼,我不應該使用不同的SDK(Google Maps API)才能做到這一點。我想如果我以正確的方式做事情,它應該按我的意願工作。 – Michel
我只是給你粗略的想法 我不是要求使用谷歌地圖。 – hussain