html 单击googleMap信息窗口中按钮的事件

sczxawaw  于 2022-12-21  发布在  Go
关注(0)|答案(1)|浏览(158)

我想为谷歌标记信息窗口中的按钮设置点击事件,这样当用户点击“获取方向”按钮时,谷歌路线就会显示在Map旁边的面板上(它从信息窗口的地址开始到用户的当前地址)。
下面是我的代码。如果你点击商店A的“获取方向”,你会看到一条路线显示在Map旁边的面板上...
如果单击其他按钮,则显示“未捕获的TypeError:无法在_. gg处读取空的属性“addEventListener”。”
我目前卡在循环为这些按钮...有人能给予我一些想法吗?

<!DOCTYPE html>
    <html>

    <head>
      <meta charset="utf-8">
      <title>Store Locations</title>

      <style>
        #map {
          width: 60%;
          height: 650px;
          margin-left: 4%;
          margin-top: 2%
        }

        #right-panel {
          font-family: 'Roboto', 'sans-serif';
          line-height: 30px;
          height: 650px;
          float: right;
          width: 30%;
          overflow: auto;
          margin-top: 2%;
          height: 650px;
          margin-right: 4%;
        }

        @media print {
          #map {
            height: 650px;
            margin-left: 4%;
            width: 60%;
          }

          #right-panel {
            float: right;
            height: 650px;
          }
        }
      </style>

    </head>

    <p id='dTitle'>
      <h3>Store Locations</h3>
    </p>

    <div id="right-panel"></div>
    <div id="map"></div>
    <div id="directionsPanel"></div>


    <script>
      // 初始化map

      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(49.0020285, -97.2347275), zoom: 4
        });
        var storeLocations = [
          { markerId: 1, title: 'Click for location details', LatLng: new google.maps.LatLng(53.483710, -113.483230), contentString: '<div><strong>Store A</strong></div>' + '<p>div>Edmonton AB,  T6E 5C5, Canada</div></p>' + '<div><button class="gDirection1">Get Directions</button></div>' },
          { markerId: 2, title: 'Click for location details', LatLng: new google.maps.LatLng(50.036490, -110.667030), contentString: '<div><strong>Store B</strong></div>' + '<p><div>Medicine Hat AB,  T1A 2Z8, Canada</div></p>' + '<div><button class="gDirection1">Get Directions</button></div>' },
          { markerId: 3, title: 'Click for location details', LatLng: new google.maps.LatLng(49.262760, -123.004020), contentString: '<div><strong>Store C</strong></div>' + '<p><div>Burnaby BC, V5C 5T3, Canada</div></p>' + '<div><button id="gDirection2">Get Directions</button></div>' }]

        var markers = []
        for (var i = 0; i < storeLocations.length; i++) {
          markers[i] = new google.maps.Marker({
            map: map,
            position: storeLocations[i].LatLng,
            content: storeLocations[i].contentString,
            title: storeLocations[i].title
          });
          var infowindow = new google.maps.InfoWindow();
          google.maps.event.addListener(markers[i], 'click', function () {
            infowindow.setContent(this.content);
            infowindow.open(this.getMap(), this);
            infowindow.set(this.title);
          });
        }

        function getCustomercurrentlocation() {
          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
              function (positionGet) {
                map.setCenter(new google.maps.LatLng(positionGet.coords.latitude, positionGet.coords.longitude)),
                  map.setZoom(10)
                var contentcurrentLocation = '<h3><center>Your current location</h3></center>';
                var icon = {
                  url: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
                  scaledSize: new google.maps.Size(55, 55), // scaled size
                };
                var newMarker = new google.maps.Marker({
                  map: map,
                  icon: icon,
                  position: new google.maps.LatLng(positionGet.coords.latitude, positionGet.coords.longitude)
                });
                infowindow.setContent(contentcurrentLocation);
                infowindow.open(map, newMarker);
              },
              function (positionNotget) {
                map.setCenter(new google.maps.LatLng(49.148160, -112.087260)),
                  map.setZoom(4)
              });
          }
          else // browser doesn't suppost Geolocation
            alert('Geolocation is not supported by your browser.');
        }

        //google.maps.event.addListener( "domready",getCustomercurrentlocation());

        var btns = document.getElementById("gDirection");
        google.maps.event.addListener(infowindow, 'domready', function () {
          btns.addListener('click', function calcRoute() {
            var directionsService = new google.maps.DirectionsService();
            var directionsRenderer = new google.maps.DirectionsRenderer();
            directionsRenderer.setMap(map);
            directionsRenderer.setPanel(document.getElementById('right-panel'));
            var start = new google.maps.LatLng(49.148160, -112.087260);
            var end = new google.maps.LatLng(44.71682, -63.58431)
            var request = {
              origin: start,
              destination: end,
              travelMode: 'DRIVING'
            };
            directionsService.route(request, function (result, status) {
              if (status == 'OK') {
                directionsRenderer.setDirections(result);
              }
            });
          })

        }
        )


      }

    </script>
    <script async defer
      src="https://maps.googleapis.com/maps/api/js?key="></script>
    </body>
aiqt4smr

aiqt4smr1#

您会在行上得到错误Uncaught TypeError: Cannot read property 'addEventListener' of null

document.getElementById("gDirection").addEventListener('click',  function calcRoute(){

因为DOM中没有id="gDirection"的元素。
按钮定义如下:

<button class="gDirection">Get Directions</button>

要访问它,需要使用getElementsByClassName("gDirection")[0]
getElementsByClassName返回一个数组,请注意元素s上的“s”)。
在您发布的代码中,DOM中只有一个InfoWindow打开,因此只需要该数组的第一个元素。
更新代码:

google.maps.event.addListener(infowindow, 'domready', function() {
  document.getElementsByClassName("gDirection")[0].addEventListener('click', function calcRoute() {
    var directionsService = new google.maps.DirectionsService();
    var directionsRenderer = new google.maps.DirectionsRenderer();
    directionsRenderer.setMap(map);
    directionsRenderer.setPanel(document.getElementById('right-panel'));
    var start = new google.maps.LatLng(49.148160, -112.087260);
    var end = new google.maps.LatLng(44.71682, -63.58431)
    var request = {
      origin: start,
      destination: end,
      travelMode: 'DRIVING'
    };
    console.log("origin="+request.origin.toUrlValue(6)+" dest="+request.destination.toUrlValue(6));
    directionsService.route(request, function(result, status) {
      if (status == 'OK') {
        directionsRenderer.setDirections(result);
      }
    });
  })
})

proof of concept fiddle

一个三个三个一个

相关问题