Knowing if I am in a region through latitude and longitude

2

I need to know through coordinates if I am in the area of a region, in this case, the code below is in PHP with polygon, but it is not working. Am I missing the coordinate question (x, y)?

I looked for something with the Google Maps API, but so far nothing.

<?php
$vertices_x = array(-4.0680,-4.0352,-4.1180,-4.0708,); // x-coordinates of the vertices of the polygon
$vertices_y = array( -63.1391,-63.0330,-63.1065, -63.0087); // y-coordinates of the vertices of the polygon
$points_polygon = count($vertices_x); // number vertices
//$longitude_x = $_GET["longitude"]; // x-coordinate of the point to test
//$latitude_y = $_GET["latitude"]; // y-coordinate of the point to test
//// For testing.  This point lies inside the test polygon.
 $longitude_x = 4.0756;
 $latitude_y =  -63.0753;

if (is_in_polygon($points_polygon, $vertices_x, $vertices_y, $longitude_x, $latitude_y)){
  echo "estou na area";
}
else echo "nao estou na area";


function is_in_polygon($points_polygon, $vertices_x, $vertices_y, $longitude_x, $latitude_y)
{
  $i = $j = $c = 0;
  for ($i = 0, $j = $points_polygon-1 ; $i < $points_polygon; $j = $i++) {
    if ( (($vertices_y[$i] > $latitude_y != ($vertices_y[$j] > $latitude_y)) &&
    ($longitude_x < ($vertices_x[$j] - $vertices_x[$i]) * ($latitude_y - $vertices_y[$i]) / ($vertices_y[$j] - $vertices_y[$i]) + $vertices_x[$i]) ) ) 
        $c = !$c;
  }
  return $c;
}
?>
    
asked by anonymous 30.04.2018 / 01:26

1 answer

1

You can simplify the function only by checking if the $longitude_x and $latitude_y coordinates are inside the polygon with the vertices entered in the arrays:

function is_in_polygon($points_polygon, $vertices_x, $vertices_y, $longitude_x, $latitude_y)
{
   $c = 0;
  for ($i = 0, $j = $points_polygon-1 ; $i < $points_polygon; $j = $i++) {
   if(
      $latitude_y <= $vertices_y[$i] && $latitude_y >= $vertices_y[$j] &&
      $longitude_x >= $vertices_x[$j] && $longitude_x <= $vertices_x[$i]
   )
   $c = !$c;
  }
  return $c;
}

The function checks whether the Y coordinate is less than or equal than the first 3 vertices and greater than or equal to than the last, and the same with the X coordinate. For the point given by the coordinates X, Y ( lng and lat , respectively) to be within the area of the polygon, / p>     

30.04.2018 / 03:33