Google Map: is a lat/lng within a polygon?

后端 未结 4 1667
-上瘾入骨i
-上瘾入骨i 2020-12-06 06:44

Given a pair of lat/lng values, how do I determine if the pair is within a polygon? I need to do this in PHP. I see that Google Maps API has a containsLocation

4条回答
  •  抹茶落季
    2020-12-06 07:19

    very big thanks to David Strachan and Darel Rex Finley

    i want to share my php version, is slightly different beacause it takes the point as an array ([lat, lng]) and the polygon as an array of point ([[lat, lng],[lat, lng],...])

      function pointInPolygon($point, $polygon){//http://alienryderflex.com/polygon/
         $return = false;
         foreach($polygon as $k=>$p){
            if(!$k) $k_prev = count($polygon)-1;
            else $k_prev = $k-1;
    
            if(($p[1]< $point[1] && $polygon[$k_prev][1]>=$point[1] || $polygon[$k_prev][1]< $point[1] && $p[1]>=$point[1]) && ($p[0]<=$point[0] || $polygon[$k_prev][0]<=$point[0])){
               if($p[0]+($point[1]-$p[1])/($polygon[$k_prev][1]-$p[1])*($polygon[$k_prev][0]-$p[0])<$point[0]){
                  $return = !$return;
               }
            }
         }
         return $return;
      }
    

提交回复
热议问题