前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >高质量编码-轨迹管理平台(JS代码)

高质量编码-轨迹管理平台(JS代码)

原创
作者头像
MiaoGIS
修改2020-12-17 14:35:10
4.7K0
修改2020-12-17 14:35:10
举报
文章被收录于专栏:Python in AI-IOTPython in AI-IOT

JS代码组织如下图:

TrackMVC.js

初始化app

代码语言:javascript
复制
 
var TrackMVC=new Backbone.Marionette.Application();
TrackMVC.addRegions({
locatorRegion:'#locator-box',
trackRegion:'#track-box',
headerRegion:'#header'
});
TrackMVC.addInitializer(function(){
console.log('TrackMVC has initialized');
Backbone.history.start();
});

TrackMVC.Layout.js

UI布局

代码语言:javascript
复制
TrackMVC.module('Layout',function(Layout,App,Backbone,Marionette,$,_){
Layout.Header=Backbone.Marionette.LayoutView.extend({
template:'#header-tmpl',
 initialize:function(){
 this.listenTo(this.collection,'all',this.updateState);
 },
ui:{
spanToggle:'.ctrl i',
spanState:'#state',
typeLocator:'#track-btn',
typeTrack:'#track-btn-2',
},
events:{
'click @ui.spanToggle':'onToggle',
'click @ui.typeLocator':'onToggleLocator',
'click @ui.typeTrack':'onToggleTrack',
},
onRender:function(){
this.updateState();
TrackMVC.getRegion('locatorRegion').$el.css('display','block');
},
updateState:function(){
console.log('updateState');
 var onlineCount=this.collection.filter(function(item){return item.attributes['locator_status']=='on'}).length;
this.ui.spanState.html(onlineCount.toString()+"/"+this.collection.length.toString());

},
onToggle:function(){
console.log('toggle');
var dataPanel=$('#data-box');
 if (dataPanel.attr('data-toggle')=='off') {
		 
            dataPanel.slideUp(400);
            this.ui.spanToggle.removeClass('fa-chevron-up').addClass('fa-chevron-down');
        dataPanel.attr('data-toggle','on');
	} else {
 
            dataPanel.slideDown(400);
            this.ui.spanToggle.removeClass('fa-chevron-down').addClass('fa-chevron-up');
       dataPanel.attr('data-toggle','off');
	 }

},
 
 onToggleLocator:function(){
 this.ui.typeLocator.addClass('active');
this.ui.typeTrack.removeClass('active');
TrackMVC.getRegion('locatorRegion').$el.css('display','block');
TrackMVC.getRegion('trackRegion').$el.css('display','none');
},
 onToggleTrack:function(){
 this.ui.typeTrack.addClass('active');
this.ui.typeLocator.removeClass('active');
 TrackMVC.getRegion('locatorRegion').$el.css('display','none');
TrackMVC.getRegion('trackRegion').$el.css('display','block');

}
});
});

TrackMVC.Locators.js

实时监控列表(Backbone.Collection)和列表中每一项(Backbone.Model)的定义

代码语言:javascript
复制
TrackMVC.module('Locators',function(Locators,App,Backbone,Marionette,$,_){
 window.app=App;
window.selectedLocators={};
Locators.Locator=Backbone.Model.extend({
defaults:{
 locator_fleedID: 0,
locator_id: 0,
locator_name: "locator0",
locator_coordinate_x: 34.730861,
locator_coordinate_y: 113.6101392,
locator_coordinate_time: "2016-10-11 16:00:04",
isShow:false,
},
idAttribute:'locator_id',
initialize:function(){
},
 });
 
 Locators.LocatorList=Backbone.Collection.extend({
model:Locators.Locator,
url:'locator/locatorsWithCoordinateByFleed?locator_fleed=1',
parse:function(response){
console.log(response);
result=response['result'];
if(app.MapLocators.myCurrentClickPoint.attributes.hasOwnProperty('locator_id'))
{
var myCurrentClickPoint=_.findWhere(result,{'locator_id':app.MapLocators.myCurrentClickPoint.attributes['locator_id']});
app.MapLocators.myCurrentClickPoint.set( myCurrentClickPoint);
}
_.each(result,function(item,index){
result[index]['isShow']=selectedLocators.hasOwnProperty(item['locator_id']);
});
return result
},
});
});

TrackMVC.LocatorList.Views.js

实时监控列表(Marionette.CompositeView)和列表中每一项(Marionette.ItemView)的视图定义

