I have what I believe to be very simple code. I draw a polygon, a marker and then throw an alert if the point I have hard-coded is within the polygon. Yet when I run this I get an ‘Uncaught TypeError: Cannot call method 'lng' of undefined‘ error in the console.
My code is as follows:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(38.990842,-76.93625),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var box = [new google.maps.LatLng(38.9913160,-76.937079),
new google.maps.LatLng(38.991333,-76.936119),
new google.maps.LatLng(38.990287, -76.936108),
new google.maps.LatLng(38.990278,-76.937057),
new google.maps.LatLng(38.990495,-76.937052),
new google.maps.LatLng(38.990499,-76.936424),
new google.maps.LatLng(38.991091,-76.93643),
new google.maps.LatLng(38.991104,-76.937079)
];
var mPoint = [new google.maps.LatLng(38.991300,-76.936165)];
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(38.991300,-76.936165),
//position: new google.maps.LatLng(mPoint),
draggable: true
});
var AVpoly = new google.maps.Polygon({path:box,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4});
AVpoly.setMap(map);
marker.setMap(map);
if(google.maps.geometry.poly.containsLocation(google.maps.LatLng(38.990842,-76.93625), box) == true) {
alert("yes");
}
}
I cannot see anything wrong with this nor do I see why the alert if not firing. I did even change it to false in the off-chance my geometry was wrong….
Box is not a google.maps.Polygon; it is an array of google.maps.LatLng objects. Use AVpoly instead (the documentation specifies the second argument is a Polygon).
That doesn’t work, you are also missing the “new” for the google.maps.LatLng constructor. This does work (using the marker.getPosition method which returns a google.maps.LatLng):
Working (if annoying) example