Skip to content

Instantly share code, notes, and snippets.

@cdvillagra
Last active June 10, 2016 17:07
Show Gist options
  • Save cdvillagra/c35ad93debbd3bef43445fce7fb17d49 to your computer and use it in GitHub Desktop.
Save cdvillagra/c35ad93debbd3bef43445fce7fb17d49 to your computer and use it in GitHub Desktop.
Method checks if a point is contained in the polygon
<?php
/*
|--------------------------------------------------------------------------------
| Point on Polygon - DVILLAGRA
|--------------------------------------------------------------------------------
|
| # Method checks if a point is contained in the polygon
|
| @author Christopher Villagra - <[email protected]>
| @param $polygon [array]
| @param $point [array]
| @return $onPolygon [boolean]
|
*/
public function pointPolygon($polygon, $point){
$onPolygon = false;
//# Get the coordinates of point
$pX = floatval($point[0]);
$pY = floatval($point[1]);
$totalPoints = count($polygon);
$j = $totalPoints - 1;
//# Looping to check
for ($i = 0; $i < $totalPoints; $i++) {
//# Obtaining coordinates of a polygon edges
$pIni = $polygon[$i];
$pEnd = $polygon[$j];
//# First check by Jordan curve theorem
if(
(floatval($pIni['x']) < $pX) && (floatval($pEnd['x']) >= $pX) ||
(floatval($pEnd['x']) < $pX) && (floatval($pIni['x']) >= $pX)
){
if(
floatval($pIni['y']) + ($pX - floatval($pIni['x'])) /
(floatval($pEnd['x']) - floatval($pIni['x'])) *
(floatval($pEnd['y']) - floatval($pIni['y'])) <
$pY
){
//# Invert status check
$onPolygon = !$onPolygon;
}
}
$j = $i;
}
//# Return if a point is contained in the polygon
return $onPolygon;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment