百度地圖API標(biāo)注+時(shí)間軸組件

工作時(shí)被要求到的,結(jié)合百度地圖api做一個(gè)動(dòng)態(tài)展示標(biāo)注變化的組件,要求地圖展示某一天的標(biāo)注,時(shí)間軸要求可以動(dòng)態(tài)播放每一天的標(biāo)注變化...然后我就開始coding...

準(zhǔn)備工作:

  1. 申請(qǐng)百度api密鑰(具體方法我也不多寫了,大家應(yīng)該都會(huì))
  2. 了解一下百度地圖API的開發(fā)指南和類參考文檔(如果嫌麻煩的話 可以直接看Demo示例)

一、首先,先加載地圖,你可以用實(shí)際的經(jīng)緯度定位、瀏覽器定位、根據(jù)ip定位、根據(jù)城市名定位,這個(gè)你可以自己選擇

// 創(chuàng)建Map實(shí)例,設(shè)置地圖允許的最小/大級(jí)別
var map = this.map;
map.centerAndZoom(new BMap.Point(121.365593, 37.528502), 15); // 初始化地圖,用城市名設(shè)置地圖中心點(diǎn)
//map.enableScrollWheelZoom(true); //啟用滾輪放大縮小

centerAndZoom(center:Point, zoom:Number)

參數(shù)解釋:

  1. Point(lng:Number, lat:Number)  以指定的經(jīng)度和緯度創(chuàng)建一個(gè)地理點(diǎn)坐標(biāo)。
  2. zoom:number         地圖縮放級(jí)別

二、標(biāo)注的使用(覆蓋物)

結(jié)合百度地圖api示例Demo 設(shè)置點(diǎn)的新圖標(biāo)和添加多個(gè)點(diǎn)示例 結(jié)合一下,就可以改寫成添加多個(gè)地圖標(biāo)注

//編寫自定義函數(shù),創(chuàng)建標(biāo)注
        addMarker: function(point, label, status) {
            //        var marker = new BMap.Marker(point);
            var myIcon = new BMap.Icon("images/rubbish_" + status + ".png", new BMap.Size(32, 32), {
                anchor: new BMap.Size(16, 32), //中心點(diǎn)設(shè)置
                infoWindowAnchor: new BMap.Size(16, 4) //消息框位置5
            });
            var marker = new BMap.Marker(point, {
                icon: myIcon
            });
            TimerLine.map.addOverlay(marker);
            //跳動(dòng)的動(dòng)畫
            //                marker.setAnimation(BMAP_ANIMATION_BOUNCE);
            marker.setAnimation(BMAP_ANIMATION_DROP);
            var p = marker.getPosition();
            var content = "<table>";
            content = content + "<tr><td> 編號(hào):" + label.content + "</td></tr>";
            content = content + "<tr><td> 坐標(biāo):" + p.lng + "," + p.lat + "</td></tr>";
            content = content + "<tr><td> 狀態(tài):" + status + "</td></tr>";
            content += "</table>";
            var infowindow = new BMap.InfoWindow(content);
            //添加綁定事件
            addEvent(marker, 'click', getAttr);
            function getAttr() {
                this.openInfoWindow(infowindow);
            }
    }

百度地圖標(biāo)注添加看懂了,接下來就是動(dòng)態(tài)添加標(biāo)注,并且隨和日期的變化而變化,比如展示垃圾箱的動(dòng)態(tài)變化,8.3號(hào)清理了顏色為綠色,8.6號(hào)沒清理為紅色..

思想:

  1. 動(dòng)態(tài):就要使用ajax異步獲取數(shù)據(jù)
  2. 變化:就要使用定時(shí)器(setInterval或者 setTimeout)
    setInterval 循環(huán)調(diào)用
    setTimeout 延遲調(diào)用 1次     具體區(qū)別可以自行百度
  3. 動(dòng)手寫插件