代码语言:javascript
复制
TrackMVC.module('LocatorList.Views', function (Views, App, Backbone, Marionette, $, _) {

    Views.LocatorItemView = Marionette.ItemView.extend({
        tagName: 'li',
        template: '#locatorItem-tmpl',

        initialize: function () {
            console.log('locatorItemView');
            this.listenTo(this.model, 'change', this.render);

        },

        onRender: function () {
            this.$el.attr('data-id', "516922851").attr('data-name', "明GC9D99").attr('data-state', "off");
            //this.$el.on('click',function(e){
            //console.log('clicked');
            //});

        },
        events: {
            'click input': 'toggleSelected',
            'click span': 'firstSelected',
            'dblclick span': 'centerAt',
        },
        destroy: function () {

            //this.$el.off('click');
            this.stopListening(this.model, 'change');
            //this.model.destroy();
            this.$el.remove();
        },
        toggleSelected: function (e) {
            this.model.set({
                'isShow': !this.model.get('isShow')
            });
            if (!selectedLocators.hasOwnProperty(this.model.get('locator_id')))
                selectedLocators[this.model.get('locator_id')] = this.model.get('locator_id');
            else
                delete selectedLocators[this.model.get('locator_id')];
            console.log('toggleSelected');
        },
        firstSelected: function (e) {
            if (!this.model.get('isShow')) {
                this.model.set({
                    'isShow': !this.model.get('isShow')
                });
                selectedLocators[this.model.get('locator_id')] = this.model.get('locator_id');
            }
            console.log('firstSelected');
        },
        centerAt: function (e) {
            if (!this.model.get('isShow')) {
                this.model.set({
                    'isShow': !this.model.get('isShow')
                });
                selectedLocators[this.model.get('locator_id')] = this.model.get('locator_id');
            }
            var pointMapItem = _.findWhere(app.MapLocators.pointMapItems, {
                'pointId': this.model.attributes['locator_id']
            });
            map.centerAndZoom(pointMapItem['marker'].getPosition(), 16);
        },
    });

    Views.LocatorListView = Backbone.Marionette.CompositeView.extend({
        template: '#locatorList-tmpl',
        childView: Views.LocatorItemView,
        childViewContainer: '#locatorList',
        ui: {
            inputSearch: '#searchKey',
            btnSearch: '.search-i',
            btnSelected: '.btn.filter',
            btnAll: '.btn.clean',
            btnOnline: '.btn.online',
        },
        events: {
            'click @ui.btnSearch': 'onSearch',
            'click @ui.btnSelected': 'onFilterSelected',
            'click @ui.btnAll': 'onFilterAll',
            'click @ui.btnOnline': 'onFilterOnline',
        },
        initialize: function () {
            console.log('locatorListView');
            this.listenTo(this.collection, 'all', this.update);
        },
        onRender: function () {
            this.update();
        },
        update: function () {
            console.log('update locator');
        },
        onSearch: function () {
            var keyword = this.ui.inputSearch.val().trim();
            if (keyword != '') {
                this.filter = function (child, index, collection) {
                    return child.get('locator_name').toString().indexOf(keyword) > -1;
                };
            } else {
                this.filter = null;
            }

            this.render();
            console.log('onSearch');
        },
        onFilterOnline: function () {
            console.info(this);
            this.filter = function (child, index, collection) {
                return child.get('locator_status') == 'on';
            };
            this.render();
            console.log('onFilterOnline');
        },
        onFilterSelected: function () {
            console.info(this);
            this.filter = function (child, index, collection) {
                return child.get('isShow');
            };
            this.render();
            console.log('onFilterSelected');
        },
        onFilterAll: function () {
            this.filter = null;
            this.render();
            console.log('onFilterAll');
        },
    });
});

TrackMVC.Tracks.js

历史轨迹列表(Backbone.Collection)和列表每一项(Backbone.Model)的定义

代码语言:javascript
复制
TrackMVC.module('Tracks',function(Tracks,App,Backbone,Marionette,$,_){
 window.selectedTracks={};
Tracks.colors= ['#3A3AD4', '#808000', '#FF4500', '#7b68ee', '#4169E1', '#2F4F4F', '#1E90FF', '#2E8B57',
            '#32CD32', '#2BAE18', '#8F502C', '#006400', '#6B8E23', '#8B4513', '#B22222',
            '#48525A', '#65723F', '#4F8848', '#965A25', '#264095', '#E8EDF2'
        ];
Tracks.Track=Backbone.Model.extend({
defaults:{
track_locatorID: 0,
track_coordinates:[],
track_locatorName: "locator0",
isShow:false,
},

initialize:function(){
this.set({'showColor':_.sample(Tracks.colors,1)[0]});
},
 });
  
Tracks.TrackList=Backbone.Collection.extend({
model:Tracks.Track,
url:'coordinate/coordinatesByTime2GroupByLocator',
parse:function(response){
console.log(response);
//var result= _.map(_.pairs(_.groupBy(response['result'],'coordinate_locatorID')),function(item){return {track_locatorID: item[0],track_coordinates:item[1]}});
var result=_.map(response['result'],function(item){
return {track_locatorID: item['locator_id'],track_locatorName:item['locator_name']};
});
_.each(result,function(item,index){
result[index]['isShow']=selectedTracks.hasOwnProperty(item['track_locatorID']);
});
return result;
},
});
});

TrackMVC.TrackList.Views.js

历史轨迹列表(Marionette.CompositeView)和列表每一项(Marionette.ItemView)的视图定义

代码语言:javascript
复制
TrackMVC.module('TrackList.Views', function (Views, App, Backbone, Marionette, $, _) {
    Views.loadCoordinatesByTime2Locator = function (locator, startTime, endTime) {
        console.log('loadCoordinatesByTime2Locator');
        $.get('coordinate/coordinatesByLocatorAndTime', {
            'coordinate_locator': locator.get('track_locatorID'),
            'coordinate_time_start': startTime,
            'coordinate_time_end': endTime
        }, function (response) {

            result = {
                'track_locatorID': locator.get('track_locatorID'),
                'coordinates': response['result'],
                'track_locatorName': locator.get('track_locatorName'),
                'showColor': locator.get('showColor')
            };
            //console.info(response['result']);
            app.MapTracks.trackListOnMap.add(result);
            app.MapTracks.trackListOnMap.findWhere({
                'track_locatorID': locator.get('track_locatorID')
            }).set({
                'isShow': true
            });


        });

        return locator;
    };
    Views.memoized_loadCoordinatesByTime2Locator = _.memoize(Views.loadCoordinatesByTime2Locator, function () {
        return _(arguments).first().get('track_locatorID') + '_' + _(arguments).rest(1).join('_')
    });


    Views.TrackItemView = Marionette.ItemView.extend({
        tagName: 'li',
        className: 'seled-track',
        template: '#trackItem-tmpl',

        initialize: function () {

            this.listenTo(this.model, 'change', this.render);
            //this.todayInterval=10000;

            //this.todayTimer=null;

        },

        onRender: function () {
            this.$el.attr('data-id', "516922851").attr('data-name', "明GC9D99").attr('data-state', "off");


        },
        events: {
            'click input': 'toggleSelected',
            'click span:not(.process)': 'firstSelected',
            'dblclick span:not(.process)': 'centerAt',
            'click span.process i.fa': 'toggleLushu'
        },
        destroy: function () {
            //this.$el.off('click');
            this.stopListening(this.model, 'change');
            //this.model.destroy();
            this.$el.remove();
        },
        toggleLushu: function (e) {

            if ($(e.target).hasClass('fa-play')) {

                $('#trackList li span.process i.fa-pause').removeClass('fa-pause').addClass('fa-play');

                $(e.target).removeClass('fa-play');
                $(e.target).addClass('fa-pause');
                var trackMapItem = app.MapTracks.trackListOnMap.findWhere({
                    'track_locatorID': this.model.get('track_locatorID')
                });
                if (trackMapItem != undefined) {
                    app.MapTracks.removeLushus();
                    app.MapTracks.addLushus(trackMapItem);
                    app.MapTracks.startLushus();
                };
            } else {
                $(e.target).removeClass('fa-pause');
                $(e.target).addClass('fa-play');

                app.MapTracks.removeLushus();


            };
        },

        toggleSelected: function () {
            this.model.set({
                'isShow': !this.model.get('isShow')
            });

            if (!selectedTracks.hasOwnProperty(this.model.get('track_locatorID'))) {
                var nowDate=DateFormat.format.date(new Date(), 'yyyy-MM-dd');
                var nowTime=DateFormat.format.date(new Date(), 'yyyy-MM-dd HH:mm:ss');
                var endDate = this._parent.searchDates.get('endDate');
                if (endDate ==nowDate ) {
                    endDate = nowTime;
                } else {
                    endDate = endDate + ' 23:59:59';
                }
                var startDate = this._parent.searchDates.get('startDate') + ' 00:00:00';

                selectedTracks[this.model.get('track_locatorID')] = this.model.get('track_locatorID');
                if (!Views.memoized_loadCoordinatesByTime2Locator.cache.hasOwnProperty([this.model.get('track_locatorID'), startDate, endDate].join('_')))
                    Views.memoized_loadCoordinatesByTime2Locator(this.model, startDate, endDate);
                else {
                    console.debug(this.model.get('track_locatorID'));
                    app.MapTracks.trackListOnMap.findWhere({
                        'track_locatorID': this.model.get('track_locatorID')
                    }).set({
                        'isShow': true
                    });

                }
            } else {
                console.debug(this.model.get('track_locatorID'));
                app.MapTracks.trackListOnMap.findWhere({
                    'track_locatorID': this.model.get('track_locatorID')
                }).set({
                    'isShow': false
                });
                delete selectedTracks[this.model.get('track_locatorID')];


            }
            console.log('toggleSelected');


        },

        firstSelected: function (e) {
            if (!this.model.get('isShow')) {
                console.log(this.model.get('track_locatorID'));
                Views.memoized_loadCoordinatesByTime2Locator(this.model, this._parent.searchDates.get('startDate') + ' 00:00:00', this._parent.searchDates.get('endDate') + ' 23:59:59');

                this.model.set({
                    'isShow': !this.model.get('isShow')
                });
                selectedTracks[this.model.get('track_locatorID')] = this.model.get('track_locatorID');
            }
            console.log('firstSelected');
        },
        centerAt: function (e) {
            if (!this.model.get('isShow')) {
                console.log(this.model.get('track_locatorID'));
                Views.memoized_loadCoordinatesByTime2Locator(this.model, this._parent.searchDates.get('startDate') + ' 00:00:00', this._parent.searchDates.get('endDate') + ' 23:59:59');
                this.model.set({
                    'isShow': !this.model.get('isShow')
                });
                selectedTracks[this.model.get('track_locatorID')] = this.model.get('track_locatorID');

            }

            var trackMapItem = _.findWhere(app.MapTracks.trackMapItems, {
                'trackId': this.model.get('track_locatorID')
            });

            var pointsPath = _.map(trackMapItem['multipolylines'], function (item) {
                return item['polyline'].getPath();
            })
            var points = _.flatten(pointsPath);
            map.setViewport(points);
            console.log('centerAt');
        },
    });
    Views.SearchDates = Backbone.Model.extend({

    });
    Views.TrackListView = Backbone.Marionette.CompositeView.extend({
        template: '#trackList-tmpl',
        childView: Views.TrackItemView,
        childViewContainer: '#trackList',
        ui: {
            btnDate1: '#div_date1',
            btnDate2: '#div_date2',
            inputSearch: '#searchKey_2',
            btnSearch: '.search-i',
            btnSelected: '.btn.filter',
            btnAll: '.btn.clean',
            lblDateSelectType: '#lblDateSelectType',
            divDatePanel2: '#date-panel2',
            cbxDateSelectType: '#cbxDateSelectType',
        },
        events: {
            'click @ui.btnSearch': 'onSearch',
            'click @ui.btnSelected': 'onFilterSelected',
            'click @ui.btnAll': 'onFilterAll',
            'change @ui.cbxDateSelectType': 'onChangeDateSelectType',
        },
        initialize: function () {

            this.listenTo(this.collection, 'all', this.update);
            this.listenTo(this.collection, 'add', this.addTrack);
            this.listenTo(this.collection, 'remove', this.removeTrack);

        },
        onRender: function () {
            var me = this;

            if (!me.searchDates) {
                var now = DateFormat.format.date(new Date(), 'yyyy/MM/dd');
                var now2 = DateFormat.format.date(new Date(), 'yyyy-MM-dd');
            } else {
                var now = me.searchDates.attributes.startDate.replace('-', '/').replace('-', '/');
                var now2 = me.searchDates.attributes.endDate;
            }
            this.ui.btnDate1.find('#date').text(now2);
            this.ui.btnDate2.find('#date').text(now2);
            this.searchDates = new Views.SearchDates({
                startDate: now2,
                endDate: now2
            });
            this.searchDates.on('change', function () {
                this.searchByTime();

            }, this)
            me.ui.btnDate1.val(now);
            me.ui.btnDate2.val(now);
            this.ui.btnDate1.datetimepicker({
                format: 'Y/m/d',
                timepicker: false,
                yearStart: 1990,
                yearEnd: new Date().getFullYear(),
                onChangeDateTime: null,
                maxDate: DateFormat.format.date(new Date(), 'yyyy/MM/dd'),
                lang: 'ch',
                onClose: this.setSearchDate.bind(this),
                onShow: function (ct) {
                    this.setOptions({

                        // maxDate:me.ui.btnDate2.val().split(' ' )[0]?me.ui.btnDate2 .val().split(' ')[0]:false
                    })
                }
            });

            this.ui.btnDate2.datetimepicker({
                format: 'Y/m/d',
                timepicker: false,
                yearStart: 1990,
                yearEnd: new Date().getFullYear(),
                onChangeDateTime: null,
                maxDate: DateFormat.format.date(new Date(), 'yyyy/MM/dd'),
                lang: 'ch',
                onClose: this.setSearchDate.bind(this),
                onShow: function (ct) {

                    this.setOptions({

                        minDate: me.ui.btnDate1.val().split(' ')[0] ? me.ui.btnDate1.val().split(' ')[0] : false
                    })
                }
            });

            this.update();
        },
        update: function () {

            console.log('update');
        },




        setSearchDate: function () {

            var startDate = Date.parseDate(this.ui.btnDate1.val(), 'Y/m/d');
            var endDate = Date.parseDate(this.ui.btnDate2.val(), 'Y/m/d');
            var startDateText = DateFormat.format.date(startDate, 'yyyy-MM-dd');
            var endDateText = DateFormat.format.date(endDate, 'yyyy-MM-dd');
            this.ui.btnDate1.find('#date').text(startDateText);
            this.ui.btnDate2.find('#date').text(endDateText);
            if (this.ui.cbxDateSelectType.prop('checked'))

                this.searchDates.set({
                    startDate: startDateText,
                    endDate: endDateText
                });
            else
                this.searchDates.set({
                    startDate: startDateText,
                    endDate: startDateText
                });

            //if(this.searchDates.get('endDate')==DateFormat.format.date(new Date(), 'yyyy-MM-dd')  )
            //{
            //this.todayTimer=setInterval(this.searchByTime.bind(this),this.todayInterval);
            //}
            //else
            //{
            //if(this.todayTimer!=null)
            //clearInterval(this.todayTimer);
            //}
        },
        searchByTime: function () {
            console.log('searchByTime');
            Views.memoized_loadCoordinatesByTime2Locator.cache = {};
            this.cloneSelectedTracks = selectedTracks;
            selectedTracks = 0;
            app.MapTracks.trackListOnMap.set([]);

            //this.destroyChildren();   
            var startDateText = this.searchDates.get('startDate');
            var endDateText = this.searchDates.get('endDate');
            //this.collection.reset();
            var me = this;
            var params;
            if (this.ui.cbxDateSelectType.prop('checked')) {
                params = {
                    startTime: (startDateText + ' 00:00:00'),
                    endTime: (endDateText + ' 23:59:59'),
                    'fleed_id': '1'
                };
                //
                //var params={coordinate_time_start:(startDateText +' 00:00:00'),coordinate_time_end:(endDateText+' 23:59:59')};
                //this.collection.fetch({data:params});
                //$.get(this.collection.url,params,function(response){
                //var data= _.map(_.pairs(_.groupBy(response['result'],'coordinate_locatorID')),function(item){return {track_locatorID: item[0],track_coordinates:item[1]}});

                //me.collection.set(data);
                //});
            } else {
                params = {
                    startTime: (startDateText + ' 00:00:00'),
                    endTime: (startDateText + ' 23:59:59'),
                    'fleed_id': '1'
                };

                //var params={coordinate_time_start:(startDateText +' 00:00:00'),coordinate_time_end:(startDateText+' 23:59:59')};
                //this.collection.fetch({data:params});
                // $.get(this.collection.url,params,function(response){
                //var data= _.map(_.pairs(_.groupBy(response['result'],'coordinate_locatorID')),function(item){return {track_locatorID: item[0],track_coordinates:item[1]}});

                //me.collection.set(data);
                //});



            }

            this.collection.fetch({
                data: params,
                context: this,
                success: this.updateCoordinates
            });

            console.log('searchByTime');

        },
        updateCoordinates: function () {

            selectedTracks = this.cloneSelectedTracks;
            this.cloneSelectedTracks = 0;

            console.log('updateCoordinates');
            console.debug(this.collection);
            _.each(_.intersection(_.map(_.keys(selectedTracks), function (item) {
                return parseInt(item);
            }), this.collection.map(function (item0) {
                return item0.get('track_locatorID');
            })), function (track_locatorID) {
                console.log('updateCoordinates' + track_locatorID);
                var item = this.collection.findWhere({
                    'track_locatorID': track_locatorID
                });
                Views.memoized_loadCoordinatesByTime2Locator(item, this.searchDates.get('startDate') + ' 00:00:00', this.searchDates.get('endDate') + ' 23:59:59');
            }, this);
            _.each(this.collection.models, function (item, index) {
                this.collection.models[index].set({
                    'isShow': selectedTracks.hasOwnProperty(item.get('track_locatorID'))
                });
            }, this);

            this.filter = null;
            this.render();
            app.MapTracks.removeLushus();


        },
        removeTrack: function (track) {
            console.log(track);
            console.log('removeTrack');
        },

        addTrack: function () {
            console.log('addTrack');
        },





        onFilterSelected: function () {
            this.filter = function (child, index, collection) {
                return child.get('isShow');
            };
            this.render();
            console.log('onFilterSelected');
        },
        onFilterAll: function () {
            this.filter = null;
            this.render();
            console.log('onFilterAll');
        },
        onSearch: function () {
            var keyword = this.ui.inputSearch.val().trim();
            if (keyword != '') {
                this.filter = function (child, index, collection) {
                    return child.get('track_locatorName').toString().indexOf(keyword) > -1;
                };
            } else
                this.filter = null;

            this.render();
            console.log('onSearch');
        },
        onChangeDateSelectType: function () {
            console.log('onChangeDateSelectType');
            if (this.ui.cbxDateSelectType.prop('checked')) {
                this.ui.divDatePanel2.show();
                //this.ui.btnDate2.find('#date').text(this.ui.btnDate1.find('#date').text());
                //this.ui.btnDate2.val(this.ui.btnDate1.val());
            } else {

                //this.ui.btnDate2.find('#date').text(this.ui.btnDate1.find('#date').text());
                //this.ui.btnDate2.val(this.ui.btnDate1.val());
                //this.setSearchDate();
                console.info('setSearchDate');
                this.ui.divDatePanel2.hide();

            }
            this.searchByTime();
        }
    });


});

