This commit is contained in:
2023-04-28 12:22:26 +08:00
parent 88e0a25ecd
commit c9723008af
1047 changed files with 443540 additions and 1 deletions

View File

@ -0,0 +1,169 @@

//************************Add Engine Hours**************************************//
var isAddEH = true;
var primarydatadourceMVEH;
var assetdataEH;
function openAddEnginHours(asset) {
primarydatadourceMVEH = undefined;
assetdataEH = asset;
var datetime = customerdatetime.split(' ');
var time = datetime[0];
var st = datetime[1].split(':');
var hours = st[0].length == 1 ? "0" + st[0] : st[0];
var minutes = st[1];
$('#dialogaddgenginehours_enginehours').val('');
$('#dialogadd_enginehourstimezone').val(customertimezone ? customertimezone : "UTC");
$('#dialogaddenginehours_date').val(time);
$('#dialogaddenginehours_timehour').val(hours);
$('#dialogaddenginehours_timeminute').val(minutes);
$('#dialogaddenginehours_Notes').val('');
if (assetdataEH.TelematicsEnabled && !assetdataEH.EngineHours.IsEmpty &&
(assetdataEH.EngineHours.DataSource.toLowerCase() == "calamp" || assetdataEH.EngineHours.DataSource.toLowerCase() == "pedigree")) {
isAddEH = false;
primarydatadourceMVEH = assetdataEH.EngineHours.DataSource;
}
else
isAddEH = true;
$('#dialog_addenginehours .dialog-title span.title').text(isAddEH ? GetTextByKey("P_MV_ADDENGINEHOURS", 'Add Engine Hours') : GetTextByKey("P_MV_ADJUSTENGINEHOURS", 'Adjust Engine Hours'));
showmaskbg(true);
$('#dialog_addenginehours')
.attr('act', 'add')
.css({
'top': (document.documentElement.clientHeight - $('#dialog_addenginehours').height()) / 3,
'left': (document.documentElement.clientWidth - $('#dialog_addenginehours').width()) / 2
})
.showDialogfixed();
$('#dialogaddgenginehours_enginehours').focus();
}
function OnAddEngineHours() {
$('#addenginehoursmask').show();
var alerttitle = isAddEH ? GetTextByKey("P_MV_ADDENGINEHOURS", 'Add Engine Hours') : GetTextByKey("P_MV_ADJUSTENGINEHOURS", 'Adjust Engine Hours');
var contractorid = $("#selContractor").val();
if (!contractorid) contractorid = "";
var item = {
'CustomerID': contractorid,
'AssetID': assetdataEH.Id,
'EngineHours': $('#dialogaddgenginehours_enginehours').val(),
'EngineHoursDate': $('#dialogaddenginehours_date').val(),
'Notes': $('#dialogaddenginehours_Notes').val(),
'DataSource': primarydatadourceMVEH
};
if (item.EngineHours !== "") {
if (isNaN(item.EngineHours)) {
_dialog.showAlert(GetTextByKey("P_MV_ENGINEHOURSFORMATERROR", 'Engine Hours format error.'), alerttitle);
$('#addenginehoursmask').hide();
return;
}
else {
if (item.EngineHours <= 0) {
_dialog.showAlert(GetTextByKey("P_MV_ENGINEHOURSMUSTBEGREATERTHAN0", 'Engine Hours must be greater than 0.'), alerttitle);
$('#addenginehoursmask').hide();
return;
}
}
}
else {
_dialog.showAlert(GetTextByKey("P_MV_ENGINEHOURSCANNOTBEEMPTY", "Engine Hours cannot be empty."), alerttitle);
$('#addenginehoursmask').hide();
return;
}
if (item.EngineHoursDate === "") {
_dialog.showAlert(GetTextByKey("P_MV_ENGINEHOURSDATECANNOTBEEMPTY", "Engine Hours Date cannot be empty."), alerttitle);
$('#addenginehoursmask').hide();
return;
}
var offset = $('#dialogadd_enginehourstimezone').find("option:selected").attr("offset");
item.OffsetMinute = offset;
var timezonetext = $('#dialogadd_enginehourstimezone').find("option:selected").text();
var hour = $('#dialogaddenginehours_timehour').val();
var minute = $('#dialogaddenginehours_timeminute').val();
item.EngineHoursDate = item.EngineHoursDate.replace("-", "/") + " " + hour + ":" + minute + ":" + "00";
var time = hour + ":" + minute
var alertmsg = "";
if (isAddEH) {
alertmsg = GetTextByKey("P_MV_UPDATEENGINEHOURS", "Do you want to update the engine hours to reflect: {0} hours at {1} {2}?").replace('{0}', item.EngineHours).replace('{1}', time).replace('{2}', timezonetext);
}
else {
alertmsg = GetTextByKey("P_MV_UPDATEENGINEHOURS1", "If you proceed, engine hours will be updated to reflect: {0} hours at {1} <br/>" +
" {2}. <br/><br/>Note that this asset is telematic enabled and the primary data source is {3}." +
"<br/><br/> Would you like to proceed?").replace('{0}', item.EngineHours).replace('{1}', time).replace('{2}', timezonetext).replace('{3}', assetdataEH.EngineHours.DataSourceName);
}
showConfirm1(alertmsg, alerttitle, function () {
$('#addenginehoursmask').hide();
if (isAddEH)
AddManuallyInputEngineHours(item, alerttitle);
else
CheckEngineHourMinimumTime(item, alerttitle);
}, function () {
$('#addenginehoursmask').hide();
});
}
function AddManuallyInputEngineHours(item, alerttitle) {
var param = JSON.stringify(item);
param = htmlencode(param);
devicerequest("AddManuallyInputEngineHours", param, function (data) {
if (data !== 'OK') {
_dialog.showAlert(data, alerttitle);
} else {
//loadAssetInfo();
_dialog.showAlert(GetTextByKey("P_MV_ENGINEHOURSUPDATESUCCESSFUL", "Engine Hours Update Successful."), alerttitle);
}
$('#dialog_addenginehours').hideDialog();
$('#addenginehoursmask').hide();
}, function (err) {
console.log(err);
_dialog.showAlert(GetTextByKey("P_MV_FAILEDTOADDENGINEHOURS", 'Failed to add Engine Hours.'), alerttitle);
$('#addenginehoursmask').hide();
});
}
function CheckEngineHourMinimumTime(item, alerttitle) {
var param = JSON.stringify(item);
param = htmlencode(param);
devicerequest("CheckEngineHourMinimumTime", param, function (data) {
if (data > 0) {
if (data == 1)
_dialog.showAlert(GetTextByKey("P_MV_CHECKENGINEHOURSMINNIMUMTIME", "The adjustment cannot be completed as provided. The engine hours reading date provided cannot be prior to initial telematic data available for the asset."), alerttitle);
else
_dialog.showAlert(GetTextByKey("P_MV_CHECKENGINEHOURSMINNIMUMTIME1", "The adjustment cannot be completed as provided. The engine hours reading date provided must be prior to or equal to the latest telematic data available for the asset."), alerttitle);
$('#addenginehoursmask').hide();
return;
} else {
SaveAdjustEngineHours(item, alerttitle);
}
}, function (err) {
});
}
function SaveAdjustEngineHours(item, alerttitle) {
var param = JSON.stringify(item);
param = htmlencode(param);
devicerequest("SaveAdjustEngineHours", param, function (data) {
if (data !== 'OK') {
_dialog.showAlert(data, alerttitle);
} else {
//loadAssetInfo();
_dialog.showAlert(GetTextByKey("P_MV_ENGINEHOURSUPDATESUCCESSFUL", "Engine Hours Update Successful."), alerttitle);
}
$('#dialog_addenginehours').hideDialog();
$('#addenginehoursmask').hide();
}, function (err) {
console.log(err);
_dialog.showAlert(GetTextByKey("P_MV_FAILEDTOADJUSTENGINEHOURS", 'Failed to adjust Engine Hours.'), alerttitle);
$('#addenginehoursmask').hide();
});
}

View File

@ -0,0 +1,165 @@

//************************Add Odometer**************************************//
var isAddOdo = true;
var primarydatadourceMVOdo;
var assetdataOdo;
function openAddOdometer(asset) {
primarydatadourceMVOdo = undefined;
assetdataOdo = asset;
var datetime = customerdatetime.split(' ');
var time = datetime[0];
var st = datetime[1].split(':');
var hours = st[0].length == 1 ? "0" + st[0] : st[0];
var minutes = st[1];
$('#dialogadd_odometer').val('');
$('#dialogadd_sel_odometeruom').val(systemunitofodometer);
$('#dialogadd_odometertimezone').val(customertimezone ? customertimezone : "UTC");
$('#dialogadd_odometerdate').val(time);
$('#dialogadd_timehour').val(hours);
$('#dialogadd_timeminute').val(minutes);
$('#dialogadd_notes').val('');
if (assetdataOdo.TelematicsEnabled && !assetdataOdo.Odometer.IsEmpty &&
(assetdataOdo.Odometer.DataSource.toLowerCase() == "calamp" || assetdataOdo.Odometer.DataSource.toLowerCase() == "pedigree")) {
isAddOdo = false;
primarydatadourceMVOdo = assetdataOdo.Odometer.DataSource;
}
else
isAddOdo = true;
$('#dialog_addodometer .dialog-title span.title').text(isAddOdo ? GetTextByKey("P_MV_ADDODOMETER", 'Add Odometer') : GetTextByKey("P_MV_ADJUSTODOMETER", 'Adjust Odometer'));
showmaskbg(true);
$('#dialog_addodometer')
.attr('act', 'add')
.css({
'top': (document.documentElement.clientHeight - $('#dialog_addodometer').height()) / 3,
'left': (document.documentElement.clientWidth - $('#dialog_addodometer').width()) / 2
})
.showDialogfixed();
$('#dialogadd_odometer').focus();
}
function OnAddOdometer() {
$('#addodomask').show();
var alerttitle = isAddOdo ? GetTextByKey("P_MV_ADDODOMETER", 'Add Odometer') : GetTextByKey("P_MV_ADJUSTODOMETER", 'Adjust Odometer');
var contractorid = $("#selContractor").val();
if (!contractorid) contractorid = "";
var item = {
'CustomerID': contractorid,
'AssetID': assetdataOdo.Id,
'Odometer': $('#dialogadd_odometer').val(),
'UOM': $('#dialogadd_sel_odometeruom').val(),
'OdometerDate': $('#dialogadd_odometerdate').val(),
'Notes': $('#dialogadd_notes').val(),
'DataSource': primarydatadourceMVOdo
};
if (item.Odometer !== "") {
if (isNaN(item.Odometer)) {
_dialog.showAlert(GetTextByKey("P_MV_ODOMETERFORMATERROR", 'Odometer format error.'), alerttitle);
$('#addodomask').hide();
return;
}
else {
if (item.Odometer <= 0) {
_dialog.showAlert(GetTextByKey("P_MV_ODOMETERMUSTBEGREATERTHAN0", 'ODOMeter must be greater than 0.'), alerttitle);
$('#addodomask').hide();
return;
}
}
}
else {
_dialog.showAlert(GetTextByKey("P_MV_ODOMETRCANNOTBEEMPTY", "Odometer cannot be empty."), alerttitle);
$('#addodomask').hide();
return;
}
if (item.OdometerDate === "") {
_dialog.showAlert(GetTextByKey("P_MV_ODOMETRDATACANNOTBEEMPTY", "Odometer date cannot be empty."), alerttitle);
$('#addodomask').hide();
return;
}
var offset = $('#dialogadd_odometertimezone').find("option:selected").attr("offset");
item.OffsetMinute = offset;
var timezonetext = $('#dialogadd_enginehourstimezone').find("option:selected").text();
var hour = $('#dialogadd_timehour').val();
var minute = $('#dialogadd_timeminute').val();
item.OdometerDate = item.OdometerDate.replace("-", "/") + " " + hour + ":" + minute + ":" + "00";
var time = hour + ":" + minute
var alertmsg = "";
if (isAddOdo) {
alertmsg = GetTextByKey("P_MV_UPDATETHEODOMETER", "Do you want to update the odometer to reflect: {0} {1} at {2} {3}?").replace('{0}', item.Odometer).replace('{1}', item.UOM).replace('{2}', time).replace('{3}', timezonetext);
}
else {
alertmsg = GetTextByKey("P_MV_UPDATETHEODOMETER1", "If you proceed, odometer will be updated to reflect: {0} {1} at {2} <br/> {3}.<br/><br/> Note that this asset is telematic enabled and the primary data source is {4}.<br/><br/>Would you like to proceed?").replace('{0}', item.Odometer).replace('{1}', item.UOM).replace('{2}', time).replace('{3}', timezonetext).replace('{4}', assetdataOdo.Odometer.DataSourceName);
}
showConfirm1(alertmsg, alerttitle, function () {
$('#addodomask').hide();
if (isAddOdo)
AddManuallyInputOdometer(item, alerttitle);
else
CheckOdometerMinnimumTime(item, alerttitle);
}, function () {
$('#addodomask').hide();
});
}
function AddManuallyInputOdometer(item, alerttitle) {
var param = JSON.stringify(item);
param = htmlencode(param);
devicerequest("AddManuallyInputOdometer", param, function (data) {
if (data !== 'OK') {
_dialog.showAlert(data, alerttitle);
} else {
//loadAssetInfo();
_dialog.showAlert(GetTextByKey("P_MV_ODOMETERUPDATESUCCESSFUL", "Odometer Update Successful."), alerttitle);
}
$('#dialog_addodometer').hideDialog();
$('#addodomask').hide();
}, function (err) {
_dialog.showAlert(GetTextByKey("P_MV_FAILEDTOADDODOMETER", 'Failed to add Odometer.'), alerttitle);
$('#addodomask').hide();
});
}
function CheckOdometerMinnimumTime(item, alerttitle) {
var param = JSON.stringify(item);
param = htmlencode(param);
devicerequest("CheckOdometerMinnimumTime", param, function (data) {
if (data > 0) {
if (data == 1)
_dialog.showAlert(GetTextByKey("P_MA_CHECKODOMETERMINNIMUMTIME", "The adjustment cannot be completed as provided. The odometer reading date provided cannot be prior to initial telematic data available for the asset."), alerttitle);
else
_dialog.showAlert(GetTextByKey("P_MA_CHECKODOMETERMINNIMUMTIME1", "The adjustment cannot be completed as provided. The odometer reading date provided must be prior to or equal to the latest telematic data available for the asset."), alerttitle);
$('#addodomask').hide();
return;
} else {
SaveAdjustOdometer(item, alerttitle);
}
}, function (err) {
});
}
function SaveAdjustOdometer(item, alerttitle) {
var param = JSON.stringify(item);
param = htmlencode(param);
devicerequest("SaveAdjustOdometer", param, function (data) {
if (data !== 'OK') {
_dialog.showAlert(data, alerttitle);
} else {
//loadAssetInfo();
_dialog.showAlert(GetTextByKey("P_MV_ODOMETERUPDATESUCCESSFUL", "Odometer Update Successful."), alerttitle);
}
$('#dialog_addodometer').hideDialog();
$('#addodomask').hide();
}, function (err) {
_dialog.showAlert(GetTextByKey("P_MV_FAILEDTOADJUSTODOMETER", 'Failed to adjust Odometer.'), alerttitle);
$('#addodomask').hide();
});
}

948
Site/js/mapview/asset.js Normal file
View File

@ -0,0 +1,948 @@

var allAssets;
var selectedAsset = undefined;
var assetDictionary = [[]];
var allGroups;
var groupAssets = [[]];
var jobsiteAssets = [[]];
function updateAssets() {
assetDictionary = [[]];
groupAssets = [[]];
jobsiteAssets = [[]];
if (allAssets) {
for (var i = 0; i < allAssets.length; i++) {
var asset = allAssets[i];
var index = "" + asset.ID % 100;
if (!assetDictionary[index])
assetDictionary[index] = [];
assetDictionary[index].push(asset);
if (asset.AssetGroups && asset.AssetGroups.length > 0) {
for (var j = 0; j < asset.AssetGroups.length; j++) {
var gid = asset.AssetGroups[j].toLowerCase();
if (!groupAssets[gid])
groupAssets[gid] = [];
groupAssets[gid].push(asset);
}
}
else {
var gid = "-1";
if (!groupAssets[gid])
groupAssets[gid] = [];
groupAssets[gid].push(asset);
}
if (asset.JobSites && asset.JobSites.length > 0) {
for (var j = 0; j < asset.JobSites.length; j++) {
var jsid = asset.JobSites[j];
if (!jobsiteAssets[jsid])
jobsiteAssets[jsid] = [];
jobsiteAssets[jsid].push(asset);
}
}
else {
var jsid = -1;
if (!jobsiteAssets[jsid])
jobsiteAssets[jsid] = [];
jobsiteAssets[jsid].push(asset);
}
}
}
}
function getAsset(aid) {
var index = "" + aid % 100;
var items = assetDictionary[index];
if (items) {
for (var i = 0; i < items.length; i++) {
if (items[i].ID == aid)
return items[i];
}
}
}
var unshownMachineID = [];//不需要显示的机器ID
/******************************AssetObject******************************/
/******************************机器信息获取及显示******************************/
if (typeof (AssetObject) != "function") {
AssetObject = function (mapHelper) {
var isFirstLoad = true;//是否第一次加载,第一次加载需定位
var allMachineCheckBox = [];
var inSearchingMachine = false;
var allLocations;
var _this = this;
var REDUN = 2;
var ROW_HEIGHT = 50;
var MIN_LENGTH = 40;
var trunc = function (val) {
return (val > 0 ? Math.floor : Math.ceil)(val);
};
var assetsummaryctr;
var vm = new Vue({
el: '#machineList',
data: {
machines: [],
startIndex: 0,
bodyContentStyle: { top: null },
bodyContainerHeight: 0,
bodyContainerStyle: { height: null },
scrollTop: 0
},
computed: {
bodyClientRowCount: function () {
var height = document.getElementById('contentCtrl').clientHeight;
return trunc((height - 1) / ROW_HEIGHT) + 1;
},
innerMachines: function () {
var start = this.startIndex;
if (start < 0) {
start = 0;
}
if (this.machines == null || this.machines.length < MIN_LENGTH) {
return this.machines.slice();
}
var end = this.bodyClientRowCount + start + (REDUN * 2) + 1;
if (end > this.machines.length) {
end = this.machines.length;
}
return this.machines.slice(start, end);
}
},
methods: {
reload: function (data) {
this.machines = data;
var height = data && data.length * ROW_HEIGHT;
this.bodyContainerHeight = height;
this.bodyContainerStyle.height = height && (height + 'px');
if (data.length < MIN_LENGTH) {
this.startIndex = -1;
this.startIndex = 0;
this.bodyContentStyle.top = '0px';
} else {
var index = this.startIndex;
var lastIndex = data.length - this.bodyClientRowCount;
if (index > lastIndex) {
index = lastIndex;
}
this.startIndex = -1;
this.startIndex = index;
}
},
refresh: function () {
var index = this.startIndex;
this.startIndex = -1;
this.startIndex = index;
},
chkMachineClick: function (m) {
chkMachineClick(m);
},
linkMachineClick: function (m) {
linkMachineClick(m);
this.refresh();
},
locationHistoryClick: function (m, ev) {
if (selectedAsset)
selectedAsset.State.Highlight = false;
m.State.Highlight = true;
this.refresh();
selectedAsset = m;
var e = { data: m };
locationHistoryClick(e);
},
assetSummaryMouseover: function (m, ev) {
$("#assetsummary").empty();
$("#assetsummary").show();
$("#assetsummarytrigle").show();
var left = ev.clientX + 10;
left = $(ev.target).offset().left + $(ev.target).width() + 90;
//var left = $("#machineCtrl").width();
//var top = ev.clientY;
var top = $(ev.target).offset().top;
if (top + 10 + $("#assetsummary").height() > document.documentElement.clientHeight)
top = document.documentElement.clientHeight - $("#assetsummary").height() - 10;
top = top - 60;
$("#assetsummary").css({ 'left': left, 'top': top });
$("#assetsummarytrigle").css({ 'left': left + 1, 'top': $(ev.target).offset().top - 60 });
if (assetsummaryctr)
assetsummaryctr.status = 1;
assetsummaryctr = new $assetsummary($("#assetsummary"), m.CompanyID, m.ID, m.AlertTips, 0);
},
assetSummaryMouseleave: function (m, ev) {
if (assetsummaryctr)
assetsummaryctr.status = 1;
var to = $(ev.toElement);
if (to.prop('id') != "assetsummary"
&& to.parents("#assetsummary").length == 0
&& to.prop('id') != "assetsummarytrigle") {
$("#assetsummary").hide();
$("#assetsummarytrigle").hide();
}
}
}
});
this.onscrollAssets = function (e) {
if (vm.machines == null || vm.machines.length < MIN_LENGTH) {
return;
}
var top = e == null ? 0 : e.target.scrollTop;
top -= (top % ROW_HEIGHT) + (REDUN * ROW_HEIGHT);
if (top < 0) {
top = 0;
} else {
var bottomTop = vm.bodyContainerHeight - ((vm.bodyClientRowCount + (REDUN * 2) + 1) * ROW_HEIGHT);
if (top > bottomTop) {
top = bottomTop;
}
}
if (vm.scrollTop !== top) {
vm.scrollTop = top;
vm.startIndex = top / ROW_HEIGHT;
vm.bodyContentStyle.top = top && (top + 'px');
}
};
this.refreshAssetList = function () {
vm.refresh();
}
var ROW_GROUP_HEIGHT = 26;
var groupData = [];
var groupMachines = [];
var agvm = new Vue({
el: '#assetGroupList',
data: {
startIndex: 0,
bodyContentStyle: { top: null },
bodyContainerHeight: 0,
bodyContainerStyle: { height: null },
scrollTop: 0
},
computed: {
bodyClientRowCount: function () {
var height = document.getElementById('contentCtrl').clientHeight;
return trunc((height - 1) / ROW_GROUP_HEIGHT) + 1;
},
innerAssetgroupMachines: function () {
var start = this.startIndex;
if (start < 0) {
start = 0;
}
if (groupMachines == null || groupMachines.length < MIN_LENGTH) {
return groupMachines.slice();
}
var end = this.bodyClientRowCount + start + (REDUN * 2) + 1;
if (end > groupMachines.length) {
end = groupMachines.length;
}
return groupMachines.slice(start, end);
}
},
methods: {
fillMachines: function () {
var g = [];
var allindeterminate = false;
var gselcount = 0;
for (var i = 0; i < groupData.length; i++) {
var o = groupData[i];
o.__isGroup = true;
o.__indeterminate = false;
g.push(o);
var selcount = 0;
if (o.Machines && o.Machines.length > 0) {
for (var j = 0; j < o.Machines.length; j++) {
var om = o.Machines[j];
if (om.State.Selected) selcount++;
if (!o.Collapsed)
g.push(om);
}
if (selcount == 0) {
o.Selected = false;
o.__indeterminate = false;
}
else if (selcount == o.Machines.length) {
o.Selected = true;
o.__indeterminate = false;
}
else {
o.__indeterminate = true;
allindeterminate = true;
}
}
else
o.__indeterminate = false;
if (o.Selected) gselcount++;
}
groupMachines = g;
var chkSelectAllAssetGroup = document.getElementById("chkSelectAllAssetGroup");
chkSelectAllAssetGroup.indeterminate = allindeterminate;
if (gselcount == 0) {
chkSelectAllAssetGroup.checked = false;
}
else if (gselcount == groupData.length) {
chkSelectAllAssetGroup.checked = true;
}
else {
chkSelectAllAssetGroup.indeterminate = true;
}
var height = g.length * ROW_GROUP_HEIGHT;
this.bodyContainerHeight = height;
this.bodyContainerStyle.height = height && (height + 'px');
var index = this.startIndex;
this.startIndex = -1;
this.startIndex = index;
// this.$set(this, 'startIndex', index);
this.$nextTick(function () {
var content = document.getElementById('contentCtrl');
if (this.bodyContainerHeight + 26 <= content.clientHeight) {
this.bodyContentStyle.top = 0;
this.startIndex = 0;
}
});
},
reload: function (data) {
groupData = data;
//this.bodyContentStyle.top = '0px';
this.fillMachines();
},
refresh: function () {
var index = this.startIndex;
this.startIndex = -1;
this.startIndex = index;
},
treeIconClick: function (e, g) {
if (g) {
var t = $(e.target);
if (t.hasClass("treeiconc"))
t.removeClass("treeiconc").addClass("treeicone");
else
t.removeClass("treeicone").addClass("treeiconc");
g.Collapsed = !g.Collapsed;
this.fillMachines();
}
else
treeIconClick(e);
},
chkMachineClick: function (m) {
chkMachineClick(m);
},
linkMachineClick: function (m) {
linkMachineClick(m);
this.refresh();
},
locationHistoryClick: function (m, ev) {
if (selectedAsset)
selectedAsset.State.Highlight = false;
m.State.Highlight = true;
this.refresh();
selectedAsset = m;
var e = { data: m };
locationHistoryClick(e);
},
chkAssetGroupClick: function (e, group) {
chkAssetGroupClick(group);
this.fillMachines();
},
linkAssetGroupClick: function (e, group) {
if (group.Selected)
zoomAssetGroup(group);
else {
group.Selected = true;
chkAssetGroupClick(group);
this.fillMachines();
zoomAssetGroup(group);
}
}
}
});
this.onscrollGroupMachines = function (e) {
if (groupMachines == null || groupMachines.length < MIN_LENGTH) {
return;
}
var top = e == null ? 0 : e.target.scrollTop;
top -= (top % ROW_GROUP_HEIGHT) + (REDUN * ROW_GROUP_HEIGHT);
if (top < 0) {
top = 0;
} else {
var bottomTop = agvm.bodyContainerHeight - ((agvm.bodyClientRowCount + (REDUN * 2) + 1) * ROW_GROUP_HEIGHT);
if (top > bottomTop) {
top = bottomTop;
}
}
if (agvm.scrollTop !== top) {
agvm.scrollTop = top;
agvm.startIndex = top / ROW_GROUP_HEIGHT;
agvm.bodyContentStyle.top = top && (top + 'px');
}
};
this.refreshAssetGroupList = function () {
agvm.refresh();
}
this.selectAllAssetGroups = function (checked) {
if (groupData) {
for (var i = 0; i < groupData.length; i++) {
var g = groupData[i];
if (g.Selected != checked) {
g.Selected = checked;
chkAssetGroupClick(g);
}
}
agvm.fillMachines();
}
}
function chkAssetGroupClick(group) {
var checked = group.Selected;
if (group && group.Machines) {
var ams = [];
var rms = [];
var rids = [];
for (var i in group.Machines) {
var machine = group.Machines[i];
if (machine.State.Selected != checked) {
machine.State.Selected = checked;
if (checked) {
ams.push(machine);
//unshownMachineID.splice(unshownMachineID.indexOf(machine.ID), 1);
rids.push(machine.ID);
}
else {
rms.push(machine);
unshownMachineID.push(machine.ID);
}
}
}
if (rids.length > 0) {
var unshownids = [];
for (var i = 0; i < unshownMachineID.length; i++) {
var id = unshownMachineID[i];
if (rids.indexOf(id) < 0)
unshownids.push(id);
}
unshownMachineID = unshownids;
}
if (ams.length > 0)
mapHelper.showMachines(ams);
if (rms.length > 0)
mapHelper.removeMachines(rms);
displayFilerIcon();
}
}
this.getUnShownMachines = function () {
return unshownMachineID;
}
this.setUnShownMachines = function (machines) {
unshownMachineID = [];
if (machines) {
for (var i in machines) {
unshownMachineID.push(eval(machines[i]));//asset id 为数值类型
}
}
}
this.searchMachine = function (isauto) {
if (inSearchingMachine)
return;
inSearchingMachine = true;
$('#loadingDiv').show();
currentShownIndex = -1;
allMachineCheckBox.splice(0, allMachineCheckBox.length);//清空CheckBox数组
//this.getMachines(isauto);//getMachines放在loadMapAlertLayer加载完成后执行
this.getCompanyLocations();
this.loadMapAlertLayer(isauto);
displayFilerIcon();
}
this.getMachines = function (isauto) {
var mal = $("#selMapAlertLayer").val();
if (!mal) mal = "";
var item = {
'IsAutoRefresh': isauto,
'ViewID': mal,
'ContractorID': companyids,
'SearchText': htmlencode($("#txtMachineSearchText").val()),
'Onroad': $("#selOnroad").val(),
'Layers': parametervalues,
'ExcludeNoLocation': $("#exclude00Div").attr("state") != "0", //$("#chkExcludeNoLoc").prop("checked"),
'Attachment': $("#selAttachment").val()
};
_network.mapviewquery("GetAssets", JSON.stringify(item), function (data) {
if (typeof (data) !== "string") {
mapHelper.clearMachine();
allAssets = convertAssetObjs(data);
updateAssets();
_this.getAssetGroups(item);//Asset取完再取group
jobsiteObject.searchJobSite(isauto);//Asset取完再取jobsite
showAssets();
if (isFirstLoad || $("#autoRecenterDiv").attr("state") == "1") {
isFirstLoad = false;
zoomMap();
}
getNowFormatDate();
}
else {
showMachineAlert();
}
inSearchingMachine = false;
$('#loadingDiv').hide();
}, function () {
inSearchingMachine = false;
showMachineAlert();
$('#loadingDiv').hide();
});
}
function convertAssetObjs(data) {
var assets = [];
for (var i = 0; i < data.length; i++) {
var a = {};
var s = data[i];
var s1 = s.split(String.fromCharCode(171));
if (s1.length == 2) {//Dealer站点返回的数据包含公司信息
var cinfos = s1[0].split(String.fromCharCode(170));
a.CompanyID = cinfos[0];
a.CompanyName = cinfos[1];
s = s1[1];
}
var ss = s.split(String.fromCharCode(170));
a.ID = Number(ss[0]);
a.VIN = ss[1];
a.Name = ss[2];
a.Name2 = ss[3];
a.Make = ss[4];
a.Model = ss[5];
a.AssetType = ss[6];
a.Latitude = Number(ss[7]);
a.Longitude = Number(ss[8]);
a.IconUrl = ss[9];
a.AlertTips = ss[10];
a.Priority = Number(ss[11]);
if (ss[12] && ss[12] !== "") {
a.AssetGroups = ss[12].split(",")
}
else {
a.AssetGroups = [];
}
if (ss[13] && ss[13] !== "") {
a.JobSites = ss[13].split(",");
}
else {
a.JobSites = [];
}
a.DisplayName = a.Name2;
if (!a.DisplayName || a.DisplayName === "")
a.DisplayName = a.Name;
if (!a.DisplayName || a.DisplayName === "")
a.DisplayName = a.VIN;
if (!a.DisplayName || a.DisplayName === "")
a.DisplayName = a.ID;
assets.push(a);
}
return assets;
}
this.getAssetGroups = function () {
var item = {
'ContractorID': companyids,
'SearchText': "",//htmlencode($("#txtAssetGroupSearchText").val()) //在前端过滤Group后端不再过滤
};
_network.mapviewquery("GetAssetGroups", JSON.stringify(item), function (data) {
if (typeof (data) !== "string") {
showAssetGroups(data);
}
}, function () {
});
}
function showMachineAlert() {
if (machineAlert) {
_dialog.close(machineAlert);
machineAlert = null;
}
machineAlert = _dialog.showAlert(GetTextByKey("P_MV_UNABLETOOBTAINASSETDATAATTEMPTINGTORECONNECT", 'Unable to obtain asset data. Attempting to reconnect...'), GetTextByKey("P_MV_REFRESHMACHINEDATA", 'Refresh machine data'));
}
function showAssets() {
var ams = [];
for (var i = 0; i < allAssets.length; i++) {
var m = allAssets[i];
m.State = getMachineStateObj(m.ID);
if (unshownMachineID.indexOf(m.ID) < 0) {//需要显示
m.State.Selected = true;
ams.push(m);
allJobSiteMachine["MID" + m.ID] = m;
}
}
mapHelper.showMachines(ams);
vm.reload(allAssets);
}
function showAssetGroups(groups) {
for (var i = groups.length - 1; i >= 0; i--) {
var g = groups[i];
g.Collapsed = true;
g.Selected = true;
if (allGroups) {//get group state
for (var j = 0; j < allGroups.length; j++) {
var lg = allGroups[j];
if (g.ID === lg.ID) {
g.Collapsed = lg.Collapsed;
g.Selected = lg.Selected;
break;
}
}
}
var filter = $.trim($("#txtAssetGroupSearchText").val());
g.Matched = true;
if (filter != "" && g.Name.toLowerCase().indexOf(filter.toLocaleLowerCase()) < 0)
g.Matched = false;
var assets = [];
if (groupAssets[g.ID.toLowerCase()]) {
var tempAssets = groupAssets[g.ID.toLowerCase()];
for (var j = 0; j < tempAssets.length; j++) {//Assets
var a = tempAssets[j];
if (g.Matched || isAssetMatch(a, filter)) {
assets.push(a);
}
}
}
g.Machines = assets;
if (!g.Matched && g.Machines.length == 0)
groups.splice(i, 1);
}
allGroups = groups;
agvm.reload(allGroups);
}
function zoomAssetGroup(group) {
zoomMap(group.Machines);
}
function zoomMap(assets) {
if (!assets)
assets = allAssets;
if (assets && assets.length > 0) {
var maxLong, minLong, maxLat, minLat = null;
for (var i in assets) {
var m = assets[i];
if (!m.State.Selected) continue;//不计算不显示的
//if (m.Longitude == 0 && m.Latitude == 0) continue;//不计算经纬度都为0的
if (maxLong == null || maxLong < m.Longitude)
maxLong = m.Longitude;
if (minLong == null || minLong > m.Longitude)
minLong = m.Longitude;
if (maxLat == null || maxLat < m.Latitude)
maxLat = m.Latitude;
if (minLat == null || minLat > m.Latitude)
minLat = m.Latitude;
}
if (maxLong != minLong || maxLat != minLat) {//至少一个不相同
var ext = new ExtentC();
ext.xmax = maxLong + 0.001;
ext.xmin = minLong - 0.001;
ext.ymax = maxLat + 0.001;
ext.ymin = minLat - 0.001;
mapHelper.gotoMap(ext);
}
else {
var point = new PointC({
longitude: assets[0].Longitude,
latitude: assets[0].Latitude
});
mapHelper.centerAt(point);
}
}
else if (assets.length == 1) {
var point = new PointC({
longitude: assets[0].Longitude,
latitude: assets[0].Latitude
});
mapHelper.centerAt(point);
}
}
function chkMachineClick(machine) {
if (machine) {
if (machine.State.Selected) {
mapHelper.showMachine(machine);
unshownMachineID.splice(unshownMachineID.indexOf(machine.ID), 1);
}
else {
mapHelper.removeMachine(machine);
unshownMachineID[unshownMachineID.length] = machine.ID;
}
agvm.reload(allGroups);
displayFilerIcon();
}
}
function linkMachineClick(machine) {
if (machine) {
if (machine.State.Selected) {
mapHelper.locateMachine(machine);
}
else {
machine.State.Selected = true;
unshownMachineID.splice(unshownMachineID.indexOf(machine.ID), 1);
mapHelper.showMachine(machine);
mapHelper.locateMachine(machine);
}
displayFilerIcon();
}
}
this.selectAllMachine = function (checked) {
var ams = [];
var rms = [];
for (var i = 0; i < allMachineCheckBox.length; i++) {
var item = allMachineCheckBox[i];
var itemChecked = item.attr("checked") == "checked";
if (checked != itemChecked) {
item.attr("checked", checked);
var machine = allMachineCheckBox[i].machine;
if (checked) {
ams.push(machine);
unshownMachineID.splice(unshownMachineID.indexOf(machine.ID), 1);
}
else {
unshownMachineID[unshownMachineID.length] = machine.ID;
rms.push(machine);
}
}
}
mapHelper.showMachines(ams);
mapHelper.removeMachines(rms);
displayFilerIcon();
}
this.getContractor = function (callback) {
_network.mapviewquery("GetContractors", "", function (data) {
showContractors(data);
if (callback)
callback();
});
}
function showContractors(data) {
if (data && data.length > 0) {
hasContractor = true;
var sel = $("#selContractor");
//for (var i = 0; i < data.length; i++) {
// var c = data[i];
// var opt = $('<option></option>').val(c.Key).text(c.Value);
// sel.append(opt);
//}
sel.data('dropdown').setSource(data);
if (userParams && userParams.MapViewContratorID && userParams.MapViewContratorID != "") {
companyids = userParams.MapViewContratorID;
sel.dropdownVals(userParams.MapViewContratorID.split(","));
}
$("#contractorCtrl").css("display", "inline-flex");
$("#contentCtrl").css("top", 115 + 30);
}
else {
$("#btnToggleTimeline").show();
$("#btnImportShapeFile").show();
}
}
this.getCompanyLocations = function () {
var _this = this;
_network.mapviewquery("GetCompanyLocations", companyids, function (data) {
allLocations = data;
if (allLocations && allLocations.length > 0)
$("#showDealerLocationsDiv").css("display", "inline-block");
else
$("#showDealerLocationsDiv").hide();
if ($("#showDealerLocationsDiv").attr("state") == "1")
_this.showLocations();
}, function () {
$('#loadingDiv').hide();
});
}
this.showLocations = function () {
if (allLocations) {
for (var li in allLocations) {
var loc = allLocations[li];
mapHelper.showLocation(loc);
}
}
}
this.clearLocations = function () {
if (allLocations) {
for (var li in allLocations) {
var loc = allLocations[li];
mapHelper.removeLocation(loc);
}
}
}
this.loadMapAlertLayer = function (isauto) {
var sel = $("#selMapAlertLayer");
var selmal = sel.val();//记录已选择的值
if (!selmal) selmal = userParams.MapAlertLayer;
var p = companyids + ";" + selmal;
var _this = this;
_network.mapviewquery("GetMapAlertLayers", p, function (data) {
if (data && data.length > 0) {
$("#mapAlertLayerDiv").show();
$("#splitIconRight").show();
$("#rightCtrl").show();
showMapAlertLayer(data);
}
else {
$("#mapAlertLayerDiv").hide();
$("#splitIconRight").hide();
$("#rightCtrl").hide();
}
_this.getMachines(isauto);
}, function () {
$('#loadingDiv').hide();
});
}
}
}
function getAssetByID(assetid) {//加载机器的详细信息
_network.mapviewquery("GetAssetByID", JSON.stringify([assetid, companyids]), function (data) {
if (data && typeof (data) !== "string") {
mapHelper.showAssetDetailInfo(data);
}
}, function () {
});
}
var assetLocations = [];//当前的位置信息
var assetHisLocations = [];//历史记录的位置信息
function getAssetPopupContent(cid, asset) {
var loc = asset.Location;
var popContent = "<b>" + GetTextByKey("P_MV_NAME_COLON", "Name:") + " </b> " + htmlencode(asset.Name) + "<br/>";
popContent += "<b>" + GetTextByKey("P_MV_NAMECUSTOM_COLON", "Name (Custom):") + " </b>" + htmlencode(asset.Name2) + "<br/>";
popContent += "<b>" + GetTextByKey("P_MV_SN_COLON", "SN:") + " </b>" + asset.VIN + "<br/>";
popContent += "<b>" + GetTextByKey("P_MV_MAKE_COLON", "Make:") + " </b>" + asset.Make + "<br/>";
popContent += "<b>" + GetTextByKey("P_MV_MODEL_COLON", "Model:") + " </b>" + asset.Model + "<br/>";
popContent += "<b>" + GetTextByKey("P_MV_TYPE_COLON", "Type:") + " </b>" + asset.AssetType + "<br/>";
if (asset.EngineHours > 0) {
popContent += "<b>" + GetTextByKey("P_MV_ENGINEHOURS_COLON", "Engine Hours:") + " </b>" + asset.EngineHours.toLocaleString() + "<br/>";
}
if (asset.Odometer > 0) {
var odometerInfo = asset.Odometer.toLocaleString();
if (asset.Odometer > 0 && asset.OdometerUOM) {
odometerInfo += " " + asset.OdometerUOM;
}
popContent += "<b>" + GetTextByKey("P_MV_ODOMETER_COLON", "Odometer:") + " </b>" + odometerInfo + "<br/>";
}
if (loc.LocationTimeText !== "")
popContent += "<b>" + GetTextByKey("P_MV_LOCATIONUPDATED_COLON", "Location Updated:") + " </b>" + loc.LocationTimeText + "<br/>";
if (asset.EngineHours > 0 && asset.EngineHoursDateText !== "")
popContent += "<b>" + GetTextByKey("P_MV_ENGINEHOURSUPDATED_COLON", "Engine Hours Updated:") + " </b>" + asset.EngineHoursDateText + "<br/>";
var speed = "";
if (loc.Speed >= 0)
speed = loc.Speed + " " + (loc.SpeedUnit === "mi/h" ? "mph" : loc.SpeedUnit);
if (speed !== "")
popContent += "<b>" + GetTextByKey("P_MV_CURRENTSPEED_COLON", "Current Speed:") + " </b>" + speed + "<br/>";
var postedspeed = "";
if (loc.PostedSpeed > 0)
postedspeed = loc.PostedSpeed + " " + loc.PostedSpeedUnit;
if (postedspeed !== "")
popContent += "<b>" + GetTextByKey("P_MV_POSTEDSPEED_COLON", "Posted Speed:") + " </b>" + postedspeed + "<br/>";
if (loc.Street !== "")
popContent += "<b>" + GetTextByKey("P_MV_STREET_COLON", "Street:") + " </b>" + loc.Street + "<br/>";
if (asset.GroupNames !== "")
popContent += "<b>" + GetTextByKey("P_MV_GROUPS_COLON", "Groups:") + " </b>" + htmlencode(asset.GroupNames) + "<br/>";
if (asset.Description && asset.Description !== "") {
asset.Description = htmlencode(asset.Description)
if (asset.Description.indexOf("\r\n") > -1) {
var reg = new RegExp("\r\n", "g");
asset.Description = asset.Description.replace(reg, "<br/>");
}
if (asset.Description.indexOf("\n") > -1) {
var reg = new RegExp("\n", "g");
asset.Description = asset.Description.replace(reg, "<br/>");
}
popContent += "<br/><b>" + GetTextByKey("P_MV_DESCRIPTION_COLON", "Description:") + " </b><br/>" + asset.Description + "<br/>";
}
if (asset.AlertTip) {
asset.AlertTip = htmlencode(asset.AlertTip)
if (asset.AlertTip.indexOf("\r\n") > -1) {
var reg = new RegExp("\r\n", "g");
asset.AlertTip = asset.AlertTip.replace(reg, "<br/>");
}
popContent += "<br/>" + asset.AlertTip + "<br/>";
}
if (!notShowIcons) {
var div_icon = '<div style="margin-top:10px;">';
div_icon += '<span class="icondetail" style="margin-right: 10px; cursor: pointer; " onclick="showMachineDetail(\'' + cid + '\',' + asset.ID + ', \'' + encodeURIComponent(asset.VIN).replace("'", "\\'") + '\')" title="' + GetTextByKey("P_MV_DETAIL", "Detail") + '"></span>';
div_icon += '<span class="icondirection" style="margin-right: 10px;cursor: pointer;" onclick="doDirections(' + loc.Latitude + ',\'' + loc.Longitude + '\')" title="' + GetTextByKey("P_MV_DIRECTIONS", "Directions") + '"></span>';
if (loc.FromSmartWitness && enableSmartWitness)
div_icon += "<span class='iconvideo' style='margin-right: 10px;cursor:pointer;' onclick='openRequestVideoDialog(\"" + cid + "\"," + asset.ID + ")' title='" + GetTextByKey("P_MV_VIDEOREQUEST", "Video Request") + "'></span>";
div_icon += "<span class='iconmail' style='margin-right: 10px;cursor:pointer;' onclick='openSendEmails(\"" + cid + "\"," + asset.ID + ",0)' title='" + GetTextByKey("P_MV_SENDLOCATION", "Send Location") + "'></span>";
assetLocations[asset.ID] = loc;
div_icon += '<span class="iconweather" style="margin-right: 10px; cursor: pointer; " onclick="doWeather(' + loc.Latitude + ',\'' + loc.Longitude + '\')" title="' + GetTextByKey("P_MV_WEATHER", "Weather") + '"></span>';
if (canEditAsset)
div_icon += '<span class="iconasset" style="margin-right: 10px; cursor: pointer; " onclick="OnEditAsset(\'' + cid + '\',\'' + asset.ID + '\')" title="' + GetTextByKey("P_MV_EDITASSET", "Edit Asset") + '"></span>';
if (canViewWorkOrder)
div_icon += '<span class="iconmapworkorder" style="margin-right: 10px; cursor: pointer; " onclick="OnViewWorkOrder(\'' + cid + '\',\'' + asset.ID + '\')" title="' + GetTextByKey("P_MV_WORKORDERS", "Work Orders") + '"></span>';
if (canViewMR)
div_icon += '<span class="iconmaintenancerecord" style="margin-right: 10px; cursor: pointer; " onclick="OnViewMaintenanceRecord(\'' + cid + '\',\'' + asset.ID + '\')" title="' + GetTextByKey("P_MV_MAINTENANCERECORD", "Maintenance Record") + '"></span>';
div_icon += '<span class="iconlochis" style="margin-right: 10px; cursor: pointer; " onclick="doLocationHistory(\'' + cid + '\',' + asset.ID + ', \'' + encodeURIComponent(asset.DisplayName).replace("'", "\\'") + '\')" title="' + GetTextByKey("P_MA_LOCATIONHISTORY", "Location History") + '" data-asset=' + asset + '></span>';
div_icon += "</div>";
popContent += div_icon;
}
return popContent;
}

View File

@ -0,0 +1,33 @@
/***this file is used in MapView.aspx****/
var PopupViewShowing = false;
function machineDetailClick(m) {
if (m) {
showMachineDetail(m.CompanyID, m.ID, m.VIN);
clearLocationHistory();//关闭历史记录
$("#locationhistoryDiv").hide();
$("#tripDiv").hide();
if (selectedAsset)
selectedAsset.State.Highlight = false;
m.State.Highlight = true;
selectedAsset = m;
}
}
function showMachineDetail(cid, mid, vin) {
$("#divassetview").show();
$('#divtimelineview').hide();
$("#divmapview").hide();
execIframeFunc("loadAsset", [cid, mid, vin, 0], "ifassetview");
PopupViewShowing = true;
}
function closePopupView() {
$("#divassetview").hide();
$('#divtimelineview').hide();
$("#divmapview").show();
PopupViewShowing = false;
if (selectedAsset)
selectedAsset.State.Highlight = false;
}

View File

@ -0,0 +1,603 @@
define([
"dojo/_base/declare",
"dojo/_base/array",
"esri/Color",
"dojo/_base/connect",
"esri/SpatialReference",
"esri/geometry/Point",
"esri/graphic",
"esri/symbols/SimpleMarkerSymbol",
"esri/symbols/PictureMarkerSymbol",
"esri/symbols/TextSymbol",
"esri/symbols/Font",
"esri/geometry/webMercatorUtils",
"esri/dijit/PopupTemplate",
"esri/layers/GraphicsLayer"
], function (
declare, arrayUtils, Color, connect,
SpatialReference, Point, Graphic, SimpleMarkerSymbol, PictureMarkerSymbol, TextSymbol, Font, webMercatorUtils,
PopupTemplate, GraphicsLayer
) {
return declare([GraphicsLayer], {
constructor: function (options) {
// options:
// data: Object[]
// Array of objects. Required. Object are required to have properties named x, y and attributes. The x and y coordinates have to be numbers that represent a points coordinates.
// distance: Number?
// Optional. The max number of pixels between points to group points in the same cluster. Default value is 50.
// labelColor: String?
// Optional. Hex string or array of rgba values used as the color for cluster labels. Default value is #fff (white).
// labelOffset: String?
// Optional. Number of pixels to shift a cluster label vertically. Defaults to -5 to align labels with circle symbols. Does not work in IE.
// resolution: Number
// Required. Width of a pixel in map coordinates. Example of how to calculate:
// map.extent.getWidth() / map.width
// showSingles: Boolean?
// Optional. Whether or graphics should be displayed when a cluster graphic is clicked. Default is true.
// singleSymbol: MarkerSymbol?
// Marker Symbol (picture or simple). Optional. Symbol to use for graphics that represent single points. Default is a small gray SimpleMarkerSymbol.
// singleTemplate: PopupTemplate?
// PopupTemplate</a>. Optional. Popup template used to format attributes for graphics that represent single points. Default shows all attributes as "attribute = value" (not recommended).
// maxSingles: Number?
// Optional. Threshold for whether or not to show graphics for points in a cluster. Default is 1000.
// webmap: Boolean?
// Optional. Whether or not the map is from an ArcGIS.com webmap. Default is false.
// spatialReference: SpatialReference?
// Optional. Spatial reference for all graphics in the layer. This has to match the spatial reference of the map. Default is 102100. Omit this if the map uses basemaps in web mercator.
this._clusterTolerance = options.distance || 60;
this._clusterData = options.data || [];
this._clusters = [];
this._clusterLabelColor = options.labelColor || "#000";
this._clusterLabelFontSize = options.labelFontSize || "12px";
this._clusterLabelFontFamily = options.labelFontFamily || "Calibri";
this._clusterLabelFontWeight = options.labelFontWeight || Font.WEIGHT_NORMAL;
// labelOffset can be zero so handle it differently
this._clusterLabelOffset = (options.hasOwnProperty("labelOffset")) ? options.labelOffset : -5;
// graphics that represent a single point
this._singles = []; // populated when a graphic is clicked
this._showSingles = options.hasOwnProperty("showSingles") ? options.showSingles : false;
// symbol for single graphics
var SMS = SimpleMarkerSymbol;
this._singleSym = options.singleSymbol || new SMS("circle", 6, null, new Color("#888"));
this._singleTemplate = options.singleTemplate || new PopupTemplate({ "title": "", "description": "{infoContent}" });
this._maxSingles = options.maxSingles || 1000;
this._webmap = options.hasOwnProperty("webmap") ? options.webmap : false;
this._sr = options.spatialReference;// || new SpatialReference({ "wkid": 4326 });
this._zoomEnd = null;
//this._popupChanged = null;
this._getClusterResolution = null;
this._popupedClusterData = null;//当前Popup显示的点
},
// override esri/layers/GraphicsLayer methods
_setMap: function (map, surface) {
this._getClusterResolution = function (map) {
// calculate and set the initial resolution
var ext = map.extent;
ext = webMercatorUtils.webMercatorToGeographic(ext);
// update resolution
this._clusterResolution = ext.getHeight() / map.height;
};
// connect to onZoomEnd so data is re-clustered when zoom level changes
this._zoomEnd = connect.connect(map, "onZoomEnd", this, function () {
this.reloadData();
});
//this._popupChanged = connect.connect(map.infoWindow, "onSelectionChange", function () {
// var graphic = map.infoWindow.getSelectedFeature();
// //showInfoWindow(graphic);
// //map.infoWindow.selectedIndex
// //map.infoWindow.count
//});
this._getClusterResolution(map);
this.clear();
this._clusterGraphics();
// GraphicsLayer will add its own listener here
var div = this.inherited(arguments);
return div;
},
_unsetMap: function () {
this.inherited(arguments);
connect.disconnect(this._zoomEnd);
connect.disconnect(this._popupChanged);
},
reloadData: function () {
if (typeof this._getClusterResolution !== 'function') {
var _this = this;
setTimeout(function () {
_this.reloadData();
}, 200);
console.log("reloadData");
return;
}
this._getClusterResolution(this._map);
this.clear();
this._clusterGraphics();
//重新显示Popup
//this._map.infoWindow.hide();
//this.clearSingles();
if (this._popupedClusterData != null)
this.locate(this._popupedClusterData);
},
// public ClusterLayer methods
add: function (p) {
// Summary: The argument is a data point to be added to an existing cluster. If the data point falls within an existing cluster, it is added to that cluster and the cluster's label is updated. If the new point does not fall within an existing cluster, a new cluster is created.
//
// if passed a graphic, use the GraphicsLayer's add method
if (p.declaredClass) {
this.inherited(arguments);
return;
}
// add the new data to _clusterData so that it's included in clusters
// when the map level changes
this._clusterData.push(p);
var clustered = false;
// look for an existing cluster for the new point
for (var i = 0; i < this._clusters.length; i++) {
var c = this._clusters[i];
if (this._clusterTest(p, c)) {
// add the point to an existing cluster
this._clusterAddPoint(p, c);
// update the cluster's geometry
this._updateClusterGeometry(c);
// update the label
this._updateLabel(c);
clustered = true;
break;
}
}
if (!clustered) {
this._clusterCreate(p);
p.attributes.clusterCount = 1;
this._showCluster(p);
}
},
// public ClusterLayer methods
adds: function (ps) {
for (var j = 0; j < ps.length; j++) {
var p = ps[j];
// Summary: The argument is a data point to be added to an existing cluster. If the data point falls within an existing cluster, it is added to that cluster and the cluster's label is updated. If the new point does not fall within an existing cluster, a new cluster is created.
//
// if passed a graphic, use the GraphicsLayer's add method
if (p.declaredClass) {
this.inherited(arguments);
return;
}
// add the new data to _clusterData so that it's included in clusters
// when the map level changes
this._clusterData.push(p);
}
this.reloadData();
},
remove: function (p) {
if (p.declaredClass) {
this.inherited(arguments);
return;
}
// look for an existing cluster for the new point
for (var i = 0; i < this._clusterData.length; i++) {
var cd = this._clusterData[i];
if (cd.id == p.id) {
this._clusterData.splice(i, 1);
this.reloadData();
break;
}
}
},
removes: function (ps) {
for (var j = 0; j < ps.length; j++) {
var p = ps[j];
if (p.declaredClass) {
this.inherited(p);
continue;
}
// look for an existing cluster for the new point
for (var i = 0; i < this._clusterData.length; i++) {
var cd = this._clusterData[i];
if (cd.id == p.id) {
this._clusterData.splice(i, 1);
break;
}
}
}
this.reloadData();
},
removebyid: function (psid) {
var clusterdata = [];
for (var i = 0; i < this._clusterData.length; i++) {
var cd = this._clusterData[i];
if (psid.indexOf(cd.id) < 0) {
clusterdata.push(cd);
}
}
this._clusterData = clusterdata;
this.reloadData();
},
locate: function (p, center, notShowInfowindow) {
// look for an existing cluster for the new point
var _this = this;
if (!this._map) {
setTimeout(function () {
_this.locate(p, center, notShowInfowindow);
},200)
return;
}
var cp = null;
for (var i = 0; i < this._clusterData.length; i++) {
var cd = this._clusterData[i];
if (cd.id == p.id) {
cp = cd;
break;
}
}
if (cp) {
// remove any previously showing single features
this.clearSingles(this._singles);
var cg = arrayUtils.filter(this.graphics, function (g) {
return g.symbol &&
g.symbol.declaredClass == "esri.symbol.PictureMarkerSymbol" &&
g.attributes.clusterId == cp.attributes.clusterId;
});
if (cg.length == 1) {
this._popupedClusterData = null;
var singles = [];
var index = 0;
for (var i = 0, il = this._clusterData.length; i < il; i++) {
if (cg[0].attributes.clusterId == this._clusterData[i].attributes.clusterId) {
singles.push(this._clusterData[i]);
if (this._popupedClusterData == null)
this._popupedClusterData = this._clusterData[i];
if (this._clusterData[i].id == p.id) {
index = singles.length - 1;
this._popupedClusterData = this._clusterData[i];
}
}
}
var tmap = this._map;
this._addSingles(singles);
setTimeout(function () {
if (enableInfoWindow && !notShowInfowindow) {
tmap.infoWindow.show(cg[0].geometry);
tmap.infoWindow.resize(320, 340);//resize只能设置max-height
$(".contentPane").css("height", 340);
}
tmap.infoWindow.select(index);
if (center) {
var point = new Point({
longitude: p.x,
latitude: p.y
});
tmap.centerAt(point);
}
});
}
}
else {
var tmap = this._map;
setTimeout(function () {
tmap.infoWindow.hide();
});
}
},
clear: function () {
// Summary: Remove all clusters and data points.
this.inherited(arguments);
this._clusters.length = 0;
},
clearData: function () {
// Summary: Remove all clusters, data and points.
this.clear();
this._clusterData = [];
this._popupedClusterData = null;
arrayUtils.clearCache();
},
clearSingles: function (singles) {
// Summary: Remove graphics that represent individual data points.
var s = singles || this._singles;
if (this._showSingles) {
arrayUtils.forEach(s, function (g) {
this.remove(g);
}, this);
}
this._singles.length = 0;
this._map.infoWindow.clearFeatures();
},
onClick: function (e) {
// remove any previously showing single features
this.clearSingles(this._singles);
// find single graphics that make up the cluster that was clicked
// would be nice to use filter but performance tanks with large arrays in IE
this._popupedClusterData = null;
var singles = [];
for (var i = 0, il = this._clusterData.length; i < il; i++) {
if (e.graphic.attributes.clusterId == this._clusterData[i].attributes.clusterId) {
singles.push(this._clusterData[i]);
if (this._popupedClusterData == null)
this._popupedClusterData = this._clusterData[i];
}
}
//if (singles.length > this._maxSingles) {
// alert("Sorry, that cluster contains more than " + this._maxSingles + " points. Zoom in for more detail.");
// return;
//} else {
// stop the click from bubbling to the map
e.stopPropagation();
if (enableInfoWindow) {
this._map.infoWindow.show(e.graphic.geometry);
this._map.infoWindow.resize(320, 340);//resize只能设置max-height
$(".contentPane").css("height", 340);
}
this._addSingles(singles);
//}
},
// internal methods
_clusterGraphics: function () {
// first time through, loop through the points
for (var j = 0, jl = this._clusterData.length; j < jl; j++) {
// see if the current feature should be added to a cluster
var point = this._clusterData[j];
var clustered = false;
var numClusters = this._clusters.length;
for (var i = 0; i < this._clusters.length; i++) {
var c = this._clusters[i];
if (this._clusterTest(point, c)) {
this._clusterAddPoint(point, c);
clustered = true;
break;
}
}
if (!clustered) {
this._clusterCreate(point);
}
}
this._showAllClusters();
},
_clusterTest: function (p, cluster) {
var distance = (
Math.sqrt(
Math.pow((cluster.x - p.x), 2) + Math.pow((cluster.y - p.y), 2)
) / this._clusterResolution
);
return (distance <= this._clusterTolerance);
},
// points passed to clusterAddPoint should be included
// in an existing cluster
// also give the point an attribute called clusterId
// that corresponds to its cluster
_clusterAddPoint: function (p, cluster) {
// average in the new point to the cluster geometry
var count, x, y;
count = cluster.attributes.clusterCount;
x = (p.x + (cluster.x * count)) / (count + 1);
y = (p.y + (cluster.y * count)) / (count + 1);
cluster.x = x;
cluster.y = y;
// build an extent that includes all points in a cluster
// extents are for debug/testing only...not used by the layer
if (p.x < cluster.attributes.extent[0]) {
cluster.attributes.extent[0] = p.x;
} else if (p.x > cluster.attributes.extent[2]) {
cluster.attributes.extent[2] = p.x;
}
if (p.y < cluster.attributes.extent[1]) {
cluster.attributes.extent[1] = p.y;
} else if (p.y > cluster.attributes.extent[3]) {
cluster.attributes.extent[3] = p.y;
}
// increment the count
cluster.attributes.clusterCount++;
// attributes might not exist
if (!p.hasOwnProperty("attributes")) {
p.attributes = {};
}
// give the graphic a cluster id
p.attributes.clusterId = cluster.attributes.clusterId;
if (p.attributes.Priority < cluster.attributes.Priority) {
cluster.attributes.Priority = p.attributes.Priority;
cluster.attributes.EmptyIconUrl = p.attributes.EmptyIconUrl;
}
},
// point passed to clusterCreate isn't within the
// clustering distance specified for the layer so
// create a new cluster for it
_clusterCreate: function (p) {
var clusterId = this._clusters.length + 1;
// console.log("cluster create, id is: ", clusterId);
// p.attributes might be undefined
if (!p.attributes) {
p.attributes = {};
}
p.attributes.clusterId = clusterId;
// create the cluster
var cluster = {
"x": p.x,
"y": p.y,
"attributes": JSON.parse(JSON.stringify(p.attributes))
};
cluster.attributes.clusterCount = 1;
cluster.attributes.extent = [p.x, p.y, p.x, p.y];
this._clusters.push(cluster);
},
_showAllClusters: function () {
for (var i = 0, il = this._clusters.length; i < il; i++) {
var c = this._clusters[i];
this._showCluster(c);
}
},
_showCluster: function (c) {
var point = new Point(c.x, c.y, this._sr);
var iconUrl = "";
if (c.attributes.clusterCount > 1)
iconUrl = c.attributes.EmptyIconUrl;
else
iconUrl = c.attributes.IconUrl;
var picSym = new PictureMarkerSymbol(iconUrl, 40, 65);//url,width,height
picSym.setOffset(0, 29);
this.add(
new Graphic(
point,
picSym,
c.attributes
)
);
// code below is used to not label clusters with a single point
if (c.attributes.clusterCount == 1) {
return;
}
// show number of points in the cluster
var label = new TextSymbol(c.attributes.clusterCount.toString())
.setColor(new Color(this._clusterLabelColor))
.setOffset(0, this._clusterLabelOffset);
var font = new Font();
font.setSize(this._clusterLabelFontSize);
font.setFamily(this._clusterLabelFontFamily);
font.setWeight(this._clusterLabelFontWeight);
label.setFont(font);
this.add(
new Graphic(
point,
label,
c.attributes
)
);
},
_addSingles: function (singles) {
// add single graphics to the map
arrayUtils.forEach(singles, function (p) {
var g = new Graphic(
new Point(p.x, p.y, this._sr),
this._singleSym,
p.attributes,
this._singleTemplate
);
this._singles.push(g);
if (this._showSingles) {
this.add(g);
}
}, this);
this._map.infoWindow.setFeatures(this._singles);
},
_updateClusterGeometry: function (c) {
// find the cluster graphic
var cg = arrayUtils.filter(this.graphics, function (g) {
return g.symbol &&
g.symbol.declaredClass == "esri.symbol.PictureMarkerSymbol" &&
g.attributes.clusterId == c.attributes.clusterId;
});
if (cg.length == 1) {
// console.log("update label...found: ", label);
this.remove(cg[0]);
}
var picSym = new PictureMarkerSymbol(c.attributes.EmptyIconUrl, 40, 65);//url,width,height
picSym.setOffset(0, 29);
this.add(
new Graphic(
new Point(c.x, c.y, this._sr),
picSym,
c.attributes
)
);
//if (cg.length == 1) {
// cg[0].geometry.update(c.x, c.y);
//} else {
// console.log("didn't find exactly one cluster geometry to update: ", cg);
//}
},
_updateLabel: function (c) {
// find the existing label
var label = arrayUtils.filter(this.graphics, function (g) {
return g.symbol &&
g.symbol.declaredClass == "esri.symbol.TextSymbol" &&
g.attributes.clusterId == c.attributes.clusterId;
});
if (label.length == 1) {
// console.log("update label...found: ", label);
this.remove(label[0]);
}
var newLabel = new TextSymbol(c.attributes.clusterCount)
.setColor(new Color(this._clusterLabelColor))
.setOffset(0, this._clusterLabelOffset);
var font = new Font();
font.setSize(this._clusterLabelFontSize);
font.setFamily(this._clusterLabelFontFamily);
font.setWeight(this._clusterLabelFontWeight);
newLabel.setFont(font);
this.add(
new Graphic(
new Point(c.x, c.y, this._sr),
newLabel,
c.attributes
)
);
// console.log("updated the label");
//else {
// console.log("didn't find exactly one label: ", label);
//}
},
// debug only...never called by the layer
_clusterMeta: function () {
// print total number of features
console.log("Total: ", this._clusterData.length);
// add up counts and print it
var count = 0;
arrayUtils.forEach(this._clusters, function (c) {
count += c.attributes.clusterCount;
});
console.log("In clusters: ", count);
}
});
});

412
Site/js/mapview/jobsite.js Normal file
View File

@ -0,0 +1,412 @@

var unshownJobSiteID = [];//不需要显示的JobSiteID
/******************************JobsiteObject******************************/
/******************************JobSite信息获取及显示******************************/
if (typeof (JobsiteObject) != "function") {
JobsiteObject = function (mapHelper) {
var allJobsites;
var REDUN = 2;
var MIN_LENGTH = 40;
var trunc = function (val) {
return (val > 0 ? Math.floor : Math.ceil)(val);
};
this.getUnShownMachines = function () {
return unshownMachineID;
}
this.setUnShownMachines = function (machines) {
//if (machines)
// unshownMachineID = JSON.parse(JSON.stringify(machines));
//else
// unshownMachineID = [];
}
this.getUnShownJobsites = function () {
return unshownJobSiteID;
}
this.setUnShownJobsites = function (jobsites) {
unshownJobSiteID = [];
if (jobsites) {
for (var i in jobsites) {
unshownJobSiteID.push(eval(jobsites[i]));//jobsite id 为数值类型
}
}
}
var ROW_JOBSITE_HEIGHT = 26;
var jobsiteData = [];
var jobsiteMachines = [];
var jsvm = new Vue({
el: '#jobsiteList',
data: {
startIndex: 0,
bodyContentStyle: { top: null },
bodyContainerHeight: 0,
bodyContainerStyle: { height: null },
scrollTop: 0
},
computed: {
bodyClientRowCount: function () {
var height = document.getElementById('contentCtrl').clientHeight;
return trunc((height - 1) / ROW_JOBSITE_HEIGHT) + 1;
},
innerJobsiteMachines: function () {
var start = this.startIndex;
if (start < 0) {
start = 0;
}
if (jobsiteMachines == null || jobsiteMachines.length < MIN_LENGTH) {
return jobsiteMachines.slice();
}
var end = this.bodyClientRowCount + start + (REDUN * 2) + 1;
if (end > jobsiteMachines.length) {
end = jobsiteMachines.length;
}
return jobsiteMachines.slice(start, end);
}
},
methods: {
fillMachines: function () {
var g = [];
var allindeterminate = false;
var jsselcount = 0;
for (var i = 0; i < jobsiteData.length; i++) {
var o = jobsiteData[i];
o.__isJobsite = true;
o.__indeterminate = false;
g.push(o);
var selcount = 0;
if (o.Machines && o.Machines.length > 0) {
for (var j = 0; j < o.Machines.length; j++) {
var om = o.Machines[j];
if (om.State.Selected) selcount++;
if (!o.Collapsed)
g.push(o.Machines[j]);
}
if (selcount == 0) {
o.Selected = false;
o.__indeterminate = false;
}
else if (selcount == o.Machines.length) {
o.Selected = true;
o.__indeterminate = false;
}
else {
o.__indeterminate = true;
allindeterminate = true;
}
}
else
o.__indeterminate = false;
if (o.Selected) jsselcount++;
}
jobsiteMachines = g;
var chkSelectAll = document.getElementById("chkSelectAll");
chkSelectAll.indeterminate = allindeterminate;
if (jsselcount == 0) {
chkSelectAll.checked = false;
}
else if (jsselcount == jobsiteData.length) {
chkSelectAll.checked = true;
}
else {
chkSelectAll.indeterminate = true;
}
var height = g.length * ROW_JOBSITE_HEIGHT;
this.bodyContainerHeight = height;
this.bodyContainerStyle.height = height && (height + 'px');
var index = this.startIndex;
this.startIndex = -1;
this.startIndex = index;
this.$nextTick(function () {
var content = document.getElementById('contentCtrl');
if (this.bodyContainerHeight + 26 <= content.clientHeight) {
this.bodyContentStyle.top = 0;
this.startIndex = 0;
}
});
},
reload: function (data) {
jobsiteData = data;
this.fillMachines();
},
refresh: function () {
var index = this.startIndex;
this.startIndex = -1;
this.startIndex = index;
},
treeIconClick: function (e, js) {
if (js) {
var t = $(e.target);
if (t.hasClass("treeiconc"))
t.removeClass("treeiconc").addClass("treeicone");
else
t.removeClass("treeicone").addClass("treeiconc");
js.Collapsed = !js.Collapsed;
this.fillMachines();
}
else
treeIconClick(e);
},
chkJobsiteClick: function (e, js) {
chkJobsiteClick(js);
this.fillMachines();
},
linkJobSiteClick: function (e, js) {
if (!js.Selected) {
js.Selected = true;
chkJobsiteClick(js);
this.fillMachines();
}
if (js.Shown)
mapHelper.locateJobSite(js);
else {
js.Shown = true;
showJobsiteClick(e, js);
mapHelper.locateJobSite(js);
}
},
showJobsiteClick: function (e, js) {
js.Shown = !js.Shown;
showJobsiteClick(e, js);
},
chkMachineClick: function (m) {
chkMachineClick(m);
},
linkMachineClick: function (m) {
linkMachineClick(m);
this.refresh();
},
locationHistoryClick: function (m, ev) {
if (selectedAsset)
selectedAsset.State.Highlight = false;
m.State.Highlight = true;
selectedAsset = m;
var e = { data: m };
locationHistoryClick(e);
}
}
});
this.refreshJobsiteList = function () {
jsvm.refresh();
}
this.selectAllJobsites = function (checked) {
if (jobsiteData) {
for (var i = 0; i < jobsiteData.length; i++) {
var js = jobsiteData[i];
if (js.Selected != checked) {
js.Selected = checked;
chkJobsiteClick(js);
}
}
jsvm.fillMachines();
}
}
this.onscrollJobsiteMachines = function (e) {
if (jobsiteMachines == null || jobsiteMachines.length < MIN_LENGTH) {
return;
}
var top = e == null ? 0 : e.target.scrollTop;
top -= (top % ROW_JOBSITE_HEIGHT) + (REDUN * ROW_JOBSITE_HEIGHT);
if (top < 0) {
top = 0;
} else {
var bottomTop = jsvm.bodyContainerHeight - ((jsvm.bodyClientRowCount + (REDUN * 2) + 1) * ROW_JOBSITE_HEIGHT);
if (top > bottomTop) {
top = bottomTop;
}
}
if (jsvm.scrollTop !== top) {
jsvm.scrollTop = top;
jsvm.startIndex = top / ROW_JOBSITE_HEIGHT;
jsvm.bodyContentStyle.top = top && (top + 'px');
}
};
function chkJobsiteClick(js) {
var checked = js.Selected;
if (js && js.Machines) {
var ams = [];
var rms = [];
var rids = [];
for (var i in js.Machines) {
var machine = js.Machines[i];
if (machine.State.Selected != checked) {
machine.State.Selected = checked;
if (checked) {
ams.push(machine);
//unshownMachineID.splice(unshownMachineID.indexOf(machine.ID), 1);
rids.push(machine.ID);
}
else {
rms.push(machine);
unshownMachineID[unshownMachineID.length] = machine.ID;
}
}
}
if (rids.length > 0) {
var unshownids = [];
for (var i = 0; i < unshownMachineID.length; i++) {
var id = unshownMachineID[i];
if (rids.indexOf(id) < 0)
unshownids.push(id);
}
unshownMachineID = unshownids;
}
if (ams.length > 0)
mapHelper.showMachines(ams);
if (rms.length > 0)
mapHelper.removeMachines(rms);
displayFilerIcon();
}
}
this.searchJobSite = function (isauto) {
this.getJobSites(isauto);
}
this.getJobSites = function (isauto) {
var item = {
'IsAutoRefresh': isauto,
'ContractorID': companyids,
'SearchText': "",//htmlencode($("#txtJobSiteSearchText").val()), //在前端过滤,后端不再过滤
'Onroad': $("#selOnroad").val(),
};
_network.mapviewquery("GetJobSites", JSON.stringify(item), function (data) {
if (data != "-1") {
showJobSite(data);
}
else {
showJobSiteAlert();
}
}, function () {
showJobSiteAlert();
});
}
function showJobSiteAlert() {
if (jobSiteAlert) {
_dialog.close(jobSiteAlert);
jobSiteAlert = null;
}
jobSiteAlert = _dialog.showAlert(GetTextByKey("P_MV_UNABLETOOBTAINJOBSITEDATAATTEMPTINGTORECONNECT", 'Unable to obtain jobsite data. Attempting to reconnect...'), GetTextByKey("P_MV_REFRESHJOBSITEDATA", 'Refresh jobsite data'));
}
function showJobSite(jobsites) {
mapHelper.removeJobsites(allJobsites);
var shownJobsites = [];
for (var i = jobsites.length - 1; i >= 0; i--) {
var js = jobsites[i];
js.Collapsed = true;
js.Selected = true;
js.Shown = true;
if (allJobsites) {//get josbite state
for (var j = 0; j < allJobsites.length; j++) {
var ljs = allJobsites[j];
if (js.ID === ljs.ID) {
js.Collapsed = ljs.Collapsed;
js.Selected = ljs.Selected;
js.Shown = ljs.Shown;
break;
}
}
}
var filter = $.trim($("#txtJobSiteSearchText").val());
js.Matched = true;
if (filter != "" && js.Name.toLowerCase().indexOf(filter.toLocaleLowerCase()) < 0)
js.Matched = false;
var assets = [];
if (jobsiteAssets[js.ID]) {
var tempAssets = jobsiteAssets[js.ID];
for (var j = 0; j < tempAssets.length; j++) {//Assets
var a = tempAssets[j];
if (js.Matched || isAssetMatch(a, filter)) {
assets.push(a);
}
}
}
js.Machines = assets;
if (!js.Matched && js.Machines.length == 0) {
jobsites.splice(i, 1);
}
else if (js.Shown) { //需要显示的JobSite
mapHelper.showJobSite(js);
shownJobsites.push(js);
}
}
mapHelper.refreshJobsiteTooltip(shownJobsites);
allJobsites = jobsites;
jsvm.reload(allJobsites);
return;
}
function showJobsiteClick(e, js) {
var t = $(e.target);
if (!t.is("span"))
t = t.prev();
if (js.Shown) {
t.removeClass("switchoff").addClass("switchon");
mapHelper.showJobSite(js);
unshownJobSiteID.splice(unshownJobSiteID.indexOf(js.ID), 1);
}
else {
t.removeClass("switchon").addClass("switchoff");
mapHelper.removeJobSite(js, true);
unshownJobSiteID[unshownJobSiteID.length] = js.ID;
}
displayFilerIcon();
}
function chkMachineClick(machine) {
if (machine) {
if (machine.State.Selected) {
mapHelper.showMachine(machine);
unshownMachineID.splice(unshownMachineID.indexOf(machine.ID), 1);
}
else {
mapHelper.removeMachine(machine);
unshownMachineID[unshownMachineID.length] = machine.ID;
}
jsvm.reload(allJobsites);
displayFilerIcon();
}
}
function linkMachineClick(machine) {
if (machine) {
if (machine.State.Selected) {
mapHelper.locateMachine(machine);
}
else {
machine.State.Selected = true;
unshownMachineID.splice(unshownMachineID.indexOf(machine.ID), 1);
mapHelper.showMachine(machine);
mapHelper.locateMachine(machine);
}
displayFilerIcon();
}
}
}
};

