Skip to content

Instantly share code, notes, and snippets.

@afiqiqmal
Created April 16, 2021 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afiqiqmal/1429a62527d137e4e41d9ea73d055669 to your computer and use it in GitHub Desktop.
Save afiqiqmal/1429a62527d137e4e41d9ea73d055669 to your computer and use it in GitHub Desktop.
Check if location is inside polygon or not
<?php
class PointLocation
{
public static function pointInPolygon($point, $vertices): string
{
if (self::pointOnVertex($point, $vertices) == true) {
return "vertex";
}
$intersections = 0;
$vertices_count = count($vertices);
for ($i=1; $i < $vertices_count; $i++) {
$vertex1 = $vertices[$i-1];
$vertex2 = $vertices[$i];
if ($vertex1['lng'] == $vertex2['lng'] && $vertex1['lng'] == $point['lng'] && $point['lat'] > min($vertex1['lat'], $vertex2['lat']) && $point['lat'] < max($vertex1['lat'], $vertex2['lat'])) { // Check if point is on an horizontal polygon boundary
return "boundary";
}
if ($point['lng'] > min($vertex1['lng'], $vertex2['lng']) && $point['lng'] <= max($vertex1['lng'], $vertex2['lng']) && $point['lat'] <= max($vertex1['lat'], $vertex2['lat']) && $vertex1['lng'] != $vertex2['lng']) {
$xinters = ($point['lng'] - $vertex1['lng']) * ($vertex2['lat'] - $vertex1['lat']) / ($vertex2['lng'] - $vertex1['lng']) + $vertex1['lat'];
if ($xinters == $point['lat']) {
return "boundary";
}
if ($vertex1['lat'] == $vertex2['lat'] || $point['lat'] <= $xinters) {
$intersections++;
}
}
}
if ($intersections % 2 != 0) {
return "inside";
} else {
return "outside";
}
}
private static function pointOnVertex($point, $vertices)
{
foreach($vertices as $vertex) {
if ($point == $vertex) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment