leaflet:使用popup.setContent()更改弹出窗口图像

时间:2016-03-18 20:13:22

标签: javascript popup leaflet

我试图让弹出窗口中的图像定期更改。函数refreshImage定期从服务器GET发送一个基于64的图像数据字符串,并使用popup.setContent()设置img的src。第二部分从json文件获取协调数据并创建标记,绑定弹出窗口并启动将触发refreshImage函数的onClick事件处理程序。从创建标记到获取数据的所有内容都能正常工作,如果在简单的HTML情况下使用,数据可以显示为图像。但它无法在弹出窗口中显示和刷新图像。我尝试了popup.setContent()$(popup._contentNode).html()document.getElementById(imageID).src =document.getElementById(imageID).innerHTML="",但似乎都没有效果。这是我的代码:

    function refreshImage(popup,cName,starttime,endtime,curtime) {//the times are Date object
        var data;
        var hour = 60 * 60 * 1000;
        var nexttime = new Date(curtime.valueOf()+hour);
        strcurtime = curtime.toLocaleString();
        strstarttime = starttime.toLocaleString();
        strendtime = endtime.toLocaleString();
        strnexttime = nexttime.toLocaleString();
        if(endtime<nexttime){
            $.get( "/images",{camname:cName, starttime: strcurtime,endtime: strendtime}, function( data, status ) {//
            });
            curtime = starttime;
        }else{
            $.get( "/images",{camname:cName,starttime:strcurtime ,endtime:strnexttime}, function( data, status ) {//      
            });
            curtime = nexttime;
        }

        popup.setContent("<img src=\"data:image/jpeg;base64, "+ data +"\" alt=\"camera_image\" width=\"305\" height=\"210\" border=\"0\" align=\"middle\" id=\"myPic\"><br><p>"+cName+"</p>");
        setTimeout(refreshImage,1000,popup,cName,starttime,endtime,curtime);
    }


    var markers = [];
    d3.csv("static/data/cam_coordinates.json", function(error, data) {
        var cameras = data;
        var starttime = new Date('2015-12-07 07:00:03');
        var endtime = new Date('2015-12-08 08:15:00');
        console.log(cameras.length);
        for(var i = 0; i<cameras.length; ++i){
            var marker = L.marker( [cameras[i].lat, cameras[i].log], {icon: cam}, {title: cameras[i].camera}).addTo(map);
            window.markers.push(marker);
            window.markers[i].bindPopup("<img src=\"\" alt=\"camera_image\" width=\"305\" height=\"210\" border=\"0\" align=\"middle\" id=\"myPic\"><br>"+cameras[i].camera);

            var popup = window.markers[i]._popup;

            window.markers[i].on('click', function(popup){

                refreshImage(popup,'Ft_Washington_@_179_St', starttime, endtime, starttime);
            });
        }
    });

1 个答案:

答案 0 :(得分:1)

要实现这一目标,您必须使用marker提供的其他活动: popupopen 弹出式关闭

此事件为事件回调提供当前弹出对象。

marker1.on('popupopen', function(e) {
   thePopup = e.popup; // has to be kept global for refreshTime() 
   refreshTime(); // do the first action
   theTimer = setInterval(refreshTime, 2000); // repeat until we stop it in popupclose
});

marker1.on('popupclose', function(e) {
   clearInterval(theTimer);
});

function refreshTime() {
   var d = new Date();
   thePopup.setContent(d.toLocaleTimeString());
}

这是一个example,我会在点击标记时不断更新弹出窗口中的时间。

注意: 弹出窗口是属于地图的图层,而不是标记。所以你不能像你那样使用点击事件。