if (typeof (Dmp) == 'undefined') Dmp = new Object(); var _TOOLKIT_LOCATION='http://parcelstream.com/api/lib\\Legacy/';Dmp.HostName='http://parcelstream.com/'; // Create namespace if (typeof (Dmp.Core) == 'undefined') Dmp.Core = new Object(); if (typeof (Dmp.Core.QueryModel) == 'undefined') Dmp.Core.QueryModel = new Object(); if (typeof (Dmp.Core.WktTools) == 'undefined') Dmp.Core.WktTools = new Object(); if (typeof (Dmp.Layers) == 'undefined') Dmp.Layers = new Object(); if (typeof (Dmp.Layer) == 'undefined') Dmp.Layer = new Object(); if (typeof(Dmp.Conn) == "undefined") Dmp.Conn = new Object(); if (typeof (Dmp.Util) == 'undefined') Dmp.Util = new Object(); if (typeof (Dmp.Abstraction) == 'undefined') Dmp.Abstraction = new Object(); if (typeof (Dmp.Legacy) == 'undefined') Dmp.Legacy = new Object(); if (typeof (Dmp.Identify) == 'undefined') Dmp.Identify = new Object(); if (typeof (Dmp.Map) == 'undefined') Dmp.Map = new Object(); if (typeof (Dmp.Cookbook) == 'undefined') Dmp.Cookbook = new Object(); /** * CONFIDENTIAL AND PROPRIETARY * This document is confidential and contains proprietary information. * Neither this document nor any of the information contained herein * may be reproduced or disclosed to any person under any circumstances * without the express written consent of Digital Map Products. * * Copyright: Copyright (c) 2006 * Company: Digital Map Products * @author Samir * @version 1.0 * */ Dmp.Util.EventPriority = new function() { this.LOW = 1000; this.MEDIUM = 20; this.HIGH = 2; this.HIGHEST = 1; }; //Dmp.Util.EventPriority Dmp.Util.EventManager = function(){ //assuming that an event will be notified more frequently than adding observers this._event2PriorityArray = new Array(); //some events are already executed and observers which are added later should be dispatched immediately. this._eventPassed = new Array(); this.notify = function (evtObj){ if (evtObj==null) throw new Dmp.Exception("Event object is NULL"); if (evtObj.eventType == null) throw new Dmp.Exception("evtObj.eventType is NULL"); if (evtObj.deadEvent){ this.setDispatchedEvent(evtObj.eventType, evtObj); } //Get an array sorted by priority var priorityArray = this._event2PriorityArray[evtObj.eventType]; //nobody listening if (priorityArray==null) return null; //the observers can choose to call removeObserver and tamper with a priority array. //I will need to create a clone of an array before calling execute. var priorityArrClone = []; //clone for ( var i=0; ib if (a.priority==null) a.priority = 20; if (b.priority==null) b.priority = 20; if (a.priorityb.priority){ return 1; }else{ return 0; } }//sortByPrirityMethod this.indexOf = function(priorityArray, observer){ if (priorityArray==null || observer==null) return -1; for ( var i=0; i 0) urlWithOid += "&"; else urlWithOid += "?"; urlWithOid += "obsId=window"; urlWithOid += "&obsSuccessMethod=" + sucCallback; urlWithOid += "&obsErrorMethod=" + errCallback; if (urlWithOid.indexOf("output=") < 0) { if (!outputType) outputType = "json"; urlWithOid += "&output=" + outputType; } //JQuery Call jQuery.getScript(urlWithOid, _loadedURL); }; //Dmp.Util.getJson /* @syntax: public static JQueryDom Dmp.Util.parseXml(String xmlString) */ Dmp.Util.parseXml = function(xml) { if (window.ActiveXObject && window.GetObject) { var dom = new ActiveXObject('Microsoft.XMLDOM'); dom.loadXML(xml); return $(dom); } else if (window.DOMParser) { var dom = new DOMParser().parseFromString(xml, 'text/xml'); return $(dom); } throw { description: 'No XML parser available' }; }; Dmp.Exception = function(ex) { this.message = ex; this.description = ex; }; //Dmp.Exception Dmp.Util.getCookie = function(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; };//getCookie Dmp.Util.FileWriter = function(servicePath) { var FILE_WRITER_NAME = servicePath + "FileWriterService.aspx"; var XML_HEADER = ""; this.writeData = function(fileName, data, observerMethod) { var paramHashtable = { "FILE_NAME": fileName, "DATA": data }; var r = new Dmp.Util.DoPost(FILE_WRITER_NAME, paramHashtable); r.execute(observerMethod); }; function createPropNode(dom, nvcNode, name, value) { var propNode = dom.createElement("property"); //add name var nameAtt = dom.createAttribute("name"); nameAtt.value = name; propNode.setAttributeNode(nameAtt); //add value var valueAtt = dom.createAttribute("value"); //llu:if the boolean check isn't there, it considers 0 as false and change the value to false if (typeof (value) == "boolean") { if (value == true) value = 'true'; else if (value == false) value = 'false'; } valueAtt.value = value; propNode.setAttributeNode(valueAtt); //add this child to a dom nvcNode.appendChild(propNode); }; //createPropNode this.writeParams = function(fileName, paramHashtable, observerMethod) { var out = XML_HEADER; out += ""; for (var key in paramHashtable) { var v = paramHashtable[key]; if (v == null) continue; out += ""; } out += ""; var htData = { "FILE_NAME": fileName, "DATA": out }; //also include DMP_CANDY if available try { if (typeof (DMP_CANDY) != 'undefined') { // global value. htData["DMP_CANDY"] = DMP_CANDY; } } catch (ex) { } var r = new Dmp.Util.DoPost(FILE_WRITER_NAME, htData); r.execute(observerMethod); }; //writeParams }; //Dmp.Util.FileWriter Dmp.Util.DoPost = function(serviceName, paramHashtable) { var guid = Dmp.Util.getGuid(); var iframeId = "tmpIfrmeID" + guid; var formId = "tmpFormID" + guid; var divId = "tmpDivID" + guid; var _this = this; var iframe = null; var form = null; var observerMethod = null; this._iframeLoaded = function() { //remove iframe var tframe = document.getElementById(iframeId); var tform = document.getElementById(formId); var div = document.getElementById(divId); if (tframe == null || tform == null) return; tframe._REQ_OBJ = null; document.body.removeChild(div); //remove form document.body.removeChild(tform); //remove iframe //make request to the actual service now (serviceName) if (observerMethod) observerMethod(); } function createIFrame() { iframe = document.createElement("IFRAME"); var iframeDiv = document.createElement("div"); iframeDiv.id = divId; iframeDiv.style.display = 'none'; iframeDiv.style.visibility = 'hidden'; document.body.appendChild(iframeDiv); if (!document.all) { iframe.setAttribute("id", iframeId); iframe.setAttribute("NAME", iframeId); iframe.setAttribute("width", "0"); iframe.setAttribute("height", "0"); iframe.setAttribute("scrolling", "no"); iframe.setAttribute("onload", "javascript:_DEFAULT_LOAD_REQUEST_FRAME(\"" + iframeId + "\", \"" + formId + "\")"); iframeDiv.appendChild(iframe); //document.body.appendChild(iframe); } else { //for ie //iframeDiv.appendChild(iframe); iframeDiv.innerHTML = ""; } document.getElementById(iframeId)._REQ_OBJ = _this; } //createIFrame function createForm() { form = document.createElement("form"); form.setAttribute("id", formId); form.setAttribute("action", serviceName); form.setAttribute("method", "post"); form.setAttribute("target", iframeId); form.style.display = 'none'; form.style.visibility = 'hidden'; for (var key in paramHashtable) { var val = paramHashtable[key]; var fld = document.createElement("textarea"); fld.setAttribute("name", key); fld.name = key; fld.ID = key; fld.style.width = "1px"; fld.style.height = "1px"; fld.value = val; //fld.text = val; form.appendChild(fld); } document.body.appendChild(form); } //createForm this.execute = function(pObserverMethod) { observerMethod = pObserverMethod; createIFrame(); //First do POST to filewriterservice createForm(); form.submit(); }; //execute }; //Dmp.Util.DoPost function _DEFAULT_LOAD_REQUEST_FRAME(frameId, formId) { var f = document.getElementById(frameId); f._REQ_OBJ._iframeLoaded(); }; //Surface-Transformer Model implementation Dmp.Util.SurfaceTransformer = function() { var _self = this; this.surfaceObj = null; this.data = null; this.surfaceName = null; this.layerName = null; var mCacheDict = []; this.load = function(succCallback, errCallback) { var stName = _self.surfaceName + "_" + _self.layerName.replace("/", "_"); stName = stName.toUpperCase(); var url = Dmp.HostName + "GetFile.aspx?File=ACCOUNT_FOLDER/Transformers/" + stName + ".xml"; function _successXml(xml) { if (!_self) return; //_self can be set to null when canceled mCacheDict[url] = xml; var jqDom = Dmp.Util.parseXml(xml).find("Transformer"); var fields = jqDom.attr("Fields"); var type = jqDom.attr("Type"); var jsurl = Dmp.HostName + "GetFile.aspx?File=" + jqDom.attr("Url"); if (type != "js") throw new Dmp.Exception("Only js type is supported for now.") function jsLoaded() { try { mCacheDict[jsurl] = true; if (!_self) return; //_self can be set to null when canceled //Transformer JS file loaded var stObj = eval("new " + stName + "();"); stObj.transform(_self.surfaceObj, _self.data, succCallback, errCallback); } catch (ex) { alert("Error in transformer " + ex); } }; //jsLoaded //now load the JS file. //The JS file must contain a class called SurfaceName_LayerName_Transformer that has a transform(record) function if (mCacheDict[jsurl]) { jsLoaded(); } else { $.getScript(jsurl, jsLoaded, _err); } }; //_successXml function _errorXml(){ //Do default transformer var def = new Dmp.Util.DefaultTransformer(); def.transform(_self.surfaceObj, _self.data, succCallback, errCallback); };//_errorXml if (mCacheDict[url]) { _success(mCacheDict[url]); } else { Dmp.Util.getJson(url, _successXml, _errorXml); } }; //load this.cancel = function() { _self = null; }; //cancel function _err(e) { if (!_self) return; //_self can be set to null when canceled alert("Surface Transformer failed " + e.Response.Error.message); }; //_err }; //Dmp.Util.SurfaceTransformer Dmp.Util.DefaultTransformer = function(){ this.transform = function(surfaceObj, record, succCallback, errCallback){ var htm = ""; for (var key in record){ htm += key+": " + record[key]+ "
"; };//for key surfaceObj.html(htm); if (succCallback) succCallback(htm); };//transform };//Dmp.Util.DefaultTransformer Dmp.Core.WktTools.getGeoStructFromWkt = function(wktString) { // parses out points var regex = new RegExp(/(?:\()([^)(]*)(?:\))/g); var matches = regex.exec(wktString); var wktPoints = null; if (matches != null && matches.length > 0) { wktPoints = matches[0].substring(1, matches[0].length - 1); } // parses out type; regex = new RegExp(/[^(]*/g); var m1 = regex.exec(wktString); var geoType = null; if (m1 != null && m1.length > 0) { geoType = m1[0].replace(/ /, ''); } if (wktPoints == null || wktPoints == '' || geoType == null || geoType == '') return null; var pointTokens = wktPoints.split(","); var retArray = []; for (var i = 0; i < pointTokens.length; i++) { var twoValues = pointTokens[i].split(" "); twoValues = Dmp.Core.WktTools._deleteBlankStringFromArray(twoValues); if (twoValues.length != 2) throw "unsupported/malformatted wkt format:" + wktPoints; retArray.push({ x: parseFloat(twoValues[0]), y: parseFloat(twoValues[1]) }); } //for i return { Type: geoType, Points: retArray }; }; //getGeoStructFromWkt // given an array of strings, delete the ones with "", " ", or multiple blanks. Preserve the original order Dmp.Core.WktTools._deleteBlankStringFromArray = function(stringArray) { var retArray = []; for (var j = 0; j < stringArray.length; j++) { var isBlank = true; var arr = stringArray[j].split(" "); for (var k = 0; k < arr.length; k++) if (arr[k].length != 0) { isBlank = false; break; } if (!isBlank) { var v = stringArray[j]; //trim value v = v.replace(/\s*$/, ""); v = v.replace(/^\s*/, ""); retArray.push(v); } } return retArray; }; //_deleteBlankStringFromArray /** * Connection object allows application to do any kind of HTTP requests to the server. * 1. Checks if there is a need for direct request or a JSON request based on the crossdomain limitations. * 2. This class virtually allows us to send huge amount of data to the server in a crossdomain environment. (Its actually a POST followed by GET.) * @syntax: new Dmp.Core.Connection (String serviceUrl, Dictionary paramHashtable, Callback onSuccessMethod, Callback onErrorMethod); */ Dmp.Core.Connection = function(serviceUrl, paramHashtable, onSuccessMethod, onErrorMethod) { var MAX_GET_CHARACTERS_ALLOWED = 2000; //Source: http://www.boutell.com/newfaq/misc/urllength.html var _fName = serviceUrl.replace(/[^\w]+/g, ""); _fName += "_" + Dmp.Util.getGuid(); function _innerObs() { if (serviceUrl.indexOf("?") < 0) { serviceUrl += "?"; } else { serviceUrl += "&"; } serviceUrl += "_DMC_REQUEST_ID=" + _fName; Dmp.Util.getJson(serviceUrl, onSuccessMethod, onErrorMethod); } /* * This method will calculate the length of a url and determine the use of GET or POST request. * @syntax: void execute() * */ this.execute = function() { var completeUrl = Dmp.Util._constructUrlFromHashtable(serviceUrl, paramHashtable); //Is small enough for GET var isSmallEnoughForGet = completeUrl.length < MAX_GET_CHARACTERS_ALLOWED; if (isSmallEnoughForGet) { Dmp.Util.getJson(completeUrl, onSuccessMethod, onErrorMethod); } else { //find baseurl path var queIndex = serviceUrl.indexOf("?"); if (queIndex < 0) queIndex = serviceUrl.length; var slashIndex = serviceUrl.lastIndexOf("/", queIndex); var baseurl = serviceUrl.substring(0, slashIndex + 1); var fw = new Dmp.Util.FileWriter(baseurl); //Fallback. Do 2 phased request based on temporary file. fw.writeParams(_fName, paramHashtable, _innerObs); } }; //execute }; //Dmp.Core.Connection /** * A model class to construct relationship queries. @syntax: new Dmp.Core.Link (String linkName, String[] selectFields); */ Dmp.Core.Link = function(/*String*/linkName, /*String[]*/selectFields) { var mLinks = []; this.linkName = linkName; this.selectFields = selectFields ? selectFields : "*"; /* *@syntax: void addLink(Dmp.Core.Link link); */ this.addLink = function(/*Dmp.Core.Link*/link) { mLinks.push(link); }; //addLink /* *@syntax: String getQueryString(); */ this.getQueryString = function() { var q = this.linkName + "(" + this.selectFields; for (var i = 0; i < mLinks.length; i++) { var l = mLinks[i]; if (!l.getQueryString) continue; q += ", " + l.getQueryString(); } q += ")"; return q; }; //getQueryString };//Link Dmp.Core.DistanceUnit = { MILES: 1, KILOMETERS: 2, METERS: 3, FEET: 4 }; Dmp.Core.QueryModel = { GEOMETRY: 1, NONE: 2, CENTROID: 3, LABELPOINT: 3 }; Dmp.Core.SpatialCriteria = function() { this.dict = {}; this.addGeometry = function(wkt, criteria) { if (!criteria) criteria = Dmp.Core.SpatialCriteria.Overlaps; if (!this.dict[criteria]) this.dict[criteria] = []; this.dict[criteria].push(wkt); }; //addGeometry this.getWkt = function(criteria) { var arr = this.dict[criteria]; if (!arr || arr.length == 0) return null; var wkt = ""; for (var i = 0; i < arr.length; i++) { if (i > 1) wkt += ";"; wkt += arr[i]; } return wkt; }; //getWkt }; //SpatialCriteria Dmp.Core.SpatialCriteria.Overlaps = "T*T***T**"; Dmp.Core.SpatialCriteria.Exclude = "F*F***T*T"; Dmp.Core.SpatialCriteria.Nearest = "Nearest"; Dmp.Core.QueryService = { Identify: 1, BrowseData: 2}; Dmp.Core.QueryEngine = function(layerName) { var mLink = null; /*Dmp.Core.Link*/ this._getParams = function() { var paramArr = ["fields", "query", "recordFrom", "recordTo", "maxRecords", "minRecords", "geoBufferDist", "geoBufferUnit", "returnGeoType", "maxCacheSize", "activeVersionId", "transformer", "orderBy", "sortDir", "keyName", "keyValue", "prefix", "cache", "maxCacheSize", "indexFields", "customFields", "fieldTypes", "fieldLengths", "fieldValues", "viewInTime", "activeVersionId", "DMP_CANDY", "identify", "useRawIndex", "output", "keyField", "bbox", "pixx", "pixy", "Lat", "Long","attributeLinks" ]; return paramArr; }; //_getParam var mCacheDict = []; this.cacheResults = false; var _self = this; /* @syntax: void execute(Callback success, Callback error); */ this.execute = function(success, error) { var struct = this._getQueryStruct(); var cacheKey = null; if (_self.cacheResults) { cacheKey = Dmp.Util._constructUrlFromHashtable(struct.url, struct.dict); if (mCacheDict[cacheKey]) { //debugger; var params = mCacheDict[cacheKey]; success(params[0], params[1], params[2], params[3]); return; } } var req = new Dmp.Core.Connection(struct.url, struct.dict, function(p1, p2, p3, p4) { //following line compensates for the bug in our server code that convers XML to JSON. //if the row is returned as a non-array, I will convert it to an array. var resultsNode if (p1.Response && p1.Response.Results) resultsNode = p1.Response.Results; if (resultsNode) { if (resultsNode.Schema != null && resultsNode.RecordSet == null) { var rs = new Object(); rs.layer = layerName; rs.Schema = resultsNode.Schema; rs.Data = resultsNode.Data; resultsNode.RecordSet = [rs]; } else if (resultsNode.RecordSet.length == null) { //if not array, make array resultsNode.RecordSet = [resultsNode.RecordSet]; } //do the same for Row objects for (var i = 0; i < resultsNode.RecordSet.length; i++) { var dataNode = resultsNode.RecordSet[i].Data; if (dataNode && dataNode.Row && dataNode.Row.length == null) { dataNode.Row = [dataNode.Row]; } } //for i } if (_self.cacheResults) mCacheDict[cacheKey] = [p1, p2, p3, p4]; success(p1, p2, p3, p4); }, error); req.execute(); return req; }; //execute this.getQueryUrl = function() { var struct = this._getQueryStruct(); return struct.url; }; //getQueryUrl this._getQueryStruct = function() { var paramArr = this._getParams(); var paramDict = Dmp.Util._constructParamsDict(this, paramArr); paramDict["dataSource"] = layerName; //identify the service to call var useService = null; if (paramDict["query"]) { useService = "GetQuery.aspx"; } else if (paramDict["keyName"]) { useService = "GetByKey.aspx"; } else { useService = "GetByGeometry.aspx"; } if (this.spatialCriteria) { if (useService == "GetByKey.aspx") { paramDict["geoFilter"] = this.spatialCriteria.getWkt(Dmp.Core.SpatialCriteria.Overlaps); } else { var w; w = this.spatialCriteria.getWkt(Dmp.Core.SpatialCriteria.Overlaps); if (w) { paramDict["inclusionGeometries"] = w; } w = this.spatialCriteria.getWkt(Dmp.Core.SpatialCriteria.Exclude); if (w) { //currently only GetQuery support exclusion geometries paramDict["exclusionGeometries"] = w; useService = "GetQuery.aspx"; } w = this.spatialCriteria.getWkt(Dmp.Core.SpatialCriteria.Nearest); if (w) { paramDict["contextPoint"] = w; useService = "GetQuery.aspx"; //Only GetQuery supports context query } } } if (this.queryService) { if (this.queryService == Dmp.Core.QueryService.Identify) { useService = "Identify.aspx"; } else if (this.queryService == Dmp.Core.QueryService.BrowseData) { useService = "BrowseData.aspx"; } } if (this.identify == true) useService = "Identify.aspx"; //Add chaining criteria if (mLink) { if (!paramDict["fields"]) paramDict["fields"] = "*"; paramDict["fields"] += "," + mLink.getQueryString(); } //add cache=true if (this.cache) { paramDict["cache"] = "true" } var finalUrl = Dmp.HostName; if (this.tempId) { finalUrl = finalUrl.toLowerCase().replace(".com/", ".com/" + this.tempId.split("/")[0] + "/"); paramDict["tempId"] = this.tempId; } else if (layerName && layerName.indexOf("_T") == 0 && layerName.indexOf("/") > 0) { finalUrl += layerName.split("/")[0] + "/"; } finalUrl += useService; return { "url": finalUrl, "dict": paramDict }; }; //getQueryUrl /* @syntax: void addLink (Dmp.Core.Link link); */ this.addLink = function(/*Dmp.Core.Link*/link) { if (!mLink) mLink = link; else mLink.addLink(link); }; //addLink }; //QueryEngine //not fully implemented (6/14/2010) /* Dmp.Env = new function(){ var _self = this; var _resourcePool = new Object(); this.LayerReferences = new Object(); this.LayerReferences.getByKey = function(key) { return _resourcePool[key]; } this.LayerReferences.add = function(key, data) { _resourcePool[key] = data; } this._getLayerFromKey = function((key)) { return _self.Dictionary[key]; } this._setLayerReference = function((key, value)) { _self.Dictionary[key] = value; } } */ /* Dmp.Env.ResourcePool = new function() { var _self = this; var _resourcePool = new Object(); this.getByKey = function(key) { return _resourcePool[key]; } this.add = function(key, data) { _resourcePool[key] = data; } } */ //collection of Dmp.Conn.Connection objects /* Dmp.Env.Connections = new function() { } */ Dmp.Conn.Connection = function(initUrl) { var _self = this; //extract the base url (http://spatialstream.com) var _baseUrl = null; var parseHelper = initUrl.split("://"); if(parseHelper.length >= 2) { _baseUrl = parseHelper[0] + "://"; } parseHelper = parseHelper[1].split("/"); _baseUrl += parseHelper[0]; this.UserId = null; /** Returns the unique string everytime we call it. @syntax: public static String Dmp.Util.getGuid() */ function Dmp.Conn.Connection.getGuid(){ if (!Dmp.Conn.Connection._guidCount) Dmp.Conn.Connection._guidCount = 1; var tday = new Date(); var rand = Math.floor(Math.random() * 2000000000) return tday.getTime() + "" + rand + "" + Dmp.Conn.Connection._guidCount++; }; //getGuid this.getJson = function(jsonUrl, succCall, errCall, outputType) { // TODO : format of jsonUrl? (does it include protocol? domain? slashes? var MAX_WAIT_TIME = 2 * 1000; var timeoutThread = null; var callbackFunc = Dmp.Conn.Connection.getGuid(); var sucCallback = "S" + callbackFunc; var errCallback = "E" + callbackFunc; //Listener for script loader function _loadedURL() { if (timeoutThread == "done") return; //in case we got called multiple times, cancel the previous threads. if (timeoutThread) window.clearTimeout(timeoutThread); //start the timer. timeoutThread = window.setTimeout(function() { //Timeout error if (errCall) { var resp = { Response: { Error: { message: "Timeout"}} }; errCall(resp); } }, MAX_WAIT_TIME); } //_loadedURL function _clean() { if (timeoutThread) window.clearTimeout(timeoutThread); else timeoutThread = "done"; window[sucCallback] = null; window[errCallback] = null; }; //_clean //On Success window[sucCallback] = function(p1, p2, p3, p4) { _clean(); if (succCall) succCall(p1, p2, p3, p4); }; //succ //On Error window[errCallback] = function(p1, p2, p3, p4) { _clean(); if (errCall) errCall(p1, p2, p3, p4); }; //err var urlWithOid = jsonUrl; if (jsonUrl.indexOf("?") > 0) urlWithOid += "&"; else urlWithOid += "?"; urlWithOid += "obsId=window"; urlWithOid += "&obsSuccessMethod=" + sucCallback; urlWithOid += "&obsErrorMethod=" + errCallback; if (urlWithOid.indexOf("output=") < 0) { if (!outputType) outputType = "json"; urlWithOid += "&output=" + outputType; } //JQuery Call jQuery.getScript(urlWithOid, _loadedURL); } //getJson this.getBaseUrl = function() { return _baseUrl; } //getBaseUrl this.init = function(sik){ //future implementation //getJson function siSuccess(r){ _self.UserId = r.Response.Results.Data.Row.attr("UserId"); var tempDomains = r.Response.Resutls.Data.Row.attr("Domains"); tempDomains = tempDomains.split(","); for(var i = 0; i < tempDomains.length; i++) { _self.Domains.push(tempDomains[i]); } } function siFailure(err) { //exception } var key = sik; var _url = _self.getBaseUrl(); if(key.charAt(0) == "/") { //parse var parseHelper = key.split("/"); //append sub-domain if(_url.indexOf("://") != -1) { _url = _url.replace("://", "://" + parseHelper[1]); } else { _url = parseHelper[1] + _url; } //append post-domain _url += "/" + parseHelper[2]; //set key (sik) key = parseHelper[2] + "/" + parseHelper[3]; } _url += "/InitSession.aspx?sik=" + key; _self.getJson(_url, siSuccess, siFailure); } //init } //Dmp.Conn.Connection /* MapComposition object Irvine Gas Stations MY_FOLDER/IrvineGasStations 1 1 */ Dmp.Layers.MapComposition = function(map) { map._dmp_map_abstraction = new Dmp.Abstraction.Map(map); this.eventManager = new Dmp.Util.EventManager(); var _self = this; var mLayers = []; var mDom = null; var mLayerInfoDom = new Object(); this.load = function(jqDom) { mDom = jqDom; _self.eventManager.notify({ eventType: "BeforeLoad", source:_self }); //Get MapView box var mapViewNode = mDom.find("MapView"); if (mapViewNode) { var bbox = mapViewNode.attr("BBox"); if (bbox) { var coordinates = bbox.split(' '); if (coordinates.length == 4) { this.defaultView = { xmin: parseFloat(coordinates[0]), ymin: parseFloat(coordinates[1]), xmax: parseFloat(coordinates[2]), ymax: parseFloat(coordinates[3]) }; //Zoom to the default view map._dmp_map_abstraction.setView(this.defaultView.xmin, this.defaultView.ymin, this.defaultView.xmax, this.defaultView.ymax) } } } jqDom.find('Layer').each(function(i) { var resObj = new Dmp.Layers.Layer() resObj.loadNode($(this)); mLayers.push(resObj); //Add the layer on the Google/Bing map. map._dmp_map_abstraction.addLayer(resObj); }); //find(Layer) _self.eventManager.notify({ eventType: "AfterLoad", source: _self }); }; //load //param: Layer Name or Layer Object this.removeLayer = function(paramRes) { if (!paramRes) return false; var removeResObj = (typeof (paramRes) == "string") ? this.getLayerByName(paramRes) : paramRes; if (!removeResObj) return false; for (var i in mLayers) { if (mLayers[i] == removeResObj) { delete mLayers[i]; map._dmp_map_abstraction.removeLayer(removeResObj); break; } } //for i _self.eventManager.notify({ eventType: "RemoveLayer", source: _self, layer:removeResObj }); return true; }; //removeLayer //param: Supports layer specific draw or all draw this.draw = function(p) { map._dmp_map_abstraction.draw(p); }; //draw //Center the map on this layer this.setCenter = function(p) { if (mLayerInfoDom && mLayerInfoDom[p]) { var dom = mLayerInfoDom[p]; map._dmp_map_abstraction.setView(dom.xMin, dom.yMin, dom.xMax, dom.yMax); } else { //LayerInfo dom has not been loaded yet. Load it by calling LayerInfo.aspx var url = this.getLayerByName(p)._getHostName() + "LayerInfo.aspx?Layer=" + p; Dmp.Util.getJson(url, function(xml) { var dom = xml.Layer; mLayerInfoDom[p] = dom; map._dmp_map_abstraction.setView(dom.xMin, dom.yMin, dom.xMax, dom.yMax); }, function(err) { alert(err.Response.Error.message); }); } }; //setCenter this.addLayer = function(resObj) { if (!resObj.description) resObj.description = resObj.name; if (!resObj.geometrySource) resObj.geometrySource = resObj.name; if (!resObj.opacity) resObj.opacity = 1; if (typeof (resObj.visible) == 'undefined') resObj.visible = true; mLayers.push(resObj); //Add the layer on the Google/Bing map. map._dmp_map_abstraction.addLayer(resObj); _self.eventManager.notify({ eventType: "AddLayer", source: _self, layer: resObj}); }; //addLayer this.getLayers = function() { return mLayers; }; //getLayers //Removes all the layers from this mapcomposition this.clear = function() { _self.eventManager.notify({ eventType: "BeforeClear", source: _self}); while (mLayers.length>0) { var l = mLayers.pop(); map._dmp_map_abstraction.removeLayer(l); } _self.eventManager.notify({ eventType: "AfterClear", source: _self}); }; //clear this.getLayerByName = function(name) { if (!name) return null; for (var i in mLayers) { var res = mLayers[i]; if (res.name.toUpperCase() == name.toUpperCase()) return res; } }; //getLayerByName this.getShapeLayer = function() { return map._dmp_map_abstraction.getShapeLayer(); }; this.getBaseMap = function() { return map; }; }; /* [Resource for Geometry] Irvine Gas Stations MY_FOLDER/IrvineGasStations true/false 1 */ //Note: Steven, we need to fix this. Why do we need successCallback and errCallback?? Dmp.Layers.Layer = function(name, versionId) { var _self = this; var mLayerNode = null; this.visible = true; this.tempCache = true; this.tempId = null; if (name) { this.name = "" + name; this.uniqueId = this.name.replace(/[^a-zA-Z0-9]+/g, '') + Dmp.Util.getGuid(); } else { this.uniqueId = "Res" + Dmp.Util.getGuid(); } if (versionId) { this.versionId = versionId; } this.loadNode = function(layerNode) { mLayerNode = layerNode; //Read attributes from layer node this.name = layerNode.attr("Name"); this.type = layerNode.attr("Type"); if (layerNode.attr("NumServers")) this.numServers = parseInt(lNode.attr("NumServers")); if (layerNode.attr("ZIndex")) this.zIndex = parseInt(lNode.attr("ZIndex")); //Layer bounds are used as boundaries for this layer. //This property may not get respected for non tiled layers var boundsBox = layerNode.attr("Bounds"); if (boundsBox) { var coordinates = boundsBox.split(' '); if (coordinates.length == 4) { this.bounds = { xmin: parseFloat(coordinates[0]), ymin: parseFloat(coordinates[1]), xmax: parseFloat(coordinates[2]), ymax: parseFloat(coordinates[3]) }; } } //end if boundsBox for this layer this.visible = nodeVal(layerNode, "Visibility"); if (!this.visible) { var statusAttr = layerNode.attr("Status"); this.visible = statusAttr == "ON" || statusAttr == "On"; } else { this.visible = this.visible == "1" || this.visible == "true"; } this.description = nodeVal(layerNode, "Description"); if (!this.description) this.description = this.name; this.opacity = nodeVal(layerNode, "Opacity"); //this.data = nodeVal(layerNode, "Data"); this.sldUrl = nodeVal(layerNode, "Style"); this.uniqueId = this.name.replace(/[^a-zA-Z0-9]+/g, '') + Dmp.Util.getGuid(); //Use ZoomInLimit and ZoomOutLimit. //ZoomOutLimit ends at around 1. this.zoomOutLimit = nodeVal(layerNode, "ZoomOutLimit"); if (!this.zoomOutLimit) this.zoomOutLimit = nodeVal(layerNode, "ZoomMin"); //ZoomInLimit ends at around 19. this.zoomInLimit = nodeVal(layerNode, "ZoomInLimit"); if (!this.zoomInLimit) this.zoomInLimit = nodeVal(layerNode, "ZoomMax"); if (this.zoomInLimit) this.zoomInLimit = parseFloat("" + this.zoomInLimit); if (this.zoomOutLimit) this.zoomOutLimit = parseFloat("" + this.zoomOutLimit); this.hotspot = nodeVal(layerNode, "Hotspot"); if (this.hotspot == "true") { this.hotspot = true; this.hotspotField = nodeVal(layerNode, "HotspotField"); if (this.hotspot && !this.hotspotField) this.hotspotField = "_DMP_ID"; } else { this.hotspot = null; } this.versionId = nodeVal(layerNode, "VersionID"); this.color = nodeVal(layerNode, "Color"); this.fields = nodeVal(layerNode, "Fields"); //Setup GeometrySource and AttributeLinks //AttributeLink is a name of a link to a resource that has attributes for this layers geometry var geoSrcNode = layerNode.find("GeometrySource"); if (geoSrcNode) { this.geometrySource = geoSrcNode.text(); //If geometry source is defined, use if (this.geometrySource) { this.attributeLink = geoSrcNode.attr("LinkName"); } } else { //For backward compatibility this.geometrySource = nodeVal(layerNode, "Sublayers"); } if (!this.geometrySource) this.geometrySource = this.name; if (!this.attributeLink) this.attributeLink = nodeVal(layerNode, "AttributeLink"); }; //loadNode //returns JQuery node innerText function nodeVal(node, name) { node = node.find(name); return node ? node.text() : null; }; //nodeVal this._validateForView = function(currZoom) { //check visibility if (this.visible == false) return false; //check the zoom level. //currentZoom reduces as we zoom out. (19, 18, 17.....1) //currentZoom increases as we zoom in. (1, 2, 3, 4,.....19) if (((!this.zoomOutLimit || currZoom >= this.zoomOutLimit) && (!this.zoomInLimit || currZoom <= this.zoomInLimit))) return true; return false; }; //_validateForView this.load = function(successCallback, errCallback) { if (mLayerNode) { if (successCallback) successCallback(_self, mLayerNode); return; } if (!this.name) throw "The layer name must exist to load the layer"; var folder = this.name.substring(0, this.name.indexOf('/')); var url = _self._getHostName() + "BrowseLayers.aspx?folder="; url += folder; url += "&layersFilter=" + this.name; Dmp.Util.getJson(url, function(json) { var jqDom = Dmp.Util.parseXml(json); jqDom.find('Layer').each(function(i) { _self.loadNode($(this)); return; }); //find(Layer) if (successCallback) successCallback(_self, mLayerNode); }, errCallback, "jsonxml"); }; //load this.setMetadata = function(jqDom) { mLayerNode = jqDom; } this.getImageUrl = function(params, succCallback, errCallback) { var url = _self._getHostName() + "GetMap.aspx?"; if (params.xMin) { url += "bbox=" + params.xMin + "," + params.yMin + "," + params.xMax + "," + params.yMax; } else if (params.tileId) { url += "TileId=" + params.tileId; } var attList = { width: params.width, height: params.height, layers: this.geometrySource, activeVersionId: this.versionId, SLD: this.sldUrl, SLD_BODY: this.sldBody, attributeLinks: this.attributeLink, color: this.color, hideField: this.hideField, hideValues: this.hideValues, showField: this.showField, showValues: this.showValues, viewInTime: this.viewInTime, hotspot: this.hotspot, hotspotField: this.hotspotField, tempCache: this.tempCache, srs: this.srs ? "EPSG:" + this.srs : null, _guid: Dmp.Util.getGuid(), _dmp_debug: params._dmp_debug }; for (var attName in attList) { var v = attList[attName]; if (v) url += "&" + attName + "=" + encodeURIComponent(v); } if (this.tempCache == true && this.hotspot == true) { //if tempCache is true, we expect XML response back. Dmp.Util.getJson(url, function(json) { _self.tempId = json.Cache.TempId; //appending _=1 in the end to trick IIS into not giving us 404 var host = Dmp.HostName.toLowerCase().replace(".com/", ".com/" + _self.tempId.split("/")[0] + "/"); var imgUrl = host + "GetFile.aspx?File=" + json.Cache.TempId + "." + json.Cache.ImageType + "&_=1"; succCallback(imgUrl); /* if (_self.tempId) { //var imgUrl = Dmp.HostName + serverId + "/GetFile.aspx?File=" + json.Cache.TempId + "." + json.Cache.ImageType; var imgUrl = Dmp.HostName + "GetFile.aspx?File=" + json.Cache.TempId + "." + json.Cache.ImageType + "&_=1"; succCallback(imgUrl); } else { var imgUrl = Dmp.HostName + "GetFile.aspx?File=" + json.Cache.TempId + "." + json.Cache.ImageType + "&_=1"; succCallback(imgUrl); }*/ }, function(err) { //Error if (errCallback) errCallback(err); else alert("GetMap Failed:" + err.Response.Error.message); }); } else if (succCallback) { succCallback(url); } return url; }; //getImageUrl this._getHostName = function(){ var n = _self.tempId; if (!n) n = _self.name; if (n.indexOf("_T")!=0) return Dmp.HostName; var arr = n.split("/"); if (arr.length >1){ return Dmp.HostName + arr[0] + "/"; }else{ return Dmp.HostName; } };// this.getSchema = function() { return mLayerNode.find('Schema'); } this.getQueryEngine = function() { var q = new Dmp.Core.QueryEngine(this.name); q.fields = this.fields; return q; }; //getQueryEngine //Getting Legend Image: To display on the legend UI or on the printed map this.getLegendModel = function() { var legend = new Dmp.Layers.Legend(); legend.layer = this.name; legend.sld = this.sldUrl; legend.sld_body = this.sld_body; return legend; }; //getLegendModel //permissions this.setPermissions = function(p) { if (p == null) return; this._permissions = p.toUpperCase(); } this.isIdentifiable = function() { if (!this.hotspot) return false; if (this._permissions == null) return true; return this._permissions.indexOf("R") >= 0; } this.isQueriable = function() { if (this._permissions == null) return true; return this._permissions.indexOf("R") >= 0; } this.isEditable = function() { if (this._permissions == null) return true; return this._permissions.indexOf("W") >= 0; } this.isReadable = function() { if (this._permissions == null) return true; return this._permissions.indexOf("R") >= 0; } this.locate = function(posObj, succCallback, errCallback) { //the layer name may not be the resource name!! var q = this.getQueryEngine() q.returnGeoType = Dmp.Core.QueryModel.GEOMETRY; q.maxRecords = 3; q.queryService = Dmp.Core.QueryService.Identify; q.bbox = posObj.extents.xMin + "," + posObj.extents.yMin + "," + posObj.extents.xMax + "," + posObj.extents.yMax; q.pixx = posObj.pixX; q.pixy = posObj.pixY; q.Lat = posObj.lat; q.Long = posObj.lon; q.keyField = this.hotspotField; q.tempId = _self.tempId; //query for this geometry //q.spatialCriteria = new Dmp.Core.SpatialCriteria(); //q.spatialCriteria.addGeometry("POINT(" + posObj.lon + " " + posObj.lat + ")"); q.execute(succCallback, errCallback); return q; }; //locate /* if (records.Response.Results.Data != null) { var count = records.Response.Results.Data.Row.length; for (var i = 0; i < count; i++) locatedRecords.push(records.Response.Results.Data.Row[i]); } */ }; //Dmp.Layers.Layer Dmp.Layers.Legend = function() { this._getParams = function() { var paramArr = ["layer", "sld", "sld_body", "width", "height", "showSize", "bbox", "orientation", "labels", "headers", "swatchWidth", "swatchHeight", "swatchSpacing", "maxSwatches", "maxLabels", "rampWidth", "rampHeight", "full_path", "contextPoint", "xPath", "backgroundStyle", "query", "labelStyle", "headerStyle"]; return paramArr; }; //_getParam this.getUrl = function() { var paramArr = this._getParams(); var paramDict = Dmp.Util._constructParamsDict(this, paramArr); return Dmp.Util._constructUrlFromHashtable(Dmp.HostName + "Legend.aspx", paramDict); }; //getUrl }; //Legend Dmp.Identify.Identify = function() { var mLayers = []; var mActiveLayerName = null; var mStackObserver = null; var mLastPos = null; var PIXEL_TOLERANCE = 3; this.getStackObserver = function() { return mStackObserver; }; this.setLayers = function(l) { mLayers = l; if (l && l.length > 0 && l[0]) mActiveLayerName = mLayers[0].name; }; //addLayers this.getByKey = function(newPos, callback) { this.identify(newPos, callback); }; //getByKey this.identify = function(newPos, callback) { if (mLastPos) { var dist = Math.sqrt(Math.pow(newPos.pixX - mLastPos.pixX, 2) + Math.pow(newPos.pixY - mLastPos.pixY, 2)); if (dist <= PIXEL_TOLERANCE) { callback(mStackObserver); return; } } //cancel the previous request if (mStackObserver) { if (mStackObserver.cancelable) mStackObserver.cancel(); else return; } mLastPos = newPos; mStackObserver = new Dmp.Identify.Stack(this); for (var i = 0; mLayers && i < mLayers.length; i++) { if (!mLayers[i] || !mLayers[i].isIdentifiable()) continue; if (!mActiveLayerName) this.setActiveLayer(mLayers[i].name); mStackObserver.addLayer(mLayers[i]); } mStackObserver.identify(newPos, callback); }; //identify /* Sets the active layer for the identify. The active layer will be the first to be displayed * @param {string} layerName The layer to set as the active layer */ this.setActiveLayer = function(layerName) { if (typeof (layerName) != "string") layerName = layerName.name; mActiveLayerName = layerName.toUpperCase(); }; this.getActiveLayerName = function() { return mActiveLayerName; }; //get name }; //Dmp.Identify.Identify Dmp.Identify.Stack = function(mIdentify) { var _self = this; var mLayers = []; var canceled = false; this.cancelable = true; var mResultsArr = []; this.getActiveRecord = function() { var actResults = this.getActiveResults(); if (!actResults || !actResults.records || actResults.records.length == 0) return null; return actResults.records[0]; }; //getActiveRecord this.getActiveLayer = function() { var actResults = this.getActiveResults(); if (!actResults) return null; return actResults.layer; }; // this.identify = function(pos, callback) { if (getCount() == 0) callback(_self); for (var n in mLayers) { if (canceled) return; locate(n, mLayers[n], pos, callback); } //for n }; //identify function locate(n, l, pos, callback) { mResultsArr = []; if (pos.waitFor) window.setTimeout(_innerLocate, pos.waitFor); else _innerLocate(); function _innerLocate() { if (canceled) return; l.locate(pos, _success, _err); function _success(data) { //locate callback if (canceled) return; mResultsArr[l.name.toUpperCase()] = _getResObj(l, data); delete mLayers[n]; if (getCount() == 0) { callback(_self); } }; //_success function _err(e) { alert(e.Response.Error.message); }; //_err }; //_innerLocate }; //locate //---------- State functions ------------ this.cancel = function() { canceled = true; mLayers = []; }; //cancel this.addLayer = function(l) { if (canceled) return; mLayers[l.name.toUpperCase()] = l; }; //addLayer this.isDone = function() { return getCount() == 0; }; function getCount() { var i = 0; for (var n in mLayers) { i++; }; //for mLayers return i; }; //getCount this.getActiveResults = function() { var activeLayerName = mIdentify.getActiveLayerName(); if (activeLayerName) activeLayerName = activeLayerName.toUpperCase(); return mResultsArr[activeLayerName]; }; //getActiveResults function _getResObj(lObj, jsonResponse) { var returnObj = { layer: lObj }; var dataNode = jsonResponse.Response.Results.RecordSet[0].Data; if (dataNode) returnObj.records = dataNode.Row; return returnObj; }; //_getResObj }; //Dmp.Identify.Stack //For Bing Map Dmp.Abstraction.Map = function(vemap) { var self = this; var mDict = {}; var mMapDiv = document.getElementById(vemap.ID).firstChild; vemap.AttachEvent("onchangeview", onViewChange); //var shapeLayer = new Dmp.Abstraction.ShapeLayer(map); this.setView = function(xmin, ymin, xmax, ymax) { var locs = new Array; locs.push(new VELatLong(ymin, xmin)); locs.push(new VELatLong(ymin, xmax)); locs.push(new VELatLong(ymax, xmax)); locs.push(new VELatLong(ymax, xmin)); vemap.SetMapView(locs); }; this.addLayer = function(res) { if (!res.visible) return; if (res.type == "Tile") { var url = res.getImageUrl({ tileId: "%4" }); var t = new VETileSourceSpecification(res.uniqueId, url); if (res.numServers) t.NumServers = res.numServers //if (res.bounds) t.Bounds = [new VELatLongRectangle(new VELatLong(49, -123), new VELatLong(47, -121))]; if (res.zoomOutLimit) t.MinZoomLevel = res.zoomOutLimit; if (res.zoomInLimit) t.MaxZoomLevel = res.zoomInLimit; if (res.opacity) t.Opacity = res.opacity; if (res.zIndex) t.ZIndex = res.zIndex; mDict[res.uniqueId] = { TileSpec: t, ResObj: res }; vemap.AddTileLayer(t, true); } else { var imgTag = document.createElement("img"); imgTag.setAttribute("id", res.uniqueId); imgTag.id = res.uniqueId; mMapDiv.appendChild(imgTag); mDict[res.uniqueId] = { ImgObj: imgTag, ResObj: res }; reloadLayer(res.uniqueId); } }; //addLayer this.removeLayer = function(resObj) { var lObj = mDict[resObj.uniqueId]; var imgTag = lObj?lObj.ImgObj:null; if (imgTag) { //Delete for Wms Layer mMapDiv.removeChild(imgTag); } else if(vemap.GetTileLayerByID(resObj.uniqueId)) { //Delete for Tiled Layer vemap.DeleteTileLayer(resObj.uniqueId); } delete mDict[resObj.uniqueId]; }; this.draw = function(p) { if (p == null) { //Render all layers onViewChange(); } else { //render a specific layer with uniqueId p. reloadLayer(typeof (p) == "string" ? p : p.uniqueId); } }; //draw function onViewChange() { for (var uniqueId in mDict) { reloadLayer(uniqueId); } //for mDict }; //onViewChange function reloadLayer(uniqueId) { var mapWidth = vemap.GetWidth(); var mapHeight = vemap.GetHeight(); var res = mDict[uniqueId].ResObj; var imgTag = mDict[uniqueId].ImgObj; var view = vemap.GetMapView(); var params = { xMin: view.TopLeftLatLong.Longitude, yMin: view.BottomRightLatLong.Latitude, xMax: view.BottomRightLatLong.Longitude, yMax: view.TopLeftLatLong.Latitude, width: mapWidth, height: mapHeight }; //Validate with the layer object if (res._validateForView(vemap.GetZoomLevel())) { //Got approval to show the map if (!imgTag) { //Show the Tiled Layer vemap.ShowTileLayer(uniqueId); } else { function _imgUrlReady(imgUrl) { //Show the Wms Layer $(imgTag).show(); var preloadImg = new Image(); $(preloadImg).load(function() { //GetMap Image downloaded completely. resetImgTag(uniqueId, res, imgUrl, mapWidth, mapHeight); //All cookies should be set now. //debugger; //var hscookie = Dmp.Util.getCookie("HS_" + res.name.replace("/", "_")); //if (hscookie) debugger; }); preloadImg.src = imgUrl; }; //_imgUrlReady res.getImageUrl(params, _imgUrlReady); } } else { //Layer object validation failed for this view try { var imgTag = mDict[uniqueId].ImgObj; if (imgTag) { //Hide the Wms Layer $(imgTag).hide(); } else { //Hide the Tiled Layer vemap.HideTileLayer(uniqueId); } } catch (ex) { } } }; //reloadLayer function resetImgTag(uniqueId, res, url, mapWidth, mapHeight) { var imgTag = mDict[uniqueId].ImgObj; imgTag.setAttribute("src", url); var topOffset = 0 - parseInt(mMapDiv.style.top); var leftOffset = 0 - parseInt(mMapDiv.style.left); var imgTag = mDict[uniqueId].ImgObj; imgTag.style.left = leftOffset + "px"; imgTag.style.top = topOffset + "px"; imgTag.style.position = "absolute"; imgTag.style.width = mapWidth + "px"; imgTag.style.height = mapHeight + "px"; imgTag.style.opacity = res.opacity; if (res.opacity < 1) { imgTag.style.filter = "alpha(opacity=" + (res.opacity * 100) + ")"; } if (res.zIndex) imgTag.style.zIndex = res.zIndex; else imgTag.style.zIndex = 2; }; //resetImgTag /* this.getShapeLayer = function() { return shapeLayer; }; */ }; //Dmp.Abstraction.Map /* Dmp.Abstraction.ShapeLayer = function(map, shapeLayer) { var _shapeLayer = shapeLayer?shapeLayer:new VEShapeLayer(); //mapComp?mapComp.getShapeLayer():null; map.AddShapeLayer(_shapeLayer); this.drawShape = function(geo) { var veShape = Dmp.Core.WktTools.toShape(result.GEOMETRY ); if(veShape.GetType() == VEShapeType.Pushpin) veShape.SetCustomIcon("http://www.spatialstream.com/images/sscircle.png"); veShape.SetDescription(output); veShape.HideIcon(); map.AddShape(veShape); return veShape; } this.showBalloon = function(shape) { map.ShowInfoBox(shape); } this.clearShapes = function() { map.DeleteAllShapes(); } }*/ //For Bing Map Dmp.Map.EventManager = function(veMap) { //this.base = Dmp.Util.EventManager; //this.base(); var mVEDivOffset = $("#" + veMap.ID).offset(); this.addCallback = function(event, callback) { if (event == "onmousepause") { var po = new _PauseHandler(callback); veMap.AttachEvent("onmousemove", po.moved); veMap.AttachEvent("onmouseout", po.clear); veMap.AttachEvent("onmouseleave", po.clear); veMap.AttachEvent("onmousedown", po.clear); } else { veMap.AttachEvent(event, function(e) { callback(getEventObj(e)); }); } }; //addCallback function _PauseHandler(callback) { var t; var lastX, lastY; this.moved = function(e) { if (lastX && lastY && e.mapX == lastX && e.mapY == lastY) return; lastX = e.mapX; lastY = e.mapY; var clonedEvt = cloneVeEvent(e); if (t) window.clearTimeout(t); t = window.setTimeout(function() { callback(getEventObj(clonedEvt)); }, 500); } this.clear = function(e) { if (t) window.clearTimeout(t); } }; //_PauseHandler function cloneVeEvent(e) { var newE = new Object(); newE.pageX = e.pageX; newE.pageY = e.pageY; newE.clientX = e.clientX; newE.clientY = e.clientY; return newE; }; //cloneVeEvent function getEventObj(e) { if (e.pageX == null && e.clientX) e.pageX = e.clientX; if (e.pageY == null && e.clientY) e.pageY = e.clientY; //Consider the browser scroll position. try { //if (e.pageX != null && e.pageX == e.clientX) e.pageX += $(document).scrollLeft(); //if (e.pageY != null && e.pageY == e.clientY) e.pageY += $(document).scrollTop(); } catch (ex) { } //ignore error. var pixOnMap = { x: (e.pageX - mVEDivOffset.left), y: (e.pageY - mVEDivOffset.top) }; var absXY = { x: e.pageX, y: e.pageY }; var latlon = veMap.PixelToLatLong(new VEPixel(pixOnMap.x, pixOnMap.y)); var evtObj = { pixX: pixOnMap.x, pixY: pixOnMap.y, absX: absXY.x, absY: absXY.y, lon: latlon.Longitude, lat: latlon.Latitude, extents: {} }; var view = veMap.GetMapView(); evtObj.extents.xMin = view.TopLeftLatLong.Longitude; evtObj.extents.yMin = view.BottomRightLatLong.Latitude; evtObj.extents.xMax = view.BottomRightLatLong.Longitude; evtObj.extents.yMax = view.TopLeftLatLong.Latitude; evtObj.date = new Date(); return evtObj; }; //getEventObj }; //Dmp.Map.EventManager //Dmp.Map.EventManager.prototype = new Dmp.Util.EventManager(); //For Bing Map Dmp.Core.WktTools.toShape = function(wktString) { var geoStruct = Dmp.Core.WktTools.getGeoStructFromWkt(wktString); var vePoints = []; for (var i = 0; i < geoStruct.Points.length; i++) { vePoints.push(new VELatLong(geoStruct.Points[i].y, geoStruct.Points[i].x)); } if (geoStruct.Type == "POINT") { if (vePoints.length != 1) throw null; return new VEShape(VEShapeType.Pushpin, vePoints[0]); } else if (geoStruct.Type == "LINESTRING") { if (vePoints.length < 2) throw null; return new VEShape(VEShapeType.Polyline, vePoints); } else if (geoStruct.Type == "POLYGON" || geoStruct.Type == "MULTIPOLYGON") { if (vePoints.length < 3) throw null; return new VEShape(VEShapeType.Polygon, vePoints); } else if (geoStruct.Type == "CIRCLE") { if (vePoints.length < 2) throw null; return new VEShape(VEShapeType.Pushpin, vePoints[0]); } else { return null; } } //Dmp.Core.WktTools if (typeof(Dmp.Env) == 'undefined') Dmp.Env = new Object(); if (typeof(Dmp.Env.Connections) == 'undefined') Dmp.Env.Connections = new Object(); Dmp.Env.Connections["SS"] = new Dmp.Conn.Connection("http://parcelstream.com/InitSession.aspx", ["t0", "t1", "t2", "t3"]);