How to check if MKCoordinateRegion contains CLLocationCoordinate2D without using MKMapView?

后端 未结 9 824
天涯浪人
天涯浪人 2020-12-13 05:08

I need to check if user location belongs to the MKCoordinateRegion. I was surprised not to find simple function for this, something like: CGRectContainsCGPoint(rect,

9条回答
  •  忘掉有多难
    2020-12-13 05:22

    In case there is anybody else confused with latitudes and longitues, here is tested, working solution:

    MKCoordinateRegion region = self.mapView.region;
    
    CLLocationCoordinate2D location = user.gpsposition.coordinate;
    CLLocationCoordinate2D center   = region.center;
    CLLocationCoordinate2D northWestCorner, southEastCorner;
    
    northWestCorner.latitude  = center.latitude  - (region.span.latitudeDelta  / 2.0);
    northWestCorner.longitude = center.longitude - (region.span.longitudeDelta / 2.0);
    southEastCorner.latitude  = center.latitude  + (region.span.latitudeDelta  / 2.0);
    southEastCorner.longitude = center.longitude + (region.span.longitudeDelta / 2.0);
    
    if (
        location.latitude  >= northWestCorner.latitude && 
        location.latitude  <= southEastCorner.latitude &&
    
        location.longitude >= northWestCorner.longitude && 
        location.longitude <= southEastCorner.longitude
        )
    {
        // User location (location) in the region - OK :-)
        NSLog(@"Center (%f, %f) span (%f, %f) user: (%f, %f)| IN!", region.center.latitude, region.center.longitude, region.span.latitudeDelta, region.span.longitudeDelta, location.latitude, location.longitude);
    
    }else {
    
        // User location (location) out of the region - NOT ok :-(
        NSLog(@"Center (%f, %f) span (%f, %f) user: (%f, %f)| OUT!", region.center.latitude, region.center.longitude, region.span.latitudeDelta, region.span.longitudeDelta, location.latitude, location.longitude);
    }
    

提交回复
热议问题