Check if lat/long point is inside polygons

Mai Muhammedb 1 Reputation point
2021-05-29T20:54:53.22+00:00
**Hi , I need help to Check if  array of lat/long point is inside polygons in map.**
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,291 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,016 Reputation points Microsoft Vendor
    2021-05-31T06:19:33.657+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    Xamarin.Forms.Maps do not have this API to check the point is inside polygons, but we can judge it by ourselves. I refer to this thread, then I change it get following answer.

       public bool IsPointInPolygon(Position p, Position[] polygon)  
               {  
                   double minX = polygon[0].Latitude;  
                   double maxX = polygon[0].Latitude;  
                   double minY = polygon[0].Longitude;  
                   double maxY = polygon[0].Longitude;  
                   for (int i = 1; i < polygon.Length; i++)  
                   {  
                       Position q = polygon[i];  
                       minX = Math.Min(q.Latitude, minX);  
                       maxX = Math.Max(q.Latitude, maxX);  
                       minY = Math.Min(q.Longitude, minY);  
                       maxY = Math.Max(q.Longitude, maxY);  
                   }  
         
                   if (p.Latitude < minX || p.Latitude > maxX || p.Longitude < minY || p.Longitude > maxY)  
                   {  
                       return false;  
                   }  
         
                   // https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html  
                   bool inside = false;  
                   for (int i = 0, j = polygon.Length - 1; i < polygon.Length; j = i++)  
                   {  
                       if ((polygon[i].Longitude > p.Longitude) != (polygon[j].Longitude > p.Longitude) &&  
                            p.Latitude < (polygon[j].Latitude - polygon[i].Latitude) * (p.Longitude - polygon[i].Longitude) / (polygon[j].Longitude - polygon[i].Longitude) + polygon[i].Latitude)  
                       {  
                           inside = !inside;  
                       }  
                   }  
         
                   return inside;  
               }  
    

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.