View File

@ -0,0 +1,436 @@
var ALL_TEXT = "(All)";
var ALL_VALUE = "@all";
$(function () {
// global event
$(document).mousedown(function (e) {
var t = $(e.target);
if (!t.hasClass("div_filter"))
t = t.parents(".div_filter");
if (t.length == 0) $('.div_panel').hide();
var divpanel = t.find(".div_panel");
$('.div_panel').each(function () {
if (!$(this).is(divpanel))
divpanel.hide();
});
});
}());
function showMapAlertLayer(data) {
var opt = $('<option></option>').val("").text("(None)");
var sel = $("#selMapAlertLayer");
sel.empty();
sel.append(opt);
for (var i = 0; i < data.length; i++) {
var mal = data[i];
opt = $('<option></option>').val(mal.ID).text(mal.Name).data("mal", mal);
sel.append(opt);
}
if (userParams && userParams.MapAlertLayer) {
sel.val(userParams.MapAlertLayer);
}
showMapAlertLayerDetail();
}
function showMapAlertLayerDetail() {
var mal = $("#selMapAlertLayer").find("option:selected").data("mal");
var tb = $("#tbLegend");
tb.empty();
var haspramameter = false;
if (mal && mal.Layers) {
for (var i = 0; i < mal.Layers.length; i++) {
var layer = mal.Layers[i];
if ((layer.Pivots && layer.Pivots.length > 0))
haspramameter = true;
var tr = $("<tr style='border-bottom: 1px solid lightgray;'></tr>");
tb.append(tr);
var td = $("<td></td>").css("width", 30);
td.append($("<img></img>").attr("src", layer.LegendUrl).css({ "width": 18, "vertical-align": "middle" }));
tr.append(td);
td = $("<td></td>").html(layer.Title).css({ "padding-left": 10, "width": 220 });
tr.append(td);
}
}
var staticlegend = ["InMotion", "StoppedOn", "StoppedOff", "CGain", "CLoss", "RoadClosure", "LaneClosure"];
var staticlegendtitle = ["In Motion", "Stopped On", "Stopped Off", "Connectivity Recovery", "Connectivity Loss", "Road Closure", "Lane Closure"];
for (var i = 0; i < staticlegend.length; i++) {
var tr = $("<tr style='border-bottom: 1px solid lightgray;'></tr>");
tb.append(tr);
var url = userParams.MachineIconURL + "?legend=" + staticlegend[i];
var td = $("<td></td>").css("width", 30);
td.append($("<img></img>").attr("src", url).css({ "width": 18, "vertical-align": "middle" }));
tr.append(td);
td = $("<td></td>").html(staticlegendtitle[i]).css({ "padding-left": 10, "width": 220 });
tr.append(td);
}
var harshdrivinglegend = ["#ff3f48cc", "#ff00a8f3", "#fffff200", "#ffff7f27", "#ffec1c24"];
var harshdrivingtitle = ["Hard Acceleration", "Hard Brake", "Hard Turn", "Speeding: Low Severity", "Speeding: High Severity"];
for (var i = 0; i < harshdrivinglegend.length; i++) {
var tr = $("<tr style='border-bottom: 1px solid lightgray;'></tr>");
tb.append(tr);
var ironurl = userParams.MachineIconURL.toLowerCase().replace("machinetypeicon.ashx", "machinemovingicon.ashx");
var url = ironurl + "?tp=0&bkcolor=" + encodeURIComponent(harshdrivinglegend[i]) + "&heading=45";
var td = $("<td></td>").css("width", 30);
td.append($("<img></img>").attr("src", url).css({ "width": 18, "vertical-align": "middle" }));
tr.append(td);
td = $("<td></td>").html(harshdrivingtitle[i]).css({ "padding-left": 10, "width": 220 });
tr.append(td);
}
if (haspramameter) {
$('#setparameter').css('display', '');
}
else {
$('#setparameter').css('display', 'none');
}
var right = $('#mapAlertLayerDiv').width() + 100;
$('#filterIconDiv').css('right', right);
}
function setParameterDatimeTimePicker(ipt) {
ipt.datetimepicker({
timepicker: false,
format: 'm/d/Y',
enterLikeTab: false,
onSelectDate: function (v, inp) {
var date = new DateFormatter().formatDate(v, 'm/d/Y 00:00:00');
inp.parent().data('val', [date]);
}
});
}
function getAlertLayerParameters() {
if (parameterinput.length > 0) {//更新参数选择的值
for (var l = 0; l < parameterinput.length; l++) {
var ipt = parameterinput[l];
var param = ipt.data("parameter");
if (ipt.data('commoninput'))
param.ParameterValue = ipt.val();
}
}
var mal = $("#selMapAlertLayer").find("option:selected").data("mal");
if (mal)
return mal.Layers;
return null;
}
var parameterinput = [];
var paramindex = -1;
function setAlertLayerParameters() {
parameterinput = [];
paramindex = -1;
var ul = $("#ul_parameter");
ul.empty();
var pdiv = $("#parameter_right");
pdiv.empty();
var mal = $("#selMapAlertLayer").find("option:selected").data("mal");
var layerHasParam = 0;
if (mal && mal.Layers) {
for (var i = 0; i < mal.Layers.length; i++) {
var layer = mal.Layers[i];
if (layer && layer.Pivots) {
var li = $("<li class='nav_item'></li>").data("layerid", layer.ID).click(layerHasParam++, layerclick);
var img = $("<img></img>").attr("src", layer.LegendUrl).css({ "width": 18, "vertical-align": "middle" });
var span = $("<span></span>").text(layer.Title).css({ "margin-left": 10, "vertical-align": "middle" });
li.append(img).append(span);
ul.append(li);
var tb = $("<table class='tb_parameter'></table>").data("layerid", layer.ID);
if (layerHasParam == 1)
li.addClass("selected");
else
tb.css('display', 'none');
pdiv.append(tb);
//if (criteriaparam && criteriaparam.length > 0)
// createParameters(criteriaparam, tb, 1);
//if (alertparam && alertparam.length > 0)
// createParameters(alertparam, tb, 2);
if (layer.Pivots && layer.Pivots.length > 0)
createParameters(layer.Pivots, tb);
}
}
}
}
function createParameters(params, tb) {
var criteriaTitle = false;
var alertTitle = false;
for (var j = 0; j < params.length; j++) {
var param = params[j];
if (param.IsCriteriaSQL && !criteriaTitle) {
var tr = $("<tr></tr>").append("<td colspan='2' style='padding-left:10px;font-weight:bold;font-size:16px;'>" + GetTextByKey("P_MV_CRITERIA", "Criteria") + "</td>");
tb.append(tr);
criteriaTitle = true;
}
if (!param.IsCriteriaSQL && !alertTitle) {
var tr = $("<tr></tr>").append("<td colspan='2' style='padding-left:10px;font-weight:bold;font-size:16px;'>" + GetTextByKey("P_MV_ALERT", "Alert") + "</td>");
tb.append(tr);
alertTitle = true;
}
var tr_param = $("<tr></tr>");
tb.append(tr_param);
tr_param.append($("<td></td>").addClass('td_paramtype').html(param.Caption));
var td = $("<td></td>");
var ipt = createParameterInput(param);
parameterinput.push(ipt);
if (param.DataType == 3 && param.DisplayStyle != 1 && param.DisplayStyle != 2) {
setParameterDatimeTimePicker(ipt);
}
td.append(ipt);
tr_param.append(td);
}
}
function FALSE() { return false; }
var idindex = 0;
function createParameterInput(param) {
var paramvalue = getParameterValue(param.ID, param.IsCriteriaSQL);
if (paramvalue == null)
paramvalue = param.DefaultValue;
if (param.DisplayStyle == 0) {//inputbox
return $("<input type='text' />").val(paramvalue).data("parameter", param).data('commoninput', true)
.attr("paramcaption", param.Name.toLowerCase())
.keyup(function () {
$("[paramcaption='" + param.Name.toLowerCase() + "']").val($(this).val());
}).change(function () {
$("[paramcaption='" + param.Name.toLowerCase() + "']").val($(this).val());
});
}
else if (param.DisplayStyle == 1 || param.DisplayStyle == 2) {//Dropdown or Combobox
var defaultcheckall = false;
if (param.IsAllAllowed && paramvalue === ALL_VALUE)
defaultcheckall = true;
if (param.IsField && param.MutipleSelect) {//多选
var divcontrol = $('<div class="div_filter"></div>').data("parameter", param);
var seldiv = $('<div class="left dropdown"></div>');
var span = $('<span class="text_span"></span>');
var spanimg = $('<span class="fa dropdown_button">&#xf078;</span>');
var divpanel = $('<div class="div_panel" style="display: none;z-index:10;margin-left:-1px;position:fixed;"></div>');
var ul = $('<ul></ul>');
divpanel.append(ul).mousedown(FALSE);
seldiv.append(span).append(spanimg).append(divpanel);
seldiv.mousedown(function (e) {
$('.div_panel').each(function () {
var t = $(this);
if (!t.is(divpanel))
t.css('display', 'none');
});
var display = divpanel.css('display');
if (display == 'none') {
var t = $(e.target);
divpanel.css('top', seldiv.offset().top + seldiv.height());
if (seldiv.offset().top + seldiv.height() + divpanel.height() > $(document).height())
divpanel.css({ 'bottom': 0 });
else
divpanel.css({ 'bottom': 'unset' });
divpanel.css({ 'display': 'block' });
} else {
divpanel.css('display', 'none');
}
return false;
});
var itemclick = function (isall, checked) {
var chks = ul.find('input');
if (isall) {
chks.prop('checked', checked);
if (checked) {
span.attr('title', ALL_TEXT).text(ALL_TEXT);
param.ParameterValue = ALL_VALUE;
}
else {
span.attr('title', "").text("");
param.ParameterValue = "";
}
return;
}
else {
if (chkall)
chkall.prop('checked', false);//(ALL)取消选中
}
var texts = [];
var paramvalues = [];
for (var i = 0; i < chks.length; i++) {
var c = $(chks[i]);
if (c.prop('checked')) {
var text = c.next('label').text();
if (!text) text = c.val();
texts.push(text);
paramvalues.push(c.val());
}
}
texts = texts.join(', ');
span.attr('title', texts).text(texts);
paramvalues = paramvalues.join('^');
param.ParameterValue = paramvalues;
};
var chkall = undefined;
if (param.IsAllAllowed) {
var liall = $('<li></li>');
chkall = $('<input type="checkbox" id="chkall' + (++idindex) + '" style="width:16px;"/>');
if (defaultcheckall)
chkall.attr('checked', true);
chkall.change(function () {//全选
itemclick(true, $(this).prop('checked'));
});
liall.append(chkall);
liall.append($('<label for="chkall' + idindex + '"></label>').text(ALL_TEXT));
ul.append(liall);
}
var ds = getLookupDatasource(param.LookupDatasourceID)
if (ds && ds.Items) {
var paramvalueAry = paramvalue.split("^");
var texts = [];
for (var s = 0; s < ds.Items.length; s++) {
var item = ds.Items[s];
var txt = param.DisplayCaptionField ? item.Value : item.Key;
var li = $('<li></li>');
var chk = $('<input type="checkbox" style="width:16px;"/>').val(item.Key).attr("id", "chkp" + ++paramindex);
chk.change(function () {
itemclick(false, $(this).prop('checked'));
});
li.append(chk);
li.append($('<label for=' + ("chkp" + paramindex) + '></label>').text(txt));
ul.append(li);
if (defaultcheckall || paramvalueAry.indexOf(item.Key) > -1) {//选中默认值
chk.attr('checked', true);
var text = chk.next('label').text();
if (!text) text = chk.val();
texts.push(text);
}
}
if (defaultcheckall)
texts = ALL_TEXT;
else
texts = texts.join(', ');
span.attr('title', texts).text(texts);
param.ParameterValue = paramvalue;
}
divcontrol.append(seldiv);
return divcontrol;
}
else {
var sel = $("<select></select>").data("parameter", param).data('commoninput', true)
.attr("paramcaption", param.Name.toLowerCase())
.change(function () {
$("[paramcaption='" + param.Name.toLowerCase() + "']").val($(this).val());
});
var ds = getLookupDatasource(param.LookupDatasourceID)
if (ds && ds.Items) {
if (param.IsField && param.IsAllAllowed) {
var opall = $("<option></option>").val(ALL_VALUE).text(ALL_TEXT);
sel.append(opall);
}
for (var s = 0; s < ds.Items.length; s++) {
var item = ds.Items[s];
var opt = $("<option></option>").val(item.Key);
var txt = param.DisplayCaptionField ? item.Value : item.Key;
opt.text(txt);
sel.append(opt);
}
sel.val(paramvalue);
}
return sel;
}
}
}
function getLookupDatasource(dsid) {
var mal = $("#selMapAlertLayer").find("option:selected").data("mal");
if (mal && mal.LookupDataSources) {
for (var i = 0; i < mal.LookupDataSources.length; i++) {
var ds = mal.LookupDataSources[i];
if (ds.ID.toLowerCase() == dsid.toLowerCase())
return ds;
}
}
return null;
}
function layerclick(e) {
$('#ul_parameter li').removeClass("selected");
$(this).addClass("selected");
var index = e.data;
var tbs = $('.tb_parameter');
tbs.hide();
$(tbs[index]).show();
}
function getParameterValue(paramid, isCriteria) {
if (parametervalues && parametervalues.length > 0) {
for (var i = 0; i < parametervalues.length; i++) {
var layer = parametervalues[i];
var params = [];
for (var j = 0; j < layer.Pivots.length; j++) {
if (layer.Pivots[j].IsCriteriaSQL == isCriteria)
params.push(layer.Pivots[j])
}
if (layer && (params || params)) {
for (var k = 0; k < params.length; k++) {
var param = params[k];
if (param.ID == paramid)
return param.ParameterValue;
}
}
}
}
return null;
}
function openSetAlertLayerParameters() {
setAlertLayerParameters();
$('#mask_bg').show();
$('#dialog_parameter .dialog-title span.title').text(GetTextByKey("P_MV_PIVOTS", 'Pivots'));
//$('#mask_bg').show();
$('#dialog_parameter')
.attr('act', 'edit')
.css({
'width': 570,
'top': (document.documentElement.clientHeight - $('#dialog_parameter').height()) / 2,
'left': (document.documentElement.clientWidth - $('#dialog_parameter').width()) / 2
})
.showDialogfixed();
pivotsDialogOpend = true;
}
var parametervalues;
function setParameterCompleted() {
parametervalues = getAlertLayerParameters();
assetObject.searchMachine(false);
$('#dialog_parameter').hideDialog();
$('#mask_bg').hide();
pivotsDialogOpend = false;
}

1589
Site/js/mapview/maphelper.js Normal file

File diff suppressed because it is too large Load Diff

252
Site/js/mapview/mapmenu.js Normal file
View File

@ -0,0 +1,252 @@

