• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
Email: info@dotnettec.com | Mobile: +91-8800268750

DotNetTec

  • Home
  • Tutorials
    • Programming Language
      • C#
      • JavaScript
    • .Net Development
      • .NET Framework
      • ASP.NET Web Forms
      • MVC Architecture
      • Web API
      • .NET Core Framework
    • Front End Frameworks
      • JavaScript
      • HTML
    • Cloud Computing
      • Microsoft Azure
    • Database
      • SQL Server
    • Google Maps API
    • RPA
      • Blue Prism
      • UiPath
  • How to
  • Knowledge Base
  • Shop

Check if point inside polygon Google Maps JavaScript

January 12, 2021 by Ravi Kumar Leave a Comment

In this blog post, you will learn how to check if point inside polygon with google maps javascript API v3 example. As you know we can draw various shapes to your map that is basically an object on the map tied to latitude/longitude coordinate. There are the following shapes available like lines, polygons, circles, and rectangles.

  • Keep reading on How to draw a circle on Google Maps, Google Maps Draw Polygon Get Coordinates

Check if point inside polygon on Google Maps using 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. The following example will demonstrate to you how to determine if latitude longitude within polygon javascript on google maps.

So first we will draw a polygon on Google Maps with coordinates and then we will check if lat-long is inside a polygon or outside. Find the code snippet below:-

<html>
<head>
    <title>determine if latitude longitude within polygon javascript</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=YOUR-KEY"></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>

Download Source Code

Conclusion

I hope you liked this article on how to check if point is inside polygon google maps javascript. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Category iconGoogle Maps API,  JavaScript Tag iconcheck if point inside polygon google maps javascript,  check if point is inside polygon,  determine if latitude longitude within polygon

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Recent Posts

  • Google Maps Draw Polygon Get Coordinates
  • Check if point inside polygon Google Maps JavaScript
  • How to Create a Calendar Control in ASP.NET
  • Interview Etiquette Before, During and After
  • How to Attend Telephonic Interview Tips

Products

  • Online Shopping ASP.NET Project Source Code Online Shopping ASP.NET Project Source Code
    Rated 5.00 out of 5
    $69.00 $39.00
  • responsive-aspnet-mvc-grid-view ASP.NET MVC full Ajaxify and Bootstrap Grid with CRUD Operation
    Rated 4.67 out of 5
    $21.00 $9.00
  • eCommerce Website Source Code in ASP.NET eCommerce Website Source Code in ASP.NET $99.00
  • Hospital Management System Project ASP.Net Source Code
    Rated 5.00 out of 5
    $99.00
  • Whatsapp Bulk Message Sender Source Code WhatsApp Bulk Message Sender Source Code
    Rated 5.00 out of 5
    $69.00

Footer

DotNetTec

A platform for Software Developers and Architects. Learn new skills and apply them in real-life to build an end to end applications.

Sitemap

  • About
  • Blog
  • Shop
  • Contact
  • Privacy Policy

Expertise

  • Web Development
  • Custom Software Development
  • Web API Development
  • Google Maps APIs
  • Facebook
  • Instagram
  • Pinterest
  • Twitter
  • YouTube

Copyright © 2021 DotNetTec. All rights reserved. Return to top