Question

I'm currently trying to create a Map where there are some polygons and then a user can enter a specific city or postcode, and then a Marker is set to the entered point. If the entered city/postcode is within the polygon, there should be an InfoWindow with some specific output like "Your place is in area X", if not there should be a different output. What I got so far are two polygons on a Map and you can enter a city and the marker is set. But what's not working is the InfoWindow (no InfoWindow at the "Click" Event) even though it should work as I used the Google Developer Examples. And I don't know how implement the described query if the Marker is in the polygon or not and the combination with a specific output in form of a InfoWindow...

Sorry my english is really bad - hope you guys understand what I'm talking about!

<!DOCTYPE html>
<html>
  <head>
    <title>Glaswelt24 Montagebereich</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body, #map-canvas {
        height: 550px;
        margin: 20px;
        padding: 20px
        width: 200px;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&language=ch"></script>
    <script>

//Deklarierung der Variablen
var geocoder;
var map;


function initialize() {

geocoder = new google.maps.Geocoder();

  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(46.8131873, 8.2242101),
   disableDefaultUI: false
  };

  var bermudaTriangle;
  var bermudaTriangle2;

//Deklarierung der neuen Google Maps Karte
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  //Inhalt des InfoWindow als Variable deklarieren
      var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
      '<div id="bodyContent">'+
      '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
      'sandstone rock formation in the southern part of the '+
      'Northern Territory, central Australia. It lies 335&#160;km (208&#160;mi) '+
      'south west of the nearest large town, Alice Springs; 450&#160;km '+
      '(280&#160;mi) by road. Kata Tjuta and Uluru are the two major '+
      'features of the Uluru - Kata Tjuta National Park. Uluru is '+
      'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
      'Aboriginal people of the area. It has many springs, waterholes, '+
      'rock caves and ancient paintings. Uluru is listed as a World '+
      'Heritage Site.</p>'+
      '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
      'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
      '(last visited June 22, 2009).</p>'+
      '</div>'+
      '</div>';

//InfoWindow erstellen und Inhalt festlegen
  var infowindow = new google.maps.InfoWindow({
      content: contentString
  });

  //Montagegebiet 1
    var triangleCoords = [
    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)
  ];

  //Montagegebiet 2
    var triangleCoords2 = [
    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)
  ];


  //Aussehen des Montagebiets
  bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#4BC4DF',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#4BC4DF',
    fillOpacity: 0.35
  });

  //Aussehen des Montagegebiets 2
  bermudaTriangle2 = new google.maps.Polygon({
    paths: triangleCoords2,
    strokeColor: '#4BC4DF',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#4BC4DF',
    fillOpacity: 0.35
  });

//Setzen der Montagegebiete auf die Karte
  bermudaTriangle.setMap(map);
  bermudaTriangle2.setMap(map);
}


//Aufrufen der Geocode Funktion die einen Marker auf die Karte setzt
function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);

      //Marker auf der Karte
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          animation: google.maps.Animation.DRPOP,
          draggable: false,
          clickable: true
     });

 } else {
      alert('Die Eingabe war falsch');
    }

        });

        //Beim "Event" Klick wird Marker geöffnet 
oogle.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });

}

//Initialisieren der Karte
google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
  <!-- HTML Teil  -->
  <h1>Montageservice Google Maps</h1>
  <div id="panel">
      <input id="address" type="textbox" value="Kundeneingabe" onFocus="if(this.value=='Kundeneingabe') this.value=''">
      <input type="button" value="Suche" onclick="codeAddress()">
    </div>
    <div id="map-canvas"></div>
  </body>
</html>   
Was it helpful?

Solution

  1. there is a typo

       oogle.maps.event.addListener(marker, 'click', function() {
    //^ missing a g
    
  2. most of your variables are defined local in the scope of initialize, but codeAddress is defined in global scope and isn't able to access these variables
  3. 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>

Demo: http://jsfiddle.net/doktormolle/nYebu/

OTHER TIPS

The code is working now, I wanted to have a InfoWindow which pops up if the Marker is set. It is working if I open the index.html File offline in my browser, bet when I use it in this "testing environment", the InfoWindow part wont work... Why is that?

http://irrturm.de/Montageservice/Index.html

Also if I try to implement my Google Maps API Key, there is a JavaScript Alert telling that my API Key is not valid, even though it should be valid since I created this:

Picture: http://s4.postimg.org/cszh2jad9/Screen_Shot_2014_03_31_at_10_16_12.png

<script>


//Deklarierung der Variablen
var geocoder;
var map;

//Initialisieren der Karte
google.maps.event.addDomListener(window, 'load', initialize);

//Schweiz als Kartenmitte anwählen 
function initialize() {
geocoder = new google.maps.Geocoder();

  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(46.8131873, 8.2242101),
   disableDefaultUI: false
  };

  var bermudaTriangle;
  var bermudaTriangle2;

//Deklarierung der neuen Google Maps Karte
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);


  //Algorithmus um rauszfinden ob Marker im Polygon ist oder nicht






  //Montagegebiet 1
    var triangleCoords = [
    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)
  ];

  //Montagegebiet 2
    var triangleCoords2 = [
    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)
  ];


  //Aussehen des Montagebiets
  bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#4BC4DF',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#4BC4DF',
    fillOpacity: 0.35
  });

  //Aussehen des Montagegebiets 2
  bermudaTriangle2 = new google.maps.Polygon({
    paths: triangleCoords2,
    strokeColor: '#4BC4DF',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#4BC4DF',
    fillOpacity: 0.35
  });

//Setzen der Montagegebiete auf die Karte
  bermudaTriangle.setMap(map);
  bermudaTriangle2.setMap(map);
}


//ContentString1 (Montage möglich)
 var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">Ihr Ort liegt im Montagegebiet</h1>'+
      '<div id="bodyContent">'+
      '<a href="http://glaswelt24.ch/Montage-Service:_:35.html">'+
      'Jetzt Montageservice buchen</a> '+
      '</div>'+
      '</div>';


 //Contentstring 2 (Montage nicht möglich)     
       var contentString2 = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">Ihr Ort liegt im Montagegebiet</h1>'+
      '<div id="bodyContent">'+
      '<a href="http://glaswelt24.ch/Montage-Service:_:35.html">'+
      'Jetzt Montageservice buchen</a> '+
      '</div>'+
      '</div>';

//InfoWindow erstellen ohne Inhalt 
var infowindow = new google.maps.InfoWindow({
content: contentString
});

//InfoWindow2
var infowindow2 = new google.maps.InfoWindow({
content: contentString2
});


//Adresseingabe
function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address
   }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);


      //Marker auf der Karte
          var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          title: address,
          navigationControl: false,
    mapTypeControl: false,
    scaleControl: false,
    draggable: false
     });

    //Click-Event für den Marker
    infowindow.open(map,marker);

    google.maps.event.addListener(infowindow, 'closeclick', function () {
                        marker.setVisible(false);
                    });

 } else {


        infowindow2.open(map,marker);


    google.maps.event.addListener(infowindow2, 'closeclick', function () {
                        marker.setVisible(false);
                    });

    }

 });      



}

    </script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top