2016-12-23 14 views
0

У меня был прошлый опыт, используя 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 
    } 
} 

Теперь вот что происходит, контакты расположены, как и ожидалось, но я не вижу этикетку на второй. Я также заметил, что если я нахожусь там, где находится второй контакт (в этом случае второй вывод останется в одном месте), тогда появляется метка (как и всегда). Если я снова коснусь (не так близко), метка снова исчезнет (хотя это не должно).

Есть что-то в моем коде (выше), что не так? Любой соответствующий совет будет оценен по достоинству.

ответ

0

Этот i'have используется для карты Google, но он должен работать для и ..

let position = CLLocationCoordinate2DMake(latitude,longitude) 
let location = GMSMarker(position: position) 
location.icon = image 
location.icon? = self.imageWithImage(image, scaledToSize: CGSize(width: 50.0, height: 50.0)) 
location.title = "the photo is clicked here!!" 
location.map = MapView 
+0

Ну, я не должен использовать другой SDK (API Карт Google), чтобы иметь возможность сделать это. Я полагаю, что если я сделаю все правильно, это должно работать так, как я хочу. – Michel

+0

Я просто даю вам приблизительную идею Я не прошу использовать карту google. – hussain

1

Название вы имеете в виду в

self.secondPoint.title = "Hello Second!" 

это название зрения выноски, который наступает, когда вы нажимаете на значок аннотации. Если вы хотите показывать ярлык вместе с пин-образным изображением каждый раз, когда вы, вероятно, можете подклассифицировать MKAnnotationView, и добавьте ярлык в свой пользовательский вид вывода. Вы можете настроить следующим способом

class CustomAnnotationView : MKPinAnnotationView 
{ 
    let helloLabel:UILabel = UILabel.init(frame:CGRectMake(0, 0, 100, 40)) //your desired frame 

    func showLabel(title : String) 
    { 
     helloLabel.text = title 
     helloLabel.textAlignment = .Center 
     //set further properties 
     self.addSubview(helloLabel) 
    } 

    fun hideLabel() { 
     helloLabel.removeFromSuperview() 
    } 
} 
+0

Я провел некоторое время, экспериментируя с вашим предложением, и это помогло мне понять, как все это работает. Вот мой нынешний вопрос: когда функция «func mapView (_ mapView: MKMapView, viewFor аннотация: MKAnnotation) -> MKAnnotationView?" называется. Как я могу узнать, вызвана ли она для touchPoint или для secondPoint? Есть ли связь между MKPointAnnotation и MKAnnotation или что-то, что я могу использовать. – Michel

+0

@ Michel, вы можете проверить, является ли аннотирование тем или иным простым «if (annotation == touchPoint) {// сделать что-то} else if (annotation == secondPoint) {// сделать что-то еще}'. Я надеюсь, что это поможет вам –

+0

@Reinier: Это не работает, потому что аннотация имеет тип MKAnnotation и touchPoint имеет тип MKPointAnnotation; вы получаете жалобу от компилятора. Но я нашел другой способ: сравнить координаты с этим кодом «if ((annotation.coordinate.latitude! = TouchPoint.coordinate.latitude) || (annotation.coordinate.longitude! = TouchPoint.coordinate.longitude)) {. ..}». Честно говоря, мне это не нравится, но сейчас у меня нет ничего лучше. – Michel

0

Попробуйте это решение Это будет помочь вам

Первый Создать MyAnnotation булавку

if(geo_accuracy == "0") 
      { 
       colorofpin = .Blue 
      }else if (geo_accuracy == "1") 
      { 
       colorofpin = .Red 
      }else 
      { 
       colorofpin = .Green 
      } 
      var locationAnnotation = MyAnnotation(coordinate: location, 
       title: p_user_name!, 
       subtitle: "", 
       pinColor: colorofpin, 
       getTag:i) 


      /* And eventually add them to the map */ 

      //aryNotation.addObject(locationAnnotation) 

      aryNotation.append(locationAnnotation) 

метод MapView Делегат

func mapView(mapView: MKMapView, 
     viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?{ 

      if annotation is MyAnnotation == false{ 
       return nil 
      } 

      /* First typecast the annotation for which the Map View has 
      fired this delegate message */ 
      let senderAnnotation = annotation as! MyAnnotation 



      // -------------------------- For ios 9 ------------------- 


      let reuseId = "pin" 
      var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) 

      if pinView == nil { 
       pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId) 
       pinView!.canShowCallout = true 

      }else{ 
       pinView!.annotation = annotation 
      } 
      pinView!.tag = senderAnnotation.getTag; 

      // print(senderAnnotation.getTag) 

      if annotation is MyAnnotation { 

       //print(senderAnnotation.pinColor) 
       if(senderAnnotation.pinColor == .Red) 
       { 
        if(currentIndex == senderAnnotation.getTag) 
        { 
         //print("currentIndex==\(currentIndex)********") 
         pinView!.image = UIImage(named: "jivemap_pin_rough_o.png") 
         pinView!.layer.zPosition = 1 
         pinView?.bringSubviewToFront(self.view) 
         // pinView!.superview!.bringSubviewToFront(view) 
        }else 
        { 
         pinView!.image = UIImage(named: "jivemap_pin_rough_g.png") 
         pinView!.layer.zPosition = 0 
        } 
       } 
       else 
       { 

       if(currentIndex == senderAnnotation.getTag) 
       { 
        //print("currentIndex==*********\(currentIndex)********") 
        pinView!.image = UIImage(named: "jivemap_pin_o.png") 
        pinView!.layer.zPosition = 1 


       }else 
       { 
        pinView!.image = UIImage(named: "jivemap_pin_g.png") 
        pinView!.layer.zPosition = 0 
       } 
      } 

       pinView!.rightCalloutAccessoryView = UIButton(type: UIButtonType.DetailDisclosure) as UIView 
       // pinView 
       // return pinView 
      } 





      return pinView 
      //return annotationView 

    } 

Это мой annation класс. Этот класс заполнит всю вашу проблему.

import UIKit 
import MapKit 

/* This will allow us to check for equality between two items 
of type PinColor */ 
func == (left: PinColor, right: PinColor) -> Bool{ 
    return left.rawValue == right.rawValue 
} 

/* The various pin colors that our annotation can have */ 
enum PinColor : String{ 
    case Blue = "Blue" 
    case Red = "Red" 
    case Green = "Green" 
    case Purple = "Purple" 

    /* We will convert our pin color to the system pin color */ 
    func toPinColor() -> MKPinAnnotationColor{ 
     switch self{ 
     case .Red: 
      return .Red 
     case .Green: 
      return .Green 
     case .Purple: 
      return .Purple 
     default: 
      /* For the blue pin, this will return .Red but we need 
      to return *a* value in this function. For this case, we will 
      ignore the return value */ 
      return .Red 
     } 
    } 
} 

class MyAnnotation: NSObject, MKAnnotation { 
    var coordinate: CLLocationCoordinate2D 
    var title: String? 
    var subtitle: String? 
    var pinColor: PinColor! 
    var getTag:Int! 
    var annoationIndex = 0 

    init(coordinate: CLLocationCoordinate2D, 
     title: String, 
     subtitle: String, 
     pinColor: PinColor, 
     getTag: Int){ 
      self.coordinate = coordinate 
      self.title = title 
      self.subtitle = subtitle 
      self.pinColor = pinColor 
      self.getTag = getTag 
      super.init() 
    } 

    convenience init(coordinate: CLLocationCoordinate2D, 
     title: String, 
     subtitle: String, 
     gettag: Int){ 
      self.init(coordinate: coordinate, 
       title: title, 
       subtitle: subtitle, 
       pinColor: .Blue, 
       getTag: gettag) 
    } 

}