TrackMVC.LocatorTrackList.js

初始化Controller,根据数据展现视图。

代码语言:javascript
复制
TrackMVC.module('LocatorTrackList',function(LocatorTrackList,App,Backbone,Marionette,$,_){
LocatorTrackList.Router=Marionette.AppRouter.extend({

});

 LocatorTrackList.Controller=function(){
this.trackList=new App.Tracks.TrackList();
 
this.locatorList=new App.Locators.LocatorList();
window.locatorList=this.locatorList;
};
_.extend(LocatorTrackList.Controller.prototype,{
start:function(){
 this.showHeaderDiv(this.locatorList);
this.showLocatorDiv(this.locatorList);
this.showTrackDiv(this.trackList); 

this.bindMapLocators(this.locatorList);
this.bindMapTracks();
App.listenTo(this.locatorList,'reset add remove',this.updateLocatorDiv );
this.locatorList.fetch();
 
setInterval(this.updateLocators,1000*3);

App.listenTo(this.trackList,'reset add remove',this.updateTrackDiv );
this.trackList.fetch({data:{'fleed_id':'1','startTime':DateFormat.format.date(new Date(),'yyyy-MM-dd 00:00:00'),'endTime':DateFormat.format.date(new Date(),'yyyy-MM-dd 23:59:59')}});
},
updateLocators:function()
{window.locatorList.fetch();
},
showHeaderDiv:function(locatorList){
var headerView=new TrackMVC.Layout.Header({
collection:locatorList
});
App.headerRegion.show( headerView);
},
showLocatorDiv:function(locatorList){
console.log('showLocatorDiv');

var locatorView=new TrackMVC.LocatorList.Views.LocatorListView({
collection:locatorList
});
App.locatorRegion.show( locatorView);
},
showTrackDiv:function(trackList){

var trackView=new TrackMVC.TrackList.Views.TrackListView({
collection:trackList
});
App.trackRegion.show( trackView);
},
updateLocatorDiv:function(locatorList){
},
updateTrackDiv:function(trackList){
},
bindMapLocators:function(locatorList){
console.debug('show locators on map');
TrackMVC.MapLocators.setLocators(locatorList);
},
bindMapTracks:function( ){
console.debug('show tracks on map');

TrackMVC.MapTracks.setTracks(TrackMVC.MapTracks.trackListOnMap);
},
});
LocatorTrackList.addInitializer(function(){
var controller=new LocatorTrackList.Controller();
new LocatorTrackList.Router({
controller: controller
});

 controller.start();

});
});

