SafeNet/SDMaps/src/Parser.js

684 lines
19 KiB
JavaScript

/*
for creating a new polygon
-- new polygon, name, color
-- then when user press save getPolygon,name
-- if cancel deletePolygon,name
for canceling an edit
-- deletePolygon, xx
-- setPolygon, xx, ...
for canceling the creation of a new polygon
-- deletePolygon, tempName
to update a polygon
-- deletePolygon,name
-- setPolygon,newName,{new settings}
*/
var DEBUG = false;
var Parser = function(sets, mapProperties, polys) {
console.log('creating parser');
return {
parseCommand: function(commandText) {
if (!commandText) return;
var args = commandText.split(',');
if (args && args.length > 0) {
var type = args.shift().toLowerCase();
if (this[type]) this[type].apply(this, args);
else {
var m = 'WARNING: method [' + type + '] is not defined in Parser.';
console.error(m);
throw new Error(m);
}
}
},
_parsePointsPoly: function(pointsArray) {
var points = [];
if (pointsArray.length % 2 != 0) {
console.error('Wrong number of args when parsing poly points:' + pointsArray);
return null;
}
for (var i = 0; i < pointsArray.length; i += 2)
points.push(new DataSetPoint(pointsArray[i], pointsArray[i + 1]));
return points;
},
_parsePoints : function(pointsArray){
// console.log("Parsing points:... new function..." + pointsArray);
// console.dir(pointsArray);
var points = Utils.parsePoints(pointsArray);
// .map(function(p) {
// return new DataSetPoint().merge(p);
// });
// console.dir(points);
return points;
},
_parsePoints2: function(pointsArray) {
console.log("_parsePoints: " + pointsArray);
var points = [];
if (pointsArray.length % 11 !== 0) {
console.error('Wrong number of point parameters at ' + JSON.stringify(pointsArray));
return null;
}
for (var i = 0; i < pointsArray.length - 4; i += 5)
points.push({
latitude: +pointsArray[i],
longitude: +pointsArray[i + 1],
time : new Date(pointsArray[i+2]),
id: pointsArray[i + 3],
speed : pointsArray[i+4],
altitude : +pointsArray[i+5],
address : pointsArray[i+6],
icon : pointsArray[i+7],
hasVoice : pointsArray[i+8],
hasText : pointsArray[i+9],
isInCall : pointsArray[i+10]
});
points.map(function(e) {
return new DataSetPoint().merge(e);
});
return points;
},
_getDataset: function(name) {
return this._getModel(sets, name);
},
_getPolygon: function(name) {
return this._getModel(polys, name);
},
_getModel: function(collection, name) {
//use collection.get(name) if name is id
var ds = collection.where({
id: name
});
if (ds.length > 0) return ds[0];
//else console.error('Could not find element with name : ' + name);
return null;
},
setdataset: function(name /*, ...*/ ) {
//parse points = la1,lng1,name1,speed1_time1,adresa1,icon_name1...
var points = this._parsePoints([].slice.call(arguments, 1));
if (points) {
var dataSet = new DataSet({
id: name,
points: points.map(function(p){p.dataset = name;return p})
});
if (sets.get(name))
this.removedataset(name);
sets.add(dataSet);
}
// console.log('There are ' + sets.length + ' sets now.');
},
//will update a dataset based on points name
updatedataset: function(name /*,...*/ ) {
var points = this._parsePoints([].slice.call(arguments, 1));
if (points) {
var ds = sets.where({
id: name
});
if (ds.length == 1) ds[0].updatePoints(points);
else console.error("can't find dataset in updateDataset : " + name);
}
},
//autosize = true | false
putonmap: function(autoSize, name) {
var ds = this._getDataset(name);
if (ds)
ds.set({
isAutosize: (autoSize === 'true'),
isVisible: true,
lastUpdated : new Date()
});
},
clearfrommap: function(name) {
var ds = this._getDataset(name);
if (ds) ds.set({
isVisible: false
});
},
removedataset: function(name) {
//var toRemove = this._getDataset(name);
var toRemove = sets.get(name);
if (toRemove)
sets.remove(toRemove);
},
deletefromdataset: function(name, pointName) {
var ds = this._getDataset(name);
if (ds) ds.removePoint(pointName);
},
centerzoom: function(latitude, longitude, zoom) {
mapProperties.set({
center: [latitude, longitude],
zoom: zoom
});
},
reset: function() {
//should it remove all datasets and polygons and polylines ????
mapProperties.set('isReset', new Date());
sets.reset();
},
resize: function(width, height) {
mapProperties.set("dimmensions", [height, width]);
},
openinfo: function(name) {
if (name !== 'null')
mapProperties.set("openedMarker", name);
},
putlabels: function(name) {
var ds = this._getDataset(name);
if (ds) ds.set('isShowLabels', true);
},
removelabels: function(name) {
var ds = this._getDataset(name);
if (ds) ds.set('isShowLabels', false);
},
setmaptype: function(type) {
mapProperties.set('mapType', type);
},
setpolygon: function(name, fillColor, fillOpacity, borderColor, borderOpacity, borderWidth /*,points...*/ ) {
var pointsArray = this._parsePointsPoly([].slice.call(arguments, 6));
if (pointsArray) {
var poly = new Polygon({
id: name,
color: fillColor,
opacity : fillOpacity,
borderColor : borderColor,
borderOpacity : borderOpacity,
borderWidth : borderWidth,
points: pointsArray
});
polys.add(poly);
console.log('Added a polygon. No of polygons:' + polys.length);
}
},
//starts the creation of a new polygon on the map
newpolygon: function(name, fillColor, fillOpacity, borderColor, borderOpacity, borderWidth) {
var poly = new Polygon({
id: name,
color: fillColor,
opacity : fillOpacity,
borderColor : borderColor,
borderOpacity : borderOpacity,
borderWidth : borderWidth,
isNew: true
})
polys.add(poly);
},
getpolygon: function(name) {
mapProperties.set('polygonToGet', {
name: name,
date: new Date()
});
}
,
deletepolygon: function(name) {
if (name != "ALL") {
var p = this._getPolygon(name);
if (p) polys.remove(p);
}else
polys.reset();
},
starteditpolygon: function(name) {
var p = this._getPolygon(name);
if (p)
p.set('isEditing', true);
},
endeditpolygon: function(name) {
var p = this._getPolygon(name);
if (p) p.set('isEditing', false);
},
poly: function(autoZoom, color, thickness, datasetName) {
var ds = sets.get(datasetName);
if (ds){
ds.set("color",color);
ds.set("thickness", thickness);
ds.set("isPolyline",true);
}
},
getmaptype : function(){
//document.getElementById('response_string').innerHTML = ;
},
clearresponse : function(){
['response_string','click_string'].forEach(function(divid){
document.getElementById(divid).innerHTML = '';
});
},
showconsole : function(on){
mapProperties.set('console',JSON.parse(on.toLowerCase()));
},
setlegacyicons : function(isLegacy){
mapProperties.set('legacyicons', isLegacy);
},
setcall : function(name,state){
sets.forEach(function(s){
var p = _.clone(s.get('points'), true);
var point = _.find(p,{id:name});
point.isInCall = JSON.parse(state.toLowerCase());
// console.dir(point);
// console.log("Set isInCall for "+point.id+" in set "+s.id +' value = '+point.isInCall);
s.updatePoints([point]);
});
},
updatepolygonstyle : function(name,fillColor,fillOpacity,borderColor,borderOpacity,borderWidth){
var p = this._getPolygon(name);
if (p){
p.set('color', fillColor);
p.set('opacity', fillOpacity);
p.set('borderColor', borderColor);
p.set('borderOpacity', borderOpacity);
p.set('borderWidth', borderWidth);
}
}
};
};
//this should stay next to the SfmbMapsOL definition
function bindEvents(map, properties, sets, polys) {
function centerZoom(p, newParams) {
var center = properties.get('center');
var zoom = properties.get('zoom');
map.centerZoom(center[0], center[1], zoom);
// console.log('centerzoom evetn');
}
properties.on('change:center change:zoom', centerZoom);
properties.on('change:dimmensions', function(o, newDim) {
map.resize(newDim[0], newDim[1]);
console.log('dimmensions changed to:' + newDim);
});
properties.on('change:polygonToGet', function(p, polyName) {
var name = polyName.name;
map.getPolygon(name);
});
properties.on('change:openedMarker', function(p, markerName) {
if (markerName) {
map.openInfoBubble(markerName);
properties.set('openedMarker', '');
}
});
properties.on('change:isReset', function(p, reset) {
map.resetAll();
});
properties.on('change:console', function(p,consoleValue){
var show = consoleValue?"show":"hide";
$('#log-area')[show]();
});
properties.on('change:traffic', function(p, tValue){
map.setTraffic(tValue);
});
properties.on('change:legacyicons', function(p, legacyiconsvalue){
map.setLegacyIcons(legacyiconsvalue);
});
sets.on('add', function(set) {
// console.log('dataset added : ' + set.get('id'));
set.on('change:isVisible change:lastUpdated', function(o, visible) {
// console.log('Making dataset: '+this.get('id')+' visible?'+(!!visible));
if (visible){
if (!this.get('isPolyline'))
map.putPoints(this.get('points'), this.get('isAutosize'));
}
else {
map.removePoints(this.get('points'));
if (this.get('isPolyline'))
map.deletePoly(this.id);
}
}, set);
set.on('change:isShowLabels', function(s, show) {
var action = show? "put":"remove";
map[action+"Labels"](this.get('points'));
// if (show) map.putLabels(this.get('points'));
// else map.removeLabels(this.get('points'));
}, set);
set.on('change:isPolyline change:color',function(s,isPoly){
if (isPoly){
map.setPoly(true,s.get('color'),s.get('thickness'),s.get('points'),s.id);
s.set('isVisible',true);
}
});
});
sets.on('remove', function(set) {
set.set('isVisible', false);
console.log('removed dataset =' + set.get('id'));
});
polys.on('add', function(poly) {
console.log('polygon added');
//TODO: newPolygon is different than setpolygon
if (!poly.get('points') || poly.get('points').length ==0){
//name, fillColor, fillOpacity, borderColor, borderOpacity, borderWidth
map.newPolygon(
poly.get('id'),
poly.get('color'),
poly.get('opacity'),
poly.get('borderColor'),
poly.get('borderOpacity'),
poly.get('borderWidth') );
}
else map.setPolygon(
poly.get('id'),
poly.get('color'),
poly.get('points'),
poly.get('opacity'),
poly.get('borderColor'),
poly.get('borderOpacity'),
poly.get('borderWidth') );
poly.on('change:isEditing', function(p, isEditing) {
if (isEditing) map.startEditPolygon(p.get('id'));
else map.endEditPolygon(p.get('id'));
});
poly.on('change:color change:opacity change:borderColor change:borderWidth change:borderOpacity', function(p,propValue){
var propName = Object.keys(p.changedAttributes())[0];
// console.log(p.get('id')+" polygon changed prop "+ propName + " = " +propValue );
map.updatePolygon(p.get('id'),propName, propValue);
});
});
polys.on('remove', function(p) {
map.deletePolygon(p.get('name'));
});
polys.on('reset', function(models, options) {
map.deleteAllPolygons();
});
}
//-----------------------moved from html file -------------------------
function initialize() {
function navigate(url){
log('setting the URL to: ' + url);
// location = "app://"+url;
//object set by the host application and intercepted in cefsharp
try{
typeof callbackObj != 'undefined' && callbackObj!=null && callbackObj.callBackMethod("app://"+url);
}catch(e){log(e);}
}
var mapTypes = {
SfmbMapsMainSatelitte : 'satellite',
SfmbMapsMain : 'hybrid',
SfmbMapsMainMap : 'map',
SfmbMapsMainTerrain : 'terrain'
};
var htmlFileName = location.href.split('/').pop().split('.').shift();
var mapType = mapTypes[htmlFileName] ||"hybrid";
var properties = new MapProperties();
var sets = new DataSetCollection();
var polys = new PolygonCollection();
var mapOpts = {
divObject: document.getElementById('Map'),
polyPointCallback: function getPoints(points) {
var res = points.map(function (p) {
return p.latitude + "," + p.longitude
}).join();
document.getElementById('click_string').innerHTML = res;
navigate('points/' + res);
},
getPolygonCallback: function getPolygon(poly) { //this is not used
var points = poly.points && poly.points.map(function (p) {
return p.latitude + "," + p.longitude
}).join();
var res = "[" + poly.name + "," + poly.color + "," + points + "]";
document.getElementById('response_string').innerHTML = res;
navigate("polygon/" + res);
},
landmarkCallback: function landmarkCallback(point) {
var res = point.latitude + "," + point.longitude
document.getElementById('click_string').innerHTML = res;
navigate("landmark/" + res);
},
fastCommandCallback : function(type, unitId, message){
if (type == 'ptt' && message == 'off')
GWTcallback("setCall,"+unitId+",False");
message = encodeURIComponent(message);
var translate = {
ptt : 'ptt-command',
text : 'text-command',
fast : 'fast-command'
}
var url = translate[type]+"/"+unitId+","+message;
// var url = [translate[type],unitId,message].join("/");
navigate(url);
// if(type == 'ptt')
// navigate("ptt-command/"+unitId+','+message);
// else if(type == 'text')
// navigate("text-command/"+unitId+','+message);
// else if(type == 'fast')
// navigate("fast-command/"+unitId);
},
mapLoaded : function(){
navigate("map-loaded");
},
streetViewOpen : function(visible){
navigate('street-view-open/'+visible);
},
mapType : mapType,
properties : properties
}
var map = new SfmbMaps(mapOpts);
bindEvents(map, properties, sets, polys);
window.parser = Parser(sets, properties, polys);
var width = $('#tools').width()-$('#open').width();
$('#tools').animate({right:"-"+width+"px"},400);
$('input:text:first').focus(function(){$(this).val('')});
//var show = map.getMapKind()==='OSM' ? "hide":"show";
var show = _.isFunction(map.setTraffic) ? "show":"hide";
$('#traffic')[show]();
$('#traffic').parent()[show]();
$('#traffic').change(function(){
properties.set('traffic',$(this).is(':checked'));
});
$('input:text:first').keyup(function(ev){
if (ev.which === 13) {
console.log('enter pressed');
var search = $(this).val();
map.geocode(search);
}
})
$('#open').click(function(){
var width = $('#tools').width()-$('#open').width();
console.log('');
var isOpen = $('#open').attr('src').indexOf('close') === -1;
var label = isOpen?'images/close_vertical.png':'images/tools.png';
$('#open').attr("src",label);
$('#tools').animate({
right:isOpen?"0px":"-"+width+"px"
}, 700);
})
// properties.set("dimmensions",[$(window).height(), $(window).width()]);
$(window).resize(function(){
var newDim = [$(this).height(), $(this).width()];
// newDim=[300,300];
properties.set("dimmensions",newDim);
});
$(window).trigger('resize');
if (DEBUG) {
properties.set("console", true);
}
}
var debugServer = "10.120.1.120:9000";
var commandsCache = [];
function GWTcallback(text) {
if (DEBUG) executeCommand(text);
if (commandsCache.length > 2000) commandsCache.shift();
commandsCache.push(text);
try {
log(text);
if (!DEBUG) executeCommand(text);
} catch (e) {
console.error(e);
log(e.toString());
}
}
function log(message) {
var ta = document.getElementById('log-area');
var isVisible = ta && ta.style.display != 'none';
if (!isVisible) return;
if (message.indexOf('Error') > -1) message = ' ' + message;
if (message.indexOf('URL') > -1) message = ' ' + message;
var val = '';
var content = ta.value;
var index = content.lastIndexOf('\n') + 1;
var lastLine = content.substr(index);
if (lastLine === message)
val = ta.value + ' x 1';
else {
var groups = /(.*)\sx\s(\d*)/.exec(lastLine);
if (groups) {
var line = groups[1];
var count = +groups[2];
if (line === message) val = ta.value.substr(0, index) + line + ' x ' + (count + 1);
else groups = null;
}
if (!groups) val = ta.value + '\n' + message;
}
ta.value = val;
ta.scrollTop = ta.scrollHeight;
}
function executeCommand(text) {
window.parser.parseCommand(text);
}
console.warning = log
localIP = null
function startSeeding(){
instanceId = Date.now();
id = setInterval(function(){
if (commandsCache.length < 1) return;
// var ip = (localIP && localIP.ip) || '127.0.0.1'
command = commandsCache.shift();
//post the command to cors server 10.120.1.120:9000/api/command/:command
var url = 'http://'+debugServer+'/api/command/'+instanceId+'/'+encodeURIComponent(command);
$.ajax({
type : 'POST',
url : url,
success : function(r){console.log("command sent.")}
});
},10);
}
if (!DEBUG)
$.ajax({
url : 'http://'+debugServer+"/api/status",
success : function(r){log('start seeding to'+debugServer);startSeeding();}
});
// setTimeout (function(){
// Utils.getLocalIP(function(ip){
// if (!localIP || localIP.priority > ip.priority) localIP=ip;
// log("IP="+localIP.ip);
// $.ajax({
// url : 'http://'+debugServer+"/api/status",
// success : function(r){log('start seeding to'+debugServer);startSeeding();}
// });
// });
// }, 5000);
// console.log = log