Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can create a path from the four points of the rectangle and then use <code>CGPathContainsPoint</code> to check whether the current location is inside the path.</p> <p>As for the conversion of latitude and longitude to planar x, y coordinates, the simplest solution is to use Mercator projection using Map Kit. Check <a href="http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/LocationAwarenessPG/MapKit/MapKit.html#//apple_ref/doc/uid/TP40009497-CH3-SW5" rel="nofollow">Understanding Map Geometry</a> for more info.</p> <p>Here's an example:</p> <pre><code>// create four rectangle points from A, B dx = (B.x - A.x) * 0.05; // 5% of the A-B length dy = (B.y - A.y) * 0.05; // topmost corner, above B points[0].x = B.x + dx - dy; points[0].y = B.y + dy + dx; //rightmost corner, to the right from B points[1].x = B.x + dx + dy; points[1].y = B.y + dy - dx; ... CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, points[0].x, points[0].y); CGPathAddLineToPoint(path, NULL, points[1].x, points[1].y); CGPathAddLineToPoint(path, NULL, points[2].x, points[2].y); CGPathAddLineToPoint(path, NULL, points[3].x, points[3].y); CGPathCloseSubpath(path); // convert latitude, longitude to planar coordinates MKMapPoint location = MKMapPointForCoordinate([newLocation coordinate]); BOOL inside = CGPathContainsPoint(path, NULL, CGPointMake(location.x, location.y), YES); CGPathRelease(path); </code></pre> <p>Note: This code expects that the current location is a point, while in reality, it is a point and a radius of accuracy, which is effectively a circle. This complicates things a bit because now you need to define how to handle situations when the current location is not known <em>exactly</em>, but you only know that it's somewhere in the circle. If the rectangle is large (say 5 km), then you may simply require radius of accuracy less than 50m, do the calculation as if the current location was exact and ignore the small inaccuracy of the computation. If the rectangle is smaller (say 50m), you may also do the calculation as if the current location was exact, but then the false positives probability would be higher (e.g. sometimes you would be detected as in the rectangle while you would be standing outside of it).</p> <p>Or you may want to go for the "perfect" solution and do circle-rectangle intersection, which is more complex and may result not only in YES and NO answers but also in "with this accuracy it cannot be determined whether you are inside or outside of the rectangle".</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload