我已经有一些使用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