Haneef Puttur

Google Map Script to Check Location in Predefined Polygon

Solution : Imagine you want a script which will highlight if you are within a scope of the Map with Red or  with Green if Outside.

 

 

<!DOCTYPE html>
<html>
 <head>
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
 <meta charset="utf-8">
 <title>Polygon arrays</title>
 <style>
 html, body, #map-canvas {
 height: 100%;
 margin: 0px;
 padding: 0px
 }
 </style>
 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=geometry"></script>
<!-- haneef added -->

<!-- Enter the GPS Codes of location to start when Map opens -->
 <script>
function initialize() {
 var mapOptions = {
 center: new google.maps.LatLng(24.44721063299807, 54.39360558986664),
 zoom: 4,
 mapTypeId: google.maps.MapTypeId.TERRAIN
 };

 var map = new google.maps.Map(document.getElementById('map-canvas'),
 mapOptions);
<!-- Enter the GPS Codes polygon areas of location -->
var triangleCoords = [
 new google.maps.LatLng(25.380013069118338, 55.399932861328125),
 new google.maps.LatLng(25.412268198336445, 55.85380554199219),
 new google.maps.LatLng(24.17682515045749, 55.667724609375), 
 new google.maps.LatLng(24.016361823963027, 52.6025390625)
 ];

 
 var haneefTriangle = new google.maps.Polygon({
 paths: triangleCoords
 });

 google.maps.event.addListener(map, 'click', function(e) {
 var result;
 if (google.maps.geometry.poly.containsLocation(e.latLng, haneefTriangle)) {
 result = 'red';
 } else {
 result = 'green';
 }

 var circle = {
 path: google.maps.SymbolPath.CIRCLE,
 fillColor: result,
 fillOpacity: .2,
 strokeColor: 'white',
 strokeWeight: .5,
 scale: 10
 };

 new google.maps.Marker({
 position: e.latLng,
 map: map,
 icon: circle
 })
 });
}

google.maps.event.addDomListener(window, 'load', initialize);
 </script>
 </head>
 <body>
 <div id="map-canvas"></div>
 </body>
</html>

.

Exit mobile version