How do I determine if the current user location is inside of my MKCoordinateRegion?
Asked Answered
H

3

8

I have a coordinate region that I have determined contains the limits of what I want to show for my app. I have set this up as an MKCoordinateRegion with center point lat, longitude and a span. How do I determine if the current userLocation is inside of my coordinate region?

Heliostat answered 1/2, 2012 at 4:39 Comment(0)
F
10

Use map rects. Here's an example using the map's current visible rect. With regards to your question, you could use convertRegion:toRectToView: to first convert your region to a MKMapRect beforehand.

MKMapPoint userPoint = MKMapPointForCoordinate(mapView.userLocation.location.coordinate);
MKMapRect mapRect = mapView.visibleMapRect;
BOOL inside = MKMapRectContainsPoint(mapRect, userPoint);
Felicle answered 27/3, 2012 at 5:44 Comment(1)
Ha, funny to get an answer so much later! Thanks, a good answer so I'll go ahead and give you the mark -- the convertRegion:toRectToView is the thing I was missing.Heliostat
R
2

Swift 3 version of firstresponder's answer:

let userPoint = MKMapPointForCoordinate(mapView.userLocation.coordinate)
let mapRect = mapView.visibleMapRect
let inside = MKMapRectContainsPoint(mapRect, userPoint)

Pretty much the same. This API has not been Swift-ified (i.e., updated to conform to the Swift API design guidelines) yet. It really should be...

let userPoint = mapView.userLocation.coordinate.mapPoint
let inside = mapView.visibleMapRect.contains(userPoint)
Returnable answered 1/1, 2017 at 13:8 Comment(0)
H
0

There is a simple solution to decide if a point is inside your area if the area is given by a polygon using the ray casting algorithm: See here http://en.wikipedia.org/wiki/Point_in_polygon

As a starting point use a location guaranteed to be outside your region, e.g. (geographic) north pole.

Hokanson answered 1/2, 2012 at 7:55 Comment(1)
I was really looking for something in MapKit that would do the work for me!Heliostat

© 2022 - 2024 — McMap. All rights reserved.