function addEvent(dom, type, fn) {
    //對(duì)于支持DOM2級(jí)事件處理程序addeventListener方法的瀏覽器
    if (dom.addEventListener) {
        dom.addEventListener(type, fn, false);
    } else if (dom.attachEvent) {
        //對(duì)于不支持addEventListener方法但支持attchEvent方法的瀏覽器    
        dom.attachEvent('on' + type, fn);
    } else {
        //對(duì)于不支持以上兩種,但支持on+'事件名'的瀏覽器
        dom['on' + type] = fn;
    }
}
var TimerLine = {
    data: {
        containerDiv: 'timerline', //容器盒子id
        datesDiv:'dates',//日期盒子id
        btnsDiv:'timerlineBtns',
        btns: {
            play: "timerbtn-play",
            stop: "timerbtn-stop",
            pre:"timerbtn-pre",
            next:"timerbtn-next"
        },
        processDiv:'processbar',    //進(jìn)度條div
    },
    protect:{
        lock_play:false,
        lock_stop:false,
        index_label:1,
        index_process:0
    },
    rubbish_datas: [], //用來存儲(chǔ)ajax獲取到的數(shù)據(jù)
    index: 0, //變化的index
    Interval_label: null,
    Interval_process:null,
    map: new BMap.Map("allmap", {
        minZoom: 14,
        maxZoom: 20
    }),
    Utils: {
        //編寫自定義函數(shù),創(chuàng)建標(biāo)注
        addMarker: function(point, label, status) {
            //        var marker = new BMap.Marker(point);
            var myIcon = new BMap.Icon("images/rubbish_" + status + ".png", new BMap.Size(32, 32), {
                anchor: new BMap.Size(16, 32), //中心點(diǎn)設(shè)置
                infoWindowAnchor: new BMap.Size(16, 4) //消息框位置5
            });
            var marker = new BMap.Marker(point, {
                icon: myIcon
            });
            TimerLine.map.addOverlay(marker);
            //跳動(dòng)的動(dòng)畫
            //                marker.setAnimation(BMAP_ANIMATION_BOUNCE);
            marker.setAnimation(BMAP_ANIMATION_DROP);
            var p = marker.getPosition();
            var content = "<table>";
            content = content + "<tr><td> 編號(hào):" + label.content + "</td></tr>";
            content = content + "<tr><td> 坐標(biāo):" + p.lng + "," + p.lat + "</td></tr>";
            content = content + "<tr><td> 狀態(tài):" + status + "</td></tr>";
            content += "</table>";
            var infowindow = new BMap.InfoWindow(content);
            //添加綁定事件
            addEvent(marker, 'click', getAttr);
            function getAttr() {
                this.openInfoWindow(infowindow);
            }
        },
        /**
         * 地圖標(biāo)注方法
         * 參數(shù):        datas:標(biāo)注物數(shù)組{date:"",info:{}}
         *             index:序數(shù)(日期)
         * */
        mapSetLabel: function(datas, n,isInterval) {
            TimerLine.map.clearOverlays();
            var index;
            console.log(TimerLine.protect.index_label);
            if(isInterval){
                TimerLine.protect.index_label++;
                if (TimerLine.protect.index_label >= TimerLine.rubbish_datas.length - 1) {
                    TimerLine.protect.index_label = TimerLine.rubbish_datas.length - 1;
                    clearInterval(TimerLine.Interval_label);
                    TimerLine.protect.lock_play=false;
                }
            }
            
            if (n == null) {
                if(TimerLine.protect.index_label==0){
                    TimerLine.protect.index_label=1
                }
                index = TimerLine.protect.index_label;
            } else {
                index = parseInt(n);
                TimerLine.protect.index_label = index;
            }
            
            var info = datas[index].info;
            var info_count=0;
            var addMarker_Interval=setInterval(function(){
                var p = info[info_count].point.split(',');
                var p_x = parseFloat(p[0].toString()); //緯度
                var p_y = parseFloat(p[1].toString()); //經(jīng)度
                //創(chuàng)建label標(biāo)簽
                var label = new BMap.Label(info[info_count].title, {
                    offset: new BMap.Size(20, -10)
                });
                //創(chuàng)建標(biāo)注點(diǎn)
                var point = new BMap.Point(p_x, p_y);
                //狀態(tài)(垃圾箱狀態(tài))
                var status = info[info_count].status;            
                //添加標(biāo)注的方法
                TimerLine.Utils.addMarker(point, label, status);
                info_count++;
                if(info_count>=info.length){
                    clearInterval(addMarker_Interval);
                }
            },0);

        },
        //添加日期點(diǎn)擊事件綁定 dates li click
        bindEvent: function() {
            var datesDiv = document.getElementById("dates");
            addEvent(datesDiv,'click',function(e){
                var event = e || window.e;
                var target = event.target || event.srcElement;
                for(var i=0;i<TimerLine.rubbish_datas.length;i++){
                    if(target.innerText==TimerLine.rubbish_datas[i].date){
//        
                        TimerLine.protect.index_process=i;
                        TimerLine.protect.index_label=i;
                        //播放解鎖
                        if(TimerLine.protect.lock_play)    TimerLine.protect.lock_play=false;
                        TimerLine.Utils.mapSetLabel(TimerLine.rubbish_datas, i,false);
                        TimerLine.Utils.Setprocess(i,false);
                        return ;
                    }
                }
            })
        },
        //進(jìn)度條滾動(dòng)
        Setprocess:function(index,isInterval){
            if(isInterval){
                TimerLine.protect.index_process++;
                console.log(TimerLine.protect.index_process);
                console.log(TimerLine.rubbish_datas.length);
                if(TimerLine.protect.index_process >= TimerLine.rubbish_datas.length-1){
                    TimerLine.protect.index_process = TimerLine.rubbish_datas.length-1;
                    clearInterval(TimerLine.Interval_process);
                    TimerLine.protect.lock_play=false;
                }
            }
            var datesDiv = document.getElementById("dates");
            var processDiv = document.getElementById(TimerLine.data.processDiv);
            if(index==null){
                processDiv.style.width =parseInt(processDiv.style.width)+datesDiv.getElementsByTagName('li')[0].offsetWidth+'px';
            }else{
                processDiv.style.width =datesDiv.getElementsByTagName('li')[0].offsetWidth*parseInt(index+1)+'px';
            }
            
        }
        
    },
    //TimerLine初始化
    init: function() {
        this.createMap();
        this.ajaxCreate();
        //事件綁定
        this.bindEvent();
    },
    createMap: function() {
        // 創(chuàng)建Map實(shí)例,設(shè)置地圖允許的最小/大級(jí)別
        var map = this.map;
        map.centerAndZoom(new BMap.Point(121.365593, 37.528502), 15); // 初始化地圖,用城市名設(shè)置地圖中心點(diǎn)
        //map.enableScrollWheelZoom(true); //啟用滾輪放大縮小
    },
    ajaxCreate: function() {
        var That = this;
        var containerDiv = That.data.containerDiv;
        $.ajax({
            type: "get",
            url: "js/json.json",
            dataType: 'json',
            success: function(data) {
                containerDiv = document.getElementById(containerDiv); //容器id
                That.rubbish_datas = data.result.datas; //
                //console.log(That.rubbish_datas);
                That.create(containerDiv, That.rubbish_datas);
                //日期時(shí)間綁定
                That.Utils.bindEvent();
            }
        });
    },
    create: function(containerDiv, datas) {
        var That = this;
        var datasDiv ='<div class="processcontainer"><div id="processbar" style="width:120px;"></div></div>';
//        var datasDiv = '<ul id="dates" class="timerlineul dates clearfix">';
        datasDiv += '<ul id="dates" class="timerlineul dates clearfix">';
        for (var i = 0; i < datas.length; i++) {
            datasDiv += '<li>' + datas[i].date + '</li>';
        }
        datasDiv += '</ul>';    
        document.getElementById(That.data.btnsDiv).innerHTML='<div class="timerline-btns clearfix"><div id="timerbtn-pre" class="iconfont icon-shangyishou"></div><div id="timerbtn-play" class="iconfont icon-zanting"></div><div id="timerbtn-next" class="iconfont icon-xiayishou"></div></div>'
        //創(chuàng)建第一天的標(biāo)注
        this.Utils.mapSetLabel(datas, 0,false);
        
//        console.log(TimerLine.index);
        That.datas = datas;
        containerDiv.innerHTML = datasDiv;
    },
    //播放 暫停 委托事件----時(shí)間綁定
    bindEvent: function() {
        if (this.data.btns == null)
            return;
        var That = this;
        addEvent(document.getElementById(That.data.btnsDiv), 'click', function(e) {
            var event = e || window.e;
            var target = event.target || event.srcElement;
            //播放事件
            if (target.id == That.data.btns.play) {
                if(!TimerLine.protect.lock_play){
                    if(TimerLine.protect.index_label >= TimerLine.rubbish_datas.length-1){
                        TimerLine.protect.index_label=0;
                        var processDiv = document.getElementById(TimerLine.data.processDiv);
                        var datesDiv = document.getElementById("dates");
                        processDiv.style.width = datesDiv.getElementsByTagName('li')[0].offsetWidth+'px';
                    }
                    if(TimerLine.protect.index_process >= TimerLine.rubbish_datas.length-1){
                        TimerLine.protect.index_process=0;
                    }
//                
                    TimerLine.Interval_label = setInterval("TimerLine.Utils.mapSetLabel(TimerLine.rubbish_datas,null,true)", 1000);
                    TimerLine.Interval_process = setInterval("TimerLine.Utils.Setprocess(null,true)",1000);    
                    $("#timerbtn-play").attr("class","iconfont icon-zanting1");
                    //播放枷鎖
                    TimerLine.protect.lock_play=true;
                    //暫停解鎖
                    TimerLine.protect.lock_stop=false;
                }else if(TimerLine.protect.lock_play){
                    $("#timerbtn-play").attr("class","iconfont icon-zanting");
                    TimerLine.Interval_label&&clearInterval(TimerLine.Interval_label);
                    TimerLine.Interval_process&&clearInterval(TimerLine.Interval_process);
                    //播放解鎖
                    TimerLine.protect.lock_play=false;
                    //暫停加鎖
                    TimerLine.protect.lock_stop=true;
                }
            }
            
            if(target.id == That.data.btns.pre){
                if(TimerLine.protect.index_label==0) return;
                TimerLine.Utils.mapSetLabel(TimerLine.rubbish_datas, TimerLine.protect.index_label-1,false);
                TimerLine.Utils.Setprocess(TimerLine.protect.index_process-1,false);
                TimerLine.protect.index_process=TimerLine.protect.index_process-1;
            }
            if(target.id == That.data.btns.next){
                if(TimerLine.protect.index_label==TimerLine.rubbish_datas.length-1) return;
                TimerLine.Utils.mapSetLabel(TimerLine.rubbish_datas, TimerLine.protect.index_label+1,false);
                TimerLine.Utils.Setprocess(TimerLine.protect.index_process+1,false);
                TimerLine.protect.index_process=TimerLine.protect.index_process+1;
            }
        });
    }
}

TimerLine.init();

以上是我自己手寫的組件代碼,對(duì)設(shè)計(jì)模式了解還是一般.本來是想用原型模式寫,不過在setInterval時(shí)候,方法沒法調(diào)用原型方法,讓后我就改成了單例模式

TimeLine組件介紹

  1. data:數(shù)據(jù)容器綁定

  2. protect 保護(hù)屬性 (對(duì)播放、暫停、時(shí)間軸index、標(biāo)注index)

  3. rubbish_datas 存儲(chǔ)ajax讀取的數(shù)據(jù)

  4. Interval_label 百度地圖標(biāo)注定時(shí)器

  5. Interval_process 時(shí)間軸定時(shí)器

  6. Utils 工具類

  7. init() TimeLine初始化

  8. createMap() 創(chuàng)建百度地圖

  9. ajaxCreate() 獲取數(shù)據(jù),創(chuàng)建容器(create()),時(shí)間綁定(bindEvent())

遇到的問題:

  1. 兩個(gè)定時(shí)器運(yùn)行時(shí),公共index 容易讀取錯(cuò)誤,一個(gè)定時(shí)器修改了index 另一個(gè)定時(shí)器還沒修改,這樣造成了創(chuàng)建標(biāo)注與當(dāng)前時(shí)間不符合,

注:要將修改公共變量盡量寫在一個(gè)方法中。公共變量最好不要在多個(gè)方法中公用,容易在增減的時(shí)候出現(xiàn)不必要的BUG

  1. 定時(shí)器運(yùn)行到最后一天的時(shí)候要將定時(shí)器清除。

程序如圖:
百度地圖API標(biāo)注+時(shí)間軸組合的組件效果圖

附上預(yù)覽地址
更多內(nèi)容可以訂閱本人微信公眾號(hào),一起開啟前端小白進(jìn)階的世界!

前端Demon

不給 Demo 地址 是不是對(duì)不起你們。哈哈??
可以關(guān)注微信公眾號(hào) 回復(fù)百度地圖時(shí)間軸組件 ,即可收到 Demo 的地址。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,608評(píng)論 4 61
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,680評(píng)論 19 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,316評(píng)論 25 708
  • 1 這一周,爸爸媽媽都很辛苦。先是媽媽去了北京,主要辦兩件事,其中一個(gè)是和我婆婆一起辦美國簽證的面簽,在京的幾天也...
    潤青jingjing閱讀 375評(píng)論 0 0
  • 2016年6月20號(hào),我最后一天在自己的崗位上工作。沒有和你說感謝,沒有和你說再見,我離開了。不必沮喪,無需失落,...
    不回頭的姑涼閱讀 313評(píng)論 0 0

友情鏈接更多精彩內(nèi)容