var allItemUrls = [];
function initMapMenuItems(data) {
if (data) {
var ul = $('#mapmenu ul').empty();
var wspItemAdded = false;
var items = {};
var wspitems = {};
var hasMemuItems = false;
//mids用于菜单排序
var mids = ['100', '150', '200', '250', '300', '350', '400', '450', '500', '550', '600', '650', '675', '700', '9999'];
//675为从150分离出来的Dispatch & Scheduling,9999 为Dashboard
for (var k = 0; k < mids.length; k++) {
var mid = mids[k];
for (var i = 0; i < data.length; i++) {
var m = data[i];
if (!m.Visible || m.ID == "100") continue;
if (m.ID == mid || (mid == '675' && m.ID == "150") || (mid == '9999' && m.ModuleType == 1)) {
hasMemuItems = true;
if (m.ModuleType == 0) {
var item = {};
item.name = m.CurrentName;
item.icon = createicon;
allItemUrls['m' + mid] = m.Url;
if (mid == '675') {
item.name = GetTextByKey("P_JS_ASSETSCHEDULINGANDDISPATCHING", "Asset Scheduling and Dispatching");
allItemUrls['m' + mid] = "JobSite/img/dispatch.png";
}
var subcount = 0;
if (m.SubItems && m.SubItems.length > 0) {
var sitems = {}
if (mid == "150" && canEditJobsite) {
var addjs = {
FeatureID: 150,
ID: "nav_addjobsite",
IconPath: "img/jobsite.png",
PageUrl: "AddJobSite.aspx",
Title: "Add JobSite",
Url: "JobSite/AddJobSite.aspx"
};
m.SubItems.push(addjs);
}
for (var j = 0; j < m.SubItems.length; j++) {
var sm = m.SubItems[j];
if (mid == "150" && sm.FeatureID != 100 && sm.FeatureID != 150)//13178-不显示Jobsite Requirements, dispatch requirements and scheduler
continue;
if (mid == "675" && (sm.FeatureID == 100 || sm.FeatureID == 150))//13178-Dispatch & Scheduling单独显示
continue;
var sitem = {}
sitem.name = getitemname(sm.ID, sm.Title);
sitem.icon = function () { return 'context-menu-icon menuicon' };
sitems['sm' + sm.ID] = sitem;
subcount++;
allItemUrls['sm' + sm.ID] = sm.Url;
}
item.items = sitems;
}
if ((mid != "150" && mid != "675") || subcount > 0)
items['m' + mid] = item;
}
else if (m.ModuleType == 1) {
if (!wspItemAdded) {
items['sep1'] = "---------";
var item = {};
item.name = "Dashboards";
item.icon = createicon;
item.items = wspitems;
items['wsp'] = item;
wspItemAdded = true;
}
var wspitem = {}
wspitem.name = m.Name;
wspitem.icon = createicon;
wspitems['w' + m.ID] = wspitem;
allItemUrls['w' + m.ID] = m.Url;
}
}
else
continue;
}
}
if (hasMemuItems) {
$.contextMenu({
selector: '#mapView',
callback: function (key, options, e) {
var url = allItemUrls[key];
if (!url) return;
if (url.length > 4 && url.substring(0, 4) == 'http') {
} else if (url.length > 0 && url[0] == '/') {
} else {
url = _network.root + url;
}
if (key.indexOf('nav_addjobsite') >= 0) {
OnAddJobsite();
}
else
window.open(url, "_blank");
},
items: items
});
}
$(".context-menu-item .context-menu-list").css({
"max-height": $(document).height() - 150,
'overflow-x': 'hidden',
'overflow-y': 'auto',
});
$(window).resize(function () {
$(".context-menu-item .context-menu-list").css("max-height", $(window).height() - 150);
});
}
}
function createicon($element, item, key) {
var cls = 'context-menu-icon menuicon';
var id = key.substr(1);
if (id == "100")
cls += ' menuiconmap';
else if (id == "150")
cls += ' menuiconjobsite';
else if (id == "200")
cls += ' menuiconpmalerts';
else if (id == "250")
cls += ' menuiconfilterq';
else if (id == "300")
cls += ' menuiconcredentials';
else if (id == "350")
cls += ' menuiconpmsecurity';
else if (id == "400")
cls += ' menuiconassets';
else if (id == "450")
cls += ' menuiconfic';
else if (id == "500")
cls += ' menuiconm3';
else if (id == "550")
cls += ' menuiconjobsitelimit';
else if (id == "600")
cls += ' menuiconotrconfig';
else if (id == "650")
cls += ' menuiconinspection';
else if (id == "675")
cls += ' menuicondispatch';
else if (id == "700")
cls += ' menuiconteam';
else {
if (id === "sp")
cls += ' menuicondashboard';
else
cls += ' menuiconwsp';
}
return cls;
}
function getitemname(id, name) {
//Jobsite
if (id === "nav_jobsiterequirements") {
name = GetTextByKey("P_JS_JOBSITEREQUIREMENTS", name);
}
else if (id === "nav_dispatchrequests") {
name = GetTextByKey("P_JS_DISPATCHREQUESTS", name);
}
else if (id === "nav_jobsitemanage") {
name = GetTextByKey("P_JOBSITES", name);
}
else if (id === "nav_scheduler") {
name = GetTextByKey("P_JS_SCHEDULER", name);
}
//Asset Health
else if (id === "nav_alertsmanagement") {
name = GetTextByKey("P_ALERTSMANAGEMENTNEW", name);
}
else if (id === "nav_workorder") {
name = GetTextByKey("P_WORKORDERNEW", name);
}
else if (id === "nav_workorderhis") {
name = GetTextByKey("P_WORKORDERHISTORY", name);
}
else if (id === "nav_record") {
name = GetTextByKey("P_MAINTENANCERECORDLEGACY", name);
}
else if (id === "nav_fuelrecord") {
name = GetTextByKey("P_FUELRECORDS", name);
}
else if (id === "nav_maintenanceschedule") {
name = GetTextByKey("P_PM_MAINTENANCESCHEDULES", name);
}
else if (id === "nav_scheduler") {
name = GetTextByKey("P_JS_SCHEDULER", name);
}
//Credentials
else if (id === "nav_credential") {
name = GetTextByKey("P_CREDENTIALS", name);
}
else if (id === "nav_jdlink") {
name = GetTextByKey("P_JOHNDEERE", name);
}
else if (id === "nav_jdnotification") {
name = GetTextByKey("P_JOHNDEERENOTIFICATIONS", name);
}
else if (id === "nav_apicredential") {
name = GetTextByKey("P_APICREDENTIALS", name);
}
//Security
else if (id === "nav_users") {
name = GetTextByKey("P_USERS", name);
}
else if (id === "nav_user_group") {
name = GetTextByKey("P_USERSGROUP", name);
}
else if (id === "nav_dts") {
name = GetTextByKey("P_DATATABLEPERMISSION", name);
}
else if (id === "nav_filters") {
name = GetTextByKey("P_DASHBOARDFILTERS", name);
}
else if (id === "nav_curfew") {
name = GetTextByKey("P_CURFEWCONFIGURATION", name);
}
else if (id === "nav_curfewmt") {
name = GetTextByKey("P_CURFEWMOVEMENTTOLERANCE", name);
}
else if (id === "nav_usertocontractor") {
name = GetTextByKey("P_USERTOCONTRACTOR", name);
}
//Manage Asset
else if (id === "nav_managmachines") {
name = GetTextByKey("P_MANAGEASSETS", name);
}
else if (id === "nav_managrentals") {
name = GetTextByKey("P_MANAGERENTALS", name);
}
else if (id === "nav_machinegroups") {
name = GetTextByKey("P_ASSETGROUPS", name);
}
else if (id === "nav_managegpsdevices") {
name = GetTextByKey("P_MANAGEDEVICES", name);
}
else if (id === "nav_managmodels") {
name = GetTextByKey("P_MANAGEMODELS", name);
}
else if (id === "nav_customerrecord") {
name = GetTextByKey("P_CUSTOMERRECORD", name);
}
else if (id === "nav_addjobsite") {
name = GetTextByKey("P_JS_ADDJOBSITE", name);
}
return name;
}

640
Site/js/mapview/mapview.js Normal file
View File

@ -0,0 +1,640 @@

/******************************全局代码******************************/
var currentLocationHistoryMachine;
var LocationHistoryInfo;
var allJobSiteMachine = [];//全部已显示机器的数据字典Key为"MID"+Machine.ID,Value为Machine对象
var machineStates = [];//所以tab下的相同机器使用同一个State状态对象
var enableInfoWindow = true;//是否显示InfoWindow
var showMapSlider = true;
var currentbasemap = "topo";
function getMachineStateObj(machineid) {
var stateObj = machineStates["MID" + machineid];
if (!stateObj) {
stateObj = { Selected: false, Highlight: false, ShowSummary: false }
machineStates["MID" + machineid] = stateObj;
}
return stateObj;
}
function resetMachineState() {
machineStates = [];
clearLocationHistory();
$("#locationhistoryDiv").hide();
$("#tripDiv").hide();
allJobsites = [];
allGroups = [];
}
function initPlayBar() {
$.playBar.addBar($("#divPlayBar"), 0);//第一个参数是需要显示播放器的容器,第二个参数为时间,单位毫秒
$.playBar.changeBarColor("#FFA500");//设置进度条颜色
$.playBar.changeFontColor("#000000")//设置时间颜色
//$.playBar.Stop()//进度条停止
//$.playBar.Begin()//进度条开始
//$.playBar.restTime(1000)//重新设置时间,并重新开始播放
//var t = $.playBar.getTheTime()//获得当前的时间
$.playBar.onPlayClick = onPlayClick;
}
function onPlayClick(last) {
var r = getLocationHistory(last);
if (r === 1) {
if (last)
$.playBar.PlayEnd();
else
$.playBar.Play();
}
}
function openSetLocationHistory() {
$('#dialog_locationhistory .dialog-title span.title').text(GetTextByKey("P_MA_LOCATIONHISTORY", 'Location History'));
//$('#mask_bg').show();
getLocationPrimaryDataSource();
$('#locationhistoryDiv').show();
}
function locationHistoryClick(e) {
locationTimeperiodChange();
$('#tripDiv').hide();
$('#tbTrips').empty();
if (PopupViewShowing) {
if (e) {
$('#mask_bg').show();
$('#dialog_lochis')
.css({
'top': 50,
'right': 100,
'bottom': 50,
'left': 100,
})
.showDialog();
execIframeFunc("getlocationhis", [e.data.CompanyID, e.data.ID, e.data.DisplayName], "iframelochis");
}
return;
}
if (e)
currentLocationHistoryMachine = e.data;
if (currentLocationHistoryMachine) {
$.playBar.Clear();
LocationHistoryInfo = null;
mapHelper.clearLocationHistory();
var mText = currentLocationHistoryMachine.DisplayName;
if (!mText || mText == "")
mText += " - " + currentLocationHistoryMachine.DisplayName;
$("#spMachineName").text(mText);
openSetLocationHistory();
}
}
function locationTimeperiodChange() {
var currentdate = getCurrentDate();
var timeperiod = $("#dialog_timeperiod").val();
var disabled = false;
if (timeperiod !== "4") {
disabled = true;
var time = new Date(currentdate);
var nowtime = new Date(currentdate);
var hours = nowtime.getHours();
var minutes = nowtime.getMinutes();
if (timeperiod === "2") {
time.setDate(time.getDate() - 1);
nowtime.setDate(nowtime.getDate() - 1);
}
else if (timeperiod === "3") {
time.setDate(time.getDate() - 6);
}
else if (timeperiod === "5") {
time.setDate(time.getDate() - 1);
}
time = time.getMonth() + 1 + "/" + time.getDate() + "/" + time.getFullYear();
nowtime = nowtime.getMonth() + 1 + "/" + nowtime.getDate() + "/" + nowtime.getFullYear();
$('#dateFrom').val(time);
$('#dateTo').val(nowtime);
$('#dialog_starttimehour').val('00');
$('#dialog_starttimeminute').val('00');
$('#dialog_endtimehour').val('23');
$('#dialog_endtimeminute').val('59');
if (timeperiod === "5") {
var s_minutes = minutes + 1;
var s_hours = hours;
if (minutes == 59) {
s_hours = s_hours + 1;
s_minutes = 0;
}
$('#dialog_starttimehour').val(setTimeSelect(s_hours));
$('#dialog_starttimeminute').val(setTimeSelect(s_minutes));
$('#dialog_endtimehour').val(setTimeSelect(hours));
$('#dialog_endtimeminute').val(setTimeSelect(minutes));
}
} }
var lastHisFromDT;
var lastHisToDT;
function getLocationHistory(last) {
var dtfrom = $("#dateFrom").val();
var dtto = $("#dateTo").val();
var start_hour = $('#dialog_starttimehour').val();
var start_minute = $('#dialog_starttimeminute').val();
var end_hour = $('#dialog_endtimehour').val();
var end_minute = $('#dialog_endtimeminute').val();
dtfrom = dtfrom.replace("-", "/") + " " + start_hour + ":" + start_minute + ":" + "00";
dtto = dtto.replace("-", "/") + " " + end_hour + ":" + end_minute + ":" + "59";
if (new Date(dtfrom) > new Date(dtto)) {
_dialog.showAlert(GetTextByKey("P_MV_FROMDATETIMEMUSTBEPRIORTOTODATETIME", 'From Date/Time must be prior to To Date/Time.'), GetTextByKey("P_MA_LOCATIONHISTORY", 'Location History'));
return;
}
if ($.playBar.getAllTime() > 0 && lastHisFromDT == dtfrom && lastHisToDT == dtto)
return 1;
else {
$.playBar.Clear();
LocationHistoryInfo = null;
mapHelper.clearLocationHistory();
lastHisFromDT = dtfrom;
lastHisToDT = dtto;
}
var cid = currentLocationHistoryMachine.CompanyID;
var mid = currentLocationHistoryMachine.ID;
var p = mid + ";" + dtfrom + ";" + dtto;
var notShow00loc = $("#chkExclude00Loc").is(":checked");
p += ";" + cid + ";" + (notShow00loc ? "1" : "0") + ";" + Datasource;
$("#btnHisLoading").show();
_network.mapviewquery("GetHistoryLocation", p, function (data) {
$("#btnHisLoading").hide();
if (data && data.Machine.ID === currentLocationHistoryMachine.ID) {
showLocationHistory(data, last);
}
}, function () {
$("#btnHisLoading").hide();
});
}
function showLocationHistory(data, last) {
LocationHistoryInfo = data
//currentTimer = setInterval(function () { locationHistoryTimer(data) }, 1000);
if (LocationHistoryInfo.Machine && LocationHistoryInfo.Locations) {
$.playBar.onBarChanged = doShowLocationHistory;
if (last) {
$.playBar.restTime(LocationHistoryInfo.Locations.length * 1000, true, true);
} else {
$.playBar.restTime(LocationHistoryInfo.Locations.length * 1000)//重新设置时间,并重新开始播放
}
}
}
function doShowLocationHistory(time, fromStart) {
var pointIndex = parseInt(time / 1000) - 1;
if (pointIndex < 0)
pointIndex = 0;
if (LocationHistoryInfo.Machine && LocationHistoryInfo.Locations) {
if (fromStart) {
mapHelper.showLocationHistoryFromStart(LocationHistoryInfo.Machine, LocationHistoryInfo.Locations, pointIndex, true);
}
else if (pointIndex < LocationHistoryInfo.Locations.length) {
mapHelper.showLocationHistory(LocationHistoryInfo.Machine, LocationHistoryInfo.Locations[pointIndex], true);
}
}
}
function clearLocationHistory() {
$.playBar.Clear();
LocationHistoryInfo = null;
if (isMapLoaded)
mapHelper.clearLocationHistory();
}
function setUserParams() {
_network.mapviewquery("SetUserParams", JSON.stringify(userParams), function (data) {
});
}
function displayFilerIcon() {
var filterText = $("#txtMachineSearchText").val();
filterText += $("#txtJobSiteSearchText").val();
filterText += $("#txtAssetGroupSearchText").val();
var unshownmachines = assetObject.getUnShownMachines();
var unshownjss = jobsiteObject.getUnShownJobsites();
var unshownjsmachines = jobsiteObject.getUnShownMachines();
if ($.trim(filterText) === ""
&& $("#selOnroad").val() == "-1"
&& $("#exclude00Div").attr("state") == "0"//!($("#chkExcludeNoLoc").prop("checked"))
&& unshownmachines.length == 0
&& unshownjss.length == 0
&& unshownjsmachines.length == 0)
$("#filterIconDiv").hide();
else
$("#filterIconDiv").show();
}
function doDirections(lat, lng) {
var directionURL = "https://www.google.com/maps/dir/?api=1&destination=" + lat + "," + lng + "&travelmode=driving";
window.open(directionURL);
}
function doWeather(lat, lng) {
var weatherURL = "https://www.wunderground.com/weather/" + lat + "," + lng;
window.open(weatherURL);
}
function doLocationHistory(cid, id, name) {
if (selectedAsset)
selectedAsset.State.Highlight = false;
var m = { CompanyID: cid, ID: id, DisplayName: decodeURIComponent(name) };
var e = { data: m };
locationHistoryClick(e);
}
// Machine
_network.mapviewquery = function (method, param, callback, error, nolog) {
_network.request("mapview.ashx?tp=ashx", -1, method, param, callback, error, nolog);
}
function getNowFormatDate() {
_network.mapviewquery("GetNowFormatDate", '', function (data) {
$("#refreshTimeDiv").text(GetTextByKey("P_MV_LASTREFRESHED", "Last Refreshed: ") + data);
});
}
function treeIconClick(e) {
var t = $(e.target);
var subItems = t.parent().children(".subul");
if (t.hasClass("treeiconc")) {
t.removeClass("treeiconc").addClass("treeicone");
subItems.show();
}
else {
t.removeClass("treeicone").addClass("treeiconc");
subItems.hide();
}
}
function isAssetMatch(asset, filter) {
if (!filter || filter == "") return true;
if (asset) {
filter = filter.toLowerCase();
if (asset.ID.toString().indexOf(filter) >= 0
|| asset.VIN.toLowerCase().indexOf(filter) >= 0
|| asset.Name.toLowerCase().indexOf(filter) >= 0
|| asset.Name2.toLowerCase().indexOf(filter) >= 0
|| asset.Make.toLowerCase().indexOf(filter) >= 0
|| asset.Model.toLowerCase().indexOf(filter) >= 0
|| asset.AssetType.toLowerCase().indexOf(filter) >= 0)
return true;
}
return false;
}
function openVideoDialog(url) {
var videourl = $.trim(decodeURIComponent(url));
var form = new $form();
form.createForm('', $('body'), 600, 400);
var gridcontent = $('<div style="height: 100%"><video width="100%" height="100%" src="' + videourl + '" controls="controls" autoplay="autoplay"></video></div>');
form.bodyCtrlAppend(gridcontent);
form.show();
form.maskbg && form.maskbg.css('z-index', 650);
form.formCtrl && form.formCtrl.css('z-index', 700);
form.maskbg.hide();
}
var _videoRequestAssetID;
function openRequestVideoDialog(assetid, logid) {
_videoRequestAssetID = assetid;
var loc;
if (logid === undefined) {
loc = assetLocations[assetid];
$('#dialog_hlogid').val("-1");
}
else {
loc = assetHisLocations[logid];
$('#dialog_hlogid').val(logid);
}
var dtstr = loc.LocationTimeText;
var timestr;
var dt;
if (!loc || !loc.LocationTimeText || loc.LocationTimeText == "") {
var dt = new Date(currentdate);
timestr = dt.getMonth() + 1 + "/" + dt.getDate() + "/" + dt.getFullYear();
}
else {
dt = new Date(dtstr);
timestr = dt.getMonth() + 1 + "/" + dt.getDate() + "/" + dt.getFullYear();
}
$('#dialog_videodate').val(timestr);
var h = dt.getHours();
h = (h < 10 ? '0' : '') + h;
$('#dialog_videohour').val(h);
var m = dt.getMinutes();
m = (m < 10 ? '0' : '') + m;
$('#dialog_videominute').val(m);
$("#dialog_videoct").prop("checked", false);
$("#dialog_videoct").change();
$('#mask_bg').show();
$('#dialog_requestvideo')
.attr('act', 'edit')
.css({
'width': 300,
'top': (document.documentElement.clientHeight - $('#dialog_requestvideo').height()) / 4,
'left': (document.documentElement.clientWidth - $('#dialog_requestvideo').width()) / 2
}).showDialogfixed();
}
function requestVideo() {
var ct = $("#dialog_videoct").prop("checked") ? 1 : 0;
var dt = $("#dialog_videodate").val();
var hour = $('#dialog_videohour').val();
var minute = $('#dialog_videominute').val();
dt = dt.replace("-", "/") + " " + hour + ":" + minute + ":" + "00";
var sec = $('#r30sec').prop("checked") ? 1 : 0;
var loc;
if ($('#dialog_hlogid').val() == "-1")
loc = assetLocations[_videoRequestAssetID];
else
loc = assetHisLocations[parseInt($('#dialog_hlogid').val())];
var cid = loc.CompanyID;
var logid = loc.LogId;
var src = loc.DataSource;
var subsrc = loc.SubSource;
var et = loc.EventType;
var msguid = loc.MsgUID;
_network.mapviewquery("RequestVideo", JSON.stringify([cid, _videoRequestAssetID, ct, dt, sec, logid, src, subsrc, et, msguid]), function (data) {
if (data == "OK") {
_dialog.showAlert(GetTextByKey("P_MV_REQUESTVIDEOSUCCESSFULLY", 'A video has been successfully requested for this Asset at the timestamp indicated. The requested video will be emailed to you once it is available. If the Asset or Camera are currently offline, the requested video will be sent as soon as it is available.'), GetTextByKey("P_MV_REQUESTVIDEO", 'Request Video'));
}
else {
_dialog.showAlert(GetTextByKey("P_MV_REQUESTVIDEOFAILED", 'Request video failed.'), GetTextByKey("P_MV_REQUESTVIDEO", 'Request Video'));
}
}, function () {
});
}
function openTrips(detail) {
$("#tbTrips").empty();
getAssetTripLins(detail);
}
function getLocationPrimaryDataSource() {
var cid = currentLocationHistoryMachine.CompanyID || "";
var mid = currentLocationHistoryMachine.ID;
var p = mid + ";" + cid;
_network.mapviewquery("GetLocationPrimaryDataSource", p, function (data) {
if (data && data.Item1.toLowerCase() === "calamp")
$("#btnLoadTrip").show();
else
$("#btnLoadTrip").hide();
}, function () {
});
}
function getAssetTripLins(detail) {
var cid = currentLocationHistoryMachine.CompanyID;
var mid = currentLocationHistoryMachine.ID;
var dtfrom = $("#dateFrom").val();
var dtto = $("#dateTo").val();
var start_hour = $('#dialog_starttimehour').val();
var start_minute = $('#dialog_starttimeminute').val();
var end_hour = $('#dialog_endtimehour').val();
var end_minute = $('#dialog_endtimeminute').val();
dtfrom = dtfrom.replace("-", "/") + " " + start_hour + ":" + start_minute + ":" + "00";
dtto = dtto.replace("-", "/") + " " + end_hour + ":" + end_minute + ":" + "59";
if (new Date(dtfrom) > new Date(dtto)) {
return;
}
if (detail)
$("#tripDiv").css({ 'left': 'unset', 'right': 11, 'bottom': 0, 'height': '65%' });
else
$("#tripDiv").css({ 'left': 0, 'right': 'unset', 'bottom': 52, 'height': 450 });
$("#tripDiv").show();
var p = mid + ";" + dtfrom + ";" + dtto;
p += ";" + cid
_network.mapviewquery("GetAssetTripLins", p, function (data) {
showAssetTripLins(data);
}, function () {
});
}
function showAssetTripLins(data) {
var tb = $("#tbTrips");
tb.empty();
for (var i = 0; i < data.length; i++) {
var trip = data[i];
var color = getTripColor(trip);
var tr = $("<tr style='border-bottom: 1px solid lightgray;'></tr>");
tb.append(tr);
var td = $('<td></td>').css('width', 30);
tr.append(td);
var div = $(' <div class="div_check"></div>');
var id = "tripitem" + i;
var chk = $('<input type="checkbox" value="1" name="" id="' + id + '"/>').data("trip", trip).data("row", tr);
var label = $('<label for="' + id + '" class="la1_check"></label>');
label.css('background-color', color);
div.append(chk).append(label);
td.append(div);
chk.click(function (e) {
var t = $(e.target).data("trip");
var row = $(e.target).data("row");
if (t && (t.TripOn || t.TripOff)) {
if ($(e.target).prop("checked")) {
mapHelper.changeLineColor(t.TripOn ? t.TripOn.LocalAsofTime : null, t.TripOff ? t.TripOff.LocalAsofTime : null, getTripColorArray(t));
row.css("background-color", "lightgray");
}
else {
mapHelper.changeLineColor(t.TripOn ? t.TripOn.LocalAsofTime : null, t.TripOff ? t.TripOff.LocalAsofTime : null, null);
row.css("background-color", "white");
}
}
});
td = $("<td></td>").css('width', 150);
tr.append(td);
var span = $('<span></span>').text(trip.TripOnLocalAsofTimeStr);
td.append(span).append($('<br>'));
span = $('<span></span>').text(trip.TripOffLocalAsofTimeStr);
td.append(span);
td = $("<td></td>").css('width', 180);
tr.append(td);
span = $('<span class="tripaddress_span"></span>').attr('title', trip.TripOnAddress).text(trip.TripOnAddress);
td.append(span).append($('<br>'));
span = $('<span class="tripaddress_span"></span>').attr('title', trip.TripOffAddress).text(trip.TripOffAddress);
td.append(span);
td = $("<td></td>").css({ 'width': 100, "text-align": "right" });
tr.append(td);
span = $('<span></span>').text(trip.TripDistance ? trip.TripDistance : "");
td.append(span);
span = $('<span></span>').text(trip.TripDistance ? " " + trip.TripDistanceUnit : "");
td.append(span);
td = $("<td></td>").css('width', 60);
tr.append(td);
span = $('<span style="padding-left:6px;"></span>').text(trip.TripTimeStr);
td.append(span);
}
}
function getTripColor(trip) {
var color = "#c8c4c4";
if (trip.Color === 0)
color = "#0000FF";
else if (trip.Color === 1)
color = "#4FBC20";
else if (trip.Color === 2)
color = "#FF00FF";
else if (trip.Color === 3)
color = "#FFFF00";
else if (trip.Color === 4)
color = "#ebbeb3";
else if (trip.Color === 5)
color = "#ff0000";
return color;
}
function getTripColorArray(trip) {
var color = [225, 95, 72];
if (trip.Color === 0)
color = [0x0, 0x0, 0xFF];
else if (trip.Color === 1)
color = [0x4F, 0xBC, 0x20];
else if (trip.Color === 2)
color = [0xFF, 0x0, 0xFF];
else if (trip.Color === 3)
color = [0xFF, 0xFF, 0x0];
else if (trip.Color === 4)
color = [0xEB, 0xBE, 0xB3];
else if (trip.Color === 5)
color = [0xFF, 0x00, 0x00];
return color;
}
var imgTypes = [".jfif", ".jpg", ".jpeg", ".bmp", ".png", ".tiff", ".gif"];
var printTypes = ['.pdf', ".jfif", ".jpg", ".jpeg", ".bmp", ".png", ".tiff", ".gif"];//types to be loaded to print
function getAssetMapAttachments(cid, assetid) {
showmaskbg(true);
$('#dialog_assetattachments').css({
'top': (document.documentElement.clientHeight - $('#dialog_assetattachments').height()) / 4,
'left': (document.documentElement.clientWidth - $('#dialog_assetattachments').width()) / 2
}).showDialogfixed();
var div_aatts = $("#divassetattachments").empty();
div_aatts.find(".attachmentsmask").show();
_network.mapviewquery("GetAssetMapAttachments", JSON.stringify([cid, assetid]), function (data) {
div_aatts.find(".attachmentsmask").hide();
if (data && data.length > 0) {
for (var i = 0; i < data.length; i++) {
var att = data[i];
if (imgTypes.indexOf(att.FileType.toLowerCase()) >= 0)
att.ThumbnailUrl = att.Url + "&thumb=1";
var div = createAttaDiv(att);
if ($.inArray(att.FileType.toLowerCase(), printTypes) >= 0) {
var sprint = $('<span class="attaprint"></span>').attr('title', GetTextByKey("P_WO_PRINT", 'Print')).click(att, function (e) {
openPrintFrame(e.data.AttachmentType, e.data.AttachmentIdStr);
});
div.append(sprint);
}
if (att.FileType.toLowerCase() != "url") {
var sdownload = $('<span class="attadownload"></span>').attr('title', GetTextByKey("P_WO_DOWNLOAD", 'Download')).click(att, function (e) {
openDownloadFrame(e.data.Url + "&d=1");
});
div.append(sdownload);
}
div_aatts.append(div);
}
}
}, function () {
div_aatts.find(".attachmentsmask").hide();
});
}
function createAttaDiv(att, iswoatta) {
var div = $('<div class="divatt"></div>').attr('title', att.Name);
if (!att.FileType || att.FileType == "") att.FileType = ".jpg";
if (imgTypes.indexOf(att.FileType.toLowerCase()) >= 0) {
var pic = $('<img class="picture"></img>').attr('src', att.ThumbnailUrl);
pic.click(att, function (e) {
window.open(e.data.Url, "_blank")
});
div.append(pic);
}
else {
var sdown = $('<img class="picture" />').click(att, function (e) {
window.open(e.data.Url);
});
setAttachemntIcon(att.FileType, sdown);
div.append(sdown);
}
return div
}
function setAttachemntIcon(filetype, sdown) {
if ([".doc", ".docx"].indexOf(filetype) >= 0) {
sdown.attr('src', 'img/icon/word.jpg')
} else if ([".xls", ".xlsx"].indexOf(filetype) >= 0) {
sdown.attr('src', 'img/icon/excel.jpg')
} else if ([".ppt", ".pptx"].indexOf(filetype) >= 0) {
sdown.attr('src', 'img/icon/ppt.jpg')
} else if ([".pdf", ".xps"].indexOf(filetype) >= 0) {
sdown.attr('src', 'img/icon/pdf.jpg')
} else if ([".mp4", ".mov", ".avi", ".mkv", ".3gp", ".ts", ".m2ts"].indexOf(filetype) >= 0) {
sdown.attr('src', 'img/icon/vedio.jpg')
} else if ([".zip", ".rar", ".7z"].indexOf(filetype) >= 0) {
sdown.attr('src', 'img/icon/zip.jpg')
} else if ([".msg"].indexOf(filetype) >= 0) {
sdown.attr('src', 'img/icon/msg.jpg')
} else if ([".xml"].indexOf(filetype) >= 0) {
sdown.attr('src', 'img/icon/xml.jpg')
} else {
sdown.attr('src', 'img/icon/txt.jpg')
}
}

