How do I determine if a coordinate is in the currently visible map region?

こ雲淡風輕ζ 提交于 2019-11-29 00:43:24

In your code, you should pass a view for the toPointToView: option. I gave it my mapView. You have to specify an upper bound for the x and y too.

Here's some code which worked for me (told me the currently visible annotations on my map, while looping through the annotation):

for (Shop *shop in self.shops) {
    ShopAnnotation *ann = [ShopAnnotation annotationWithShop:shop];
    [self.mapView addAnnotation:ann];

    CGPoint annPoint = [self.mapView convertCoordinate:ann.coordinate 
            toPointToView:self.mapView];

    if (annPoint.x > 0.0 && annPoint.y > 0.0 && 
            annPoint.x < self.mapView.frame.size.width && 
            annPoint.y < self.mapView.frame.size.height) {
        NSLog(@"%@ Coordinate: %f %f", ann.title, annPoint.x, annPoint.y);
    }
}

I know this is an old thread, not sure what was available back then... But you should rather do:

// -- Your previous code and CLLocationCoordinate2D init --
MKMapRect visibleRect = [mapView visibleMapRect];
if(MKMapRectContainsPoint(visibleRect, MKMapPointForCoordinate(coordinate))) {

    // Do your stuff

}

No need to convert back to the screen space. Also I am not sure the reason why you are trying to do this, I think this is strange to not add annotations when they are not on the screen... MapKit already optimizes this and only creates (and recycles) annotation views that are visible.

After a little bit of reading I can't find anything that says this is a bad idea. I've done a bit of testing in my app and I always get correct results. The app loads much quicker when I only add coordinates that will show up in the currently visible map region instead of all the 300+ coordinates at once.

What I was looking for was a method like [mapView isCoordinateInVisibleRegion:myCoordinate], but so far this method is quick and seems accurate.

I've also changed the title to read "in the visible map region" instead of the previous because I think the incorrect title may have confused my meaning.

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