benjamin wong
benjamin wong

Reputation: 111

Google maps api containsLocation always returning false

I have drawn a polygon with google maps and tried to include a location that is in the polygon but the containsLocation function always returns false. Not sure if the points on the polygon have to start and end at the exact same location, or if there's an issue with my code.

The location for my containsLocation lat lng is in the shape. Here is the polygon i drew


var rightShoulderFront = new google.maps.Polygon({
  paths: outerCoords
});
const map = new google.maps.Map(document.getElementById("mapSect"), {
  center: { lat:3.528319665937775,lng:101.7580347776062 },
  zoom: 5,
});


var outerCoords =[
  {lat:3.528319665937775,lng:101.7580347776062},
  {lat:3.003044444012029,lng:101.4085838669952},
  {lat:2.9951223092598767,lng:101.82611927913445},
  {lat:3.5216453,lng:101.7636108}
]

      geocoder.geocode({address: selectedFullAddress,},function(results,status)
      {
        lat = results[0].geometry.location.lat();
        lng = results[0].geometry.location.lng();
     
        var curPosition     = new google.maps.LatLng(lat,lng);
        var isWithinPolygon = google.maps.geometry.poly.containsLocation(curPosition, rightShoulderFront)
      });

Upvotes: 0

Views: 1140

Answers (2)

geocodezip
geocodezip

Reputation: 161324

You have issues with the posted code:

  1. A javascript error: InvalidValueError: not an Array on this line: var rightShoulderFront = new google.maps.Polygon({paths: outerCoords}); because outerCoords is not yet defined, and null/undefined is not an Array.
  2. A javascript error: Uncaught (in promise) ReferenceError: geocoder is not defined on this line: geocoder.geocode({address: selectedFullAddress,},function(results,status), because geocoder is not defined in your code.
  3. A javascript error: Uncaught (in promise) ReferenceError: selectedFullAddress is not defined, because selectedFullAddress is not defined in your code.

proof of concept fiddle

screenshot of resulting map

code snippet:

function initMap() {
  var infowindow = new google.maps.InfoWindow();
  var outerCoords = [{
      lat: 3.528319665937775,
      lng: 101.7580347776062
    },
    {
      lat: 3.003044444012029,
      lng: 101.4085838669952
    },
    {
      lat: 2.9951223092598767,
      lng: 101.82611927913445
    },
    {
      lat: 3.5216453,
      lng: 101.7636108
    }
  ]
  const map = new google.maps.Map(document.getElementById("mapSect"));
  var rightShoulderFront = new google.maps.Polygon({
    paths: outerCoords,
    map: map
  });
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < outerCoords.length; i++) {
    bounds.extend(outerCoords[i]);
  }
  map.fitBounds(bounds);


  var geocoder = new google.maps.Geocoder();
  var selectedFullAddress = "Kuala Lumpur"
  geocoder.geocode({
    address: selectedFullAddress,
  }, function(results, status) {
    lat = results[0].geometry.location.lat();
    lng = results[0].geometry.location.lng();
    var marker = new google.maps.Marker({
      position: results[0].geometry.location,
      map: map
    })
    var curPosition = new google.maps.LatLng(lat, lng);
    var isWithinPolygon = google.maps.geometry.poly.containsLocation(curPosition, rightShoulderFront);
    if (isWithinPolygon) {
      infowindow.setContent("isWithinPolygon:" + curPosition.toUrlValue(6));
      infowindow.open(map, marker);
    }
  });
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#mapSect {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Simple Map</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="mapSect"></div>
</body>

</html>

Upvotes: 1

Professor Abronsius
Professor Abronsius

Reputation: 33804

Perhaps the following will help. I rearranged things a little and made a some minor mods but essentially the same. In the original you were calling outerCoords as avalue before it had been declared so I'd imagine there were errors in the console.

<!doctype html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Google Maps: </title>
        <style>
            #mapSect{
                width:100%;
                height:100vh;
                float:none;
                margin:auto;
            }
        </style>
        <script>
            function initMap(){
                // It is unclear where "selectedFullAddress" is defined hence manually assigning here.
                const selectedFullAddress='Jalan Chengal, Kampung Melayu Subang, 40150 Shah Alam, Selangor, Malaysia';
                
                const map = new google.maps.Map( document.getElementById("mapSect"), {
                    center: { lat:3.528319665937775, lng:101.7580347776062 },
                    zoom: 5
                });
                
                const geocoder = new google.maps.Geocoder();
                
                // very basic function to add simple marker to aid visualisation
                const addmarker=function( pos,i ){
                    let marker=new google.maps.Marker({
                        position:pos,
                        title:i + ' [ '+pos+' ]',
                        map:map,
                        draggable:true
                    });
                    return marker;
                };
                let bounds=new google.maps.LatLngBounds();

                var outerCoords =[
                    {lat:3.326413,lng:101.258009},
                    {lat:3.388127,lng:101.787869},
                    {lat:2.9951223092598767,lng:101.82611927913445},
                    {lat:3.003044444012029,lng:101.4085838669952},
                    
                ];
                var rightShoulderFront = new google.maps.Polygon({
                    paths: outerCoords,
                    strokeColor: '#0000CC',
                    strokeOpacity: 0.5,
                    strokeWeight:1,
                    fillColor:'red',
                    fillOpacity:0.25
                });
                
                // iterate over coordinates and extend the bounds object
                outerCoords.forEach( (obj,i)=>{
                    bounds.extend(obj);
                });
                
                map.fitBounds( bounds );
                rightShoulderFront.setMap( map );
                
                
                geocoder.geocode({ address: selectedFullAddress },function(results,status){
                    lat = results[0].geometry.location.lat();
                    lng = results[0].geometry.location.lng();
                    var curPosition     = new google.maps.LatLng(lat,lng);
                    var isWithinPolygon = google.maps.geometry.poly.containsLocation(curPosition, rightShoulderFront)
                    if( isWithinPolygon ) addmarker( curPosition, 'Found Address: '+isWithinPolygon )
                    console.info(results,isWithinPolygon,status)
                });
                
                
            }
        </script>
        <script async defer src='//maps.googleapis.com/maps/api/js?key=<APIKEY>&callback=initMap'></script>
    </head>
    <body>
        <div id='mapSect'></div>
    </body>
</html>

enter image description here

Upvotes: 1

Related Questions