简体   繁体   English

谷歌地图信息窗口中按钮的点击事件

[英]click event for buttons in the google map info window

I want to set up click events for buttons inside google marker infowindow so that when a user click "Get Direction" buttons, google route will show up ( it starts from the infowindow's address to user's current address) at the panel right beside the map.我想为谷歌标记信息窗口内的按钮设置点击事件,以便当用户点击“获取方向”按钮时,谷歌路线将显示在地图旁边的面板上(从信息窗口的地址开始到用户的当前地址)。

Below is my code.下面是我的代码。 If you click 'Get Direction' of store A, you will see a route show up at the panel right beside the map...如果您单击商店 A 的“获取方向”,您将在地图右侧的面板上看到一条路线...

if I click other buttons, it says " Uncaught TypeError: Cannot read property 'addEventListener' of null at _.gg."如果我单击其他按钮,它会显示“未捕获的类型错误:无法读取 _.gg 处的 null 属性‘addEventListener’。”

I currently stuck on the loop for these buttons... can someone give me some ideas?我目前停留在这些按钮的循环中......有人可以给我一些想法吗?


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

You get the error Uncaught TypeError: Cannot read property 'addEventListener' of null on the line:您在行中收到错误Uncaught TypeError: Cannot read property 'addEventListener' of null

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

because there is no element in the DOM with id="gDirection" .因为 DOM 中没有id="gDirection"元素。

The button is defined like this:按钮定义如下:

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

To access that, you need to use getElementsByClassName("gDirection")[0]要访问它,您需要使用getElementsByClassName("gDirection")[0]

Updated code:更新代码:

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概念证明小提琴

结果地图的屏幕截图

 html, body { height: 100%; width: 100%; margin: 0px; padding: 0px; } #map { width: 60%; height: 80%; margin-left: 4%; margin-top: 2% } #right-panel { font-family: 'Roboto', 'sans-serif'; line-height: 30px; height: 80%; 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; } }
 <p id='dTitle'> <h3>Store Locations</h3> </p> <div id="right-panel"></div> <div id="map"></div> <div id="directionsPanel"></div> <script> 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.553429, -113.639793), contentString: '<div><strong>Store A</strong></div>' + '<p><<div>Edmonton AB, T5S 2T2, Canada</div></p>' + '<div><button class="gDirection">Get Directions</div>' }, { markerId: 2, title: 'Click for location details', LatLng: new google.maps.LatLng(53.483710, -113.483230), contentString: '<div><strong>Store B</strong></div>' + '<p>div>Edmonton AB, T6E 5C5, Canada</div></p>' + '<div><button class="gDirection">Get Directions</button></div>' }, { markerId: 3, title: 'Click for location details', LatLng: new google.maps.LatLng(50.036490, -110.667030), contentString: '<div><strong>Store C</strong></div>' + '<p><div>Medicine Hat AB, T1A 2Z8, Canada</div></p>' + '<div><button class="gDirection">Get Directions</button></div>' }, { markerId: 4, title: 'Click for location details', LatLng: new google.maps.LatLng(49.262760, -123.004020), contentString: '<div><strong>Store D</strong></div>' + '<p><div>Burnaby BC, V5C 5T3, Canada</div></p>' + '<div><button class="gDirection">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()); 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); } }); }) }) } </script> <!-- Replace the value of the key parameter with your own API key. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM