Search code examples
phpgoogle-mapsgoogle-maps-api-3point-in-polygon

Find Point 2 mile away from polygon PHP


I have the polygon data, in the form of an array of latitudes and longitudes in mysql database, ex:

an array of latitudes and longitudes in mysql database.

[["x":23.628134,  "y":27.458334],
["x":23.629867,   "y":27.449021],
["x":23.62324,    "y":27.445416],
["x":23.622424,   "y":27.457819],
["x":23.622424,   "y":27.457819]]

And i have a point (Vertex) with coordinates of latitude and longitude, ex:

$location = new vertex($_GET["longitude"], $_GET["latitude"]);

Now i want to find whether this vertex (point) is 2 miles away from each corner of the polygon or not. How can i do this in php?


Solution

  • If you consider that your points are near compare to the size of the earth, you could compute distance from a coordinate to another using this formula :

    It's a csharp function but easy to port to php

        double getGroundDistance(double latA, double lonA, double latB, double lonB)
        {
            double a = Math.PI / 180;
            double lat1 = latA * a;
            double lat2 = latB * a;
            double lon1 = lonA * a;
            double lon2 = lonB * a;
            double t1 = Math.Sin(lat1) * Math.Sin(lat2);
            double t2 = Math.Cos(lat1) * Math.Cos(lat2);
            double t3 = Math.Cos(lon1 - lon2);
            double t4 = t2 * t3;
            double t5 = t1 + t4;
            double radDist = Math.Atan(-t5 / Math.Sqrt(-t5 * t5 + 1)) + 2 * Math.Atan(1);
            return (radDist * 3437.74677 * 1.1508) * 1.6093470878864446 * 1000;
        }
    

    So you just need to check your distance from each point.

    Hope it help