Latest

random

How to Check If Point Exist in a Polygon - Google Maps API v3

Check if a point is Inside a Polygon or not with Google Maps API v3


In the previous article I explained about how to get Latitude and Longitude Coordinates of a Polygon - Google Maps API v3. In this article we will check if a point is inside a Polygon using Google Maps API v3. Find the source code below:-

Check if a point is Inside a Polygon or not with Google Maps API v3
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>How to 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&sensor=false"></script>
    <script type="text/javascript">
        var map;
        var boundaryPolygon;
        function initialize() {

            var mapProp = {
                center: new google.maps.LatLng(26.038586842564317, 75.06787185438634),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            map = new google.maps.Map(document.getElementById("map-canvas"), mapProp);

            google.maps.Polygon.prototype.Contains = function (point) {
                // ray casting alogrithm http://rosettacode.org/wiki/Ray-casting_algorithm
                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)) {

                    document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " inside the polygon.";
                } else {
                    document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " outside the polygon.";
                }

            });
        }


        function drawPolygon() {

            initialize();
            var boundary = '77.702866 28.987153, 77.699776 28.978594 ,77.735996 28.974164 ,77.719946 28.99346 ,77.713423 28.994361 ,77.711706 28.990382 ';
            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: "#0000FF",
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: 'Red',
                fillOpacity: 0.4

            });

            google.maps.event.addListener(boundaryPolygon, 'click', function (event) {
                document.getElementById("spnMsg").innerText = '';
                if (boundaryPolygon.Contains(event.latLng)) {
                    document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " inside the polygon.";
                } else {
                    document.getElementById("spnMsg").innerText = "This location is " + event.latLng + " outside the polygon.";
                }

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

        }

    </script>
</head>
<body onload="initialize();drawPolygon();">
    <form id="form1" runat="server">
        <h3>Check If Point Exist in a Polygon</h3>
        <span id="spnMsg" style="font-family: Arial; text-align: center; font-size: 14px; color: red;"></span>
        <br />
        <br />
        <div id="map-canvas" style="width: auto; height: 500px;">
        </div>

    </form>
</body>
</html>

Download the source code click here..
Please leave your comments, suggestions and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!

2 comments:

All Rights Reserved by Etechpulse © 2015 - 2016
Powered By Blogger

Contact Form

Name

Email *

Message *

Powered by Blogger.