如何在放大时显示地图注释?

时间:2016-01-06 16:05:47

标签: ios swift mkmapview mkannotation

我有一张带有很多注释的地图,这些地图都固定在整个国家/地区。现在我想在有人放大地图时自动显示注释。你知道怎么开始吗?现在我有几行代码:

  

注释类

class myAnnotation: NSObject, MKAnnotation{

var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D

init(title: String, subtitle: String, coordinates: CLLocationCoordinate2D){
    self.title = title
    self.subtitle = subtitle
    self.coordinate = coordinates
} 
} // end of class
  

MapView类

class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

/* OUTLETS */    

@IBOutlet weak var mapOutlet: MKMapView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!

/* VARIABLES */

let lm = CLLocationManager()
var data = [[String:String]]()

override func viewDidLoad() {
    super.viewDidLoad()

    // pin's data is loaded from the server and added to `data`

} 

override func viewDidAppear(animated: Bool) {
         self.addAnnotationToTheMap()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func addAnnotationToTheMap(){

    for i in data{

        let latitude = Double(i["latitude"]!)
        let longtitude = Double(i["longitude"]!)

        let coordinates = CLLocationCoordinate2DMake(latitude!, longtitude!)

        let pinOnTheMap = myAnnotation(title: i["title"]!, subtitle: i["subtitle"]!, coordinates: coordinates)
        mapOutlet.addAnnotation(pinOnTheMap)
    }    
}
} // end of class

任何想法怎么做?

2 个答案:

答案 0 :(得分:0)

您可以通过调用mapView.selectAnnotation(annotation, animated:true)以编程方式选择任何更接近地图中心的注释或注释。但是,一次只能选择一个注释。

答案 1 :(得分:0)

我这样做:

extension  Double{

    func between( a:Double, b:Double) -> Bool{
        if self > a && self < b{
            return true
        }
        return false
    }

}


extension MapViewController : MKMapViewDelegate{

    //using special image for standard view for the annotation
    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
        var anView = mapView.dequeueReusableAnnotationViewWithIdentifier("wtg")
        if anView == nil {
            anView = MKAnnotationView(annotation: annotation, reuseIdentifier: "wtg")
            anView!.canShowCallout = true
            anView!.image = UIImage(named: "wtg")
        }
        else {
            anView!.annotation = annotation
        } 
        return anView
    }

    //if the region center is close to something, show the annotations
    func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        let region = mapView.region
        if region.center.latitude.between(myLatA, b: mylatB) && region.center.longitude.between(myLonA, b: myLonB)
        {
            //Add extra anotations or do other stuff
        }
    }
}

Apple在这个问题上有很好的documentation。您应该查看“显示多个注释对象”部分,并使用委托方法mapView:regionWillChangeAnimated:和mapView:regionDidChangeAnimated:Methods。