TrackMVC.MapLocators.js

实时监控对应地图叠加层(实时位置图标)的管理

代码语言:javascript
复制
TrackMVC.module('MapLocators',function(MapLocators,App,Backbone,Marionette,$,_){
MapLocators.myListener=Backbone.Events;
var myModel=Backbone.Model.extend({idAttribute: 'locator_id'});
MapLocators.myCurrentClickPoint=new myModel();
MapLocators.myCurrentClickPoint.on('change',function(point){
console.debug( 'myCurrentClickPoint changed');
 
 var latlng=new BMap.Point(point.attributes['locator_coordinate_y'],point.attributes['locator_coordinate_x'])
MapLocators.infoWindow .setWidth(240);		
MapLocators.infoWindow .setHeight(70);	
MapLocators.infoWindow.setPosition(latlng); 
MapLocators.infoWindow.setTitle( point.attributes['locator_name']+" "+point.attributes['locator_coordinate_time']);
        
MapLocators.myGeo.getLocation(latlng, function(rs){
				var addComp = rs.addressComponents;
	
	MapLocators.infoWindow.setContent(addComp.district + ", " +  addComp.street + ", " + addComp.streetNumber);
	 
});
});
 var onIcon=new BMap.Icon("http://"+location.host+'/static/images/online.png',new BMap.Size(44,51),{imageSize:new BMap.Size(30,36)});
 
 var offIcon=new BMap.Icon("http://"+location.host+'/static/images/offline.png',new BMap.Size(44,51),{imageSize:new BMap.Size(30,36)});
var defLabelStyle = {
		 color : "#fff",
			 borderStyle : "none",
			 backgroundColor : "transparent",
			 width : 60,
			 textAlign : "center",
			 fontSize : "15px",
			 left: "8px",
			 top: "9px",
			 fontStyle : "bold"
	};
MapLocators. pointMapItems=[];
MapLocators.myGeo = new BMap.Geocoder();
MapLocators.infoWindow = new BMap.InfoWindow("",{width:620,height:550});
MapLocators.setLocators=function(locatorList ) {
    console.debug(locatorList); 
   this.myListener.listenTo(locatorList,'add',this.addLocator);
this.myListener.listenTo(locatorList,'remove',this.removeLocator);
 _.each(locatorList.models,function(item){
this.myListener.listenTo(item,'change',function(model){
console.debug('changed');
console.debug(model);
});
},this);
 }; 

MapLocators.removeLocator=function(locator)
{
 MapLocators.myListener.stopListening(locator,'change');
console.debug('remove listening');
console.debug(locator);
 MapLocators.removePointLayer(locator);
};
 MapLocators.addLocator=function(locator)
{
 
 MapLocators.myListener.listenTo(locator,'change',MapLocators.updatePointLayer);
console.debug('addLocator');
console.debug(locator);
 MapLocators.addPointLayer(locator); 
};
MapLocators.updatePointLayer=function(point){
console.debug('changed');
var pointMapItem=  _.findWhere(MapLocators. pointMapItems,{'pointId':point.attributes['locator_id']});
if(pointMapItem!=undefined)
{
var latlng=new BMap.Point(point.attributes['locator_coordinate_y'],point.attributes['locator_coordinate_x'])
pointMapItem['marker'].setPosition(latlng);

 var icon=point.attributes['locator_status']=='on'?onIcon:offIcon;

pointMapItem['marker'].setIcon(icon);
pointMapItem['marker'].setTitle(point.attributes['locator_coordinate_time']);
//var label=new BMap.Label(point.attributes['locator_name'],{offset:new BMap.Size(13-point.attributes['locator_name'].length*7,-15)});
 pointMapItem['label'].setContent(point.attributes['locator_name']);
 pointMapItem['label'].setPosition(latlng);
 pointMapItem['label'].setOffset(new BMap.Size(13-point.attributes['locator_name'].length*7,-15));
//label.setStyle(defLabelStyle);
//pointMapItem['marker'].setLabel(label);

if(point.attributes['isShow'])
MapLocators.showPointLayer(point);
else
MapLocators.hidePointLayer(point);
console.debug(point);
} 
};
MapLocators.removePointLayer=function(point)
{
 console.debug(point);
 var pointMapItem=  _.findWhere(MapLocators. pointMapItems,{'pointId':point.attributes['locator_id']});
 var pointMapItemIndex=_.findIndex(MapLocators. pointMapItems,{'pointId':point.attributes['locator_id']})
if(pointMapItem!=undefined)
{
map.removeOverlay(pointMapItem['marker']);
pointMapItem['marker'].removeEventListener('click');
delete MapLocators. pointMapItems[pointMapItemIndex];
delete selectedLocators[point.attributes['locator_id']];
MapLocators. pointMapItems=_.compact(MapLocators. pointMapItems);
}
};
MapLocators.addPointLayer=function(point)
{
console.debug('addOverlay');
console.debug(point);
var latlng=new BMap.Point(point.attributes['locator_coordinate_y'],point.attributes['locator_coordinate_x']);
var icon=point.attributes['locator_status']=='on'?onIcon:offIcon;
var marker=new BMap.Marker(latlng,{icon:icon,title:point.attributes['locator_coordinate_time']});
var label=new BMap.Label(point.attributes['locator_name'],{offset:new BMap.Size(13-point.attributes['locator_name'].length*7,-15)});

label.setStyle(defLabelStyle);
marker.setLabel(label);
marker.addEventListener('click',function(){
 var me=this;
//MapLocators.infoWindow .setWidth(240);		
	//MapLocators.infoWindow .setHeight(70);	
	//MapLocators.infoWindow.setTitle( point.attributes['locator_name']+" "+point.attributes['locator_coordinate_time']);
  
	//MapLocators.myGeo.getLocation(this.getPosition(), function(rs){
				//var addComp = rs.addressComponents;
		 
	   MapLocators.myCurrentClickPoint.set(point.attributes);
	//MapLocators.infoWindow.setContent(addComp.district + ", " +  addComp.street + ", " + addComp.streetNumber);
	 me.openInfoWindow(MapLocators.infoWindow);


	// });

     
 });
var pointMapItem={'pointId':point.attributes['locator_id'],'marker':marker,label:label};
 MapLocators. pointMapItems.push(pointMapItem);

map.addOverlay(marker);
marker.hide();	
	 
};
MapLocators.showPointLayer=function(point){

var pointMapItem=  _.findWhere(MapLocators. pointMapItems,{'pointId':point.attributes['locator_id']});
if(pointMapItem!=undefined)
{

pointMapItem['marker'].show();
} 

};
MapLocators.hidePointLayer=function(point){
var pointMapItem=  _.findWhere(MapLocators. pointMapItems,{'pointId':point.attributes['locator_id']});
if(pointMapItem!=undefined)
{
pointMapItem['marker'].hide();
} 
};
})
 

