Swift fit annotations

三世轮回 提交于 2019-12-12 01:27:05

问题


I have a few locations in parse which I'm query-ing. It shows all annotations but it only zoom the last one. How can I find max and min latitudes and longitudes and make them fit ?

There is plenty of these on stackoverflow but they're almost all in objective-c.


回答1:


The examples in Objective-C are still essentially valid since the underlying SDK/API is still the same -- just being called using a different language (and there's always the documentation).

To show all annotations, there are essentially two ways to do it:

  1. Use the convenient showAnnotations method. You pass it an array of annotations and it will automatically calculate a reasonable region to display. You call it after adding all the annotations (after your for loop). In fact, showAnnotations will even add the annotations itself if they aren't already on the map. To show all annotations that are already on the map, just pass it the map's own annotations array. Example:

    self.mapView.showAnnotations(self.mapView.annotations, animated: true)
    
  2. If you are not happy with the default region calculated by showAnnotations, you can calculate one yourself. Instead of calculating minimum/maximum latitudes and longitudes, etc, I prefer to use the built-in MKMapRectUnion function to create an MKMapRect that fits all annotations and then call setVisibleMapRect(mapRect,edgePadding,animated) which lets one conveniently define padding in screen points around the fitted map rect. This technique was originally found in a very early map view sample app from Apple. Example:

    var allAnnMapRect = MKMapRectNull
    
    for object in objects! {
        //existing code that creates annotation...
        //existing code that calls addAnnotation...
    
        let thisAnnMapPoint = MKMapPointForCoordinate(annotation.coordinate)
        let thisAnnMapRect = MKMapRectMake(thisAnnMapPoint.x, thisAnnMapPoint.y, 1, 1)
        allAnnMapRect = MKMapRectUnion(allAnnMapRect, thisAnnMapRect)
    }
    
    //Set inset (blank space around all annotations) as needed...
    //These numbers are in screen CGPoints...
    let edgeInset = UIEdgeInsetsMake(20, 20, 20, 20)
    
    self.mapView.setVisibleMapRect(allAnnMapRect, edgePadding: edgeInset, animated: true)
    


来源:https://stackoverflow.com/questions/29317517/swift-fit-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!