View File

@ -0,0 +1,303 @@
$(function () {
InitSavedSearchGrid();
InitSaveSearchGrid();
$("#btnSavedSearches").click(openSavedSearches);
$("#btnSaveSearchDetault").click(openSaveSearch);
$('#dialog_savedsearches').dialog(function () {
$('#mask_bg').hide();
});
$('#dialog_savesearch').dialog(function () {
$('#mask_bg').hide();
});
});
function showGridList(grid_dt) {
showSearchList(grid_dt, userParams.MapViewSearches);
}
function showSearchList(grid_dt, data) {
grid_dt.setData([]);
if (!data || data.length === 0)
return;
var rows = [];
for (var i = 0; i < data.length; i++) {
var r = data[i];
for (var j in r) {
if (j === "IsDefault") {
r.IsDefaultText = r.IsDefault ? GetTextByKey("P_MV_YES", "Yes") : GetTextByKey("P_MV_NO", "No");
}
}
r.Text = false;
r.Email = false;
var fr = { Values: r };
rows.push(fr);
}
grid_dt.setData(rows);
}
/**********************Saved Searches***********************************/
function openSavedSearches() {
$('#mask_bg').show();
$('#dialog_savedsearches .dialog-title span.title').text(GetTextByKey("P_MV_SAVEDSEARCHES", 'Saved Searches'));
$('#dialog_savedsearches')
.attr('act', 'edit')
.css({
'width': 450,
'top': (document.documentElement.clientHeight - $('#dialog_savedsearches').height()) / 4,
'left': (document.documentElement.clientWidth - $('#dialog_savedsearches').width()) / 2
})
.showDialogfixed();
showGridList(savedsearches_dt)
}
var savedsearches_dt;
function InitSavedSearchGrid() {
savedsearches_dt = new GridView('#savedsearchlist');
savedsearches_dt.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
var list_columns = [
{ name: 'Name', caption: GetTextByKey("P_MV_SEARCHNAME", "Search Name"), valueIndex: 'Name', css: { 'width': 250, 'text-align': 'left' } },
{ name: 'IsDefault', caption: GetTextByKey("P_MV_DEFAULT", "Default"), valueIndex: 'IsDefaultText', css: { 'width': 70, 'text-align': 'left' } },
{ name: 'Apply', caption: "", css: { 'width': 30, 'text-align': 'center' } },
{ name: 'Delete', caption: "", css: { 'width': 30, 'text-align': 'center' } }
];
var columns = [];
// head
for (var hd in list_columns) {
var col = {};
col.name = list_columns[hd].name;
col.caption = list_columns[hd].caption;
col.visible = true;
col.sortable = true;
col.width = list_columns[hd].css.width;
col.align = list_columns[hd].css["text-align"]
col.key = list_columns[hd].valueIndex;
if (list_columns[hd].type) {
col.type = list_columns[hd].type;
}
if (col.name === "Apply") {
col.isurl = true;
col.text = "\uf1da";
col.events = {
onclick: function () {
onLoadSavedSearches(this);
}
};
col.classFilter = function (e) {
return "icon-col";
}
col.attrs = { 'title': GetTextByKey("P_MV_APPLY", 'Apply') };
}
else if (col.name === "Delete") {
col.isurl = true;
col.text = "\uf00d";
col.events = {
onclick: function () {
OnDeleteSavedSearches(this);
}
};
col.classFilter = function (e) {
return "icon-col";
};
col.attrs = { 'title': GetTextByKey("P_MV_DELETE", 'Delete') };
}
columns.push(col);
}
savedsearches_dt.canMultiSelect = false;
savedsearches_dt.columns = columns;
savedsearches_dt.init();
savedsearches_dt.selectedrowchanged = function (rowindex) {
var rowdata = savedsearches_dt.source[rowindex];
if (rowdata) {
$('#savedsearch_searchname').val(rowdata.Values.Name);
}
};
savedsearches_dt.rowdblclick = function (rowindex) {
var rowdata = savedsearches_dt.source[rowindex];
if (rowdata) {
onLoadSavedSearches(rowdata.Values);
}
};
}
function OnDeleteSavedSearches(search) {
if (!search) {
return;
}
showConfirm(GetTextByKey("P_MV_SEARCHDELETEWANTTOCONTINUE", 'Search {0} will be permanently deleted.Do you want to continue?').replace('{0}', search.Name), GetTextByKey("P_MV_DELETESEARCH", 'Delete Search'), function () {
_network.mapviewquery("DeleteMapViewSearch", search.Name, function (data) {
if (data) {
userParams.MapViewSearches = data;
showGridList(savedsearches_dt);
}
}, function (err) {
_dialog.showAlert(GetTextByKey("P_MV_FAILEDTODELETETHISSEARCH", 'Failed to delete this search.'), GetTextByKey("P_MV_DELETESEARCH", 'Delete Search'));
});
});
}
function onLoadSavedSearches(search) {
if (!search) {
var name = $('#savedsearch_searchname').val();
if (name === "")
return;
if (!userParams.MapViewSearches || userParams.MapViewSearches.length == 0) {
_dialog.showAlert(GetTextByKey("P_MV_YOUHAVENOSAVEDSEARCHES", 'You have no saved searches.'), '');
return;
}
for (var i = 0; i < userParams.MapViewSearches.length; i++) {
if (userParams.MapViewSearches[i].Name.toLowerCase() === name.toLowerCase()) {
search = userParams.MapViewSearches[i];
break;
}
}
}
if (!search) {
_dialog.showAlert(GetTextByKey("P_MV_SEARCHDOESNOTEXIST", 'Search {0} does not exist.').replace('{0}', $('#savedsearch_searchname').val()), '');
return;
}
setSavedSearche(search);
refreshData();
$('#dialog_savedsearches').hideDialog();
$('#mask_bg').hide();
}
function setSavedSearche(search) {
$("#selOnroad").val(search.Onroad);
$("#selAttachment").val(search.Attachment);
$('#txtMachineSearchText').val(search.AssetDefaultSearch);
$('#txtJobSiteSearchText').val(search.JobSiteDefaultSearch);
$('#txtAssetGroupSearchText').val(search.AssetGroupDefaultSearch);
//$('#chkExcludeNoLoc').prop("checked", search.ExcludeNoLocation);
setExclude00(search.ExcludeNoLocation);
assetObject.setUnShownMachines(search.UnShownMachines);
jobsiteObject.setUnShownJobsites(search.UnShownJobsites);
jobsiteObject.setUnShownMachines(search.UnShownJobsiteMachines);
resetMachineState();
}
/**********************Save Searche***********************************/
function openSaveSearch() {
$('#savesearch_searchname').val('');
$('#savesearch_default').prop('checked', false);
$('#mask_bg').show();
$('#dialog_savesearch .dialog-title span.title').text(GetTextByKey("P_MV_SAVESEARCH", 'Save Search'));
$('#dialog_savesearch')
.attr('act', 'edit')
.css({
'width': 450,
'top': (document.documentElement.clientHeight - $('#dialog_savesearch').height()) / 4,
'left': (document.documentElement.clientWidth - $('#dialog_savesearch').width()) / 2
})
.showDialogfixed();
showGridList(savesearch_dt);
}
var savesearch_dt;
function InitSaveSearchGrid() {
savesearch_dt = new GridView('#savesearchlist');
savesearch_dt.lang = {
all: GetTextByKey("P_GRID_ALL", "(All)"),
ok: GetTextByKey("P_GRID_OK", "OK"),
reset: GetTextByKey("P_GRID_RESET", "Reset")
};
var list_columns = [
{ name: 'Name', caption: GetTextByKey("P_MV_SEARCHNAME", "Search Name"), valueIndex: 'Name', css: { 'width': 250, 'text-align': 'left' } },
{ name: 'IsDefault', caption: GetTextByKey("P_MV_DEFAULT", "Default"), valueIndex: 'IsDefaultText', css: { 'width': 70, 'text-align': 'left' } }
];
var columns = [];
// head
for (var hd in list_columns) {
var col = {};
col.name = list_columns[hd].name;
col.caption = list_columns[hd].caption;
col.visible = true;
col.sortable = true;
col.width = list_columns[hd].css.width;
col.align = list_columns[hd].css["text-align"]
col.key = list_columns[hd].valueIndex;
if (list_columns[hd].type) {
col.type = list_columns[hd].type;
}
columns.push(col);
}
savesearch_dt.canMultiSelect = false;
savesearch_dt.columns = columns;
savesearch_dt.init();
savesearch_dt.selectedrowchanged = function (rowindex) {
var rowdata = savesearch_dt.source[rowindex];
if (rowdata) {
}
}
}
function onSaveSearch() {
var name = $('#savesearch_searchname').val();
var item = {
'Name': name,
'IsDefault': $('#savesearch_default').prop('checked'),
'Onroad': $("#selOnroad").val(),
'Attachment': $("#selAttachment").val(),
'AssetDefaultSearch': $('#txtMachineSearchText').val(),
'JobSiteDefaultSearch': $('#txtJobSiteSearchText').val(),
'AssetGroupDefaultSearch': $('#txtAssetGroupSearchText').val(),
'ExcludeNoLocation': $("#exclude00Div").attr("state") != "0", //$("#chkExcludeNoLoc").prop("checked"),
'UnShownMachines': assetObject.getUnShownMachines(),
'UnShownJobsites': jobsiteObject.getUnShownJobsites(),
'UnShownJobsiteMachines': jobsiteObject.getUnShownMachines()
};
if (item.Name === "") {
_dialog.showAlert(GetTextByKey("P_MV_SEARCHNAMEISREQUIRED", 'Search Name is required.'), GetTextByKey("P_MV_SAVESEARCH", 'Save Search'));
return;
}
var exists = false;
if (userParams.MapViewSearches) {
for (var i = 0; i < userParams.MapViewSearches.length; i++) {
var search = userParams.MapViewSearches[i];
if (search.Name.toLowerCase() === item.Name.toLowerCase()) {
exists = true;
break;
}
}
}
if (exists) {
showConfirm(GetTextByKey("P_MV_SEARCHALREADYEXIST", 'Search {0} already exists. Would you like to replace?').replace('{0}', item.Name), GetTextByKey("P_MV_SAVESEARCH", 'Save Search'), function () {
SaveMapViewSearch(item);
});
} else
SaveMapViewSearch(item);
}
function SaveMapViewSearch(item) {
_network.mapviewquery("SaveMapViewSearch", JSON.stringify(item), function (data) {
if (data) {
userParams.MapViewSearches = data;
showGridList(savesearch_dt);
$('#savesearch_searchname').val('');
$('#savesearch_default').prop('checked', false);
_dialog.showAlert(GetTextByKey("P_MV_SAVSUCCESSFULLY", 'Saved successfully.'), GetTextByKey("P_MV_SAVESEARCH", 'Save Search'));
$('#dialog_savesearch').hideDialog();
$('#mask_bg').hide();
}
}, function (err) {
_dialog.showAlert(GetTextByKey("P_MV_FAILEDTOSAVETHISSEARCH", 'Failed to save this search.'), GetTextByKey("P_MV_SAVESEARCH", 'Save Search'));
});
}

