Check if point inside polygon Google Maps-thumb

Check if point is inside polygon JavaScript

In the previous tutorial, I have explained and demonstrated about Google Maps Draw Polygon Get Coordinates with an example. Next, to this, we will learn how to check if a point inside polygon Google Maps.

Check if point inside polygon google maps javascript

A polygonal area may include several separate paths (specifies an array of arrays), each array defines a separate sequence of ordered Latitude and Longitude coordinates. So the following google maps API example will show you how we can check if marker is inside circle radius JavaScript or check if point inside polygon google maps:-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Check If Point Exist in a Polygon | Google Maps API v3</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyDSO3AY5oHy5pGgRcPq4glHlPAbDsL9HQ0"></script>
    <script type="text/javascript">
        var map;
        var boundaryPolygon;

        function initialize() {
            var myLatlng = new google.maps.LatLng(28.612253845413395, 77.222900390625);
            var mapOptions = {
                center: myLatlng
            };

            map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
            var marker = new google.maps.Marker({
                position: myLatlng,
                title: "Hi!"
            });

            marker.setMap(map);

            google.maps.Polygon.prototype.Contains = function (point) {

                var crossings = 0,
                    path = this.getPath();

                // for each edge
                for (var i = 0; i < path.getLength(); i++) {
                    var a = path.getAt(i),
                        j = i + 1;
                    if (j >= path.getLength()) {
                        j = 0;
                    }
                    var b = path.getAt(j);
                    if (rayCrossesSegment(point, a, b)) {
                        crossings++;
                    }
                }

                // odd number of crossings?
                return (crossings % 2 == 1);

                function rayCrossesSegment(point, a, b) {
                    var px = point.lng(),
                        py = point.lat(),
                        ax = a.lng(),
                        ay = a.lat(),
                        bx = b.lng(),
                        by = b.lat();
                    if (ay > by) {
                        ax = b.lng();
                        ay = b.lat();
                        bx = a.lng();
                        by = a.lat();
                    }
                    if (py == ay || py == by) py += 0.00000001;
                    if ((py > by || py < ay) || (px > Math.max(ax, bx))) return false;
                    if (px < Math.min(ax, bx)) return true;

                    var red = (ax != bx) ? ((by - ay) / (bx - ax)) : Infinity;
                    var blue = (ax != px) ? ((py - ay) / (px - ax)) : Infinity;
                    return (blue >= red);
                }
            };


            google.maps.event.addListener(map, 'click', function (event) {

                if (boundaryPolygon != null && boundaryPolygon.Contains(event.latLng)) {
                    alert(event.latLng + " Inside Polygon.");
                } else {
                    alert(event.latLng + " Outside Polygon.");
                }

            });
        }


        function drawPolygon() {

            initialize();
            var boundary = '79.3103 28.8146, 77.699776 27.4833, 76.31928 28.18801, 75.40466 29.17628, 77.35474 29.69368';
            var boundarydata = new Array();

            var latlongs = boundary.split(",");

            for (var i = 0; i < latlongs.length; i++) {
                latlong = latlongs[i].trim().split(" ");
                boundarydata[i] = new google.maps.LatLng(latlong[1], latlong[0]);
            }

            boundaryPolygon = new google.maps.Polygon({
                path: boundarydata,
                strokeColor: "",
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: '#ADFF2F',
                fillOpacity: 0.4

            });

            google.maps.event.addListener(boundaryPolygon, 'click', function (event) {
                if (boundaryPolygon.Contains(event.latLng)) {
                    alert(event.latLng + " Inside Polygon.");
                } else {
                    alert(event.latLng + " Outside Polygon.");
                }

            });

            map.setZoom(7);
            map.setCenter(boundarydata[0]);
            boundaryPolygon.setMap(map);

        }

    </script>
</head>
<body onload="initialize();drawPolygon();">
    <h1>Check if point inside polygon google maps</h1>
    <div id="map-canvas" style="width: auto; height: 500px;">
    </div>
</body>
</html>

Also, you can use the Geometry Library of the Google Maps JavaScript API. There’s a function called containsLocation which tells you if a given LatLng is inside a Polygon. So there is no such thing as a point being inside a polyline. You can check if a point is inside a Polygon with the containsLocation function.

Did you find this post useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here