Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if coordinate is inside region (MKMapView, solve in PHP)

I'm using MKMapView and I send my php program the visible region (center lat, center lon, span lat, span lon). I need to determine if a coordinate is inside that region using php. I'm hoping there's a standard formula somewhere, but I haven't found one. I'll keep trying to come up with a formula, but it's surprisingly complicated (hopefully not as much as the haversine, which I don't believe I could have figured out myself).

like image 781
Elliot Alderson Avatar asked Jun 14 '15 08:06

Elliot Alderson


1 Answers

lets try this logic

$topRightLongitude = $centerLongitude + $spanLongitude/2;
if($topRightLongitude > 180 and ($pointLongitude < 0))
    $topRightLongitude = $topRightLongitude - 360; // (180*2) - positive becomes negative

$bottomLeftLongitude = $centerLongitude - $spanLongitude/2;
if($bottomLeftLongitude< -180 and ($pointLongitude > 0))
    $bottomLeftLongitude= 360 + $bottomLeftLongitude; // now is negative and will become positive

$topRightLatitude = $centerLatitude + $spanLatitude/2;
if($topRightLatitude > 90 and ($pointLatitude < 0))
    $topRightLatitude = $topRightLatitude - 180; // (90*2) - positive becomes negative

$bottomLeftLatitude = $centerLatitude - $spanLatitude/2;
if($bottomLeftLatitude< -90 and ($pointLatitude > 0))
    $bottomLeftLatitude= 180 + $bottomLeftLongitude; // now is negative and will become positive

if you have

$centerLongitude = 179;
$spanLongitude = 20;
$pointLongitude = -179;

results

$topRightLongitude = -171;
$bottomLeftLongitude = 169;

so your point is in if you test like this:

if($pointLongitude < $topRightLongitude &&
    $pointLongitude > $bottomLeftLongitude &&
    $pointLatitude < $topRightLatitude &&
    $pointLatitude > $bottomLeftLatitude){
    echo 'in';
}else{
    echo 'out';
}
like image 197
Macerier Avatar answered Nov 15 '22 05:11

Macerier