2016-12-23 14 views
0

MKMapViewMKPointAnnotation을 사용하여 이전에 몇 가지 경험을 쌓았습니다. 일부 핀을지도에 넣었습니다. 이번에는 한 단계 더 나아가서 MKPinAnnotationView을 사용하여 일부 핀과 함께 라벨을 작성하려고합니다.MKPinAnnotationView의 제목이 표시되지 않습니다.

불행히도, 예상대로 모든 것이 작동하지는 않습니다. 여기

는 내가하고 싶은 것입니다 :

을 내가 (AN 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을하지만 유 작동합니다 .. 당신이

self.secondPoint.title = "Hello Second!" 

에서 언급하는

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 (Google Maps API)를 사용하지 않아도됩니다. 나는 내가 올바른 일을한다면 그것이 내가 원하는대로 일할 것이라고 생각한다. – Michel

+0

나는 단지 거친 아이디어를주고있다. 나는 구글 맵을 사용할 것을 요구하지 않고있다. – hussain

1

제목이 오면 콜 아웃 뷰의 제목입니다 주석 핀을 탭합니다. MKAnnotationView을 서브 클래스 화하고 사용자 정의 핀보기에 레이블을 추가 할 때마다 핀 이미지와 함께 레이블을 표시하려고 할 때마다. 당신이 당신이

먼저 MyAnnotation 핀을 만드는 데 도움이 될 것입니다이 솔루션을보십시오 방법

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) {// do something} else if (annotation == secondPoint) {// 다른 작업 수행}'을 통해 도청 된 주석이 하나 또는 다른 것인지 확인할 수 있습니다. 이 도움이 되었기를 바랍니다. –

+0

@Reinier : 주석은 MKAnnotation 유형이고 touchPoint는 MKPointAnnotation 유형이므로이 기능이 작동하지 않습니다. 당신은 컴파일러로부터 불평을받습니다. 그러나 나는 다른 방법을 찾았습니다 : 좌표를이 코드와 비교하는 것 "if ((annotation.coordinate.latitude! = touchPoint.coordinate.latitude) || (annotation.coordinate.longitude! = touchPoint.coordinate.longitude)) {. ..} ". 솔직하게 말해서 나는 그것을 좋아하지 않는다. 그러나 나는 지금 더 좋은 아무것도 없다. – Michel

0

다음의 사용자 정의 할 수 있습니다

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) 

지도보기 위임 방법

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) 
    } 

}