试图在 googlemap infoWindow 中添加按钮

Trying to add button in googlemap infoWindow

我正在尝试在 googlemap infoWindow 中添加一个按钮,但我是 javascript 的初学者,我已经在这方面花费了数周时间,但仍然无法正常工作...所以我希望你们中的一个能够来帮助我。

稍微解释一下...我从 bdd 获取标记以在地图上显示它们。然后点击标记,一个信息窗口打开,上面有所有信息标记。

一切正常,但我不明白。

我已经为每个 infoWindow 标记添加了一个提交按钮,我希望在提交按钮单击时执行一个操作(保存到数据库)。但是按钮一点反应都没有...

我删除了所有包含保存功能的代码以保持清晰,因为有一个警报(“单击”)来测试按钮...

<script type="text/javascript">
var bounds;
var markers = [];
var markerCount = 0;
    function initialize(){
            bounds = new google.maps.LatLngBounds();
            var myLatLng = new google.maps.LatLng(46.775090, 2.507969);
            var mapOptions={
                zoom: 6,
                center: myLatLng,
                maxZoom: 11,
            },
            map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
            setMarkers(map,marker);
            const geocoder = new google.maps.Geocoder();
        
            document.getElementById("submit").addEventListener("click", () => {
              geocodeAddress(geocoder, map);
            }); 
    }
    
    function setMarkers(map,locations){
            for(var i=0; i<locations.length; i++){
                var station = locations[i];
                var myLatLng = new google.maps.LatLng(station['marker_latitude'], station['marker_longitude']);
                var infoWindow = new google.maps.InfoWindow();
                var image = 'https://marchad.fr/wp-includes/images/marchad.png';
                var description = station['marker_text'];

                var marker = new google.maps.Marker({
                    position: myLatLng,
                    map: map,
                    icon: image,
                    title: station['marker_ville'],
                    id: station['marker_id']
                });
            
                (function(marker, i){
                    google.maps.event.addListener(marker, "click",function(){
                        var station = locations[i];
                        var mId  = station['marker_id']; //description input field value
                        var contentString = ("<div id='infoWindow"+station['marker_id']+">"
                            +"<p class='texte'><strong>"+station['marker_text']+"</strong><p>"
                            +"<p class='texte'>Ce staliad est géré par un "+station['marker_user_type']+"<p>"
                            +"<p class='texte'><strong>Adresse : </strong>"+station['marker_adresse']+"<p>"
                            +"<p class='texte'><strong>Jour de permanence : </strong>"+station['marker_day']+"<p>"
                            +"<p class='texte'><strong>Dépôts : </strong>de "+station['marker_depot_start_time']+" à "+station['marker_depot_end_time']+"<p>"
                            +"<p class='texte'><strong>Retraits : </strong>de "+station['marker_start_time']+" à "+station['marker_end_time']+"<p>"
                            +"<p class='texte'><strong>Téléphone : </strong>"+station['marker_user_contact']+"<p>"
                            +"<p class='texte'><strong>Mail : </strong>"+station['marker_contact_mail']+"<p>"
                            +"<p class='texte'><strong>Commentaire : </strong>"+station['marker_commentaire']+"<p>"
                            +'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker'+station['marker_id']+'">'
                            +'<input id="idInput'+station['marker_id']+'" type="hidden" name="marker-id" class="marker-id'+station['marker_id']+'" value='+station['marker_id']+' />'+station['marker_id']+'</input>'
                            +'</form>'
                            +'<input id="inputButton'+station['marker_id']+'" type="button" id="save-marker'+station['marker_id']+'" name="save-marker" class="save-marker'+station['marker_id']+'" data-id="'+station['marker_id']+'" value="M\'inscrire" />'
                            +'<div id="test'+station['marker_id']+'">'+vendorId+'</div>'
                            +'<span class="info-content'+station['marker_id']+'">'
                            +'<h1 class="marker-heading"></h1>'
                            +'</span>'
                            +"</div>"
    );  
                        
                            infoWindow.close();
                            infoWindow.setContent(contentString);
                            infoWindow.open(map,this);
                        
                            var class_name_removeBtn  = 'remove-marker'+station['marker_id'];
                            var class_name_saveBtn  = 'save-marker'+station['marker_id'];
                            var removeBtn   = document.getElementsByClassName(class_name_removeBtn);
                            var saveBtn     = document.getElementsByClassName(class_name_saveBtn);
                            console.log(removeBtn);
                            console.log(saveBtn);
                
                        
                            //add click listner to save marker button
                            google.maps.event.addDomListener(saveBtn, "click", function(event) {
                                var class_name_mReplace  = 'info-content'+station['marker_id'];
                                var class_name_mName  = 'marker-id'+station['marker_id'];
                                var mReplace = document.getElementsByClassName(class_name_mReplace); //html to be replaced after success
                                var mName = document.getElementsByClassName(class_name_mName); //name input field value
                                var mId = station['marker_id'];
                                var vId = vendorId;

                                console.log(mReplace);
                                console.log(mName);
                                console.log(mId);
                                console.log(vId);

                                if(mId !=='')
                                {
                                    alert("click");
                                    save_marker( mName, mId, mReplace,vId); //call save marker function
                                }else{
                                    alert("Something went wrong. Please contact admin");
                                }
                            });


                            if(typeof removeBtn !== 'undefined') //continue only when save button is present
                            {
                                google.maps.event.addDomListener(removeBtn, "click", function(event) {
                                    var class_name_mName  = 'marker-id'+station['marker_id'];
                                    var mName = document.getElementsByClassName(class_name_mName);  //name input field value
                                    var vId = vendorId;
                                    remove_marker(mName,vId);
                                });
                            }

                
                    }); 
                })(marker, i);
                
        }
    }

 </script>

