Issue toggle on/off with infowindow

自闭症网瘾萝莉.ら 提交于 2019-12-26 13:50:09

问题


today i saw an answer about toggle on/off in the same button, and i decided to try to use.

What i want is to click in the marker and than a infowindow appear in my map, but it doesn't work.

JSFiddle simple marker with infowindow

JSFiddle toogle on/off but no infowindow

When i try to join(toogle with infowindow) like this:

google.maps.event.addDomListener(buttonCarrosUI, 'click', function() {
  if(marker && marker.setMap){
      if (marker.getMap() != null)
          marker.setMap(null);
     else marker.setMap(map_canvas);
  }else{
      var myLatLng;
      var title = marker.title;
      $.each( data.markers, function(i, marker) {
          myLatLng = new google.maps.LatLng(marker.latitude, marker.longitude);
      });
      var infowindow = new google.maps.InfoWindow({
          content: title,
      });
          marker = new google.maps.Marker({
              position: myLatLng,
              map: map_canvas,  
              icon: image,
              title: title
          });
          google.maps.event.addListener(marker, 'click', function() {
              infowindow.open(map_canvas,marker);
          });
   }
});

I Got this issue

TypeError: marker is undefined

var title = marker.title;

I'll be very gratefull if someone can help me, thanks.


回答1:


You are creating the marker outside of the $.each. Unless you want more than one infowindow open at a time, it is better to make a global infowindow and reuse it. Also, you are overwriting the "marker" variable inside the $.each. Note that this wont work for more than one marker. You need to keep references to the markers in an array if you have more than one (the original example from which this code came toggled a single polyline). The code below works for me:

google.maps.event.addDomListener(buttonCarrosUI, 'click', function () {
    var data = JSON;
    var myLatLng;
    if (marker && marker.setMap) {
        if (marker.getMap() != null) marker.setMap(null);
        else marker.setMap(map_canvas);
    } else {
        $.each(data.markers, function (i, markerInfo) {
            myLatLng = new google.maps.LatLng(markerInfo.latitude, markerInfo.longitude);
            marker = new google.maps.Marker({
                position: myLatLng,
                map: map_canvas,
                title: markerInfo.title
            });
            google.maps.event.addListener(marker, 'click', function () {
                infowindow.setContent(marker.getTitle());
                infowindow.open(map_canvas, marker);
            });
        });

    }
});

working fiddle



来源:https://stackoverflow.com/questions/28750179/issue-toggle-on-off-with-infowindow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!