View File

@ -0,0 +1,237 @@
var shapevm;
$(function () {
initshape();
});
var selectedShapeFileID = [];
function initshape() {
shapevm = new Vue({
el: '#shapeList',
data: {
shapes: []
},
methods: {
reload: function (data) {
this.shapes = data;
var selcount = 0;
for (var i = 0; i < this.shapes.length; i++) {
var o = this.shapes[i];
if (o.Selected) selcount++;
}
var chkSelectAllShape = document.getElementById("chkSelectAllShape");
if (selcount == 0) {
chkSelectAllShape.checked = false;
chkSelectAllShape.indeterminate = false;
}
else if (selcount == this.shapes.length) {
chkSelectAllShape.checked = true;
chkSelectAllShape.indeterminate = false;
}
else {
chkSelectAllShape.indeterminate = true;
}
},
chkShapeClick: function (e, s) {
var t = $(e.target);
var checked = t.prop("checked");
if (checked) {
getShapeFileData(s);
if (selectedShapeFileID.indexOf(s.ID) < 0) {
selectedShapeFileID.push(s.ID);
}
}
else {
mapHelper.removeShape(s);
selectedShapeFileID.splice(selectedShapeFileID.indexOf(s.ID), 1);
}
this.reload(this.shapes);
},
linkShapeClick: function (s) {
locateShape(s);
s.Selected = true;
if (selectedShapeFileID.indexOf(s.ID) < 0) {
selectedShapeFileID.push(s.ID);
}
this.reload(this.shapes);
},
deleteShapeClick: function (m, ev) {
var e = { data: m };
deleteShapeClick(e);
}
}
});
}
function getShapeFileInfos() {
var item = {
'Key': companyids,
'Value': htmlencode($("#txtShapeSearchText").val())
};
_network.mapviewquery("GetShapeFileInfos", JSON.stringify(item), function (data) {
if (typeof (data) === "string") {
_dialog.showAlert(data, GetTextByKey("P_MV_ERROR", 'Error'));
return;
}
for (var i in data) {
if (selectedShapeFileID.indexOf(data[i].ID) < 0)
data[i].Selected = false;
else
data[i].Selected = true;
}
shapevm.reload(data);
}, function () {
});
}
function showConfirm1(msg, title, fok, fcancel) {
$('#mask_bg').show();
$('#addodomask').show();
$('#addenginehoursmask').show();
_dialog.showConfirm(msg, title, function (e) {
$('#mask_bg').hide();
$('#addodomask').hide();
$('#addenginehoursmask').hide();
if (typeof fok === 'function') {
fok(e);
}
}, function () {
$('#mask_bg').hide();
$('#addodomask').hide();
$('#addenginehoursmask').hide();
});
}
function deleteShapeClick(e) {
if (!e.data) {
return;
}
var item = {
'Key': e.data.CompanyID,
'Value': e.data.ID
};
$('#mask_bg').show();
showConfirm1(GetTextByKey("P_MV_DOYOUWANTTODELETETHESHAPEFILE", 'Do you want to delete the shape file?'), GetTextByKey("p_MV_DELETESHAPEFILE", 'Delete Shape File'), function () {
_network.mapviewquery("DeleteShape", JSON.stringify(item), function (data) {
mapHelper.removeShape(e.data);
getShapeFileInfos();
}, function (err) {
_dialog.showAlert(GetTextByKey("P_MV_FAILEDTODELETETHISSHAPLEFILE", 'Failed to delete this shaple file.'), GetTextByKey("p_MV_DELETESHAPEFILE", 'Delete Shape File'));
});
});
}
function openImportShapeFile() {
$('#dialog_shapename').val('');
$('#dialog_shapenotes').val('');
$('#span_filename').text('');
$('#mask_bg').show();
$('#dialog_importshapefile .dialog-title span.title').text(GetTextByKey("P_MV_IMPORTSHAPEFILE", 'Import Shape File'));
$('#dialog_importshapefile')
.attr('act', 'edit')
.css({
'width': 500,
'top': (document.documentElement.clientHeight - $('#dialog_importshapefile').height()) / 4,
'left': (document.documentElement.clientWidth - $('#dialog_importshapefile').width()) / 2
})
.showDialogfixed();
}
var shapefiledata;
function UploadImportShapeFile() {
var file = $('<input type="file" style="display: none;" accept=".shp,.kml,.kmz"/>');
file.change(function () {
var file = this.files[0];
shapefiledata = file;
$('#span_filename').text(file.name);
var name = $("#dialog_shapename").val();
if (!name || name.length == 0) {
if (file.name.length > 100)
$("#dialog_shapename").val(file.name.substring(0, 100));
else
$("#dialog_shapename").val(file.name);
}
}).click();
}
function SaveImportShapeFile() {
if (!shapefiledata)
return;
var item = {
'Key': companyids,
'Value': $("#dialog_shapename").val(),
'Tag1': $("#dialog_shapenotes").val(),
};
if (!item.Value || item.Value.length == 0) {
_dialog.showAlert(GetTextByKey("P_MV_SHAPENAMECANNOTBEEMPTY", 'Shape name cannot be empty.'), GetTextByKey("P_MV_IMPORTSHAPEFILE", 'Import Shape File'));
return;
}
var param = JSON.stringify(item);
param = htmlencode(param);
var formData = new FormData();
formData.append("iconFile", shapefiledata);
formData.append("MethodName", "ImportShape");
formData.append("ClientData", param);
$.ajax({
url: 'mapview.ashx?tp=ashx',
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
data: formData,
async: true,
success: function (data) {
if (data !== "OK") {
_dialog.showAlert(data, GetTextByKey("P_MV_ERROR", 'Error'));
return;
}
getShapeFileInfos();
shapefiledata = undefined;
$('#dialog_importshapefile').hideDialog();
$('#mask_bg').hide();
},
error: function (err) {
_dialog.showAlert(err.statusText, GetTextByKey("P_MV_IMPORTSHAPEFILE", 'Import Shape File'));
}
});
}
function getShapeFileData(s, needLocate) {
var item = {
'Key': s.CompanyID,
'Value': s.ID,
'Tag1': s.FileName
};
_network.mapviewquery("GetShapeData", JSON.stringify(item), function (data) {
if (typeof (data) === "string") {
_dialog.showAlert(data, GetTextByKey("P_MV_ERROR", 'Error'));
return;
}
s.Shape = data;
if (needLocate)
locateShape(s);
else
mapHelper.showShape(s);
}, function () {
});
}
function locateShape(s) {
if (s.Shape) {
mapHelper.showShape(s);
mapHelper.locateShape(s);
}
else
getShapeFileData(s, true);
}

354
Site/js/mapview/playbar.js Normal file
View File

@ -0,0 +1,354 @@
// JavaScript Document
(function ($) {
var isAction = true;
var width = 0;
var thewidth = 0;
var CurrTime = 0;
var t;
var addHour = 0,
addMinute = 0,
addSecond = 0,
TheHour = 0,
TheMinute = 0,
TheSecond = 0;
var flag = 0;
var alltime = 0;
var addwidth = 0;
var offsetW = 0;
var times = 0;
var rwidth = 0;
var valueChanged = false;
jQuery.playBar = {
addBar: function (DOM, allTime) {
CleanAll();
alltime = allTime;
DOM.empty();
DOM.append("<div class='BarControl'><div class='BarBeginTime'>00:00</div></div>");
$(".BarControl").append('<div class="TheBar"><div class="TimeBall"></div><div class="TheColorBar"></div><div class="TheWhiteBar"></div></div><div class="BarFinishTime">10:35</div><div id="btnPlay" class="BarPlay"></div><div id="btnPlayEnd" class="BarPlayEnd">');
width = $('.TheBar').width();
times = allTime / 1000;
rwidth = width - 8;
addwidth = (width - 10) / times;
var t = TransitionTime(allTime);
$('.BarFinishTime').html(t.StringTime);
$('#btnPlay').click(function () {
if ($.playBar.onPlayClick)
$.playBar.onPlayClick(false);
}).attr("title", GetTextByKey("P_MV_PLAYBACK", "Playback"));
$('#btnPlayEnd').click(function () {
if ($.playBar.onPlayClick)
$.playBar.onPlayClick(true);
}).attr("title", GetTextByKey("P_MV_QUICKLOADSKIPTOEND", "Quick Load/Skip to End"));
OpenBar();
},
restTime: function (allTime, valuechanged, jump) {
CleanAll();
StopBar();
alltime = allTime;
width = $('.TheBar').width();
times = allTime / 1000;
rwidth = width - 8;
addwidth = (width - 10) / times;
var t = TransitionTime(allTime);
$('.BarFinishTime').html(t.StringTime);
$('.TheColorBar').css("width", 0);
$('.TimeBall').css("left", 0);
if (valuechanged === undefined)
valueChanged = false;
else
valueChanged = valuechanged;
if (allTime > 0) {
if (jump) {
thewidth = rwidth;
timechange();
changeBar();
} else {
OpenBar();
}
}
},
Play: function () {
if (isAction)
jQuery.playBar.Stop();
else
jQuery.playBar.Begin();
},
PlayEnd: function () {
jQuery.playBar.restTime(alltime, true, true);
},
Stop: function () {
StopBar();
},
Clear: function () {
StopBar();
this.restTime(0);
$('#btnPlay').removeClass("BarPause");
$('#btnPlay').addClass("BarPlay");
},
Begin: function () {
if (CurrTime >= alltime) {
this.restTime(alltime, true);
}
else
OpenBar()
},
changeBarColor: function (COLOR) {
var color = typeof (COLOR) != "undefined" ? COLOR : '#3498DB';
$('.TheColorBar').css("background", color);
$('.TimeBall').css("background", color)
},
changeFontColor: function (COLOR) {
var color = typeof (COLOR) != "undefined" ? COLOR : '#3498DB';
$('.BarBeginTime,.BarFinishTime').css("color", color)
},
getAllTime: function () {
return alltime;
},
getTheTime: function () {
return CurrTime
},
onBarChanged: undefined,
onPlayClick: undefined
};
function CleanAll() {
isAction = true;
thewidth = 0;
CurrTime = 0;
addHour = 0;
addMinute = 0;
addSecond = 0;
TheHour = 0;
TheMinute = 0;
TheSecond = 0;
offsetW = 0;
thewidth = 0;
flag = 0
}
var down = false;
var BarMove = false;
var lastX = 0,
NewX = 0;
$(document).on("mousedown", '.TimeBall', function (event) {
lastX = event.clientX;
//event.preventDefault();
down = true;
BarMove = true;
if (isAction) {
StopBar()
}
$(document).mousemove(dragmove);
$(document).mouseup(dragup);
});
function dragmove(event) {
//event.preventDefault();
NewX = event.clientX;
if (BarMove) {
var mcs = NewX - lastX;
lastX = NewX;
if (mcs < 0) {
if (thewidth - (-mcs) > 0) {
thewidth = thewidth - (-mcs)
}
} else {
if (thewidth + mcs < rwidth) {
thewidth = thewidth + mcs
} else {
thewidth = rwidth
}
}
timechange();
$('.TheColorBar').css("width", thewidth + 1);
$('.TimeBall').css("left", thewidth)
}
}
function dragup() {
if (BarMove) {
BarMove = false;
down = false;
NewX = 0;
var xo = parseInt(CurrTime / 1000);
offsetW = thewidth - xo * addwidth;
if (isAction) {
OpenBar()
}
valueChanged = true;
}
$(document).unbind('mousemove', dragmove);
$(document).unbind('mouseup', dragup);
};
function timechange() {
CurrTime = parseInt(thewidth / rwidth * alltime);
var ltx = TransitionTime(CurrTime);
if (TheHour > 0) {
if (ltx.hHour) {
$('.BarBeginTime').html(ltx.StringTime)
} else {
$('.BarBeginTime').html("00:" + ltx.StringTime)
}
} else {
$('.BarBeginTime').html(ltx.StringTime)
}
addSecond = ltx.Tsec;
addMinute = ltx.Tmin;
addHour = ltx.Thour
}
function changeBar() {
var second, minute, hour;
thewidth = thewidth * 1 + addwidth - offsetW;
if (offsetW > 0) {
offsetW = 0
}
if (thewidth < rwidth && CurrTime < alltime) {
CurrTime = CurrTime + 1 * 1000;
addSecond = addSecond + 1;
if (addSecond > 59) {
addSecond = 0;
addMinute = addMinute + 1;
if (addMinute > 59) {
addMinute = 0;
addHour = addHour + 1
}
}
if (addSecond > 9) {
second = "" + addSecond
} else {
second = "0" + addSecond
} if (addMinute > 9) {
minute = "" + addMinute
} else {
minute = "0" + addMinute
} if (addHour > 9) {
hour = "" + addHour
} else {
hour = "0" + addHour
} if (addHour > 0) {
flag = 1
}
if (flag == 0) {
$('.BarBeginTime').html(minute + ":" + second)
} else {
$('.BarBeginTime').html(hour + ":" + minute + ":" + second)
}
} else {
thewidth = rwidth;
StopBar();
}
$('.TheColorBar').css("width", thewidth + 1);
$('.TimeBall').css("left", thewidth)
if ($.playBar.onBarChanged)
$.playBar.onBarChanged(CurrTime, valueChanged);
valueChanged = false;
}
function TransitionTime(str) {
var m = parseFloat(str) / 1000;
var time = "";
var second, minute, hour;
var haveHour = false;
var ch = 0,
csx = 0,
cm = 0;
if (m >= 60 && m < 60 * 60) {
if (parseInt(m / 60.0) < 10) {
minute = "0" + parseInt(m / 60.0)
} else {
minute = parseInt(m / 60.0)
}
var cs = parseInt(m - parseInt(m / 60.0) * 60);
if (cs < 10) {
second = "0" + cs
} else {
second = "" + cs
}
TheMinute = parseInt(m / 60.0);
TheSecond = cs;
cm = TheMinute;
TheHour = 0;
csx = cs;
time = minute + ":" + second;
$('.BarBeginTime').html("00:00")
} else if (m >= 60 * 60) {
flag = 1;
haveHour = true;
ch = parseInt(m / 3600.0);
cm = parseInt((parseFloat(m / 3600.0) - parseInt(m / 3600.0)) * 60);
csx = parseInt((parseFloat((parseFloat(m / 3600.0) - parseInt(m / 3600.0)) * 60) - parseInt((parseFloat(m / 3600.0) - parseInt(m / 3600.0)) * 60)) * 60);
if (ch < 10) {
hour = "0" + ch
} else {
hour = "" + ch
} if (cm < 10) {
minute = "0" + cm
} else {
minute = "" + cm
} if (csx < 10) {
second = "0" + csx
} else {
second = "" + csx
}
TheHour = ch;
TheMinute = cm;
TheSecond = csx;
time = hour + ":" + minute + ":" + second;
$('.BarBeginTime').html("00:00:00")
} else {
$('.BarBeginTime').html("00:00");
csx = parseInt(m);
if (parseInt(m) > 9) {
second = "" + parseInt(m)
} else {
second = "0" + parseInt(m)
}
TheMinute = 0;
TheSecond = parseInt(m);
TheHour = 0;
time = "00:" + second
}
var tt = {
hHour: haveHour,
Thour: ch,
Tmin: cm,
Tsec: csx,
StringTime: time
};
return tt
}
function StopBar() {
if (!down) {
isAction = false
}
clearInterval(t)
$('#btnPlay').removeClass("BarPause");
$('#btnPlay').addClass("BarPlay");
}
function OpenBar() {
if (CurrTime <= alltime) {
if (valueChanged && $.playBar.onBarChanged) {
$.playBar.onBarChanged(CurrTime, valueChanged);
valueChanged = false;
}
isAction = true;
if (t) clearInterval(t);
t = setInterval(changeBar, 1000);
$('#btnPlay').removeClass("BarPlay");
$('#btnPlay').addClass("BarPause");
}
}
})(jQuery);