我的目标是将视图的左上角和右下角转换为纬度/经度坐标。这些lat / lon坐标将用于查询仅存在于视图中的注释位置(不是全部5000 +)。
我发现了Objective-C tip on Stackoverflow。但我遇到的问题是它从mapView转换0,0(纬度/经度为-180,-180.Aka,南极)。
所以而不是:
topLeft = mapView.convertPoint(CGPointMake(0, 0), toCoordinateFromView: self.mapView)
我想我可以这样做:
topLeft = view.convertPoint(CGPointMake(0, 0), toCoordinateFromView: self.mapView)
但我收到错误:
无法使用类型'的参数列表调用'convertPoint'(CGPoint, toCoordinateFromView:MKMapView!)'
我花了一天时间试图解决这个问题,但无济于事,我来找你寻求指导。任何帮助将不胜感激。
这是完整的功能:
func findCornerLocations(){
var topLeft = CLLocationCoordinate2D()
let mapView = MKMapView()
topLeft = view.convertPoint(CGPointMake(0, 0), toCoordinateFromView: self.mapView)
print(topLeft.latitude, topLeft.longitude)
}
答案 0 :(得分:7)
你非常非常接近!
let topLeft = map.convertPoint(CGPointMake(0, 0), toCoordinateFromView: self.view)
let bottomleft = map.convertPoint(CGPointMake(0, self.view.frame.size.height), toCoordinateFromView: self.view)
实施后,它将如下所示:
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)")
答案 1 :(得分:0)
普通视图没有convertPoint(_:toCoordinateFromView:)
函数,只有MKMapView
,这解释了您看到的编译器错误。是什么让你停止使用这个版本?
topLeft = mapView.convertPoint(CGPointMake(0, 0), toCoordinateFromView: self.mapView)
此外,如果所有注释都已添加到地图视图中,那么使用annotationsInMapRect
方法可以获得更好的成功:
let visibleAnnotations = mapView.annotationsInMapRect(mapView.visibleMapRect)
for element in visibleAnnotations {
guard let annotation = element as? MKAnnotation
else { continue }
print(annotation)
}