there is a typo
oogle.maps.event.addListener(marker, 'click', function() { //^ missing a g
- most of your variables are defined local in the scope of
initialize
, butcodeAddress
is defined in global scope and isn't able to access these variables - use the method
google.maps.geometry.poly.containsLocation
to detect if the marker is within a polygon(Note: you must include the geometry-library, it's not loaded by default)
fixed code(I've removed irrelevant stuff):
<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&language=ch&libraries=geometry"></script>
<script>
function initialize() {
var geocoder = new google.maps.Geocoder(),
mapOptions = { zoom: 8,
center: new google.maps.LatLng(46.8131873, 8.2242101)
},
//use only a single marker
marker = new google.maps.Marker(),
infowindow = new google.maps.InfoWindow(),
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions),
//store the polygons in an array for iteration
polys = [];
polys[0] = new google.maps.Polygon({
title:'Montagegebiet 1',
paths: [
new google.maps.LatLng(47.554615, 7.59446),
new google.maps.LatLng(47.377455, 8.536715),
new google.maps.LatLng(46.9546699, 7.39487),
new google.maps.LatLng(47.554615, 7.59446)
],
map:map
});
polys[1] = new google.maps.Polygon({
title:'Montagegebiet 2',
paths: [
new google.maps.LatLng(46.74021, 7.638205),
new google.maps.LatLng(46.1731573, 8.7772588),
new google.maps.LatLng(47.04739, 8.3183349),
new google.maps.LatLng(46.74021, 7.638205)
],
map:map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
//define the codeAdress-function in the scope of initialize
//to be able to access all variables without declaring them global
window.codeAddress = function() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var position = results[0].geometry.location,
//default-content for infowindow
content = 'Die Eingabe befindet sich in keinem der Bereiche';
map.setCenter(position);
marker.setOptions({
map:map,
animation: google.maps.Animation.DRPOP,
position: position
});
for(var i=0;i<polys.length;++i){
//check if the latLng is placed within the polygon
if(google.maps.geometry.poly.containsLocation(position,polys[i])){
//if it does, update the content for the infowindow
content = 'Die Eingabe wurde in '+polys[i].title+' lokalisiert';
//and leave the loop
break;
}
}
//open the infowindow
infowindow.setOptions({
map:map,
position:position,
content:content
});
}
else {
//hide the infowindow
infowindow.setMap(null);
alert('Die Eingabe lieferte kein Ergebnis');
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>