谷歌地图API3信息窗口,并查询标记是否在多边形中

Google Maps API3 InfoWindow and query if Marker is in polygon or not

本文关键字:是否 多边形 查询 信息 API3 信息窗 窗口 谷歌地图      更新时间:2023-09-26

>我目前正在尝试创建一个地图,其中有一些多边形,然后用户可以输入特定的城市或邮政编码,然后将标记设置为输入的点。如果输入的城市/邮政编码位于多边形内,则应该有一个带有一些特定输出的信息窗口,例如"您的位置在区域 X 中",如果没有,则应该有不同的输出。到目前为止,我得到的是地图上的两个多边形,您可以输入一个城市并设置标记。但是不起作用的是InfoWindow(在"点击"事件中没有InfoWindow),即使它应该像我使用Google开发人员示例一样工作。而且我不知道如何实现所描述的查询,如果标记是否在多边形中,以及如何以信息窗口的形式与特定输出的组合......

对不起,我的英语真的很差 - 希望你们明白我在说什么!

<!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>   
  1. 有错别字

       oogle.maps.event.addListener(marker, 'click', function() {
    //^ missing a g
    
  2. 大多数变量在 initialize 的作用域中局部定义,但codeAddress变量是在全局范围内定义的,无法访问这些变量
  3. 使用方法google.maps.geometry.poly.containsLocation检测标记是否在多边形内(注意:您必须包含几何库,默认情况下不会加载)

固定代码(我删除了不相关的东西):


<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>

演示:http://jsfiddle.net/doktormolle/nYebu/

代码现在可以工作了,我想有一个信息窗口,如果设置了标记,它会弹出。如果我打开索引,它正在工作.html 在我的浏览器中离线文件,打赌当我在这个"测试环境"中使用它时,InfoWindow 部分将无法工作......为什么?

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

此外,如果我尝试实现我的谷歌地图API密钥,有一个JavaScript警报告诉我的API密钥无效,即使它应该是有效的,因为我创建了这个:

图片: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>