TrackMVC.MapTracks.js

历史轨迹对应地图叠加层(线轨迹,途经点图标和路书)的管理

代码语言:javascript
复制
TrackMVC.module('MapTracks', function (MapTracks, App, Backbone, Marionette, $, _) {
    MapTracks.myListener = Backbone.Events;

    MapTracks.lushus = [];

    MapTracks.myCollection = Backbone.Collection.extend({});
    MapTracks.trackMapItems = [];
    MapTracks.trackListOnMap = new MapTracks.myCollection();
    MapTracks.myGeo = new BMap.Geocoder();
    MapTracks.infoWindow = new BMap.InfoWindow("", {
        width: 620,
        height: 550
    });
    MapTracks.setTracks = function (trackList) {
        console.debug(trackList);
        this.myListener.listenTo(trackList, 'add', this.addTrack);
        this.myListener.listenTo(trackList, 'remove', this.removeTrack);
        _.each(trackList.models, function (item) {
            this.myListener.listenTo(item, 'change', function (model) {
                console.debug('changed');
                console.debug(model);
            });
        }, this);
    };
    MapTracks.addLushus = function (track) {
        var trackMapItem = _.findWhere(MapTracks.trackMapItems, {
            'trackId': track.attributes['track_locatorID']
        });
        if (trackMapItem != undefined) {
            _.each(trackMapItem['multipolylines'], function (overlay) {

                var lushu = new BMapLib.LuShu(map, overlay['polyline'].getPath(), {
                    defaultContent: "",
                    autoView: true,
                    icon: new BMap.Icon('http://developer.baidu.com/map/jsdemo/img/car.png', new BMap.Size(36, 18), {
                        anchor: new BMap.Size(20, 10),
                        imageSize: new BMap.Size(36, 18)
                    }),
                    speed: 500,
                    enableRotation: true, //是否设置marker随着道路的走向进行旋转
                    landmarkPois: []
                });

                MapTracks.lushus.push(lushu);

            });
        };

    };
    MapTracks.startLushus = function (track) {
        _.each(MapTracks.lushus, function (lushu) {
            lushu.start();
        });

    };
    MapTracks.removeLushus = function (track) {
        _.each(MapTracks.lushus, function (lushu) {
            lushu.stop();
            map.removeOverlay(lushu._overlay);
            map.removeOverlay(lushu._marker);
            delete lushu;
        });
        MapTracks.lushus = [];

    };
    MapTracks.removeTrack = function (track) {
        MapTracks.myListener.stopListening(track, 'change');
        console.debug('remove listening');
        console.debug(track);
        MapTracks.removeTrackLayer(track);
    };
    MapTracks.addTrack = function (track) {

        MapTracks.myListener.listenTo(track, 'change', MapTracks.updateTrackLayer);
        console.debug('addTrack');
        console.debug(track);
        MapTracks.addTrackLayer(track);
    };
    MapTracks.updateTrackLayer = function (track) {
        console.debug('changed');
        var trackMapItem = _.findWhere(MapTracks.trackMapItems, {
            'trackId': track.attributes['track_locatorID']
        });
        if (trackMapItem != undefined) {
            if (track.attributes['isShow'])
                MapTracks.showTrackLayer(track);
            else
                MapTracks.hideTrackLayer(track);
            console.debug(track);
        }
    };
    MapTracks.removeTrackLayer = function (track) {
        console.debug(track);
        var trackMapItem = _.findWhere(MapTracks.trackMapItems, {
            'trackId': track.attributes['track_locatorID']
        });
        var trackMapItemIndex = _.findIndex(MapTracks.trackMapItems, {
            'trackId': track.attributes['track_locatorID']
        });
        if (trackMapItem != undefined) {
            _.each(trackMapItem['multipolylines'], function (overlay) {
                map.removeOverlay(overlay['polyline']);
                _.each(overlay['markers'], function (marker) {
                    marker.removeEventListener('click');
                    map.removeOverlay(marker);
                });
            });
            delete MapTracks.trackMapItems[trackMapItemIndex];
            delete selectedTracks[track.attributes['track_locatorID']];
            MapTracks.trackMapItems = _.compact(MapTracks.trackMapItems);
        }

    };
    MapTracks.addTrackLayer = function (track) {
        console.debug('addOverlay');
        console.info(track);
        window.track = track;
        var timeDeltas = _.map(_.zip(_.initial(track.get('coordinates'), 1), _.rest(track.get('coordinates'), 1)), function (item) {
            return DateFormat.format.parseDate(item[1]['coordinate_time']).date - DateFormat.format.parseDate(item[0]['coordinate_time']).date
        });
        var sliceIndexes = _.map(timeDeltas, function (item, index) {
            if (item > 1000 * 60 * 60)
                return index;
            else return -1
        });
        sliceIndexes = _.without(sliceIndexes, -1);
        var coordinatesSlices = _.groupBy(track.attributes['coordinates'], function (item, index) {
            return _.sortedIndex(sliceIndexes, index);
        })
        window.overlays = _.map(_.values(coordinatesSlices), function (coordinates) {

            //var sampleSize=Math.round(_.size(coordinates)/60);
            var sampleSize = _.size(coordinates) - 2;
            var coordinates2 = _.rest(_.initial(coordinates, 1), 1);
            var startCoordinate = _.first(coordinates);
            var endCoordinate = _.last(coordinates);

            var point2times = _.map([startCoordinate].concat(coordinates2).concat([endCoordinate]), function (coordinate) {
                return {
                    'point': new BMap.Point(coordinate['coordinate_y'], coordinate['coordinate_x']),
                    'time': coordinate['coordinate_time']
                };
            });

            var markers = _.map(point2times, function (point2time) {
                var marker = new BMap.Marker(point2time['point']);
                marker.addEventListener('click', function () {
                    var me = this;
                    MapTracks.infoWindow.setWidth(240);
                    MapTracks.infoWindow.setHeight(70);
                    MapTracks.infoWindow.setTitle(track.attributes['track_locatorName'] + " " + point2time['time']);

                    MapTracks.myGeo.getLocation(this.getPosition(), function (rs) {
                        var addComp = rs.addressComponents;
                        MapTracks.infoWindow.setContent(addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
                        me.openInfoWindow(MapTracks.infoWindow);

                    });

                });
                return marker;

            });

            var polyline = new BMap.Polyline(_.pluck(point2times, 'point'), {
                strokeColor: track.get('showColor'),
                strokeWeight: 2,
                strokeOpacity: 0.8
            });
            return {
                polyline: polyline,
                markers: markers
            }

        });
        _.each(overlays, function (overlay) {

            map.addOverlay(overlay['polyline']);
            overlay['polyline'].hide();
            _.each(overlay['markers'], function (marker) {
                map.addOverlay(marker); //增加折线
                marker.hide();

            });

        });

        var trackMapItem = {
            'trackId': track.attributes['track_locatorID'],
            'multipolylines': overlays
        };
        MapTracks.trackMapItems.push(trackMapItem);

        //map.addOverlay(marker);
        //marker.hide();	

    };
    MapTracks.showTrackLayer = function (track) {
        console.log('showTrackLayer');
        var trackMapItem = _.findWhere(MapTracks.trackMapItems, {
            'trackId': track.attributes['track_locatorID']
        });
        if (trackMapItem != undefined) {

            _.each(trackMapItem['multipolylines'], function (overlay) {
                overlay['polyline'].show(); //增加折线
                _.each(overlay['markers'], function (marker) {
                    marker.show(); //增加折线
                });
            });

            //trackMapItem['marker'].show();
        }
    };
    MapTracks.hideTrackLayer = function (track) {
        var trackMapItem = _.findWhere(MapTracks.trackMapItems, {
            'trackId': track.attributes['track_locatorID']
        });
        if (trackMapItem != undefined) {
            _.each(trackMapItem['multipolylines'], function (overlay) {
                overlay['polyline'].hide(); //增加折线
                _.each(overlay['markers'], function (marker) {
                    marker.hide(); //增加折线
                });

            });
        }
    };
})

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • TrackMVC.js
  • TrackMVC.Layout.js
  • TrackMVC.Locators.js
  • TrackMVC.LocatorList.Views.js
  • TrackMVC.Tracks.js
  • TrackMVC.TrackList.Views.js
  • TrackMVC.LocatorTrackList.js
  • TrackMVC.MapLocators.js
  • TrackMVC.MapTracks.js
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档