你的第一个问题是 saveBtn 不是 DOM 的一部分,直到 InfoWindow 被打开,因为你在 InfoWindow 内容中添加一个字符串.

相关问题:

  • using addDomListener with googlemaps not working
  • Turn off google map's infowindow.open(map) asynchronous behaviour

第二个问题是document.getElementsByClassName(class_name_saveBtn);returns一个数组。而不是:

document.getElementsByClassName(class_name_saveBtn);

对于单个标记,您需要:

document.getElementsByClassName(class_name_saveBtn)[0];

对于多个 markers/infowindows(获取最后创建的一个):

var removeBtn = document.getElementsByClassName(class_name_removeBtn);
removeBtn = removeBtn[removeBtn.length-1];
var saveBtn = document.getElementsByClassName(class_name_saveBtn);
saveBtn = saveBtn[saveBtn.length-1];

proof of concept fiddle

代码片段:

var bounds;
var markers = [];
var markerCount = 0;
/* var marker = [{
  marker_latitude: 47.394144,
  marker_longitude: 0.68484,
  marker_id: 1
}] */
var marker = [{"marker_id":"6","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"5","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Toulouse","marker_departement":"31","marker_region":"0","marker_longitude":"1.434917","marker_latitude":"43.573085","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Casino Barri\u00e8re","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"7","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"6","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Toulouse","marker_departement":"31","marker_region":"0","marker_longitude":"1.447856","marker_latitude":"43.604573","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Cinema Gaumont Wilson","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"8","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"6","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Lab\u00e8ge","marker_departement":"31","marker_region":"0","marker_longitude":"1.511496","marker_latitude":"43.53992","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Cinema Gaumont Lab\u00e8ge","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"9","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"6","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Blagnac","marker_departement":"31","marker_region":"0","marker_longitude":"1.373341","marker_latitude":"43.644029","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Cinema Mega CGR Blagnac","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"10","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"4","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Toulouse","marker_departement":"31","marker_region":"0","marker_longitude":"1.435198","marker_latitude":"43.62186","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Bowling Minimes\r\n108 Bis Avenue des Minimes, 31200 Toulouse \u200e\r\n05 61 47 95 60","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"11","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"4","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Montaudran","marker_departement":"31","marker_region":"0","marker_longitude":"1.496152","marker_latitude":"43.568863","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Bowling Montaudran Impasse Louise Lab\u00e9 31400 Toulouse 05 61 20 20 70","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"12","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"4","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Colomiers","marker_departement":"31","marker_region":"0","marker_longitude":"1.304691","marker_latitude":"43.609902","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Bowling Stadium Colomiers\r\n29 Chemin du Loudet\r\n33770 Colomiers\r\n05 34 36 42 50","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"13","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"10","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Plaisance-du-Touch","marker_departement":"31","marker_region":"0","marker_longitude":"1.260248","marker_latitude":"43.55854","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"African Safari\r\n41 Rue des Landes\r\n31830 Plaisance-du-Touch\r\n05 61 86 45 03","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"29","marker_user_id":"2","marker_user_type":"marchand","marker_user_stal":"Aux petits l\u00e9gumes","marker_categorie":"test","marker_adresse":"12 Rue du Bocage, Tr\u00e9gueux, France","marker_numero_voie":"12","marker_voie":"Rue du Bocage","marker_zip":"22950","marker_ville":"Tr\u00e9gueux","marker_departement":"C\u00f4tes-d'Armor","marker_region":"Bretagne","marker_longitude":"-2.7515737","marker_latitude":"48.4831891","marker_day":"Lundi","marker_depot_start_time":"09:00:00","marker_depot_end_time":"12:00:00","marker_start_time":"12:00:00","marker_end_time":"18:46:00","marker_text":"Aux petits l\u00e9gumes","marker_user_contact":"0783312456","marker_contact_mail":"nattydreadnatty@live.fr","marker_enable_contact_telephone":"yes","marker_enable_contact_mail":"yes","marker_commentaire":"test test test test test testing out","marker_actif":"oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"30","marker_user_id":"3","marker_user_type":"marchand","marker_user_stal":"Poivrons et compagnie","marker_categorie":"","marker_adresse":"12t Rue du Vau Hello, 22360 Langueux, France","marker_numero_voie":"12","marker_voie":"Rue du Vau Hello","marker_zip":"22360","marker_ville":"Langueux","marker_departement":"C\u00f4tes-d'Armor","marker_region":"Bretagne","marker_longitude":"-2.7262882","marker_latitude":"48.50448799999999","marker_day":"Vendredi","marker_depot_start_time":"08:00:00","marker_depot_end_time":"10:00:00","marker_start_time":"10:00:00","marker_end_time":"18:00:00","marker_text":"Poivrons et compagnie","marker_user_contact":"","marker_contact_mail":"lucbinard4@gmail.com","marker_enable_contact_telephone":"yes","marker_enable_contact_mail":"yes","marker_commentaire":"","marker_actif":"oui","id":null,"mark_id":null,"user_id":null,"user_actif":null}];

var vendorId = "vendorId";

function initialize() {
  bounds = new google.maps.LatLngBounds();
  var myLatLng = new google.maps.LatLng(46.775090, 2.507969);
  var mapOptions = {
      zoom: 6,
      center: myLatLng,
      maxZoom: 11,
    },
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  setMarkers(map, marker);
  const geocoder = new google.maps.Geocoder();

  document.getElementById("submit").addEventListener("click", () => {
    geocodeAddress(geocoder, map);
  });
}

function setMarkers(map, locations) {
  for (var i = 0; i < locations.length; i++) {
    var station = locations[i];
    var myLatLng = new google.maps.LatLng(station['marker_latitude'], station['marker_longitude']);
    var infoWindow = new google.maps.InfoWindow();
    var image = 'https://marchad.fr/wp-includes/images/marchad.png';
    var description = station['marker_text'];

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: image,
      title: station['marker_ville'],
      id: station['marker_id']
    });

    (function(marker, i) {
      google.maps.event.addListener(marker, "click", function() {
        var station = locations[i];
        var mId = station['marker_id']; //description input field value
        var contentString = ("<div id='infoWindow" + station['marker_id'] + ">" +
          "<p class='texte'><strong>" + station['marker_text'] + "</strong><p>" +
          "<p class='texte'>Ce staliad est géré par un " + station['marker_user_type'] + "<p>" +
          "<p class='texte'><strong>Adresse : </strong>" + station['marker_adresse'] + "<p>" +
          "<p class='texte'><strong>Jour de permanence : </strong>" + station['marker_day'] + "<p>" +
          "<p class='texte'><strong>Dépôts : </strong>de " + station['marker_depot_start_time'] + " à " + station['marker_depot_end_time'] + "<p>" +
          "<p class='texte'><strong>Retraits : </strong>de " + station['marker_start_time'] + " à " + station['marker_end_time'] + "<p>" +
          "<p class='texte'><strong>Téléphone : </strong>" + station['marker_user_contact'] + "<p>" +
          "<p class='texte'><strong>Mail : </strong>" + station['marker_contact_mail'] + "<p>" +
          "<p class='texte'><strong>Commentaire : </strong>" + station['marker_commentaire'] + "<p>" +
          '<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker' + station['marker_id'] + '">' +
          '<input id="idInput' + station['marker_id'] + '" type="hidden" name="marker-id" class="marker-id' + station['marker_id'] + '" value=' + station['marker_id'] + ' />' + station['marker_id'] + '</input>' +
          '</form>' +
          '<input id="inputButton' + station['marker_id'] + '" type="button" id="save-marker' + station['marker_id'] + '" name="save-marker" class="save-marker' + station['marker_id'] + '" data-id="' + station['marker_id'] + '" value="M\'inscrire" />' +
          '<div id="test' + station['marker_id'] + '">' + vendorId + '</div>' +
          '<span class="info-content' + station['marker_id'] + '">' +
          '<h1 class="marker-heading"></h1>' +
          '</span>' +
          "</div>"
        );

        infoWindow.close();
        infoWindow.setContent(contentString);
        infoWindow.open(map, this);

        var class_name_removeBtn = 'remove-marker' + station['marker_id'];
        var class_name_saveBtn = 'save-marker' + station['marker_id'];
        google.maps.event.addListenerOnce(infoWindow,'domready', function() {
          var removeBtn = document.getElementsByClassName(class_name_removeBtn);
          removeBtn = removeBtn[removeBtn.length-1];
          var saveBtn = document.getElementsByClassName(class_name_saveBtn);
          saveBtn = saveBtn[saveBtn.length-1];
          console.log(removeBtn);
          console.log(saveBtn);

          //add click listner to save marker button
          google.maps.event.addDomListener(saveBtn, "click", function(event) {
            var class_name_mReplace = 'info-content' + station['marker_id'];
            var class_name_mName = 'marker-id' + station['marker_id'];
            var mReplace = document.getElementsByClassName(class_name_mReplace); //html to be replaced after success
            var mName = document.getElementsByClassName(class_name_mName); //name input field value
            var mId = station['marker_id'];
            var vId = vendorId;

            console.log(mReplace);
            console.log(mName);
            console.log(mId);
            console.log(vId);

            if (mId !== '') {
              alert("click");
              save_marker(mName, mId, mReplace, vId); //call save marker function
            } else {
              alert("Something went wrong. Please contact admin");
            }
          });


          if (typeof removeBtn !== 'undefined') //continue only when save button is present
          {
            google.maps.event.addDomListener(removeBtn, "click", function(event) {
              var class_name_mName = 'marker-id' + station['marker_id'];
              var mName = document.getElementsByClassName(class_name_mName); //name input field value
              var vId = vendorId;
              remove_marker(mName, vId);
            });
          }
        })

      });
    })(marker, i);

  }
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map-canvas {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Simple Map</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <input id="submit" type="button" value="submit" />
  <div id="map-canvas"></div>

  <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize&libraries=&v=weekly" async></script>
</body>

</html>

我的是这样工作的..在信息中检测点击事件 window

  google.maps.event.addListener(infowindow, 'domready', function() {
      $('.classname').click(function(){
         // code               
     });