Converting View Points to MKMapView Coordinates

笑着哭i 提交于 2019-12-22 10:20:05

问题


My objective is to convert the top left and bottom right points of my view to lat/lon coordinates. These lat/lon coordinates will be used to query annotation locations that only exist within the view (not all 5000+).

I found this Objective-C tip on Stackoverflow. But the issue I have is that it is converting 0,0 from the mapView (a lat/lon of -180,-180. Aka, the Southpole).

So instead of:

topLeft = mapView.convertPoint(CGPointMake(0, 0), toCoordinateFromView: self.mapView)

I figured I could simply do:

topLeft = view.convertPoint(CGPointMake(0, 0), toCoordinateFromView: self.mapView)

But I get the error:

Cannot invoke 'convertPoint' with an argument list of type '(CGPoint, toCoordinateFromView: MKMapView!)'

I have spent a day trying to figure it out, but to no avail, and I have come to you seeking guidance. Any help would be much appreciated.

Here is the complete function:

func findCornerLocations(){

    var topLeft = CLLocationCoordinate2D()
    let mapView = MKMapView()
    topLeft = view.convertPoint(CGPointMake(0, 0), toCoordinateFromView: self.mapView)

    print(topLeft.latitude, topLeft.longitude)
}

回答1:


You were very, very close!

let topLeft = map.convertPoint(CGPointMake(0, 0), toCoordinateFromView: self.view)
let bottomleft = map.convertPoint(CGPointMake(0, self.view.frame.size.height), toCoordinateFromView: self.view)

When implemented, it'll look like this:

        let map = MKMapView()
        map.frame = CGRectMake(100, 100, 100, 100)
        let coord = CLLocationCoordinate2DMake(37, -122)
        let span = MKCoordinateSpanMake(1, 1)
        map.region = MKCoordinateRegionMake(coord, span)
        self.view.addSubview(map)

        let topleft = map.convertPoint(CGPointMake(0, 0), toCoordinateFromView: self.view)
        let bottomleft = map.convertPoint(CGPointMake(0, self.view.frame.size.height), toCoordinateFromView: self.view)

        print("top left = \(topleft)")
        print("bottom left = \(bottomleft)")



回答2:


A normal view doesn't have the convertPoint(_:toCoordinateFromView:) function, only an MKMapView, which explains the compiler error you're seeing. What made you stop using this version?

topLeft = mapView.convertPoint(CGPointMake(0, 0), toCoordinateFromView: self.mapView)

Additionally, if all the annotations are already added to the map view, you'll have much better success using the annotationsInMapRect method:

let visibleAnnotations = mapView.annotationsInMapRect(mapView.visibleMapRect)
for element in visibleAnnotations {
    guard let annotation = element as? MKAnnotation
        else { continue }

    print(annotation)
}


来源:https://stackoverflow.com/questions/33784742/converting-view-points-to-mkmapview-coordinates

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