Google Maps v3: check if point exists in polygon

后端 未结 7 1857
-上瘾入骨i
-上瘾入骨i 2020-11-27 14:09

I am looking to find a way of checking if a point exists inside a polygon in Google Maps v3 (JavaScript). I\'ve searched everywhere and the only solutions I have found so fa

相关标签:
7条回答
  • 2020-11-27 14:34

    You can do this quite simply with Google maps geometry library.

    First be sure to add the google maps geometry library.

    <script type="text/javascript" src="//maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
    

    Then, define your polygon

    var rightShoulderFront = new google.maps.Polygon({
                paths: myCoordinates
            });
    rightShoulderFront .setMap(map);
    

    I'm going to add an event listener to handle a 'click' event, but you can adapt to fit your needs

    google.maps.event.addListener(rightShoulderFront , 'click', isWithinPoly);
    

    Create a function to handle our click event an check if coordinate exists within polygon using Google's geometry library

    /** @this {google.maps.Polygon} */
    function isWithinPoly(event){
       var isWithinPolygon = google.maps.geometry.poly.containsLocation(event.latLng, this);
        console.log(isWithinPolygon);
    }
    
    0 讨论(0)
提交回复
热议问题