From 272204a84ca15be7c13d2984897fe26b1f3cc18d Mon Sep 17 00:00:00 2001 From: Ryan Morrison~Westphal Date: Thu, 14 Jul 2016 23:43:10 -0400 Subject: [PATCH] #221 - removing historic builds from dist --- Gruntfile.js | 2 +- dist/jquery.geo-1.0.0-b1.5.js | 7224 ---------------- dist/jquery.geo-1.0.0-b1.5.min.js | 4 - dist/jquery.geo-1.0.0-b2.js | 7245 ---------------- dist/jquery.geo-1.0.0-b2.min.js | 6 - dist/jquery.geo-1.0.0-b3.2.js | 7515 ---------------- dist/jquery.geo-1.0.0-b3.2.min.js | 7 - dist/jquery.geo-1.0.0-b3.js | 7515 ---------------- dist/jquery.geo-1.0.0-b3.min.js | 7 - dist/jquery.geo-1.0.0-rc1.1.min.js | 7 - dist/jquery.geo-1.0.0-rc1.js | 7522 ----------------- dist/jquery.geo-1.0.0-rc1.min.js | 7 - dist/jquery.geo-1.0.0-test.js | 7522 ----------------- dist/jquery.geo-1.0.0-test.min.js | 7 - dist/jquery.geo-1.0a3.js | 4826 ----------- dist/jquery.geo-1.0a3.min.js | 128 - dist/jquery.geo-1.0a4.js | 6233 -------------- dist/jquery.geo-1.0a4.min.js | 171 - dist/jquery.geo-1.0b1.1.js | 6956 --------------- dist/jquery.geo-1.0b1.1.min.js | 4 - dist/jquery.geo-1.0b1.5.js | 7224 ---------------- dist/jquery.geo-1.0b1.js | 6943 --------------- dist/jquery.geo-1.0b1.min.js | 4 - ...query.geo-1.0.0-rc1.1.js => jquery.geo.js} | 8 +- dist/jquery.geo.min.js | 7 + 25 files changed, 12 insertions(+), 77082 deletions(-) delete mode 100644 dist/jquery.geo-1.0.0-b1.5.js delete mode 100644 dist/jquery.geo-1.0.0-b1.5.min.js delete mode 100644 dist/jquery.geo-1.0.0-b2.js delete mode 100644 dist/jquery.geo-1.0.0-b2.min.js delete mode 100644 dist/jquery.geo-1.0.0-b3.2.js delete mode 100644 dist/jquery.geo-1.0.0-b3.2.min.js delete mode 100644 dist/jquery.geo-1.0.0-b3.js delete mode 100644 dist/jquery.geo-1.0.0-b3.min.js delete mode 100644 dist/jquery.geo-1.0.0-rc1.1.min.js delete mode 100644 dist/jquery.geo-1.0.0-rc1.js delete mode 100644 dist/jquery.geo-1.0.0-rc1.min.js delete mode 100644 dist/jquery.geo-1.0.0-test.js delete mode 100644 dist/jquery.geo-1.0.0-test.min.js delete mode 100644 dist/jquery.geo-1.0a3.js delete mode 100644 dist/jquery.geo-1.0a3.min.js delete mode 100644 dist/jquery.geo-1.0a4.js delete mode 100644 dist/jquery.geo-1.0a4.min.js delete mode 100644 dist/jquery.geo-1.0b1.1.js delete mode 100644 dist/jquery.geo-1.0b1.1.min.js delete mode 100644 dist/jquery.geo-1.0b1.5.js delete mode 100644 dist/jquery.geo-1.0b1.js delete mode 100644 dist/jquery.geo-1.0b1.min.js rename dist/{jquery.geo-1.0.0-rc1.1.js => jquery.geo.js} (99%) create mode 100644 dist/jquery.geo.min.js diff --git a/Gruntfile.js b/Gruntfile.js index dd9a665..7c0d2e0 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -13,7 +13,7 @@ module.exports = function(grunt) { ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n', // Task configuration. clean: { - files: ['dist/<%= pkg.name %>-<%= pkg.version %>.js', 'dist/<%= pkg.name %>-<%= pkg.version %>.min.js'] + files: ['dist/<%= pkg.name %>.js', 'dist/<%= pkg.name %>.min.js'] }, concat: { options: { diff --git a/dist/jquery.geo-1.0.0-b1.5.js b/dist/jquery.geo-1.0.0-b1.5.js deleted file mode 100644 index 0e4a7eb..0000000 --- a/dist/jquery.geo-1.0.0-b1.5.js +++ /dev/null @@ -1,7224 +0,0 @@ -/*! jQuery Geo - v1.0.0-b1.5 - 2013-01-17 - * http://jquerygeo.com - * Copyright (c) 2013 Ryan Westphal/Applied Geographics, Inc.; Licensed MIT, GPL */ - -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -// Known Issues: -// -// * Patterns only support repeat. -// * Radial gradient are not implemented. The VML version of these look very -// different from the canvas one. -// * Clipping paths are not implemented. -// * Coordsize. The width and height attribute have higher priority than the -// width and height style values which isn't correct. -// * Painting mode isn't implemented. -// * Canvas width/height should is using content-box by default. IE in -// Quirks mode will draw the canvas using border-box. Either change your -// doctype to HTML5 -// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) -// or use Box Sizing Behavior from WebFX -// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) -// * Non uniform scaling does not correctly scale strokes. -// * Optimize. There is always room for speed improvements. - -// Only add this code if we do not already have a canvas implementation -if (!document.createElement('canvas').getContext) { - - (function () { - - // alias some functions to make (compiled) code shorter - var m = Math; - var mr = m.round; - var ms = m.sin; - var mc = m.cos; - var abs = m.abs; - var sqrt = m.sqrt; - - // this is used for sub pixel precision - var Z = 10; - var Z2 = Z / 2; - - var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; - - /** - * This funtion is assigned to the elements as element.getContext(). - * @this {HTMLElement} - * @return {CanvasRenderingContext2D_} - */ - function getContext() { - return this.context_ || - (this.context_ = new CanvasRenderingContext2D_(this)); - } - - var slice = Array.prototype.slice; - - /** - * Binds a function to an object. The returned function will always use the - * passed in {@code obj} as {@code this}. - * - * Example: - * - * g = bind(f, obj, a, b) - * g(c, d) // will do f.call(obj, a, b, c, d) - * - * @param {Function} f The function to bind the object to - * @param {Object} obj The object that should act as this when the function - * is called - * @param {*} var_args Rest arguments that will be used as the initial - * arguments when the function is called - * @return {Function} A new function that has bound this - */ - function bind(f, obj, var_args) { - var a = slice.call(arguments, 2); - return function () { - return f.apply(obj, a.concat(slice.call(arguments))); - }; - } - - function encodeHtmlAttribute(s) { - return String(s).replace(/&/g, '&').replace(/"/g, '"'); - } - - function addNamespace(doc, prefix, urn) { - if (!doc.namespaces[prefix]) { - doc.namespaces.add(prefix, urn, '#default#VML'); - } - } - - function addNamespacesAndStylesheet(doc) { - addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); - addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); - - // Setup default CSS. Only add one style sheet per document - if (!doc.styleSheets['ex_canvas_']) { - var ss = doc.createStyleSheet(); - ss.owningElement.id = 'ex_canvas_'; - ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + - // default size is 300x150 in Gecko and Opera - 'text-align:left;width:300px;height:150px}'; - } - } - - // Add namespaces and stylesheet at startup. - addNamespacesAndStylesheet(document); - - var G_vmlCanvasManager_ = { - init: function (opt_doc) { - var doc = opt_doc || document; - // Create a dummy element so that IE will allow canvas elements to be - // recognized. - doc.createElement('canvas'); - doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); - }, - - init_: function (doc) { - // find all canvas elements - var els = doc.getElementsByTagName('canvas'); - for (var i = 0; i < els.length; i++) { - this.initElement(els[i]); - } - }, - - /** - * Public initializes a canvas element so that it can be used as canvas - * element from now on. This is called automatically before the page is - * loaded but if you are creating elements using createElement you need to - * make sure this is called on the element. - * @param {HTMLElement} el The canvas element to initialize. - * @return {HTMLElement} the element that was created. - */ - initElement: function (el) { - if (!el.getContext) { - el.getContext = getContext; - - // Add namespaces and stylesheet to document of the element. - addNamespacesAndStylesheet(el.ownerDocument); - - // Remove fallback content. There is no way to hide text nodes so we - // just remove all childNodes. We could hide all elements and remove - // text nodes but who really cares about the fallback content. - el.innerHTML = ''; - - // do not use inline function because that will leak memory - el.attachEvent('onpropertychange', onPropertyChange); - el.attachEvent('onresize', onResize); - - var attrs = el.attributes; - if (attrs.width && attrs.width.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setWidth_(attrs.width.nodeValue); - el.style.width = attrs.width.nodeValue + 'px'; - } else { - el.width = el.clientWidth; - } - if (attrs.height && attrs.height.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setHeight_(attrs.height.nodeValue); - el.style.height = attrs.height.nodeValue + 'px'; - } else { - el.height = el.clientHeight; - } - //el.getContext().setCoordsize_() - } - return el; - } - }; - - function onPropertyChange(e) { - var el = e.srcElement; - - switch (e.propertyName) { - case 'width': - el.getContext().clearRect(); - el.style.width = el.attributes.width.nodeValue + 'px'; - // In IE8 this does not trigger onresize. - el.firstChild.style.width = el.clientWidth + 'px'; - break; - case 'height': - el.getContext().clearRect(); - el.style.height = el.attributes.height.nodeValue + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - break; - } - } - - function onResize(e) { - var el = e.srcElement; - if (el.firstChild) { - el.firstChild.style.width = el.clientWidth + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - } - } - - G_vmlCanvasManager_.init(); - - // precompute "00" to "FF" - var decToHex = []; - for (var i = 0; i < 16; i++) { - for (var j = 0; j < 16; j++) { - decToHex[i * 16 + j] = i.toString(16) + j.toString(16); - } - } - - function createMatrixIdentity() { - return [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1] - ]; - } - - function matrixMultiply(m1, m2) { - var result = createMatrixIdentity(); - - for (var x = 0; x < 3; x++) { - for (var y = 0; y < 3; y++) { - var sum = 0; - - for (var z = 0; z < 3; z++) { - sum += m1[x][z] * m2[z][y]; - } - - result[x][y] = sum; - } - } - return result; - } - - function copyState(o1, o2) { - o2.fillStyle = o1.fillStyle; - o2.lineCap = o1.lineCap; - o2.lineJoin = o1.lineJoin; - o2.lineWidth = o1.lineWidth; - o2.miterLimit = o1.miterLimit; - o2.shadowBlur = o1.shadowBlur; - o2.shadowColor = o1.shadowColor; - o2.shadowOffsetX = o1.shadowOffsetX; - o2.shadowOffsetY = o1.shadowOffsetY; - o2.strokeStyle = o1.strokeStyle; - o2.globalAlpha = o1.globalAlpha; - o2.font = o1.font; - o2.textAlign = o1.textAlign; - o2.textBaseline = o1.textBaseline; - o2.arcScaleX_ = o1.arcScaleX_; - o2.arcScaleY_ = o1.arcScaleY_; - o2.lineScale_ = o1.lineScale_; - } - - // var colorData = { - // aliceblue: '#F0F8FF', - // antiquewhite: '#FAEBD7', - // aquamarine: '#7FFFD4', - // azure: '#F0FFFF', - // beige: '#F5F5DC', - // bisque: '#FFE4C4', - // black: '#000000', - // blanchedalmond: '#FFEBCD', - // blueviolet: '#8A2BE2', - // brown: '#A52A2A', - // burlywood: '#DEB887', - // cadetblue: '#5F9EA0', - // chartreuse: '#7FFF00', - // chocolate: '#D2691E', - // coral: '#FF7F50', - // cornflowerblue: '#6495ED', - // cornsilk: '#FFF8DC', - // crimson: '#DC143C', - // cyan: '#00FFFF', - // darkblue: '#00008B', - // darkcyan: '#008B8B', - // darkgoldenrod: '#B8860B', - // darkgray: '#A9A9A9', - // darkgreen: '#006400', - // darkgrey: '#A9A9A9', - // darkkhaki: '#BDB76B', - // darkmagenta: '#8B008B', - // darkolivegreen: '#556B2F', - // darkorange: '#FF8C00', - // darkorchid: '#9932CC', - // darkred: '#8B0000', - // darksalmon: '#E9967A', - // darkseagreen: '#8FBC8F', - // darkslateblue: '#483D8B', - // darkslategray: '#2F4F4F', - // darkslategrey: '#2F4F4F', - // darkturquoise: '#00CED1', - // darkviolet: '#9400D3', - // deeppink: '#FF1493', - // deepskyblue: '#00BFFF', - // dimgray: '#696969', - // dimgrey: '#696969', - // dodgerblue: '#1E90FF', - // firebrick: '#B22222', - // floralwhite: '#FFFAF0', - // forestgreen: '#228B22', - // gainsboro: '#DCDCDC', - // ghostwhite: '#F8F8FF', - // gold: '#FFD700', - // goldenrod: '#DAA520', - // grey: '#808080', - // greenyellow: '#ADFF2F', - // honeydew: '#F0FFF0', - // hotpink: '#FF69B4', - // indianred: '#CD5C5C', - // indigo: '#4B0082', - // ivory: '#FFFFF0', - // khaki: '#F0E68C', - // lavender: '#E6E6FA', - // lavenderblush: '#FFF0F5', - // lawngreen: '#7CFC00', - // lemonchiffon: '#FFFACD', - // lightblue: '#ADD8E6', - // lightcoral: '#F08080', - // lightcyan: '#E0FFFF', - // lightgoldenrodyellow: '#FAFAD2', - // lightgreen: '#90EE90', - // lightgrey: '#D3D3D3', - // lightpink: '#FFB6C1', - // lightsalmon: '#FFA07A', - // lightseagreen: '#20B2AA', - // lightskyblue: '#87CEFA', - // lightslategray: '#778899', - // lightslategrey: '#778899', - // lightsteelblue: '#B0C4DE', - // lightyellow: '#FFFFE0', - // limegreen: '#32CD32', - // linen: '#FAF0E6', - // magenta: '#FF00FF', - // mediumaquamarine: '#66CDAA', - // mediumblue: '#0000CD', - // mediumorchid: '#BA55D3', - // mediumpurple: '#9370DB', - // mediumseagreen: '#3CB371', - // mediumslateblue: '#7B68EE', - // mediumspringgreen: '#00FA9A', - // mediumturquoise: '#48D1CC', - // mediumvioletred: '#C71585', - // midnightblue: '#191970', - // mintcream: '#F5FFFA', - // mistyrose: '#FFE4E1', - // moccasin: '#FFE4B5', - // navajowhite: '#FFDEAD', - // oldlace: '#FDF5E6', - // olivedrab: '#6B8E23', - // orange: '#FFA500', - // orangered: '#FF4500', - // orchid: '#DA70D6', - // palegoldenrod: '#EEE8AA', - // palegreen: '#98FB98', - // paleturquoise: '#AFEEEE', - // palevioletred: '#DB7093', - // papayawhip: '#FFEFD5', - // peachpuff: '#FFDAB9', - // peru: '#CD853F', - // pink: '#FFC0CB', - // plum: '#DDA0DD', - // powderblue: '#B0E0E6', - // rosybrown: '#BC8F8F', - // royalblue: '#4169E1', - // saddlebrown: '#8B4513', - // salmon: '#FA8072', - // sandybrown: '#F4A460', - // seagreen: '#2E8B57', - // seashell: '#FFF5EE', - // sienna: '#A0522D', - // skyblue: '#87CEEB', - // slateblue: '#6A5ACD', - // slategray: '#708090', - // slategrey: '#708090', - // snow: '#FFFAFA', - // springgreen: '#00FF7F', - // steelblue: '#4682B4', - // tan: '#D2B48C', - // thistle: '#D8BFD8', - // tomato: '#FF6347', - // turquoise: '#40E0D0', - // violet: '#EE82EE', - // wheat: '#F5DEB3', - // whitesmoke: '#F5F5F5', - // yellowgreen: '#9ACD32' - // }; - - - function getRgbHslContent(styleString) { - var start = styleString.indexOf('(', 3); - var end = styleString.indexOf(')', start + 1); - var parts = styleString.substring(start + 1, end).split(','); - // add alpha if needed - if (parts.length != 4 || styleString.charAt(3) != 'a') { - parts[3] = 1; - } - return parts; - } - - function percent(s) { - return parseFloat(s) / 100; - } - - function clamp(v, min, max) { - return Math.min(max, Math.max(min, v)); - } - - function hslToRgb(parts) { - var r, g, b, h, s, l; - h = parseFloat(parts[0]) / 360 % 360; - if (h < 0) - h++; - s = clamp(percent(parts[1]), 0, 1); - l = clamp(percent(parts[2]), 0, 1); - if (s == 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1 / 3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1 / 3); - } - - return '#' + decToHex[Math.floor(r * 255)] + - decToHex[Math.floor(g * 255)] + - decToHex[Math.floor(b * 255)]; - } - - function hueToRgb(m1, m2, h) { - if (h < 0) - h++; - if (h > 1) - h--; - - if (6 * h < 1) - return m1 + (m2 - m1) * 6 * h; - else if (2 * h < 1) - return m2; - else if (3 * h < 2) - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - else - return m1; - } - - var processStyleCache = {}; - - function processStyle(styleString) { - if (styleString in processStyleCache) { - return processStyleCache[styleString]; - } - - var str, alpha = 1; - - styleString = String(styleString); - if (styleString.charAt(0) == '#') { - str = styleString; - } else if (/^rgb/.test(styleString)) { - var parts = getRgbHslContent(styleString); - var str = '#', n; - for (var i = 0; i < 3; i++) { - if (parts[i].indexOf('%') != -1) { - n = Math.floor(percent(parts[i]) * 255); - } else { - n = +parts[i]; - } - str += decToHex[clamp(n, 0, 255)]; - } - alpha = +parts[3]; - } else if (/^hsl/.test(styleString)) { - var parts = getRgbHslContent(styleString); - str = hslToRgb(parts); - alpha = parts[3]; - } else { - str = /*colorData[styleString] ||*/styleString; - } - return processStyleCache[styleString] = { color: str, alpha: alpha }; - } - - var DEFAULT_STYLE = { - style: 'normal', - variant: 'normal', - weight: 'normal', - size: 10, - family: 'sans-serif' - }; - - // Internal text style cache - // var fontStyleCache = {}; - - // function processFontStyle(styleString) { - // if (fontStyleCache[styleString]) { - // return fontStyleCache[styleString]; - // } - - // var el = document.createElement('div'); - // var style = el.style; - // try { - // style.font = styleString; - // } catch (ex) { - // // Ignore failures to set to invalid font. - // } - - // return fontStyleCache[styleString] = { - // style: style.fontStyle || DEFAULT_STYLE.style, - // variant: style.fontVariant || DEFAULT_STYLE.variant, - // weight: style.fontWeight || DEFAULT_STYLE.weight, - // size: style.fontSize || DEFAULT_STYLE.size, - // family: style.fontFamily || DEFAULT_STYLE.family - // }; - // } - - // function getComputedStyle(style, element) { - // var computedStyle = {}; - - // for (var p in style) { - // computedStyle[p] = style[p]; - // } - - // // Compute the size - // var canvasFontSize = parseFloat(element.currentStyle.fontSize), - // fontSize = parseFloat(style.size); - - // if (typeof style.size == 'number') { - // computedStyle.size = style.size; - // } else if (style.size.indexOf('px') != -1) { - // computedStyle.size = fontSize; - // } else if (style.size.indexOf('em') != -1) { - // computedStyle.size = canvasFontSize * fontSize; - // } else if(style.size.indexOf('%') != -1) { - // computedStyle.size = (canvasFontSize / 100) * fontSize; - // } else if (style.size.indexOf('pt') != -1) { - // computedStyle.size = fontSize / .75; - // } else { - // computedStyle.size = canvasFontSize; - // } - - // // Different scaling between normal text and VML text. This was found using - // // trial and error to get the same size as non VML text. - // computedStyle.size *= 0.981; - - // return computedStyle; - // } - - // function buildStyle(style) { - // return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + - // style.size + 'px ' + style.family; - // } - - var lineCapMap = { - 'butt': 'flat', - 'round': 'round' - }; - - function processLineCap(lineCap) { - return lineCapMap[lineCap] || 'square'; - } - - /** - * This class implements CanvasRenderingContext2D interface as described by - * the WHATWG. - * @param {HTMLElement} canvasElement The element that the 2D context should - * be associated with - */ - function CanvasRenderingContext2D_(canvasElement) { - this.m_ = createMatrixIdentity(); - - this.mStack_ = []; - this.aStack_ = []; - this.currentPath_ = []; - - // Canvas context properties - this.strokeStyle = '#000'; - this.fillStyle = '#000'; - - this.lineWidth = 1; - this.lineJoin = 'miter'; - this.lineCap = 'butt'; - this.miterLimit = Z * 1; - this.globalAlpha = 1; - //this.font = '10px sans-serif'; - //this.textAlign = 'left'; - //this.textBaseline = 'alphabetic'; - this.canvas = canvasElement; - - var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + - canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; - var el = canvasElement.ownerDocument.createElement('div'); - el.style.cssText = cssText; - canvasElement.appendChild(el); - - var overlayEl = el.cloneNode(false); - // Use a non transparent background. - overlayEl.style.backgroundColor = 'red'; - overlayEl.style.filter = 'alpha(opacity=0)'; - canvasElement.appendChild(overlayEl); - - this.element_ = el; - this.arcScaleX_ = 1; - this.arcScaleY_ = 1; - this.lineScale_ = 1; - } - - var contextPrototype = CanvasRenderingContext2D_.prototype; - contextPrototype.clearRect = function () { - if (this.textMeasureEl_) { - this.textMeasureEl_.removeNode(true); - this.textMeasureEl_ = null; - } - this.element_.innerHTML = ''; - }; - - contextPrototype.beginPath = function () { - // TODO: Branch current matrix so that save/restore has no effect - // as per safari docs. - this.currentPath_ = []; - }; - - contextPrototype.moveTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'moveTo', x: p.x, y: p.y }); - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.lineTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'lineTo', x: p.x, y: p.y }); - - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY) { - var p = getCoords(this, aX, aY); - var cp1 = getCoords(this, aCP1x, aCP1y); - var cp2 = getCoords(this, aCP2x, aCP2y); - bezierCurveTo(this, cp1, cp2, p); - }; - - // Helper function that takes the already fixed cordinates. - function bezierCurveTo(self, cp1, cp2, p) { - self.currentPath_.push({ - type: 'bezierCurveTo', - cp1x: cp1.x, - cp1y: cp1.y, - cp2x: cp2.x, - cp2y: cp2.y, - x: p.x, - y: p.y - }); - self.currentX_ = p.x; - self.currentY_ = p.y; - } - - contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { - // the following is lifted almost directly from - // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes - - var cp = getCoords(this, aCPx, aCPy); - var p = getCoords(this, aX, aY); - - var cp1 = { - x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), - y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) - }; - var cp2 = { - x: cp1.x + (p.x - this.currentX_) / 3.0, - y: cp1.y + (p.y - this.currentY_) / 3.0 - }; - - bezierCurveTo(this, cp1, cp2, p); - }; - - contextPrototype.arc = function (aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise) { - aRadius *= Z; - var arcType = aClockwise ? 'at' : 'wa'; - - var xStart = aX + mc(aStartAngle) * aRadius - Z2; - var yStart = aY + ms(aStartAngle) * aRadius - Z2; - - var xEnd = aX + mc(aEndAngle) * aRadius - Z2; - var yEnd = aY + ms(aEndAngle) * aRadius - Z2; - - // IE won't render arches drawn counter clockwise if xStart == xEnd. - if (xStart == xEnd && !aClockwise) { - xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something - // that can be represented in binary - } - - var p = getCoords(this, aX, aY); - var pStart = getCoords(this, xStart, yStart); - var pEnd = getCoords(this, xEnd, yEnd); - - this.currentPath_.push({ type: arcType, - x: p.x, - y: p.y, - radius: aRadius, - xStart: pStart.x, - yStart: pStart.y, - xEnd: pEnd.x, - yEnd: pEnd.y - }); - - }; - - // contextPrototype.rect = function(aX, aY, aWidth, aHeight) { - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // }; - - // contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.stroke(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.fill(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { - // var gradient = new CanvasGradient_('gradient'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // return gradient; - // }; - - // contextPrototype.createRadialGradient = function(aX0, aY0, aR0, - // aX1, aY1, aR1) { - // var gradient = new CanvasGradient_('gradientradial'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.r0_ = aR0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // gradient.r1_ = aR1; - // return gradient; - // }; - - // contextPrototype.drawImage = function(image, var_args) { - // var dx, dy, dw, dh, sx, sy, sw, sh; - - // // to find the original width we overide the width and height - // var oldRuntimeWidth = image.runtimeStyle.width; - // var oldRuntimeHeight = image.runtimeStyle.height; - // image.runtimeStyle.width = 'auto'; - // image.runtimeStyle.height = 'auto'; - - // // get the original size - // var w = image.width; - // var h = image.height; - - // // and remove overides - // image.runtimeStyle.width = oldRuntimeWidth; - // image.runtimeStyle.height = oldRuntimeHeight; - - // if (arguments.length == 3) { - // dx = arguments[1]; - // dy = arguments[2]; - // sx = sy = 0; - // sw = dw = w; - // sh = dh = h; - // } else if (arguments.length == 5) { - // dx = arguments[1]; - // dy = arguments[2]; - // dw = arguments[3]; - // dh = arguments[4]; - // sx = sy = 0; - // sw = w; - // sh = h; - // } else if (arguments.length == 9) { - // sx = arguments[1]; - // sy = arguments[2]; - // sw = arguments[3]; - // sh = arguments[4]; - // dx = arguments[5]; - // dy = arguments[6]; - // dw = arguments[7]; - // dh = arguments[8]; - // } else { - // throw Error('Invalid number of arguments'); - // } - - // var d = getCoords(this, dx, dy); - - // var w2 = sw / 2; - // var h2 = sh / 2; - - // var vmlStr = []; - - // var W = 10; - // var H = 10; - - // // For some reason that I've now forgotten, using divs didn't work - // vmlStr.push(' ' , - // '', - // ''); - - // this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); - // }; - - contextPrototype.stroke = function (aFill) { - var lineStr = []; - var lineOpen = false; - - var W = 10; - var H = 10; - - lineStr.push(''); - - if (!aFill) { - appendStroke(this, lineStr); - } else { - appendFill(this, lineStr, min, max); - } - - lineStr.push(''); - - this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - }; - - function appendStroke(ctx, lineStr) { - var a = processStyle(ctx.strokeStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - var lineWidth = ctx.lineScale_ * ctx.lineWidth; - - // VML cannot correctly render a line if the width is less than 1px. - // In that case, we dilute the color to make the line look thinner. - if (lineWidth < 1) { - opacity *= lineWidth; - } - - lineStr.push( - '' - ); - } - - function appendFill(ctx, lineStr, min, max) { - var fillStyle = ctx.fillStyle; - var arcScaleX = ctx.arcScaleX_; - var arcScaleY = ctx.arcScaleY_; - var width = max.x - min.x; - var height = max.y - min.y; - // if (fillStyle instanceof CanvasGradient_) { - // // TODO: Gradients transformed with the transformation matrix. - // var angle = 0; - // var focus = {x: 0, y: 0}; - - // // additional offset - // var shift = 0; - // // scale factor for offset - // var expansion = 1; - - // if (fillStyle.type_ == 'gradient') { - // var x0 = fillStyle.x0_ / arcScaleX; - // var y0 = fillStyle.y0_ / arcScaleY; - // var x1 = fillStyle.x1_ / arcScaleX; - // var y1 = fillStyle.y1_ / arcScaleY; - // var p0 = getCoords(ctx, x0, y0); - // var p1 = getCoords(ctx, x1, y1); - // var dx = p1.x - p0.x; - // var dy = p1.y - p0.y; - // angle = Math.atan2(dx, dy) * 180 / Math.PI; - - // // The angle should be a non-negative number. - // if (angle < 0) { - // angle += 360; - // } - - // // Very small angles produce an unexpected result because they are - // // converted to a scientific notation string. - // if (angle < 1e-6) { - // angle = 0; - // } - // } else { - // var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); - // focus = { - // x: (p0.x - min.x) / width, - // y: (p0.y - min.y) / height - // }; - - // width /= arcScaleX * Z; - // height /= arcScaleY * Z; - // var dimension = m.max(width, height); - // shift = 2 * fillStyle.r0_ / dimension; - // expansion = 2 * fillStyle.r1_ / dimension - shift; - // } - - // // We need to sort the color stops in ascending order by offset, - // // otherwise IE won't interpret it correctly. - // var stops = fillStyle.colors_; - // stops.sort(function(cs1, cs2) { - // return cs1.offset - cs2.offset; - // }); - - // var length = stops.length; - // var color1 = stops[0].color; - // var color2 = stops[length - 1].color; - // var opacity1 = stops[0].alpha * ctx.globalAlpha; - // var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; - - // var colors = []; - // for (var i = 0; i < length; i++) { - // var stop = stops[i]; - // colors.push(stop.offset * expansion + shift + ' ' + stop.color); - // } - - // // When colors attribute is used, the meanings of opacity and o:opacity2 - // // are reversed. - // lineStr.push(''); - // } else if (fillStyle instanceof CanvasPattern_) { - // if (width && height) { - // var deltaLeft = -min.x; - // var deltaTop = -min.y; - // lineStr.push(''); - // } - // } else { - var a = processStyle(ctx.fillStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - lineStr.push(''); - // } - } - - contextPrototype.fill = function () { - this.stroke(true); - }; - - contextPrototype.closePath = function () { - this.currentPath_.push({ type: 'close' }); - }; - - function getCoords(ctx, aX, aY) { - var m = ctx.m_; - return { - x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, - y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 - }; - }; - - contextPrototype.save = function () { - var o = {}; - copyState(this, o); - this.aStack_.push(o); - this.mStack_.push(this.m_); - this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); - }; - - contextPrototype.restore = function () { - if (this.aStack_.length) { - copyState(this.aStack_.pop(), this); - this.m_ = this.mStack_.pop(); - } - }; - - function matrixIsFinite(m) { - return isFinite(m[0][0]) && isFinite(m[0][1]) && - isFinite(m[1][0]) && isFinite(m[1][1]) && - isFinite(m[2][0]) && isFinite(m[2][1]); - } - - function setM(ctx, m, updateLineScale) { - if (!matrixIsFinite(m)) { - return; - } - ctx.m_ = m; - - if (updateLineScale) { - // Get the line scale. - // Determinant of this.m_ means how much the area is enlarged by the - // transformation. So its square root can be used as a scale factor - // for width. - var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; - ctx.lineScale_ = sqrt(abs(det)); - } - } - - contextPrototype.translate = function (aX, aY) { - var m1 = [ - [1, 0, 0], - [0, 1, 0], - [aX, aY, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), false); - }; - - // contextPrototype.rotate = function(aRot) { - // var c = mc(aRot); - // var s = ms(aRot); - - // var m1 = [ - // [c, s, 0], - // [-s, c, 0], - // [0, 0, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), false); - // }; - - contextPrototype.scale = function (aX, aY) { - this.arcScaleX_ *= aX; - this.arcScaleY_ *= aY; - var m1 = [ - [aX, 0, 0], - [0, aY, 0], - [0, 0, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), true); - }; - - // contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { - // var m1 = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), true); - // }; - - // contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { - // var m = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, m, true); - // }; - - /** - * The text drawing function. - * The maxWidth argument isn't taken in account, since no browser supports - * it yet. - */ - // contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { - // var m = this.m_, - // delta = 1000, - // left = 0, - // right = delta, - // offset = {x: 0, y: 0}, - // lineStr = []; - - // var fontStyle = getComputedStyle(processFontStyle(this.font), - // this.element_); - - // var fontStyleString = buildStyle(fontStyle); - - // var elementStyle = this.element_.currentStyle; - // var textAlign = this.textAlign.toLowerCase(); - // switch (textAlign) { - // case 'left': - // case 'center': - // case 'right': - // break; - // case 'end': - // textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; - // break; - // case 'start': - // textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; - // break; - // default: - // textAlign = 'left'; - // } - - // // 1.75 is an arbitrary number, as there is no info about the text baseline - // switch (this.textBaseline) { - // case 'hanging': - // case 'top': - // offset.y = fontStyle.size / 1.75; - // break; - // case 'middle': - // break; - // default: - // case null: - // case 'alphabetic': - // case 'ideographic': - // case 'bottom': - // offset.y = -fontStyle.size / 2.25; - // break; - // } - - // switch(textAlign) { - // case 'right': - // left = delta; - // right = 0.05; - // break; - // case 'center': - // left = right = delta / 2; - // break; - // } - - // var d = getCoords(this, x + offset.x, y + offset.y); - - // lineStr.push(''); - - // if (stroke) { - // appendStroke(this, lineStr); - // } else { - // // TODO: Fix the min and max params. - // appendFill(this, lineStr, {x: -left, y: 0}, - // {x: right, y: fontStyle.size}); - // } - - // var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + - // m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; - - // var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); - - // lineStr.push('', - // '', - // ''); - - // this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - // }; - - // contextPrototype.fillText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, false); - // }; - - // contextPrototype.strokeText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, true); - // }; - - // contextPrototype.measureText = function(text) { - // if (!this.textMeasureEl_) { - // var s = ''; - // this.element_.insertAdjacentHTML('beforeEnd', s); - // this.textMeasureEl_ = this.element_.lastChild; - // } - // var doc = this.element_.ownerDocument; - // this.textMeasureEl_.innerHTML = ''; - // this.textMeasureEl_.style.font = this.font; - // // Don't use innerHTML or innerText because they allow markup/whitespace. - // this.textMeasureEl_.appendChild(doc.createTextNode(text)); - // return {width: this.textMeasureEl_.offsetWidth}; - // }; - - /******** STUBS ********/ - // contextPrototype.clip = function() { - // // TODO: Implement - // }; - - // contextPrototype.arcTo = function() { - // // TODO: Implement - // }; - - // contextPrototype.createPattern = function(image, repetition) { - // return new CanvasPattern_(image, repetition); - // }; - - // // Gradient / Pattern Stubs - // function CanvasGradient_(aType) { - // this.type_ = aType; - // this.x0_ = 0; - // this.y0_ = 0; - // this.r0_ = 0; - // this.x1_ = 0; - // this.y1_ = 0; - // this.r1_ = 0; - // this.colors_ = []; - // } - - // CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { - // aColor = processStyle(aColor); - // this.colors_.push({offset: aOffset, - // color: aColor.color, - // alpha: aColor.alpha}); - // }; - - // function CanvasPattern_(image, repetition) { - // assertImageIsValid(image); - // switch (repetition) { - // case 'repeat': - // case null: - // case '': - // this.repetition_ = 'repeat'; - // break - // case 'repeat-x': - // case 'repeat-y': - // case 'no-repeat': - // this.repetition_ = repetition; - // break; - // default: - // throwException('SYNTAX_ERR'); - // } - - // this.src_ = image.src; - // this.width_ = image.width; - // this.height_ = image.height; - // } - - function throwException(s) { - throw new DOMException_(s); - } - - // function assertImageIsValid(img) { - // if (!img || img.nodeType != 1 || img.tagName != 'IMG') { - // throwException('TYPE_MISMATCH_ERR'); - // } - // if (img.readyState != 'complete') { - // throwException('INVALID_STATE_ERR'); - // } - // } - - function DOMException_(s) { - this.code = this[s]; - this.message = s + ': DOM Exception ' + this.code; - } - var p = DOMException_.prototype = new Error; - p.INDEX_SIZE_ERR = 1; - p.DOMSTRING_SIZE_ERR = 2; - p.HIERARCHY_REQUEST_ERR = 3; - p.WRONG_DOCUMENT_ERR = 4; - p.INVALID_CHARACTER_ERR = 5; - p.NO_DATA_ALLOWED_ERR = 6; - p.NO_MODIFICATION_ALLOWED_ERR = 7; - p.NOT_FOUND_ERR = 8; - p.NOT_SUPPORTED_ERR = 9; - p.INUSE_ATTRIBUTE_ERR = 10; - p.INVALID_STATE_ERR = 11; - p.SYNTAX_ERR = 12; - p.INVALID_MODIFICATION_ERR = 13; - p.NAMESPACE_ERR = 14; - p.INVALID_ACCESS_ERR = 15; - p.VALIDATION_ERR = 16; - p.TYPE_MISMATCH_ERR = 17; - - // set up externs - G_vmlCanvasManager = G_vmlCanvasManager_; - CanvasRenderingContext2D = CanvasRenderingContext2D_; - //CanvasGradient = CanvasGradient_; - //CanvasPattern = CanvasPattern_; - DOMException = DOMException_; - })(); - -} // if - -/*! JsRender v1.0pre: http://github.com/BorisMoore/jsrender */ -/* - * Optimized version of jQuery Templates, for rendering to string. - * Does not require jQuery, or HTML DOM - * Integrates with JsViews (http://github.com/BorisMoore/jsviews) - * Copyright 2012, Boris Moore - * Released under the MIT License. - */ -// informal pre beta commit counter: 3 - -this.jsviews || this.jQuery && jQuery.views || (function( window, undefined ) { - -//========================== Top-level vars ========================== - -var versionNumber = "v1.0pre", - - $, rTag, rTmplString, extend, - sub = {}, - FALSE = false, TRUE = true, - jQuery = window.jQuery, - - rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // nil object helper view viewProperty pathTokens leafToken string - - rParams = /(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - - rNewLine = /\r?\n/g, - rUnescapeQuotes = /\\(['"])/g, - rEscapeQuotes = /\\?(['"])/g, - rBuildHash = /\x08(~)?([^\x08]+)\x08/g, - - autoViewKey = 0, - autoTmplName = 0, - escapeMapForHtml = { - "&": "&", - "<": "<", - ">": ">" - }, - tmplAttr = "data-jsv-tmpl", - fnDeclStr = "var j=j||" + (jQuery ? "jQuery." : "js") + "views,", - htmlSpecialChar = /[\x00"&'<>]/g, - slice = Array.prototype.slice, - - render = {}, - - // jsviews object ($.views if jQuery is loaded) - jsv = { - jsviews: versionNumber, - sub: sub, // subscription, e.g. JsViews integration - debugMode: TRUE, - err: function( e ) { - return jsv.debugMode ? ("
Error: " + (e.message || e) + ". ") : '""'; - }, - tmplFn: tmplFn, - render: render, - templates: templates, - tags: tags, - helpers: helpers, - converters: converters, - View: View, - convert: convert, - delimiters: setDelimiters, - tag: renderTag - }; - -//========================== Top-level functions ========================== - -//=================== -// jsviews.delimiters -//=================== - -function setDelimiters( openChars, closeChars ) { - // Set the tag opening and closing delimiters. Default is "{{" and "}}" - // openChar, closeChars: opening and closing strings, each with two characters - var firstOpenChar = "\\" + openChars.charAt( 0 ), // Escape the characters - since they could be regex special characters - secondOpenChar = "\\" + openChars.charAt( 1 ), - firstCloseChar = "\\" + closeChars.charAt( 0 ), - secondCloseChar = "\\" + closeChars.charAt( 1 ); - // Build regex with new delimiters - jsv.rTag = rTag // make rTag available to JsViews (or other components) for parsing binding expressions - = secondOpenChar - // tag (followed by / space or }) or colon or html or code - + "(?:(?:(\\w+(?=[\\/\\s" + firstCloseChar + "]))|(?:(\\w+)?(:)|(>)|(\\*)))" - // params - + "\\s*((?:[^" + firstCloseChar + "]|" + firstCloseChar + "(?!" + secondCloseChar + "))*?)" - // slash or closeBlock - + "(\\/)?|(?:\\/(\\w+)))" - // }} - + firstCloseChar; - - // Default rTag: tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/\s\}]))|(?:(\w+)?(:)|(>)|(\*)))\s*((?:[^}]|}(?!\}))*?)(\/)?|(?:\/(\w+)))}} - - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - rTag = new RegExp( firstOpenChar + rTag + secondCloseChar, "g" ); - rTmplString = new RegExp( "<.*>|" + openChars + ".*" + closeChars ); - return this; -} - -//================= -// View.hlp -//================= - -function getHelper( helper ) { - // Helper method called as view.hlp() from compiled template, for helper functions or template parameters ~foo - var view = this, - tmplHelpers = view.tmpl.helpers || {}; - helper = (view.ctx[ helper ] !== undefined ? view.ctx : tmplHelpers[ helper ] !== undefined ? tmplHelpers : helpers[ helper ] !== undefined ? helpers : {})[ helper ]; - return typeof helper !== "function" ? helper : function() { - return helper.apply(view, arguments); - }; -} - -//================= -// jsviews.convert -//================= - -function convert( converter, view, text ) { - var tmplConverters = view.tmpl.converters; - converter = tmplConverters && tmplConverters[ converter ] || converters[ converter ]; - return converter ? converter.call( view, text ) : text; -} - -//================= -// jsviews.tag -//================= - -function renderTag( tag, parentView, converter, content, tagObject ) { - // Called from within compiled template function, to render a nested tag - // Returns the rendered tag - tagObject.props = tagObject.props || {}; - var ret, - tmpl = tagObject.props.tmpl, - tmplTags = parentView.tmpl.tags, - nestedTemplates = parentView.tmpl.templates, - args = arguments, - tagFn = tmplTags && tmplTags[ tag ] || tags[ tag ]; - - if ( !tagFn ) { - return ""; - } - // Set the tmpl property to the content of the block tag, unless set as an override property on the tag - content = content && parentView.tmpl.tmpls[ content - 1 ]; - tmpl = tmpl || content || undefined; - tagObject.tmpl = - "" + tmpl === tmpl // if a string - ? nestedTemplates && nestedTemplates[ tmpl ] || templates[ tmpl ] || templates( tmpl ) - : tmpl; - - tagObject.isTag = TRUE; - tagObject.converter = converter; - tagObject.view = parentView; - tagObject.renderContent = renderContent; - if ( parentView.ctx ) { - extend( tagObject.ctx, parentView.ctx); - } - - ret = tagFn.apply( tagObject, args.length > 5 ? slice.call( args, 5 ) : [] ); - return ret || ( ret == undefined ? "" : ret.toString()); // (If ret is the value 0 or false, will render to string) -} - -//================= -// View constructor -//================= - -function View( context, path, parentView, data, template, index ) { - // Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded) - var views = parentView.views, -// TODO: add this, as part of smart re-linking on existing content ($.link method), or remove completely -// self = parentView.views[ index ]; -// if ( !self ) { ... } - self = { - tmpl: template, - path: path, - parent: parentView, - data: data, - ctx: context, - views: $.isArray( data ) ? [] : {}, - hlp: getHelper - }; - - if ( $.isArray( views )) { - views.splice( - self.index = index !== undefined - ? index - : views.length, 0, self - ); - } else { - views[ self.index = "_" + autoViewKey++ ] = self; - } - return self; -} - -//================= -// Registration -//================= - -function addToStore( self, store, name, item, process ) { - // Add item to named store such as templates, helpers, converters... - var key, onStore; - if ( name && typeof name === "object" && !name.nodeType ) { - // If name is a map, iterate over map and call store for key - for ( key in name ) { - store( key, name[ key ]); - } - return self; - } - if ( !name || item === undefined ) { - if ( process ) { - item = process( undefined, item || name ); - } - } else if ( "" + name === name ) { // name must be a string - if ( item === null ) { - // If item is null, delete this entry - delete store[name]; - } else if ( item = process ? process( name, item ) : item ) { - store[ name ] = item; - } - } - if ( onStore = sub.onStoreItem ) { - // e.g. JsViews integration - onStore( store, name, item, process ); - } - return item; -} - -function templates( name, tmpl ) { - // Register templates - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, templates, name, tmpl, compile ); -} - -function tags( name, tagFn ) { - // Register template tags - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, tags, name, tagFn ); -} - -function helpers( name, helperFn ) { - // Register helper functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.helpers( name, helperFn ) or $.view.helpers({ name: helperFn, ... }) to add additional helpers to the registered helpers collection. - // Getter: Use var helperFn = $.views.helpers( name ) or $.views.helpers[name] or $.views.helpers.name to return the function. - // Remove: Use $.view.helpers( name, null ) to remove a registered helper function from $.view.helpers. - // Within a template, access the helper using the syntax: {{... ~myHelper(...) ...}}. - return addToStore( this, helpers, name, helperFn ); -} - -function converters( name, converterFn ) { - // Register converter functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.converters( name, converterFn ) or $.view.converters({ name: converterFn, ... }) to add additional converters to the registered converters collection. - // Getter: Use var converterFn = $.views.converters( name ) or $.views.converters[name] or $.views.converters.name to return the converter function. - // Remove: Use $.view.converters( name, null ) to remove a registered converter from $.view.converters. - // Within a template, access the converter using the syntax: {{myConverter:...}}. - return addToStore( this, converters, name, converterFn ); -} - -//================= -// renderContent -//================= - -function renderContent( data, context, parentView, path, index ) { - // Render template against data as a tree of subviews (nested template), or as a string (top-level template). - // tagName parameter for internal use only. Used for rendering templates registered as tags (which may have associated presenter objects) - var i, l, dataItem, newView, itemWrap, itemsWrap, itemResult, parentContext, tmpl, layout, - props = {}, - swapContent = index === TRUE, - self = this, - result = ""; - - if ( self.isTag ) { - // This is a call from renderTag - tmpl = self.tmpl; - context = context || self.ctx; - parentView = parentView || self.view; - path = path || self.path; - index = index || self.index; - props = self.props; - } else { - tmpl = self.jquery && self[0] // This is a call $.fn.render - || self; // This is a call from tmpl.render - } - parentView = parentView || jsv.topView; - parentContext = parentView.ctx; - layout = tmpl.layout; - if ( data === parentView ) { - // Inherit the data from the parent view. - // This may be the contents of an {{if}} block - data = parentView.data; - layout = TRUE; - } - - // Set additional context on views created here, (as modified context inherited from the parent, and be inherited by child views) - // Note: If no jQuery, extend does not support chained copies - so limit extend() to two parameters - context = (context && context === parentContext) - ? parentContext - : (parentContext - // if parentContext, make copy - ? ((parentContext = extend( {}, parentContext ), context) - // If context, merge context with copied parentContext - ? extend( parentContext, context ) - : parentContext) - // if no parentContext, use context, or default to {} - : context || {}); - - if ( props.link === FALSE ) { - // Override inherited value of link by an explicit setting in props: link=false - // The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect. - context.link = FALSE; - } - if ( !tmpl.fn ) { - tmpl = templates[ tmpl ] || templates( tmpl ); - } - itemWrap = context.link && sub.onRenderItem; - itemsWrap = context.link && sub.onRenderItems; - - if ( tmpl ) { - if ( $.isArray( data ) && !layout ) { - // Create a view for the array, whose child views correspond to each data item. - // (Note: if index and parentView are passed in along with parent view, treat as - // insert -e.g. from view.addViews - so parentView is already the view item for array) - newView = swapContent ? parentView : (index !== undefined && parentView) || View( context, path, parentView, data, tmpl, index ); - - for ( i = 0, l = data.length; i < l; i++ ) { - // Create a view for each data item. - dataItem = data[ i ]; - itemResult = tmpl.fn( dataItem, View( context, path, newView, dataItem, tmpl, (index||0) + i ), jsv ); - result += itemWrap ? itemWrap( itemResult, props ) : itemResult; - } - } else { - // Create a view for singleton data object. - newView = swapContent ? parentView : View( context, path, parentView, data, tmpl, index ); - result += (data || layout) ? tmpl.fn( data, newView, jsv ) : ""; - } - parentView.topKey = newView.index; - return itemsWrap ? itemsWrap( result, path, newView.index, tmpl, props ) : result; - } - return ""; // No tmpl. Could throw... -} - -//=========================== -// Build and compile template -//=========================== - -// Generate a reusable function that will serve to render a template against data -// (Compile AST then build template function) - -function syntaxError() { - throw "Syntax error"; -} - -function tmplFn( markup, tmpl, bind ) { - // Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes - // Used for compiling templates, and also by JsViews to build functions for data link expressions - var newNode, node, i, l, code, hasTag, hasEncoder, getsValue, hasConverter, hasViewPath, tag, converter, params, hash, nestedTmpl, allowCode, - tmplOptions = tmpl ? { - allowCode: allowCode = tmpl.allowCode, - debug: tmpl.debug - } : {}, - nested = tmpl && tmpl.tmpls, - astTop = [], - loc = 0, - stack = [], - content = astTop, - current = [,,,astTop], - nestedIndex = 0; - - //==== nested functions ==== - function pushPreceedingContent( shift ) { - shift -= loc; - if ( shift ) { - content.push( markup.substr( loc, shift ).replace( rNewLine, "\\n" )); - } - } - - function parseTag( all, tagName, converter, colon, html, code, params, slash, closeBlock, index ) { - // tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(?:(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - // Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, contentMarkup ] - if ( html ) { - colon = ":"; - converter = "html"; - } - var hash = "", - passedCtx = "", - block = !slash && !colon; // Block tag if not self-closing and not {{:}} or {{>}} (special case) - - //==== nested helper function ==== - - tagName = tagName || colon; - pushPreceedingContent( index ); - loc = index + all.length; // location marker - parsed up to here - if ( code ) { - if ( allowCode ) { - content.push([ "*", params.replace( rUnescapeQuotes, "$1" ) ]); - } - } else if ( tagName ) { - if ( tagName === "else" ) { - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - content = current[ 3 ]; - block = TRUE; - } - params = (params - ? parseParams( params, bind ) - .replace( rBuildHash, function( all, isCtx, keyValue ) { - if ( isCtx ) { - passedCtx += keyValue + ","; - } else { - hash += keyValue + ","; - } - return ""; - }) - : ""); - hash = hash.slice( 0, -1 ); - params = params.slice( 0, -1 ); - newNode = [ - tagName, - converter || "", - params, - block && [], - "{" + (hash ? ("props:{" + hash + "},"): "") + "path:'" + params + "'" + (passedCtx ? ",ctx:{" + passedCtx.slice( 0, -1 ) + "}" : "") + "}" - ]; - if ( block ) { - stack.push( current ); - current = newNode; - current[ 5 ] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag - } - content.push( newNode ); - } else if ( closeBlock ) { - //if ( closeBlock !== current[ 0 ]) { - // throw "unmatched close tag: /" + closeBlock + ". Expected /" + current[ 0 ]; - //} - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - } - if ( !current ) { - throw "Expected block tag"; - } - content = current[ 3 ]; - } - //==== /end of nested functions ==== - - markup = markup.replace( rEscapeQuotes, "\\$1" ); - - // Build the AST (abstract syntax tree) under astTop - markup.replace( rTag, parseTag ); - - pushPreceedingContent( markup.length ); - - // Use the AST (astTop) to build the template function - l = astTop.length; - code = (l ? "" : '"";'); - - for ( i = 0; i < l; i++ ) { - // AST nodes: [ tagName, converter, params, content, hash, contentMarkup ] - node = astTop[ i ]; - if ( node[ 0 ] === "*" ) { - code = code.slice( 0, i ? -1 : -3 ) + ";" + node[ 1 ] + (i + 1 < l ? "ret+=" : ""); - } else if ( "" + node === node ) { // type string - code += '"' + node + '"+'; - } else { - tag = node[ 0 ]; - converter = node[ 1 ]; - params = node[ 2 ]; - content = node[ 3 ]; - hash = node[ 4 ]; - markup = node[ 5 ]; - if ( content ) { - // Create template object for nested template - nestedTmpl = TmplObject( markup, tmplOptions, tmpl, nestedIndex++ ); - // Compile to AST and then to compiled function - tmplFn( markup, nestedTmpl); - nested.push( nestedTmpl ); - } - hasViewPath = hasViewPath || hash.indexOf( "view" ) > -1; - code += (tag === ":" - ? (converter === "html" - ? (hasEncoder = TRUE, "e(" + params) - : converter - ? (hasConverter = TRUE, 'c("' + converter + '",view,' + params) - : (getsValue = TRUE, "((v=" + params + ')!=u?v:""') - ) - : (hasTag = TRUE, 't("' + tag + '",view,"' + (converter || "") + '",' - + (content ? nested.length : '""') // For block tags, pass in the key (nested.length) to the nested content template - + "," + hash + (params ? "," : "") + params)) - + ")+"; - } - } - code = new Function( "data, view, j, b, u", fnDeclStr - + (getsValue ? "v," : "") - + (hasTag ? "t=j.tag," : "") - + (hasConverter ? "c=j.convert," : "") - + (hasEncoder ? "e=j.converters.html," : "") - + "ret; try{\n\n" - + (tmplOptions.debug ? "debugger;" : "") - + (allowCode ? 'ret=' : 'return ') - + code.slice( 0, -1 ) + ";\n\n" - + (allowCode ? "return ret;" : "") - + "}catch(e){return j.err(e);}" - ); - - // Include only the var references that are needed in the code - if ( tmpl ) { - tmpl.fn = code; - tmpl.useVw = hasConverter || hasViewPath || hasTag; - } - return code; -} - -function parseParams( params, bind ) { - var named, - fnCall = {}, - parenDepth = 0, - quoted = FALSE, // boolean for string content in double quotes - aposed = FALSE; // or in single quotes - - function parseTokens( all, lftPrn0, lftPrn, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, prn2, space ) { - // rParams = /(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn path operator err eq path2 prn comma lftPrn3 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - operator = operator || ""; - lftPrn = lftPrn || lftPrn0 || lftPrn2; - path = path || path2; - prn = prn || prn2 || ""; - operator = operator || ""; - - function parsePath( all, object, helper, view, viewProperty, pathTokens, leafToken ) { - // rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // object helper view viewProperty pathTokens leafToken string - if ( object ) { - var ret = (helper - ? 'view.hlp("' + helper + '")' - : view - ? "view" - : "data") - + (leafToken - ? (viewProperty - ? "." + viewProperty - : helper - ? "" - : (view ? "" : "." + object) - ) + (pathTokens || "") - : (leafToken = helper ? "" : view ? viewProperty || "" : object, "")); - - if ( bind && prn !== "(" ) { - ret = "b(" + ret + ',"' + leafToken + '")'; - } - return ret + (leafToken ? "." + leafToken : ""); - } - return all; - } - - if ( err ) { - syntaxError(); - } else { - return (aposed - // within single-quoted string - ? (aposed = !apos, (aposed ? all : '"')) - : quoted - // within double-quoted string - ? (quoted = !quot, (quoted ? all : '"')) - : - ( - (lftPrn - ? (parenDepth++, lftPrn) - : "") - + (space - ? (parenDepth - ? "" - : named - ? (named = FALSE, "\b") - : "," - ) - : eq - // named param - ? (parenDepth && syntaxError(), named = TRUE, '\b' + path + ':') - : path - // path - ? (path.replace( rPath, parsePath ) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : operator) - ) - : operator - ? all - : rtPrn - // function - ? ((fnCall[ parenDepth-- ] = FALSE, rtPrn) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : "") - ) - : comma - ? (fnCall[ parenDepth ] || syntaxError(), ",") // We don't allow top-level literal arrays or objects - : lftPrn0 - ? "" - : (aposed = apos, quoted = quot, '"') - )) - ); - } - } - params = (params + " " ).replace( rParams, parseTokens ); - return params; -} - -function compile( name, tmpl, parent, options ) { - // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object - // options is the set of template properties, c - var tmplOrMarkup, elem, key, nested, nestedItem; - - //==== nested functions ==== - function tmplOrMarkupFromStr( value ) { - // If value is of type string - treat as selector, or name of compiled template - // Return the template object, if already compiled, or the markup string - - if ( ("" + value === value) || value.nodeType > 0 ) { - // If selector is valid and returns at least one element, get first element - elem = value.nodeType > 0 ? value : !rTmplString.test( value ) && jQuery && jQuery( value )[0]; - if ( elem && elem.type ) { - // It is a script element - // Create a name for data linking if none provided - value = templates[ elem.getAttribute( tmplAttr )]; - if ( !value ) { - // Not already compiled and cached, so compile and cache the name - name = name || "_" + autoTmplName++; - elem.setAttribute( tmplAttr, name ); - value = compile( name, elem.innerHTML, parent, options ); // Use tmpl as options - templates[ name ] = value; - } - } - return value; - } - // If value is not a string or dom element, return undefined - } - - //==== Compile the template ==== - tmplOrMarkup = tmplOrMarkupFromStr( tmpl ); - - // If tmpl is a template object, use it for options - options = options || (tmpl.markup ? tmpl : {}); - options.name = name; - nested = options.templates; - - // If tmpl is not a markup string or a selector string, then it must be a template object - // In that case, get it from the markup property of the object - if ( !tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr( tmpl.markup ))) { - if ( tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode )) { - // if the string references a compiled template object, but the debug or allowCode props are different, need to recompile - tmplOrMarkup = tmplOrMarkup.markup; - } - } - if ( tmplOrMarkup !== undefined ) { - if ( name && !parent ) { - render[ name ] = function() { - return tmpl.render.apply( tmpl, arguments ); - }; - } - if ( tmplOrMarkup.fn || tmpl.fn ) { - // tmpl is already compiled, so use it, or if different name is provided, clone it - if ( tmplOrMarkup.fn ) { - if ( name && name !== tmplOrMarkup.name ) { - tmpl = extend( extend( {}, tmplOrMarkup ), options); - } else { - tmpl = tmplOrMarkup; - } - } - } else { - // tmplOrMarkup is a markup string, not a compiled template - // Create template object - tmpl = TmplObject( tmplOrMarkup, options, parent, 0 ); - // Compile to AST and then to compiled function - tmplFn( tmplOrMarkup, tmpl ); - } - for ( key in nested ) { - // compile nested template declarations - nestedItem = nested[ key ]; - if ( nestedItem.name !== key ) { - nested[ key ] = compile( key, nestedItem, tmpl ); - } - } - return tmpl; - } -} -//==== /end of function compile ==== - -function TmplObject( markup, options, parent, index ) { - // Template object constructor - - // nested helper function - function extendStore( storeName ) { - if ( parent[ storeName ]) { - // Include parent items except if overridden by item of same name in options - tmpl[ storeName ] = extend( extend( {}, parent[ storeName ] ), options[ storeName ] ); - } - } - - options = options || {}; - var tmpl = { - markup: markup, - tmpls: [], - links: [], - render: renderContent - }; - if ( parent ) { - if ( parent.templates ) { - tmpl.templates = extend( extend( {}, parent.templates ), options.templates ); - } - tmpl.parent = parent; - tmpl.name = parent.name + "[" + index + "]"; - tmpl.index = index; - } - - extend( tmpl, options ); - if ( parent ) { - extendStore( "templates" ); - extendStore( "tags" ); - extendStore( "helpers" ); - extendStore( "converters" ); - } - return tmpl; -} - -//========================== Initialize ========================== - -if ( jQuery ) { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is loaded, so make $ the jQuery object - $ = jQuery; - $.templates = templates; - $.render = render; - $.views = jsv; - $.fn.render = renderContent; - -} else { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is not loaded. - - $ = window.jsviews = jsv; - $.extend = function( target, source ) { - var name; - target = target || {}; - for ( name in source ) { - target[ name ] = source[ name ]; - } - return target; - }; - - $.isArray = Array && Array.isArray || function( obj ) { - return Object.prototype.toString.call( obj ) === "[object Array]"; - }; -} - -extend = $.extend; - -jsv.topView = { views: {}, tmpl: {}, hlp: getHelper, ctx: jsv.helpers }; - -function replacerForHtml( ch ) { - // Original code from Mike Samuel - return escapeMapForHtml[ ch ] - // Intentional assignment that caches the result of encoding ch. - || (escapeMapForHtml[ ch ] = "&#" + ch.charCodeAt( 0 ) + ";"); -} - -//========================== Register tags ========================== - -tags({ - "if": function() { - var ifTag = this, - view = ifTag.view; - - view.onElse = function( tagObject, args ) { - var i = 0, - l = args.length; - - while ( l && !args[ i++ ]) { - // Only render content if args.length === 0 (i.e. this is an else with no condition) or if a condition argument is truey - if ( i === l ) { - return ""; - } - } - view.onElse = undefined; // If condition satisfied, so won't run 'else'. - tagObject.path = ""; - return tagObject.renderContent( view ); - // Test is satisfied, so render content, while remaining in current data context - // By passing the view, we inherit data context from the parent view, and the content is treated as a layout template - // (so if the data is an array, it will not iterate over the data - }; - return view.onElse( this, arguments ); - }, - "else": function() { - var view = this.view; - return view.onElse ? view.onElse( this, arguments ) : ""; - }, - "for": function() { - var i, - self = this, - result = "", - args = arguments, - l = args.length; - if ( self.props.layout ) { - self.tmpl.layout = TRUE; - } - for ( i = 0; i < l; i++ ) { - result += self.renderContent( args[ i ]); - } - return result; - }, - "=": function( value ) { - return value; - }, - "*": function( value ) { - return value; - } -}); - -//========================== Register global helpers ========================== - -// helpers({ // Global helper functions -// // TODO add any useful built-in helper functions -// }); - -//========================== Register converters ========================== - -converters({ - html: function( text ) { - // HTML encoding helper: Replace < > & and ' and " by corresponding entities. - // inspired by Mike Samuel - return text != undefined ? String( text ).replace( htmlSpecialChar, replacerForHtml ) : ""; - } -}); - -//========================== Define default delimiters ========================== -setDelimiters( "{{", "}}" ); - -})( this ); - -/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) - * Licensed under the MIT License (LICENSE.txt). - * - * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. - * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. - * Thanks to: Seamus Leahy for adding deltaX and deltaY - * - * Version: 3.0.6 - * - * Requires: 1.2.2+ - */ - -(function($) { - -var types = ['DOMMouseScroll', 'mousewheel']; - -if ($.event.fixHooks) { - for ( var i=types.length; i; ) { - $.event.fixHooks[ types[--i] ] = $.event.mouseHooks; - } -} - -$.event.special.mousewheel = { - setup: function() { - if ( this.addEventListener ) { - for ( var i=types.length; i; ) { - this.addEventListener( types[--i], handler, false ); - } - } else { - this.onmousewheel = handler; - } - }, - - teardown: function() { - if ( this.removeEventListener ) { - for ( var i=types.length; i; ) { - this.removeEventListener( types[--i], handler, false ); - } - } else { - this.onmousewheel = null; - } - } -}; - -$.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); - }, - - unmousewheel: function(fn) { - return this.unbind("mousewheel", fn); - } -}); - - -function handler(event) { - var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0; - event = $.event.fix(orgEvent); - event.type = "mousewheel"; - - // Old school scrollwheel delta - if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; } - if ( orgEvent.detail ) { delta = -orgEvent.detail/3; } - - // New school multidimensional scroll (touchpads) deltas - deltaY = delta; - - // Gecko - if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { - deltaY = 0; - deltaX = -1*delta; - } - - // Webkit - if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; } - if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; } - - // Add event and delta to the front of the arguments - args.unshift(event, delta, deltaX, deltaY); - - return ($.event.dispatch || $.event.handle).apply(this, args); -} - -})(jQuery); - -/*! - * jQuery UI Widget 1.8.18 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ - -if ( ! $.widget ) { - -(function( $, undefined ) { - -// jQuery 1.4+ -if ( $.cleanData ) { - var _cleanData = $.cleanData; - $.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); - }; -} else { - var _remove = $.fn.remove; - $.fn.remove = function( selector, keepData ) { - return this.each(function() { - if ( !keepData ) { - if ( !selector || $.filter( selector, [ this ] ).length ) { - $( "*", this ).add( [ this ] ).each(function() { - try { - $( this ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - }); - } - } - return _remove.call( $(this), selector, keepData ); - }); - }; -} - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from -// $.each( basePrototype, function( key, val ) { -// if ( $.isPlainObject(val) ) { -// basePrototype[ key ] = $.extend( {}, val ); -// } -// }); - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = Array.prototype.slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - // prevent calls to internal methods - if ( isMethodCall && options.charAt( 0 ) === "_" ) { - return returnValue; - } - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ), - methodValue = instance && $.isFunction( instance[options] ) ? - instance[ options ].apply( instance, args ) : - instance; - // TODO: add this back in 1.9 and use $.error() (see #5972) -// if ( !instance ) { -// throw "cannot call methods on " + name + " prior to initialization; " + -// "attempted to call method '" + options + "'"; -// } -// if ( !$.isFunction( instance[options] ) ) { -// throw "no such method '" + options + "' for " + name + " widget instance"; -// } -// var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, name, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - // $.widget.bridge stores the plugin instance, but we do it anyway - // so that it's stored even before the _create function runs - $.data( element, this.widgetName, this ); - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - var self = this; - this.element.bind( "remove." + this.widgetName, function() { - self.destroy(); - }); - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: function() {}, - _init: function() {}, - - destroy: function() { - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - }, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - [ value ? "addClass" : "removeClass"]( - this.widgetBaseClass + "-disabled" + " " + - "ui-state-disabled" ) - .attr( "aria-disabled", value ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - - return !( $.isFunction(callback) && - callback.call( this.element[0], event, data ) === false || - event.isDefaultPrevented() ); - } -}; - -})( jQuery ); - -}; - - -(function ($, window, undefined) { - var pos_oo = Number.POSITIVE_INFINITY, - neg_oo = Number.NEGATIVE_INFINITY; - - $.geo = { - // - // utility functions - // - - _allCoordinates: function (geom) { - // return array of all positions in all geometries of geom - // not in JTS - var geometries = this._flatten(geom), - curGeom = 0, - result = []; - - for (; curGeom < geometries.length; curGeom++) { - var coordinates = geometries[curGeom].coordinates, - isArray = coordinates && $.isArray(coordinates[0]), - isDblArray = isArray && $.isArray(coordinates[0][0]), - isTriArray = isDblArray && $.isArray(coordinates[0][0][0]), - i, j, k; - - if (!isTriArray) { - if (!isDblArray) { - if (!isArray) { - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - for (k = 0; k < coordinates[i][j].length; k++) { - result.push(coordinates[i][j][k]); - } - } - } - } - return result; - }, - - _isGeodetic: function( coords ) { - // returns true if the first coordinate it can find is geodetic - - while ( $.isArray( coords ) ) { - if ( coords.length > 1 && ! $.isArray( coords[ 0 ] ) ) { - return ( coords[ 0 ] >= -180 && coords[ 0 ] <= 180 && coords[ 1 ] >= -85 && coords[ 1 ] <= 85 ); - } else { - coords = coords[ 0 ]; - } - } - - return false; - }, - - // - // bbox functions - // - - center: function (bbox, _ignoreGeo /* Internal Use Only */) { - // Envelope.centre in JTS - // bbox only, use centroid for geom - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return wasGeodetic ? $.geo.proj.toGeodetic(center) : center; - }, - - expandBy: function (bbox, dx, dy, _ignoreGeo /* Internal Use Only */) { - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - bbox = [bbox[0] - dx, bbox[1] - dy, bbox[2] + dx, bbox[3] + dy]; - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - height: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[3] - bbox[1]; - }, - - _in: function(bbox1, bbox2) { - return bbox1[0] <= bbox2[0] && - bbox1[1] <= bbox2[1] && - bbox1[2] >= bbox2[2] && - bbox1[3] >= bbox2[3]; - }, - - _bboxDisjoint: function( bbox1, bbox2 ) { - return bbox2[ 0 ] > bbox1[ 2 ] || - bbox2[ 2 ] < bbox1[ 0 ] || - bbox2[ 1 ] > bbox1[ 3 ] || - bbox2[ 3 ] < bbox1[ 1 ]; - }, - - include: function( bbox, value, _ignoreGeo /* Internal Use Only */ ) { - // similar to Envelope.expandToInclude in JTS - if ( !value || !$.isArray( value ) ) { - return bbox; - } - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox || value ) ) { - wasGeodetic = true; - } - - if ( !bbox ) { - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - } else if ( wasGeodetic ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - - if ( value.length === 2 ) { - value = [ value[ 0 ], value[ 1 ], value[ 0 ], value[ 1 ] ]; - } - - value = $.geo.proj.fromGeodetic( value ); - - bbox[0] = Math.min( value[ 0 ], bbox[ 0 ] ); - bbox[1] = Math.min( value[ 1 ], bbox[ 1 ] ); - bbox[2] = Math.max( value[ 2 ], bbox[ 2 ] ); - bbox[3] = Math.max( value[ 3 ], bbox[ 3 ] ); - - return wasGeodetic ? $.geo.proj.toGeodetic( bbox ) : bbox; - }, - - polygonize: function( bbox, _ignoreGeo /* Internal Use Only */ ) { - // adaptation of Polygonizer class in JTS for use with bboxes - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var polygon = { - type: "Polygon", - coordinates: [ [ - [ bbox[ 0 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 1 ] ] - ] ] - }; - - if ( wasGeodetic ) { - polygon.coordinates = $.geo.proj.toGeodetic( polygon.coordinates ); - } - - return polygon; - }, - - reaspect: function (bbox, ratio, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var width = this.width(bbox, true), - height = this.height(bbox, true), - center = this.center(bbox, true), - dx, dy; - - if (width !== 0 && height !== 0 && ratio > 0) { - if (width / height > ratio) { - dx = width / 2; - dy = dx / ratio; - } else { - dy = height / 2; - dx = dy * ratio; - } - - bbox = [center[0] - dx, center[1] - dy, center[0] + dx, center[1] + dy]; - } - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - recenter: function( bbox, center, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj ) { - if ( this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - if ( this._isGeodetic( center ) ) { - center = $.geo.proj.fromGeodetic(center); - } - } - - var halfWidth = ( bbox[ 2 ] - bbox[ 0 ] ) / 2, - halfHeight = ( bbox[ 3 ] - bbox[ 1 ] ) / 2; - - bbox = [ - center[ 0 ] - halfWidth, - center[ 1 ] - halfHeight, - center[ 0 ] + halfWidth, - center[ 1 ] + halfHeight - ]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - scaleBy: function ( bbox, scale, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var c = this.center(bbox, true), - dx = (bbox[2] - bbox[0]) * scale / 2, - dy = (bbox[3] - bbox[1]) * scale / 2; - - bbox = [c[0] - dx, c[1] - dy, c[0] + dx, c[1] + dy]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - width: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[2] - bbox[0]; - }, - - // - // geometry functions - // - - // bbox (Geometry.getEnvelope in JTS) - - bbox: function ( geom, _ignoreGeo /* Internal Use Only */ ) { - var result, wasGeodetic = false; - if ( !geom ) { - return undefined; - } else if ( geom.bbox ) { - result = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.bbox ) ) ? $.geo.proj.fromGeodetic( geom.bbox ) : geom.bbox; - } else { - result = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var coordinates = this._allCoordinates( geom ), - curCoord = 0; - - if ( coordinates.length === 0 ) { - return undefined; - } - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coordinates ) ) { - wasGeodetic = true; - coordinates = $.geo.proj.fromGeodetic( coordinates ); - } - - for ( ; curCoord < coordinates.length; curCoord++ ) { - result[0] = Math.min(coordinates[curCoord][0], result[0]); - result[1] = Math.min(coordinates[curCoord][1], result[1]); - result[2] = Math.max(coordinates[curCoord][0], result[2]); - result[3] = Math.max(coordinates[curCoord][1], result[3]); - } - } - - return wasGeodetic ? $.geo.proj.toGeodetic(result) : result; - }, - - // centroid - - centroid: function( geom, _ignoreGeo /* Internal Use Only */ ) { - switch (geom.type) { - case "Point": - return $.extend({}, geom); - - case "LineString": - case "Polygon": - var a = 0, - c = [0, 0], - coords = $.merge( [ ], geom.type == "Polygon" ? geom.coordinates[0] : geom.coordinates ), - i = 1, j, n, - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coords ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic(coords); - } - - //if (coords[0][0] != coords[coords.length - 1][0] || coords[0][1] != coords[coords.length - 1][1]) { - // coords.push(coords[0]); - //} - - for (; i <= coords.length; i++) { - j = i % coords.length; - - bbox[0] = Math.min(coords[j][0], bbox[0]); - bbox[1] = Math.min(coords[j][1], bbox[1]); - bbox[2] = Math.max(coords[j][0], bbox[2]); - bbox[3] = Math.max(coords[j][1], bbox[3]); - - n = (coords[i - 1][0] * coords[j][1]) - (coords[j][0] * coords[i - 1][1]); - a += n; - c[0] += (coords[i - 1][0] + coords[j][0]) * n; - c[1] += (coords[i - 1][1] + coords[j][1]) * n; - } - - if (a === 0) { - if (coords.length > 0) { - c[0] = Math.min( Math.max( coords[0][0], bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( coords[0][1], bbox[ 1 ] ), bbox[ 3 ] ); - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } else { - return undefined; - } - } - - a *= 3; - //c[0] /= a; - //c[1] /= a; - - c[0] = Math.min( Math.max( c[0] / a, bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( c[1] / a, bbox[ 1 ] ), bbox[ 3 ] ); - - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } - return undefined; - }, - - // contains - - contains: function (geom1, geom2) { - if (geom1.type != "Polygon") { - return false; - } - - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1.coordinates, geom2.coordinates); - - case "LineString": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates); - - case "Polygon": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates[0]); - - default: - return false; - } - }, - - _containsPolygonPoint: function (polygonCoordinates, pointCoordinate) { - if (polygonCoordinates.length === 0 || polygonCoordinates[0].length < 4) { - return false; - } - - var rayCross = 0, - a = polygonCoordinates[0][0], - i = 1, - b, - x; - - for (; i < polygonCoordinates[0].length; i++) { - b = polygonCoordinates[0][i]; - - if ((a[1] <= pointCoordinate[1] && pointCoordinate[1] < b[1]) || (b[1] <= pointCoordinate[1] && pointCoordinate[1] < a[1]) && (pointCoordinate[0] < a[0] || pointCoordinate[0] < b[0])) { - x = a[0] + (b[0] - a[0]) * (pointCoordinate[1] - a[1]) / (b[1] - a[1]); - - if (x > pointCoordinate[0]) { - rayCross++; - } - } - - a = b; - } - - return rayCross % 2 == 1; - }, - - _containsPolygonLineString: function (polygonCoordinates, lineStringCoordinates) { - for (var i = 0; i < lineStringCoordinates.length; i++) { - if (!this._containsPolygonPoint(polygonCoordinates, lineStringCoordinates[i])) { - return false; - } - } - return true; - }, - - // distance - - distance: function ( geom1, geom2, _ignoreGeo /* Internal Use Only */ ) { - var geom1CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom1.coordinates ) ) ? $.geo.proj.fromGeodetic(geom1.coordinates) : geom1.coordinates, - geom2CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom2.coordinates ) ) ? $.geo.proj.fromGeodetic(geom2.coordinates) : geom2.coordinates; - - switch (geom1.type) { - case "Point": - switch (geom2.type) { - case "Point": - return this._distancePointPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "LineString": - return this._distanceLineStringPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "Polygon": - return this._containsPolygonPoint(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "LineString": - switch (geom2.type) { - case "Point": - return this._distanceLineStringPoint(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "LineString": - return this._distanceLineStringLineString(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "Polygon": - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "LineString": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected[0]) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected[0]); - default: - return undefined; - } - break; - } - }, - - _distancePointPoint: function (coordinate1, coordinate2) { - var dx = coordinate2[0] - coordinate1[0], - dy = coordinate2[1] - coordinate1[1]; - return Math.sqrt((dx * dx) + (dy * dy)); - }, - - _distanceLineStringPoint: function (lineStringCoordinates, pointCoordinate) { - var minDist = pos_oo; - - if (lineStringCoordinates.length > 0) { - var a = lineStringCoordinates[0], - - apx = pointCoordinate[0] - a[0], - apy = pointCoordinate[1] - a[1]; - - if (lineStringCoordinates.length == 1) { - return Math.sqrt(apx * apx + apy * apy); - } else { - for (var i = 1; i < lineStringCoordinates.length; i++) { - var b = lineStringCoordinates[i], - - abx = b[0] - a[0], - aby = b[1] - a[1], - bpx = pointCoordinate[0] - b[0], - bpy = pointCoordinate[1] - b[1], - - d = this._distanceSegmentPoint(abx, aby, apx, apy, bpx, bpy); - - if (d === 0) { - return 0; - } - - if (d < minDist) { - minDist = d; - } - - a = b; - apx = bpx; - apy = bpy; - } - } - } - - return Math.sqrt(minDist); - }, - - _distanceSegmentPoint: function (abx, aby, apx, apy, bpx, bpy) { - var dot1 = abx * apx + aby * apy; - - if (dot1 <= 0) { - return apx * apx + apy * apy; - } - - var dot2 = abx * abx + aby * aby; - - if (dot1 >= dot2) { - return bpx * bpx + bpy * bpy; - } - - return apx * apx + apy * apy - dot1 * dot1 / dot2; - }, - - _distanceLineStringLineString: function (lineStringCoordinates1, lineStringCoordinates2) { - var minDist = pos_oo; - for (var i = 0; i < lineStringCoordinates2.length; i++) { - minDist = Math.min(minDist, this._distanceLineStringPoint(lineStringCoordinates1, lineStringCoordinates2[i])); - } - return minDist; - }, - - // buffer - - _buffer: function( geom, distance, _ignoreGeo /* Internal Use Only */ ) { - var wasGeodetic = false, - coords = geom.coordinates; - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.coordinates ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic( geom.coordinates ); - } - - if ( geom.type === "Point" ) { - var resultCoords = [], - slices = 180, - i = 0, - a; - - for ( ; i <= slices; i++ ) { - a = ( i * 360 / slices ) * ( Math.PI / 180 ); - resultCoords.push( [ - coords[ 0 ] + Math.cos( a ) * distance, - coords[ 1 ] + Math.sin( a ) * distance - ] ); - } - - return { - type: "Polygon", - coordinates: [ ( wasGeodetic ? $.geo.proj.toGeodetic( resultCoords ) : resultCoords ) ] - }; - } else { - return undefined; - } - }, - - - // - // feature - // - - _flatten: function (geom) { - // return an array of all basic geometries - // not in JTS - var geometries = [], - curGeom = 0; - switch (geom.type) { - case "Feature": - $.merge(geometries, this._flatten(geom.geometry)); - break; - - case "FeatureCollection": - for (; curGeom < geom.features.length; curGeom++) { - $.merge(geometries, this._flatten(geom.features[curGeom].geometry)); - } - break; - - case "GeometryCollection": - for (; curGeom < geom.geometries.length; curGeom++) { - $.merge(geometries, this._flatten(geom.geometries[curGeom])); - } - break; - - default: - geometries[0] = geom; - break; - } - return geometries; - }, - - length: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - lineStringCoordinates, - i = 1, dx, dy; - - switch ( geom.type ) { - case "Point": - return 0; - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][0] - lineStringCoordinates[ i - 1 ][0]; - dy = lineStringCoordinates[ i ][1] - lineStringCoordinates[ i - 1 ][1]; - sum += Math.sqrt((dx * dx) + (dy * dy)); - } - - return sum; - } - - // return undefined; - }, - - area: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - polygonCoordinates, - i = 1, j; - - switch ( geom.type ) { - case "Point": - case "LineString": - return 0; - - case "Polygon": - polygonCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( polygonCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( polygonCoordinates ) ) { - polygonCoordinates = $.geo.proj.fromGeodetic( polygonCoordinates ); - } - - for ( ; i <= polygonCoordinates.length; i++) { - j = i % polygonCoordinates.length; - sum += ( polygonCoordinates[ i - 1 ][ 0 ] - polygonCoordinates[ j ][ 0 ] ) * ( polygonCoordinates[ i - 1 ][ 1 ] + polygonCoordinates[ j ][ 1 ] ) / 2; - } - - return Math.abs( sum ); - } - }, - - pointAlong: function( geom, percentage, _ignoreGeo /* Internal Use Only */ ) { - var totalLength = 0, - previousPercentageSum = 0, - percentageSum = 0, - remainderPercentageSum, - len, - lineStringCoordinates, - segmentLengths = [], - i = 1, dx, dy, - c, c0, c1, - wasGeodetic = false; - - switch ( geom.type ) { - case "Point": - return $.extend( { }, geom ); - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( percentage === 0 ) { - return { - type: "Point", - coordinates: [ lineStringCoordinates[ 0 ][ 0 ], lineStringCoordinates[ 0 ][ 1 ] ] - }; - } else if ( percentage === 1 ) { - i = lineStringCoordinates.length - 1; - return { - type: "Point", - coordinates: [ lineStringCoordinates[ i ][ 0 ], lineStringCoordinates[ i ][ 1 ] ] - }; - } else { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - wasGeodetic = true; - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][ 0 ] - lineStringCoordinates[ i - 1 ][ 0 ]; - dy = lineStringCoordinates[ i ][ 1 ] - lineStringCoordinates[ i - 1 ][ 1 ]; - len = Math.sqrt((dx * dx) + (dy * dy)); - segmentLengths.push( len ); - totalLength += len; - } - - for ( i = 0; i < segmentLengths.length && percentageSum < percentage; i++ ) { - previousPercentageSum = percentageSum; - percentageSum += ( segmentLengths[ i ] / totalLength ); - } - - remainderPercentageSum = percentage - previousPercentageSum; - - c0 = lineStringCoordinates[ i - 1 ]; - c1 = lineStringCoordinates[ i ]; - - c = [ - c0[ 0 ] + ( remainderPercentageSum * ( c1[ 0 ] - c0[ 0 ] ) ), - c0[ 1 ] + ( remainderPercentageSum * ( c1[ 1 ] - c0[ 1 ] ) ) - ]; - - return { - type: "Point", - coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c - }; - } - } - }, - - // - // WKT functions - // - - _WKT: (function () { - function pointToString(value) { - return "POINT " + pointToUntaggedString(value.coordinates); - } - - function pointToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - return "(" + coordinates.join(" ") + ")"; - } - } - - function lineStringToString(value) { - return "LINESTRING " + lineStringToUntaggedString(value.coordinates); - } - - function lineStringToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var points = []; - - for (var i = 0; i < coordinates.length; i++) { - points.push(coordinates[i].join(" ")); - } - - return "(" + points + ")"; - } - } - - function polygonToString(value) { - return "POLYGON " + polygonToUntaggedString(value.coordinates); - } - - function polygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMTPY"; - } else { - var lineStrings = []; - - for (var i = 0; i < coordinates.length; i++) { - lineStrings.push(lineStringToUntaggedString(coordinates[i])); - } - - return "(" + lineStrings + ")"; - } - } - - function multiPointToString(value) { - return "MULTIPOINT " + lineStringToUntaggedString(value.coordinates); - } - - function multiLineStringToString(value) { - return "MULTILINSTRING " + polygonToUntaggedString(value.coordinates); - } - - function multiPolygonToString(value) { - return "MULTIPOLYGON " + multiPolygonToUntaggedString(value.coordinates); - } - - function multiPolygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var polygons = []; - for (var i = 0; i < coordinates.length; i++) { - polygons.push(polygonToUntaggedString(coordinates[i])); - } - return "(" + polygons + ")"; - } - } - - function geometryCollectionToString(value) { - return "GEOMETRYCOLLECTION " + geometryCollectionToUntaggedString(value.geometries); - } - - function geometryCollectionToUntaggedString(geometries) { - if (!(geometries && geometries.length)) { - return "EMPTY"; - } else { - var geometryText = []; - for (var i = 0; i < geometries.length; i++) { - geometryText.push(stringify(geometries[i])); - } - return "(" + geometries + ")"; - } - } - - function stringify(value) { - if (!(value && value.type)) { - return ""; - } else { - switch (value.type) { - case "Point": - return pointToString(value); - - case "LineString": - return lineStringToString(value); - - case "Polygon": - return polygonToString(value); - - case "MultiPoint": - return multiPointToString(value); - - case "MultiLineString": - return multiLineStringToString(value); - - case "MultiPolygon": - return multiPolygonToString(value); - - case "GeometryCollection": - return geometryCollectionToString(value); - - default: - return ""; - } - } - } - - function pointParseUntagged(wkt) { - var pointString = wkt.match( /\(\s*([\d\.\-]+)\s+([\d\.\-]+)\s*\)/ ); - return pointString && pointString.length > 2 ? { - type: "Point", - coordinates: [ - parseFloat(pointString[1]), - parseFloat(pointString[2]) - ] - } : null; - } - - function lineStringParseUntagged(wkt) { - var lineString = wkt.match( /\s*\((.*)\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( lineString && lineString.length > 1 ) { - pointStrings = lineString[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "LineString", - coordinates: coords - }; - } else { - return null; - } - } - - function polygonParseUntagged(wkt) { - var polygon = wkt.match( /\s*\(\s*\((.*)\)\s*\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( polygon && polygon.length > 1 ) { - pointStrings = polygon[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "Polygon", - coordinates: [ coords ] - }; - } else { - return null; - } - } - - function multiPointParseUntagged(wkt) { - var multiSomething; - - if ( wkt.indexOf( "((" ) === -1 ) { - multiSomething = lineStringParseUntagged( wkt ); - } else { - multiSomething = multiLineStringParseUntagged( wkt ); - multiSomething.coordinates = $.geo._allCoordinates( multiSomething ); - } - - multiSomething.type = "MultiPoint"; - - return multiSomething; - } - - function multiLineStringParseUntagged(wkt) { - var lineStringsWkt = wkt.substr( 1, wkt.length - 2 ), - lineStrings = lineStringsWkt.split( ")),((" ), - i = 0, - multiLineString = { - type: "MultiLineString", - coordinates: [ ] - }; - - for ( ; i < lineStrings.length; i++ ) { - multiLineString.coordinates.push( lineStringParseUntagged( lineStrings[ i ] ).coordinates ); - } - - return multiLineString; - } - - function multiPolygonParseUntagged(wkt) { - var polygonsWkt = wkt.substr( 1, wkt.length - 2 ), - polygons = polygonsWkt.split( ")),((" ), - i = 0, - multiPolygon = { - type: "MultiPolygon", - coordinates: [ ] - }; - - for ( ; i < polygons.length; i++ ) { - multiPolygon.coordinates.push( polygonParseUntagged( polygons[ i ] ).coordinates ); - } - - return multiPolygon; - } - - function geometryCollectionParseUntagged( wkt ) { - var geometriesWkt = wkt.substr( 1, wkt.length - 2 ), - geometries = geometriesWkt.match( /\),[a-zA-Z]/g ), - geometryCollection = { - type: "GeometryCollection", - geometries: [ ] - }, - curGeom, - i = 0, curStart = 0, curLen; - - if ( geometries && geometries.length > 0 ) { - for ( ; i < geometries.length; i++ ) { - curLen = geometriesWkt.indexOf( geometries[ i ], curStart ) - curStart + 1; - curGeom = parse( geometriesWkt.substr( curStart, curLen ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - curStart += curLen + 1; - } - - // one more - curGeom = parse( geometriesWkt.substr( curStart ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - - return geometryCollection; - } else { - return null; - } - } - - function parse(wkt) { - wkt = $.trim(wkt); - - var typeIndex = wkt.indexOf( "(" ), - untagged = wkt.substr( typeIndex ); - - switch ($.trim(wkt.substr(0, typeIndex)).toUpperCase()) { - case "POINT": - return pointParseUntagged( untagged ); - - case "LINESTRING": - return lineStringParseUntagged( untagged ); - - case "POLYGON": - return polygonParseUntagged( untagged ); - - case "MULTIPOINT": - return multiPointParseUntagged( untagged ); - - case "MULTILINESTRING": - return multiLineStringParseUntagged( untagged ); - - case "MULTIPOLYGON": - return multiPolygonParseUntagged( untagged ); - - case "GEOMETRYCOLLECTION": - return geometryCollectionParseUntagged( untagged ); - - default: - return null; - } - } - - return { - stringify: stringify, - - parse: parse - }; - }()), - - // - // projection functions - // - - proj: (function () { - var halfPi = 1.5707963267948966192, - quarterPi = 0.7853981633974483096, - radiansPerDegree = 0.0174532925199432958, - degreesPerRadian = 57.295779513082320877, - semiMajorAxis = 6378137; - - return { - fromGeodeticPos: function (coordinate) { - return [ - semiMajorAxis * coordinate[ 0 ] * radiansPerDegree, - semiMajorAxis * Math.log(Math.tan(quarterPi + coordinate[ 1 ] * radiansPerDegree / 2)) - ]; - }, - - fromGeodetic: function ( coordinates ) { - if ( ! $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - fromGeodeticPos = this.fromGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length == 4) { - // bbox - var min = fromGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = fromGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = fromGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - }, - - toGeodeticPos: function (coordinate) { - return [ - (coordinate[ 0 ] / semiMajorAxis) * degreesPerRadian, - (halfPi - 2 * Math.atan(1 / Math.exp(coordinate[ 1 ] / semiMajorAxis))) * degreesPerRadian - ]; - }, - - toGeodetic: function (coordinates) { - if ( $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - toGeodeticPos = this.toGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length == 4) { - // bbox - var min = toGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = toGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = toGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - } - }; - }()), - - // - // service types (defined in other files) - // - - _serviceTypes: {} - }; -}(jQuery, this)); - -(function ($, undefined) { - var _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ); - - $.widget("geo.geographics", { - _$elem: undefined, - _options: {}, - _trueCanvas: true, - _trueDoubleBuffer: true, - - _width: 0, - _height: 0, - - _$canvas: undefined, - _context: undefined, - - _$canvasSceneFront: undefined, //< if _trueCanvas, where canvas images get written (front buffer) - _$canvasSceneBack: undefined, //< if _trueCanvas, where canvas images get written (back buffer) - _timeoutEnd: null, - _requireFlip: false, - - _blitcanvas: undefined, - _blitcontext: undefined, - - _$labelsContainerFront: undefined, - _$labelsContainerBack: undefined, - _labelsHtml: "", - - options: { - style: { - borderRadius: "8px", - color: "#7f0000", - //fill: undefined, - fillOpacity: 0.2, - height: "8px", - opacity: 1, - //stroke: undefined, - strokeOpacity: 1, - strokeWidth: "2px", - visibility: "visible", - width: "8px" - }, - - doubleBuffer: true - }, - - _create: function () { - this._$elem = this.element; - this._options = this.options; - - this._$elem.css( { - webkitTransform: "translateZ(0)", - display: "inline-block", - overflow: "hidden", - textAlign: "left" - } ); - - if (this._$elem.css("position") == "static") { - this._$elem.css("position", "relative"); - } - - this._$elem.addClass( "geo-graphics" ); - - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - var posCss = 'position:absolute;left:0;top:0;margin:0;padding:0;', - sizeCss = 'width:' + this._width + 'px;height:' + this._height + 'px;', - sizeAttr = 'width="' + this._width + '" height="' + this._height + '"'; - - this._blitcanvas = document.createElement( "canvas" ); - - if ( this._blitcanvas.getContext ) { - //this._$elem.append(''); - //this._$canvas = this._$elem.children(':last'); - this._$canvas = $(''); - - // test _trueDoubleBuffer - this._blitcanvas.width = 1; - this._blitcanvas.height = 1; - this._trueDoubleBuffer = this._blitcanvas.toDataURL().length > 6; - - if ( !(this._options.doubleBuffer && this._trueDoubleBuffer) ) { - this._$elem.append( this._$canvas ); - } - - this._context = this._$canvas[0].getContext("2d"); - - //this._blitcanvas = document.createElement( "canvas" ); - this._blitcanvas.width = this._width; - this._blitcanvas.height = this._height; - this._blitcontext = this._blitcanvas.getContext("2d"); - - // create our front & back buffers - this._$canvasSceneFront = $(''); - this._$canvasSceneBack = $(''); - - } else if (_ieVersion <= 8) { - this._trueCanvas = false; - this._$elem.append( '
'); - this._$canvas = this._$elem.children(':last'); - - G_vmlCanvasManager.initElement(this._$canvas[0]); - this._context = this._$canvas[0].getContext("2d"); - this._$canvas.children().css({ backgroundColor: "transparent", width: this._width, height: this._height }); - } - - // create our front & back label containers - this._$labelsContainerFront = $('
'); - this._$labelsContainerBack = $('
'); - }, - - _setOption: function (key, value) { - if (key == "style") { - value = $.extend({}, this._options.style, value); - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - destroy: function () { - $.Widget.prototype.destroy.apply(this, arguments); - this._$elem.html(""); - this._$elem.removeClass( "geo-graphics" ); - }, - - clear: function () { - this._context.clearRect(0, 0, this._width, this._height); - this._labelsHtml = ""; - - //if ( this._options.doubleBuffer ) console.log("clear:_end " + $.now()); - this._end( ); - }, - - drawArc: function (coordinates, startAngle, sweepAngle, style) { - style = this._getGraphicStyle(style); - - if (style.visibility != "hidden" && style.opacity > 0 && style.widthValue > 0 && style.heightValue > 0) { - var r = Math.min(style.widthValue, style.heightValue) / 2; - - startAngle = (startAngle * Math.PI / 180); - sweepAngle = (sweepAngle * Math.PI / 180); - - this._context.save(); - this._context.translate(coordinates[0], coordinates[1]); - if (style.widthValue > style.heightValue) { - this._context.scale(style.widthValue / style.heightValue, 1); - } else { - this._context.scale(1, style.heightValue / style.widthValue); - } - - this._context.beginPath(); - this._context.arc(0, 0, r, startAngle, sweepAngle, false); - - if (this._trueCanvas) { - this._context.restore(); - } - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - if (!this._trueCanvas) { - this._context.restore(); - } - } - - //if ( this._options.doubleBuffer ) console.log("drawArc:_end " + $.now()); - this._end( ); - }, - - drawPoint: function (coordinates, style) { - style = this._getGraphicStyle(style); - if (style.widthValue == style.heightValue && style.heightValue == style.borderRadiusValue) { - this.drawArc(coordinates, 0, 360, style); - } else if (style.visibility != "hidden" && style.opacity > 0) { - style.borderRadiusValue = Math.min(Math.min(style.widthValue, style.heightValue) / 2, style.borderRadiusValue); - coordinates[0] -= style.widthValue / 2; - coordinates[1] -= style.heightValue / 2; - this._context.beginPath(); - this._context.moveTo(coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.lineTo(coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1]); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1], coordinates[0] + style.widthValue, coordinates[1] + style.borderRadiusValue); - this._context.lineTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue, coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.lineTo(coordinates[0] + style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1] + style.heightValue, coordinates[0], coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.lineTo(coordinates[0], coordinates[1] + style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1], coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.closePath(); - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - - this._context.stroke(); - } - - //if ( this._options.doubleBuffer ) console.log("drawPoint:_end " + $.now()); - this._end( ); - } - }, - - drawLineString: function (coordinates, style) { - this._drawLines([coordinates], false, style); - }, - - drawPolygon: function (coordinates, style) { - if ( !this._trueCanvas || coordinates.length == 1 ) { - // either we don't have fancy rendering or there's no need for it (no holes) - this._drawLines( coordinates, true, style ); - } else { - if ( !coordinates || !coordinates.length || coordinates[ 0 ].length < 3 ) { - // this is not a Polygon or it doesn't have a proper outer ring - return; - } - - style = this._getGraphicStyle(style); - - var pixelBbox, i, j; - - if ( style.visibility != "hidden" && style.opacity > 0 ) { - this._blitcontext.clearRect(0, 0, this._width, this._height); - - if ( style.doFill ) { - if ( coordinates.length > 1 ) { - // stencil inner rings - this._blitcontext.globalCompositeOperation = "source-out"; - this._blitcontext.globalAlpha = 1; - - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.fill( ); - } - } - } - - // path outer ring - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ 0 ][ 0 ][ 0 ], coordinates[ 0 ][ 0 ][ 1 ] ); - - pixelBbox = [ coordinates[ 0 ][ 0 ][ 0 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 0 ] + style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] + style.strokeWidthValue ]; - - for ( i = 1; i < coordinates[ 0 ].length - 1; i++ ) { - this._blitcontext.lineTo( coordinates[ 0 ][ i ][ 0 ], coordinates[ 0 ][ i ][ 1 ] ); - - pixelBbox[ 0 ] = Math.min( coordinates[ 0 ][ i ][ 0 ] - style.strokeWidthValue, pixelBbox[ 0 ] ); - pixelBbox[ 1 ] = Math.min( coordinates[ 0 ][ i ][ 1 ] - style.strokeWidthValue, pixelBbox[ 1 ] ); - pixelBbox[ 2 ] = Math.max( coordinates[ 0 ][ i ][ 0 ] + style.strokeWidthValue, pixelBbox[ 2 ] ); - pixelBbox[ 3 ] = Math.max( coordinates[ 0 ][ i ][ 1 ] + style.strokeWidthValue, pixelBbox[ 3 ] ); - } - - this._blitcontext.closePath(); - - this._blitcontext.globalCompositeOperation = "source-out"; - if ( style.doFill ) { - // fill outer ring - this._blitcontext.fillStyle = style.fill; - this._blitcontext.globalAlpha = style.opacity * style.fillOpacity; - this._blitcontext.fill( ); - } - - this._blitcontext.globalCompositeOperation = "source-over"; - if ( style.doStroke ) { - // stroke outer ring - this._blitcontext.lineCap = this._blitcontext.lineJoin = "round"; - this._blitcontext.lineWidth = style.strokeWidthValue; - this._blitcontext.strokeStyle = style.stroke; - - this._blitcontext.globalAlpha = style.opacity * style.strokeOpacity; - this._blitcontext.stroke( ); - - if ( coordinates.length > 1 ) { - // stroke inner rings - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.stroke( ); - } - } - } - - // blit - pixelBbox[ 0 ] = Math.min( Math.max( pixelBbox[ 0 ], 0), this._width ); - pixelBbox[ 1 ] = Math.min( Math.max( pixelBbox[ 1 ], 0), this._height ); - pixelBbox[ 2 ] = Math.min( Math.max( pixelBbox[ 2 ], 0), this._width ); - pixelBbox[ 3 ] = Math.min( Math.max( pixelBbox[ 3 ], 0), this._height ); - - if ( pixelBbox[ 0 ] !== pixelBbox[ 2 ] && pixelBbox[ 1 ] !== pixelBbox[ 3 ] ) { - this._context.drawImage(this._blitcanvas, pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ], pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ] ); - - //if ( this._options.doubleBuffer ) console.log("drawPolygon:_end " + $.now()); - this._end( ); - } - } - } - }, - - drawBbox: function (bbox, style) { - this._drawLines([[ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ]], true, style); - }, - - drawLabel: function( coordinates, label ) { - this._labelsHtml += '
' + label + '
'; - }, - - resize: function( ) { - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - if ( this._trueCanvas ) { - this._$canvas[0].width = this._width; - this._$canvas[0].height = this._height; - - this._$canvasSceneFront.css( { - width: this._width, - height: this._height - } ); - - this._$canvasSceneBack.css( { - width: this._width, - height: this._height - } ); - } else { - this._$canvas.css( { - width: this._width, - height: this._height - } ); - } - - this._$labelsContainerFront.css( { - width: this._width, - height: this._height - } ); - - this._$labelsContainerBack.css( { - width: this._width, - height: this._height - } ); - }, - - interactiveTransform: function( origin, scale ) { - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - // hide labels for now until they are on the interactive div - //this._$labelsContainerFront.html(""); - - if ( this._trueCanvas ) { - if ( this._options.doubleBuffer && this._trueDoubleBuffer ) { - - - if ( this._requireFlip ) { - var geographics = this; - - var oldCanvasScene = geographics._$canvasSceneFront; - - geographics._$canvasSceneFront = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ).prependTo( geographics._$elem ); - - geographics._$canvasSceneBack = oldCanvasScene.detach(); - - geographics._requireFlip = false; - } - - - //console.log("geographics:interactiveTransform " + this._$canvasSceneFront.prop( "id" ) + ": origin: " + origin.toString() + ", scale: " + scale); - // transform a finished scene, can assume no drawing during these calls - this._$canvasSceneFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - - // transform labels - this._$labelsContainerFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - }, - - _end: function( ) { - // end/finalize a scene - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - this._requireFlip = true; - - var geographics = this; - - function endCallback( ) { - if ( !geographics._timeoutEnd ) { - // something has canceled the draw - return; - } - - if ( geographics._trueCanvas && geographics._options.doubleBuffer && geographics._trueDoubleBuffer ) { - //console.log(" endCallback..."); - - //geographics._$canvasSceneFront = - geographics._$canvasSceneBack.prop( "src", "" ).one( "load", function( e ) { - //console.log(" ...flip: show " + geographics._$canvasSceneBack.prop( "id" ) + ", hide " + geographics._$canvasSceneFront.prop("id")); - geographics._requireFlip = false; - var oldCanvasScene = geographics._$canvasSceneFront; - - geographics._$canvasSceneFront = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prependTo( geographics._$elem ); - - geographics._$canvasSceneBack = oldCanvasScene.detach(); - } ).prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ); - } - - - geographics._$labelsContainerBack.html( geographics._labelsHtml ).find("a").css({ - position: "relative", - zIndex: 100, - display: "inline-block", - webkitTransform: "translateZ(0)" - }); - - var oldLabelsContainer = geographics._$labelsContainerFront; - - geographics._$labelsContainerFront = geographics._$labelsContainerBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prependTo( geographics._$elem ); - - geographics._$labelsContainerBack = oldLabelsContainer.detach(); - - - geographics._timeoutEnd = null; - } - - //if ( this._options.doubleBuffer ) { - this._timeoutEnd = setTimeout( endCallback, 20 ); - //} else { - //geographics._$labelsContainerFront.html( geographics._labelsHtml ); - //} - }, - - _getGraphicStyle: function (style) { - function safeParse(value) { - value = parseInt(value, 10); - return (+value + '') === value ? +value : value; - } - - style = $.extend({}, this._options.style, style); - style.borderRadiusValue = safeParse(style.borderRadius); - style.fill = style.fill || style.color; - style.doFill = style.fill && style.fillOpacity > 0; - style.stroke = style.stroke || style.color; - style.strokeWidthValue = safeParse(style.strokeWidth); - style.doStroke = style.stroke && style.strokeOpacity > 0 && style.strokeWidthValue > 0; - style.widthValue = safeParse(style.width); - style.heightValue = safeParse(style.height); - return style; - }, - - _drawLines: function (coordinates, close, style) { - if (!coordinates || !coordinates.length || coordinates[0].length < 2) { - return; - } - - var i, j; - style = this._getGraphicStyle(style); - - if (style.visibility != "hidden" && style.opacity > 0) { - this._context.beginPath(); - - for (i = 0; i < coordinates.length; i++) { - this._context.moveTo(coordinates[i][0][0], coordinates[i][0][1]); - for (j = 1; j < coordinates[i].length; j++) { - this._context.lineTo(coordinates[i][j][0], coordinates[i][j][1]); - } - } - - if (close) { - this._context.closePath(); - } - - if (close && style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineCap = this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - //if ( this._options.doubleBuffer ) console.log("_drawLines:_end " + $.now()); - this._end( ); - } - } - }); -}(jQuery)); - - -(function ($, undefined) { - var _widgetIdSeed = 0, - _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ), - - _defaultOptions = { - bbox: [-180, -85, 180, 85], - bboxMax: [-180, -85, 180, 85], - center: [0, 0], - cursors: { - "static": "default", - pan: "url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move", - zoom: "crosshair", - dragBox: "crosshair", - dragCircle: "crosshair", - drawPoint: "crosshair", - drawLineString: "crosshair", - drawPolygon: "crosshair", - measureLength: "crosshair", - measureArea: "crosshair" - }, - measureLabels: { - length: "{{:length.toFixed( 2 )}} m", - area: "{{:area.toFixed( 2 )}} sq m" - }, - drawStyle: {}, - shapeStyle: {}, - mode: "pan", - pannable: true, - scroll: "default", - shift: "default", - services: [ - { - "class": "osm", - type: "tiled", - src: function (view) { - return "http://otile" + ((view.index % 4) + 1) + ".mqcdn.com/tiles/1.0.0/osm/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; - }, - attr: "Tiles Courtesy of MapQuest " - } - ], - tilingScheme: { - tileWidth: 256, - tileHeight: 256, - levels: 18, - basePixelSize: 156543.03392799936, - origin: [-20037508.342787, 20037508.342787] - }, - axisLayout: "map", - zoom: 0, - zoomMin: 0, - zoomMax: Number.POSITIVE_INFINITY, - pixelSize: 0 - }; - - $.widget("geo.geomap", { - // private widget members - _$elem: undefined, //< map div for maps, service div for services - _map: undefined, //< only defined in services - _created: false, - _createdGraphics: false, - _widgetId: 0, - _tmplLengthId: "", - _tmplAreaId: "", - - _contentBounds: {}, - - _$resizeContainer: undefined, //< all elements that should match _contentBounds' size - - _$eventTarget: undefined, - _$contentFrame: undefined, - _$existingChildren: undefined, - _$attrList: undefined, - _$servicesContainer: undefined, - _$shapesContainers: undefined, //< all shapesContainer divs (map only) - - _$panContainer: undefined, //< all non-service elements that move while panning - _$shapesContainer: undefined, //< just "our" shapesContainer div (map & service) - _$drawContainer: undefined, - _$measureContainer: undefined, - _$measureLabel: undefined, - - _dpi: 96, - - _currentServices: [], //< internal copy - - _center: undefined, - _pixelSize: undefined, - _centerMax: undefined, - _pixelSizeMax: undefined, - - _userGeodetic: true, - - _centerInteractive: undefined, - _pixelSizeInteractive: undefined, - _timeoutInteractive: null, - _triggerInteractive: false, - - _timeoutRefreshShapes: null, - - _loadCount: 0, - - _wheelTimeout: null, - _wheelLevel: 0, - - _zoomFactor: 2, //< determines what a zoom level means - - _fullZoomFactor: 2, //< interactiveScale factor needed to zoom a whole level - _partialZoomFactor: 1.18920711500273, //< interactiveScale factor needed to zoom a fraction of a level (the fourth root of 2) - - _mouseDown: undefined, - _inOp: undefined, - _toolPan: undefined, - _shiftDown: undefined, - _anchor: undefined, - _current: undefined, - _downDate: undefined, - _moveDate: undefined, - _clickDate: undefined, - _lastMove: undefined, - _lastDrag: undefined, - - _windowHandler: null, - _resizeTimeout: null, - - _panning: undefined, - _velocity: undefined, - _friction: undefined, - - _supportTouch: undefined, - _softDblClick: undefined, - _isTap: undefined, - _isDbltap: undefined, - - _isMultiTouch: undefined, - _multiTouchAnchor: [], //< TouchList - _multiTouchAnchorBbox: undefined, //< bbox - _multiTouchCurrentBbox: undefined, //< bbox - - _drawTimeout: null, //< used in drawPoint mode so we don't send two shape events on dbltap - _drawPixels: [], //< an array of coordinate arrays for drawing lines & polygons, in pixel coordinates - _drawCoords: [], - - _graphicShapes: [], //< an array of objects containing style object refs & GeoJSON object refs - - _initOptions: {}, - - _options: {}, - - options: $.extend({}, _defaultOptions), - - _createWidget: function (options, element) { - this._$elem = $(element); - - if (this._$elem.is(".geo-service")) { - this._graphicShapes = []; - $.Widget.prototype._createWidget.apply(this, arguments); - return; - } - - this._widgetId = _widgetIdSeed++; - this._tmplLengthId = "geoMeasureLength" + this._widgetId; - this._tmplAreaId = "geoMeasureArea" + this._widgetId; - - this._$elem.addClass("geo-map").css( { - webkitTransform: "translateZ(0)" - } ); - - - this._initOptions = options || {}; - - this._forcePosition(this._$elem); - - this._$elem.css("text-align", "left"); - - var size = this._findMapSize(); - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._createChildren(); - - this._center = [ 0, 0 ]; - this._centerMax = [ 0, 0 ]; - this._centerInteractive = [ 0, 0 ]; - - this.options["pixelSize"] = this._pixelSize = this._pixelSizeMax = 156543.03392799936; - - this._mouseDown = - this._inOp = - this._toolPan = - this._shiftDown = - this._panning = - this._isTap = - this._isDbltap = false; - - this._anchor = [ 0, 0 ]; - this._current = [ 0, 0 ]; - this._lastMove = [ 0, 0 ]; - this._lastDrag = [ 0, 0 ]; - this._velocity = [ 0, 0 ]; - - this._friction = [0.8, 0.8]; - - this._downDate = - this._moveDate = - this._clickDate = 0; - - this._drawPixels = []; - this._drawCoords = []; - this._graphicShapes = []; - - - $.Widget.prototype._createWidget.apply(this, arguments); - }, - - _create: function () { - this._options = this.options; - - if (this._$elem.is(".geo-service")) { - this._map = this._$elem.data( "geoMap" ); - this._$elem.data( "geoService", this ); - return; - } - - this._map = this; - - this._supportTouch = "ontouchend" in document; - this._softDblClick = this._supportTouch || _ieVersion == 7; - - var geomap = this, - touchStartEvent = this._supportTouch ? "touchstart" : "mousedown", - touchStopEvent = this._supportTouch ? "touchend touchcancel" : "mouseup", - touchMoveEvent = this._supportTouch ? "touchmove" : "mousemove"; - - $(document).keydown($.proxy(this._document_keydown, this)); - - this._$eventTarget.dblclick($.proxy(this._eventTarget_dblclick, this)); - - this._$eventTarget.bind(touchStartEvent, $.proxy(this._eventTarget_touchstart, this)); - - var dragTarget = (this._$eventTarget[0].setCapture) ? this._$eventTarget : $(document); - dragTarget.bind(touchMoveEvent, $.proxy(this._dragTarget_touchmove, this)); - dragTarget.bind(touchStopEvent, $.proxy(this._dragTarget_touchstop, this)); - - this._$eventTarget.mousewheel($.proxy(this._eventTarget_mousewheel, this)); - - this._windowHandler = function () { - if (geomap._resizeTimeout) { - clearTimeout(geomap._resizeTimeout); - } - geomap._resizeTimeout = setTimeout(function () { - if (geomap._created) { - geomap._$elem.geomap( "resize", true ); - } - }, 500); - }; - - $(window).resize(this._windowHandler); - - this._$drawContainer.geographics({ style: this._initOptions.drawStyle || {}, doubleBuffer: false }); - this._options["drawStyle"] = this._$drawContainer.geographics("option", "style"); - - this._$shapesContainer.geographics( { style: this._initOptions.shapeStyle || { } } ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - - if (this._initOptions) { - // always init tilingScheme right away, even if it's null - if ( this._initOptions.tilingScheme !== undefined ) { - this._setOption("tilingScheme", this._initOptions.tilingScheme || null, false); - } - - if ( this._initOptions.services ) { - // jQuery UI Widget Factory merges user services with our default, we want to clobber the default - this._options[ "services" ] = $.merge( [ ], this._initOptions.services ); - } - if (this._initOptions.bboxMax) { - this._setOption("bboxMax", this._initOptions.bboxMax, false); - this._setOption("bbox", this._initOptions.bboxMax, false); - } - if (this._initOptions.zoomMin !== undefined) { - this._setOption("zoomMin", this._initOptions.zoomMin, false); - } - if (this._initOptions.zoomMax !== undefined) { - this._setOption("zoomMax", this._initOptions.zoomMax, false); - } - if (this._initOptions.bbox) { - this._setOption("bbox", this._initOptions.bbox, false); - } - if (this._initOptions.center) { - this._setOption("center", this._initOptions.center, false); - } - if (this._initOptions.zoom !== undefined) { - this._setOption("zoom", this._initOptions.zoom, false); - } - } - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._createServices(); - this._refresh(); - - this._created = true; - }, - - _setOption: function (key, value, refresh) { - if ( key == "pixelSize" ) { - return; - } - - refresh = (refresh === undefined || refresh); - - if ( this._$elem.is( ".geo-map" ) ) { - this._panFinalize(); - } - - var center, pixelSize, bbox, zoom; - - switch (key) { - case "bbox": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2]; - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height); - - // clamp to zoom - zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( center, pixelSize ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( center, pixelSize, false, refresh ); - } - - value = this._getBbox( center, pixelSize ); - break; - - case "bboxMax": - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - break; - - case "center": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( value, this._pixelSizeInteractive ); - this._interactiveTransform( ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( value, this._pixelSize, false, refresh ); - } - break; - - case "measureLabels": - value = $.extend( this._options[ "measureLabels" ], value ); - - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - break; - - case "drawStyle": - if (this._$drawContainer) { - this._$drawContainer.geographics("option", "style", value); - value = this._$drawContainer.geographics("option", "style"); - } - break; - - case "shapeStyle": - if ( this._$elem.is( ".geo-service" ) && !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("option", "style", value); - value = this._$shapesContainer.geographics("option", "style"); - } - break; - - case "mode": - this._resetDrawing( ); - this._$eventTarget.css("cursor", this._options["cursors"][value]); - break; - - case "zoom": - if ( this._created ) { - this._setZoom(value, false, refresh); - } else { - value = Math.max( value, 0 ); - this._setCenterAndSize( this._center, this._getPixelSize( value ), false, refresh ); - } - break; - } - - $.Widget.prototype._setOption.apply(this, arguments); - - switch ( key ) { - case "bbox": - case "center": - if ( this._userGeodetic ) { - this._options[ "bbox" ] = $.geo.proj.toGeodetic( this._options[ "bbox" ] ); - this._options[ "center" ] = $.geo.proj.toGeodetic( this._center ); - } - break; - - case "tilingScheme": - if ( value !== null ) { - this._pixelSizeMax = this._getPixelSize( 0 ); - this._centerMax = [ - value.origin[ 0 ] + this._pixelSizeMax * value.tileWidth / 2, - value.origin[ 1 ] + this._pixelSizeMax * value.tileHeight / 2 - ]; - } - break; - - case "bboxMax": - if ( $.geo.proj && $.geo._isGeodetic( value ) ) { - bbox = $.geo.proj.fromGeodetic( value ); - } else { - bbox = value; - } - - this._centerMax = $.geo.center( bbox ); - this._pixelSizeMax = Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - break; - - case "services": - this._createServices(); - if (refresh) { - this._refresh(); - this._refreshAllShapes(); - } - break; - - case "shapeStyle": - if ( refresh && this._createdGraphics ) { - this._$shapesContainer.geographics("clear"); - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - break; - } - }, - - destroy: function () { - if ( this._$elem.is(".geo-service") ) { - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - } - } else { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - - this._created = false; - - $(window).unbind("resize", this._windowHandler); - - for ( var i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - - this._$drawContainer.geographics("destroy"); - this._$drawContainer = undefined; - - this._$existingChildren.detach(); - this._$elem.html(""); - this._$elem.append(this._$existingChildren); - this._$elem.removeClass("geo-map"); - } - - $.Widget.prototype.destroy.apply(this, arguments); - }, - - toMap: function (p) { - p = this._toMap(p); - return this._userGeodetic ? $.geo.proj.toGeodetic(p) : p; - }, - - toPixel: function ( p, _center /* Internal Use Only */, _pixelSize /* Internal Use Only */ ) { - return this._toPixel( $.geo.proj ? $.geo.proj.fromGeodetic( p ) : p, _center, _pixelSize ); - }, - - opacity: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "opacity", value, this._$elem ); - } else { - if ( value >= 0 || value <= 1 ) { - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - service.style.opacity = value; - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - $.geo[ "_serviceTypes" ][ service.type ].opacity( this, service ); - } - } - } - } - }, - - toggle: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "toggle", value, this._$elem ); - } else { - - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - if ( value === undefined ) { - // toggle visibility - value = ( service.style.visibility !== "visible" ); - } - - service.style.visibility = ( value ? "visible" : "hidden" ); - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - service.serviceContainer.toggle( value ); - - if ( value ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service ); - } - } - } - } - }, - - zoom: function (numberOfLevels) { - if (numberOfLevels !== null) { - this._setZoom(this._options["zoom"] + numberOfLevels, false, true); - } - }, - - refresh: function ( force, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "refresh", force, this._$elem ); - } else { - this._refresh( force, _serviceContainer ); - this._refreshAllShapes( ); - } - }, - - resize: function ( _trigger /* Internal Use Only */ ) { - var size = this._findMapSize(), - dx = size["width"]/2 - this._contentBounds.width/2, - dy = size["height"]/2 - this._contentBounds.height/2, - i; - - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._$resizeContainer.css( { - width: size["width"], - height: size["height"] - } ); - - for (i = 0; i < this._currentServices.length; i++) { - $.geo["_serviceTypes"][this._currentServices[i].type].resize(this, this._currentServices[i]); - } - - this._$elem.find( ".geo-graphics" ).css( { - width: size["width"], - height: size["height"] - }).geographics( "resize" ); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._setCenterAndSize(this._center, this._pixelSize, _trigger, true); - }, - - append: function ( shape, style, label, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - if ( !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - var shapes, arg, i, realStyle, realLabel, realRefresh; - - if ( $.isArray( shape ) ) { - shapes = shape; - } else if ( shape.type == "FeatureCollection" ) { - shapes = shape.features; - } else { - shapes = [ shape ]; - } - - for ( i = 1; i < arguments.length; i++ ) { - arg = arguments[ i ]; - - if ( typeof arg === "object" ) { - realStyle = arg; - } else if ( typeof arg === "number" || typeof arg === "string" ) { - realLabel = arg; - } else if ( typeof arg === "boolean" ) { - realRefresh = arg; - } - } - - for ( i = 0; i < shapes.length; i++ ) { - if ( shapes[ i ].type != "Point" ) { - var bbox = $.geo.bbox( shapes[ i ] ); - if ( $.geo.proj && $.geo._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - $.data( shapes[ i ], "geoBbox", bbox ); - } - - this._graphicShapes.push( { - shape: shapes[ i ], - style: realStyle, - label: realLabel - } ); - } - - if ( realRefresh === undefined || realRefresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - empty: function ( refresh ) { - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - $.removeData( this._graphicShapes[ i ].shape, "geoBbox" ); - } - - this._graphicShapes = []; - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - }, - - find: function ( selector, pixelTolerance ) { - var isPoint = $.isPlainObject( selector ), - searchPixel = isPoint ? this._map.toPixel( selector.coordinates ) : undefined, - mapTol = this._map._pixelSize * pixelTolerance, - result = [], - graphicShape, - geometries, - curGeom, - i = 0; - - for ( ; i < this._graphicShapes.length; i++ ) { - graphicShape = this._graphicShapes[ i ]; - - if ( isPoint ) { - if ( graphicShape.shape.type == "Point" ) { - if ( $.geo.distance( graphicShape.shape, selector ) <= mapTol ) { - result.push( graphicShape.shape ); - } - } else { - var bbox = $.data( graphicShape.shape, "geoBbox" ), - bboxPolygon = { - type: "Polygon", - coordinates: [ [ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ] ] - }, - projectedPoint = { - type: "Point", - coordinates: $.geo.proj && $.geo._isGeodetic( selector.coordinates ) ? $.geo.proj.fromGeodetic( selector.coordinates ) : selector.coordinates - }; - - if ( $.geo.distance( bboxPolygon, projectedPoint, true ) <= mapTol ) { - geometries = $.geo._flatten( graphicShape.shape ); - for ( curGeom = 0; curGeom < geometries.length; curGeom++ ) { - if ( $.geo.distance( geometries[ curGeom ], selector ) <= mapTol ) { - result.push( graphicShape.shape ); - break; - } - } - } - } - } else { - result.push( graphicShape.shape ); - } - } - - if ( this._$elem.is( ".geo-map" ) ) { - this._$elem.find( ".geo-service" ).each( function( ) { - result = $.merge( result, $( this ).geomap( "find", selector, pixelTolerance ) ); - } ); - } - - return result; - }, - - remove: function ( shape, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - var shapes = $.isArray( shape ) ? shape : [ shape ], - rest; - - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - if ( $.inArray( this._graphicShapes[ i ].shape, shapes ) >= 0 ) { - $.removeData( shape, "geoBbox" ); - rest = this._graphicShapes.slice( i + 1 ); - this._graphicShapes.length = i; - this._graphicShapes.push.apply( this._graphicShapes, rest ); - i--; - } - } - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - _getBbox: function (center, pixelSize) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - // calculate the internal bbox - var halfWidth = this._contentBounds[ "width" ] / 2 * pixelSize, - halfHeight = this._contentBounds[ "height" ] / 2 * pixelSize; - return [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - }, - - _setBbox: function (value, trigger, refresh) { - var center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2], - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height), - zoom = this._getZoom( center, pixelSize ); - - // clamp to zoom - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._setInteractiveCenterAndSize( center, pixelSize ); - this._interactiveTransform( ); - }, - - _getBboxMax: function () { - // calculate the internal bboxMax - var halfWidth = this._contentBounds["width"] / 2 * this._pixelSizeMax, - halfHeight = this._contentBounds["height"] / 2 * this._pixelSizeMax; - return [this._centerMax[0] - halfWidth, this._centerMax[1] - halfHeight, this._centerMax[0] + halfWidth, this._centerMax[1] + halfHeight]; - }, - - _getCenter: function () { - return this._center; - }, - - _getContentBounds: function () { - return this._contentBounds; - }, - - _getServicesContainer: function () { - return this._$servicesContainer; - }, - - _getZoom: function ( center, pixelSize ) { - // calculate the internal zoom level, vs. public zoom property - // this does not take zoomMin or zoomMax into account - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var tilingScheme = this._options["tilingScheme"]; - if ( tilingScheme ) { - if ( tilingScheme.pixelSizes ) { - var roundedPixelSize = Math.floor(pixelSize * 1000), - levels = tilingScheme.pixelSizes.length, - i = levels - 1; - - for ( ; i >= 0; i-- ) { - if ( Math.floor( tilingScheme.pixelSizes[ i ] * 1000 ) >= roundedPixelSize ) { - return i; - } - } - - return 0; - } else { - return Math.round( Math.log( tilingScheme.basePixelSize / pixelSize) / Math.log( 2 ) ); - } - } else { - var ratio = this._contentBounds["width"] / this._contentBounds["height"], - bbox = $.geo.reaspect( this._getBbox( center, pixelSize ), ratio, true ), - bboxMax = $.geo.reaspect(this._getBboxMax(), ratio, true); - - return Math.round( Math.log($.geo.width(bboxMax, true) / $.geo.width(bbox, true)) / Math.log(this._zoomFactor) ); - } - }, - - _setZoom: function ( value, trigger, refresh ) { - // set the map widget's zoom, taking zoomMin and zoomMax into account - this._clearInteractiveTimeout( ); - - value = Math.min( Math.max( value, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ); - - this._setInteractiveCenterAndSize( this._centerInteractive, this._getPixelSize( value ) ); - this._interactiveTransform( ); - this._setInteractiveTimeout( trigger ); - }, - - _createChildren: function () { - this._$existingChildren = this._$elem.children(); - - this._forcePosition(this._$existingChildren); - - this._$existingChildren.detach().css( { - mozUserSelect: "none" - } ); - - - var contentSizeCss = "width:" + this._contentBounds["width"] + "px; height:" + this._contentBounds["height"] + "px; margin:0; padding:0;", - contentPosCss = "position:absolute; left:0; top:0;"; - - this._$elem.prepend('
'); - this._$eventTarget = this._$contentFrame = this._$elem.children(':first'); - - this._$contentFrame.append('
'); - this._$servicesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append( '
    ' ); - this._$attrList = this._$contentFrame.children( ":last" ); - - this._$contentFrame.append('
    '); - this._$drawContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
    '); - this._$measureContainer = this._$contentFrame.children(':last'); - this._$measureLabel = this._$measureContainer.children(); - - this._$contentFrame.append('
    '); - this._$shapesContainer = this._$contentFrame.children(':last'); - - this._$panContainer = $( [ this._$shapesContainer[ 0 ], this._$drawContainer[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$resizeContainer = $( [ this._$contentFrame[ 0 ], this._$servicesContainer[ 0 ], this._$eventTarget[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$contentFrame.append(this._$existingChildren); - - if ( ! $("#geo-measure-style").length ) { - $("head").prepend( '' ); - } - }, - - _createServices: function () { - var service, i; - - for ( i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap( "destroy" ); - $.geo[ "_serviceTypes" ][ this._currentServices[ i ].type ].destroy( this, this._$servicesContainer, this._currentServices[ i ] ); - } - - this._currentServices = [ ]; - this._$servicesContainer.html( "" ); - this._$attrList.html( "" ); - - for ( i = 0; i < this._options[ "services" ].length; i++ ) { - service = this._currentServices[ i ] = $.extend( { }, this._options[ "services" ][ i ] ); - - // keep a reference to the original - service.serviceObject = this._options[ "services" ][ i ]; - - // default the service style property on our copy - service.style = $.extend( { - visibility: "visible", - opacity: 1 - }, service.style ); - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = 'class="geo-service ' + ( service["class"] ? service["class"] : '' ) + '"', - scHtml = '
    ', - servicesContainer; - - this._$servicesContainer.append( scHtml ); - serviceContainer = this._$servicesContainer.children( ":last" ); - service.serviceContainer = serviceContainer; - - $.geo[ "_serviceTypes" ][ service.type ].create( this, serviceContainer, service, i ); - - serviceContainer.data( "geoMap", this ).geomap(); - - if ( service.attr ) { - this._$attrList.append( '
  • ' + service.attr + '
  • ' ); - } - } - - // start with our map-level shapesContainer - this._$shapesContainers = this._$shapesContainer; - - this._$attrList.find( "a" ).css( { - position: "relative", - zIndex: 100 - } ); - }, - - _createServiceGraphics: function( ) { - // only called in the context of a service-level geomap - var $contentFrame = this._$elem.closest( ".geo-content-frame" ); - this._$elem.append('
    '); - this._$shapesContainer = this._$elem.children(':last'); - - this._map._$shapesContainers = this._map._$shapesContainers.add( this._$shapesContainer ); - - this._$shapesContainer.geographics( ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - }, - - _refreshDrawing: function ( ) { - this._$drawContainer.geographics("clear"); - - if ( this._drawPixels.length > 0 ) { - var mode = this._options[ "mode" ], - pixels = this._drawPixels, - coords = this._drawCoords, - label, - labelShape, - labelPixel, - widthOver, - heightOver; - - switch ( mode ) { - case "measureLength": - mode = "drawLineString"; - labelShape = { - type: "LineString", - coordinates: coords - }; - label = $.render[ this._tmplLengthId ]( { length: $.geo.length( labelShape, true ) } ); - labelPixel = $.merge( [], pixels[ pixels.length - 1 ] ); - break; - - case "measureArea": - mode = "drawPolygon"; - - labelShape = { - type: "Polygon", - coordinates: [ $.merge( [ ], coords ) ] - }; - labelShape.coordinates[ 0 ].push( coords[ 0 ] ); - - label = $.render[ this._tmplAreaId ]( { area: $.geo.area( labelShape, true ) } ); - labelPixel = this._toPixel( $.geo.centroid( labelShape ).coordinates ); - pixels = [ pixels ]; - break; - - case "drawPolygon": - pixels = [ pixels ]; - break; - } - - this._$drawContainer.geographics( mode, pixels ); - - if ( label ) { - this._$measureLabel.html( label ); - - widthOver = this._contentBounds.width - ( this._$measureLabel.outerWidth( true ) + labelPixel[ 0 ] ); - heightOver = this._contentBounds.height - ( this._$measureLabel.outerHeight( true ) + labelPixel[ 1 ] ); - - if ( widthOver < 0 ) { - labelPixel[ 0 ] += widthOver; - } - - if ( heightOver < 0 ) { - labelPixel[ 1 ] += heightOver; - } - - this._$measureLabel.css( { - left: Math.max( labelPixel[ 0 ], 0 ), - top: Math.max( labelPixel[ 1 ], 0 ) - } ).show(); - } - } - }, - - _resetDrawing: function () { - this._drawPixels = []; - this._drawCoords = []; - this._$drawContainer.geographics("clear"); - this._$measureLabel.hide(); - }, - - _refreshAllShapes: function ( ) { - this._timeoutRefreshShapes = null; - - var service, - geoService, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - geoService = service.serviceContainer.data( "geoService" ); - - if ( geoService._createdGraphics ) { - geoService._$shapesContainer.geographics( "clear" ); - if ( geoService._graphicShapes.length > 0 ) { - geoService._refreshShapes( geoService._$shapesContainer, geoService._graphicShapes, geoService._graphicShapes, geoService._graphicShapes ); - } - } - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics( "clear" ); - if ( this._graphicShapes.length > 0 ) { - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - } - }, - - - _refreshShapes: function (geographics, shapes, styles, labels, center, pixelSize) { - var i, mgi, - shape, - shapeBbox, - style, - label, - hasLabel, - labelPixel, - bbox = this._map._getBbox(center, pixelSize); - - /* - if ( shapes.length > 0 ) { - console.log( "_refreshShapes " + $.now() ); - } - */ - for (i = 0; i < shapes.length; i++) { - shape = shapes[i].shape || shapes[i]; - shape = shape.geometry || shape; - shapeBbox = $.data(shape, "geoBbox"); - - if ( shapeBbox && $.geo._bboxDisjoint( bbox, shapeBbox ) ) { - continue; - } - - style = $.isArray(styles) ? styles[i].style : styles; - label = $.isArray(labels) ? labels[i].label : labels; - hasLabel = ( label !== undefined ); - labelPixel = undefined; - - switch (shape.type) { - case "Point": - labelPixel = this._map.toPixel( shape.coordinates, center, pixelSize ); - this._$shapesContainer.geographics("drawPoint", labelPixel, style); - break; - case "LineString": - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.pointAlong( shape, 0.5 ).coordinates, center, pixelSize ); - } - break; - case "Polygon": - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiPoint": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPoint", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiLineString": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiPolygon": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - - case "GeometryCollection": - this._refreshShapes(geographics, shape.geometries, style, label, center, pixelSize); - break; - } - - if ( hasLabel && labelPixel ) { - this._$shapesContainer.geographics( "drawLabel", labelPixel, label ); - } - } - }, - - _findMapSize: function () { - // really, really attempt to find a size for this thing - // even if it's hidden (look at parents) - var size = { width: 0, height: 0 }, - sizeContainer = this._$elem; - - while (sizeContainer.size() && !(size["width"] > 0 && size["height"] > 0)) { - size = { width: sizeContainer.width(), height: sizeContainer.height() }; - if (size["width"] <= 0 || size["height"] <= 0) { - size = { width: parseInt(sizeContainer.css("width"), 10), height: parseInt(sizeContainer.css("height"), 10) }; - } - sizeContainer = sizeContainer.parent(); - } - return size; - }, - - _forcePosition: function (elem) { - var cssPosition = elem.css("position"); - if (cssPosition != "relative" && cssPosition != "absolute" && cssPosition != "fixed") { - elem.css("position", "relative"); - } - }, - - _getPixelSize: function ( zoom ) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme !== null) { - if (zoom === 0) { - return tilingScheme.pixelSizes ? tilingScheme.pixelSizes[0] : tilingScheme.basePixelSize; - } - - zoom = Math.round(zoom); - zoom = Math.max(zoom, 0); - var levels = tilingScheme.pixelSizes ? tilingScheme.pixelSizes.length : tilingScheme.levels; - zoom = Math.min(zoom, levels - 1); - - if ( tilingScheme.pixelSizes ) { - return tilingScheme.pixelSizes[zoom]; - } else { - return tilingScheme.basePixelSize / Math.pow(2, zoom); - } - } else { - var bbox = $.geo.scaleBy( this._getBboxMax(), 1 / Math.pow( this._zoomFactor, zoom ), true ); - return Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - } - }, - - _getZoomCenterAndSize: function ( anchor, zoomDelta, full ) { - var zoomFactor = ( full ? this._fullZoomFactor : this._partialZoomFactor ), - scale = Math.pow( zoomFactor, -zoomDelta ), - pixelSize = this._pixelSizeInteractive * scale, - zoom = this._getZoom(this._centerInteractive, pixelSize); - - // clamp to zoom - if ( full && this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoomDelta < 0 && zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._pixelSizeInteractive; - } else if ( zoomDelta > 0 && zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._pixelSizeInteractive; - } - } - - var ratio = pixelSize / this._pixelSizeInteractive, - anchorMapCoord = this._toMap( anchor, this._centerInteractive, this._pixelSizeInteractive ), - centerDelta = [(this._centerInteractive[0] - anchorMapCoord[0]) * ratio, (this._centerInteractive[1] - anchorMapCoord[1]) * ratio], - scaleCenter = [anchorMapCoord[0] + centerDelta[0], anchorMapCoord[1] + centerDelta[1]]; - - return { pixelSize: pixelSize, center: scaleCenter }; - }, - - _mouseWheelFinish: function ( refresh ) { - this._wheelTimeout = null; - - if (this._wheelLevel !== 0) { - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, this._wheelLevel, this._options[ "tilingScheme" ] !== null ); - - this._wheelLevel = 0; - } else if ( refresh ) { - this._refresh(); - this._refreshAllShapes( ); - } - }, - - _panFinalize: function () { - if (this._panning) { - this._velocity = [0, 0]; - - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - image = this._options[ "axisLayout" ] === "image", - dxMap = -dx * this._pixelSize, - dyMap = ( image ? -1 : 1 ) * dy * this._pixelSize; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._inOp = false; - this._anchor = this._current; - this._mouseDown = this._toolPan = this._panning = false; - } - }, - - _panMove: function () { - if ( ! this._options[ "pannable" ] ) { - return; - } - - var dx = this._current[0] - this._lastDrag[0], - dy = this._current[1] - this._lastDrag[1], - i = 0, - service, - translateObj; - - if (this._toolPan || dx > 3 || dx < -3 || dy > 3 || dy < -3) { - if (!this._toolPan) { - this._toolPan = true; - this._$eventTarget.css("cursor", this._options["cursors"]["pan"]); - } - - if (this._mouseDown) { - this._velocity = [dx, dy]; - } - - if (dx !== 0 || dy !== 0) { - this._panning = true; - this._lastDrag = this._current; - - this._centerInteractive[ 0 ] -= ( dx * this._pixelSizeInteractive ); - this._centerInteractive[ 1 ] += ( ( this._options[ "axisLayout" ] === "image" ? -1 : 1 ) * dy * this._pixelSizeInteractive ); - this._setInteractiveCenterAndSize( this._centerInteractive, this._pixelSizeInteractive ); - this._interactiveTransform( ); - } - } - }, - - _clearInteractiveTimeout: function() { - if ( this._timeoutRefreshShapes ) { - clearTimeout( this._timeoutRefreshShapes ); - this._timeoutRefreshShapes = null; - } - - if ( this._timeoutInteractive ) { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - return true; - } else { - this._centerInteractive[ 0 ] = this._center[ 0 ]; - this._centerInteractive[ 1 ] = this._center[ 1 ]; - this._pixelSizeInteractive = this._pixelSize; - return false; - } - }, - - _interactiveTransform: function( ) { - var mapWidth = this._contentBounds[ "width" ], - mapHeight = this._contentBounds[ "height" ], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - bbox = [ this._centerInteractive[ 0 ] - halfWidth, this._centerInteractive[ 1 ] - halfHeight, this._centerInteractive[ 0 ] + halfWidth, this._centerInteractive[ 1 ] + halfHeight ]; - - var scalePixelSize = this._pixelSize, - scaleRatio = scalePixelSize / this._pixelSizeInteractive; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = this._toMap( [ 0, 0 ] ), - newPixelPoint = this._toPixel( oldMapOrigin, this._centerInteractive, this._pixelSizeInteractive ); - - - this._$shapesContainers.geographics("interactiveTransform", newPixelPoint, scaleRatio); - - /* - $scaleContainer.css( { - left: Math.round( newPixelPoint[ 0 ] ), - top: Math.round( newPixelPoint[ 1 ] ), - width: mapWidth * scaleRatio, - height: mapHeight * scaleRatio - } ); - */ - - } - - - - - - - - - - - - - - - - - - - - - for ( var i = 0; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo[ "_serviceTypes" ][ service.type ].interactiveTransform( this, service, this._centerInteractive, this._pixelSizeInteractive ); - } - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel( this._drawCoords, this._centerInteractive, this._pixelSizeInteractive ); - this._refreshDrawing(); - } - }, - - _interactiveTimeout: function( ) { - if ( this._isMultiTouch ) { - this._timeoutInteractive = setTimeout( $.proxy( interactiveTimeout, this ), 128 ); - } else if ( this._created && this._timeoutInteractive ) { - this._setCenterAndSize( this._centerInteractive, this._pixelSizeInteractive, this._triggerInteractive, true ); - this._timeoutInteractive = null; - this._triggerInteractive = false; - - this._timeoutRefreshShapes = setTimeout( $.proxy( this._refreshAllShapes, this ), 128 ); - } - }, - - _setInteractiveTimeout: function( trigger ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - this._triggerInteractive |= trigger; - }, - - _refresh: function ( force, _serviceContainer ) { - var service, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service, force ); - } - } - }, - - _setInteractiveCenterAndSize: function ( center, pixelSize ) { - // set the temporary (interactive) center & size - // also, update the public-facing options - // this does not take zoomMin or zoomMax into account - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - this._pixelSizeInteractive = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox( center, pixelSize ) ); - this._options["center"] = $.geo.proj.toGeodetic( center ); - } else { - this._options["bbox"] = this._getBbox( center, pixelSize ); - this._options["center"][ 0 ] = center[ 0 ]; - this._options["center"][ 1 ] = center[ 1 ]; - } - - this._options["pixelSize"] = pixelSize; - this._options["zoom"] = this._getZoom( center, pixelSize ); - }, - - _setCenterAndSize: function (center, pixelSize, trigger, refresh) { - if ( ! $.isArray( center ) || center.length != 2 || typeof center[ 0 ] !== "number" || typeof center[ 1 ] !== "number" ) { - return; - } - - // the final call during any extent change - // only called by timeoutInteractive & resize - // clamp to zoom - var zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._center[ 0 ] = center[ 0 ]; - this._center[ 1 ] = center[ 1 ]; - this._options["pixelSize"] = this._pixelSize = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox() ); - this._options["center"] = $.geo.proj.toGeodetic( this._center ); - } else { - this._options["bbox"] = this._getBbox(); - this._options["center"] = $.merge( [ ], center ); - } - - this._options["zoom"] = zoom; - - if (trigger) { - this._trigger("bboxchange", window.event, { bbox: $.merge( [ ], this._options["bbox"] ) }); - } - - if (refresh) { - this._refresh(); - this._refreshAllShapes( ); - this._refreshDrawing(); - } - }, - - _requestQueued: function ( ) { - if ( this._loadCount === 0 ) { - this._trigger( "loadstart", window.event ); - } - this._loadCount++; - }, - - _requestComplete: function ( ) { - this._loadCount--; - if ( this._loadCount <= 0 ) { - this._loadCount = 0; - this._trigger( "loadend", window.event ); - } - }, - - _toMap: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - xRatio = $.geo.width(bbox, true) / width, - yRatio = $.geo.height(bbox, true) / height, - yOffset, - image = this._options[ "axisLayout" ] === "image", - result = [], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - yOffset = (p[ i ][ j ][ k ][1] * yRatio); - result[ i ][ j ][ k ] = [ - bbox[ 0 ] + ( p[ i ][ j ][ k ][ 0 ] * xRatio ), - image ? bbox[ 1 ] + yOffset : bbox[ 3 ] - yOffset - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _toPixel: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - bboxWidth = $.geo.width(bbox, true), - bboxHeight = $.geo.height(bbox, true), - image = this._options[ "axisLayout" ] === "image", - xRatio = width / bboxWidth, - yRatio = height / bboxHeight, - result = [ ], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = [ - Math.round( ( p[ i ][ j ][ k ][ 0 ] - bbox[ 0 ] ) * xRatio ), - Math.round( ( image ? p[ i ][ j ][ k ][ 1 ] - bbox[ 1 ] : bbox[ 3 ] - p[ i ][ j ][ k ][ 1 ] ) * yRatio ) - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _document_keydown: function (e) { - var len = this._drawCoords.length; - if (len > 0 && e.which == 27) { - if (len <= 2) { - this._resetDrawing(); - this._inOp = false; - } else { - this._drawCoords[len - 2] = $.merge( [], this._drawCoords[ len - 1 ] ); - this._drawPixels[len - 2] = $.merge( [], this._drawPixels[ len - 1 ] ); - - this._drawCoords.length--; - this._drawPixels.length--; - - this._refreshDrawing(); - } - } - }, - - _eventTarget_dblclick_zoom: function(e) { - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - this._trigger("dblclick", e, { type: "Point", coordinates: this._toMap(this._current, this._centerInteractive, this._pixelSizeInteractive ) }); - - if (!e.isDefaultPrevented()) { - var centerAndSize = this._getZoomCenterAndSize(this._current, 1, true ); - - this._setInteractiveCenterAndSize( centerAndSize.center, centerAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - }, - - _eventTarget_dblclick: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - var offset = $(e.currentTarget).offset(); - - switch (this._options["mode"]) { - case "drawLineString": - case "measureLength": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - this._drawCoords.length--; - this._trigger( "shape", e, { - type: "LineString", - coordinates: this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords - } ); - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "drawPolygon": - case "measureArea": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - var endIndex = this._drawCoords.length - 1; - if (endIndex > 2) { - this._drawCoords[endIndex] = $.merge( [], this._drawCoords[0] ); - this._trigger( "shape", e, { - type: "Polygon", - coordinates: [ this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords ] - } ); - } - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - default: - this._eventTarget_dblclick_zoom(e); - break; - } - - this._inOp = false; - }, - - _eventTarget_touchstart: function (e) { - if (typeof(document.elementFromPoint) !== "undefined" && document.elementFromPoint(e.pageX, e.pageY).nodeName === "A") { - return; - } - - var mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ); - - if ( mode === "static" ) { - return; - } - - if ( !this._supportTouch && e.which != 1 ) { - return; - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var offset = $(e.currentTarget).offset(), - touches = e.originalEvent.changedTouches; - - if ( this._supportTouch ) { - this._multiTouchAnchor = $.merge( [ ], touches ); - - this._isMultiTouch = this._multiTouchAnchor.length > 1; - - if ( this._isMultiTouch ) { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - touches[1].pageX - offset.left, - touches[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ touches[0].pageX - offset.left, touches[0].pageY - offset.top ]; - } - } else { - this._current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - var downDate = $.now(); - if (downDate - this._downDate < 750) { - if (this._isTap) { - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance > 8) { - this._isTap = false; - } else { - this._current = $.merge( [ ], this._anchor ); - } - } - - if (this._isDbltap) { - this._isDbltap = false; - } else { - this._isDbltap = this._isTap; - } - } else { - this._isDbltap = false; - } - this._isTap = true; - this._downDate = downDate; - } - - this._mouseDown = true; - this._anchor = $.merge( [ ], this._current ); - - if (!this._inOp && e.shiftKey && shift !== "off") { - this._shiftDown = true; - this._$eventTarget.css( "cursor", this._options[ "cursors" ][ shift === "default" ? defaultShift : shift ] ); - } else if ( !this._isMultiTouch && ( this._options[ "pannable" ] || mode === "dragBox" || mode === "dragCircle" ) ) { - this._inOp = true; - - if ( mode !== "zoom" && mode !== "dragBox" && mode !== "dragCircle" ) { - this._lastDrag = this._current; - - if (e.currentTarget.setCapture) { - e.currentTarget.setCapture(); - } - } - } - - e.preventDefault(); - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - }, - - _dragTarget_touchmove: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - var doInteractiveTimeout = false; - if ( this._mouseDown ) { - doInteractiveTimeout = this._clearInteractiveTimeout( ); - } - - var offset = this._$eventTarget.offset(), - drawCoordsLen = this._drawCoords.length, - touches = e.originalEvent.changedTouches, - current, - service, - i = 0; - - if ( this._supportTouch ) { - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 && touches[ 0 ].identifier !== this._multiTouchAnchor[ 0 ].identifier ) { - // switch to multitouch - this._mouseDown = false; - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( touches[ 0 ] ); - - - - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._mouseDown = true; - this._anchor = this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - if ( this._isMultiTouch ) { - - for ( ; i < touches.length; i++ ) { - if ( touches[ i ].identifier === this._multiTouchAnchor[ 0 ].identifier ) { - this._multiTouchCurrentBbox[ 0 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = touches[ i ].pageY - offset.top; - } else if ( touches[ i ].identifier === this._multiTouchAnchor[ 1 ].identifier ) { - this._multiTouchCurrentBbox[ 2 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = touches[ i ].pageY - offset.top; - } - } - - var anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ), - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - var wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - var delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - var pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (current[0] === this._lastMove[0] && current[1] === this._lastMove[1]) { - if ( this._inOp ) { - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - } - - if ( _ieVersion == 7 ) { - this._isDbltap = this._isTap = false; - } - - if (this._mouseDown) { - this._current = current; - this._moveDate = $.now(); - } - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - var mode = this._options["mode"], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - dx, dy, circleSize; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - switch (mode) { - case "zoom": - case "dragBox": - if ( this._mouseDown ) { - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawBbox", [ - this._anchor[ 0 ], - this._anchor[ 1 ], - current[ 0 ], - current[ 1 ] - ] ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "dragCircle": - if ( this._mouseDown ) { - dx = current[ 0 ] - this._anchor[ 0 ]; - dy = current[ 1 ] - this._anchor[ 1 ]; - circleSize = Math.sqrt( ( dx * dx) + ( dy * dy ) ) * 2; - //circleSize = Math.max( Math.abs( current[ 0 ] - this._anchor[ 0 ] ), Math.abs( current[ 1 ] - this._anchor[ 1 ] ) ) * 2; - - // not part of _refreshDrawing - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawArc", this._anchor, 0, 360, { - width: circleSize, - height: circleSize - } ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - if (drawCoordsLen > 0) { - this._drawCoords[drawCoordsLen - 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[drawCoordsLen - 1] = current; - - this._refreshDrawing(); - } - - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - default: - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - } - - this._lastMove = current; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchstop: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if ( !this._mouseDown ) { - if ( _ieVersion == 7 ) { - // ie7 doesn't appear to trigger dblclick on this._$eventTarget, - // we fake regular click here to cause soft dblclick - this._eventTarget_touchstart(e); - } else { - // Chrome & Firefox trigger a rogue mouseup event when doing a dblclick maximize in Windows(/Linux?) - // ignore it - return; - } - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var mouseWasDown = this._mouseDown, - wasToolPan = this._toolPan, - offset = this._$eventTarget.offset(), - mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - current, i, clickDate, - dx, dy, - coordBuffer, - triggerShape; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - if (this._supportTouch) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - this._multiTouchAnchor = []; - this._inOp = false; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - if (this._isTap) { - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - if (Math.sqrt((dx * dx) + (dy * dy)) <= 8) { - current = $.merge( [ ], this._anchor ); - } - } - } - - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._shiftDown = this._mouseDown = this._toolPan = false; - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isMultiTouch = false; - - this._wheelLevel = 0; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return; - } - - if (document.releaseCapture) { - document.releaseCapture(); - } - - if (mouseWasDown) { - clickDate = $.now(); - this._current = current; - - switch ( mode ) { - case "zoom": - case "dragBox": - if ( dx !== 0 || dy !== 0 ) { - var minSize = this._pixelSize * 6, - bboxCoords = this._toMap( [ [ - Math.min( this._anchor[ 0 ], current[ 0 ] ), - Math.max( this._anchor[ 1 ], current[ 1 ] ) - ], [ - Math.max( this._anchor[ 0 ], current[ 0 ] ), - Math.min( this._anchor[ 1 ], current[ 1 ] ) - ] - ] ), - bbox = [ - bboxCoords[0][0], - bboxCoords[0][1], - bboxCoords[1][0], - bboxCoords[1][1] - ]; - - if ( mode === "zoom" ) { - if ( ( bbox[2] - bbox[0] ) < minSize && ( bbox[3] - bbox[1] ) < minSize ) { - bbox = $.geo.scaleBy( this._getBbox( $.geo.center( bbox, true ) ), 0.5, true ); - } - - this._setBbox(bbox, true, true); - doInteractiveTimeout = true; - } else { - triggerShape = $.geo.polygonize( bbox, true ); - triggerShape.bbox = bbox; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - this._trigger( "shape", e, triggerShape ); - } - } else { - if ( mode === "dragBox" ) { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - } - - this._resetDrawing(); - break; - - case "dragCircle": - if ( dx !== 0 || dy !== 0 ) { - var image = this._options[ "axisLayout" ] === "image", - d = Math.sqrt( ( dx * dx) + ( dy * dy ) ), - n = 180, - a; - - this._drawPixels.length = n + 1; - - for ( i = 0; i < n; i++ ) { - a = ( i * 360 / n ) * ( Math.PI / 180 ); - this._drawPixels[ i ] = [ - this._anchor[ 0 ] + Math.cos( a ) * d, - this._anchor[ 1 ] + Math.sin( a ) * d - ]; - } - - this._drawPixels[ n ] = [ - this._drawPixels[ 0 ][ 0 ], - this._drawPixels[ 0 ][ 1 ] - ]; - - // using coordBuffer for bbox coords - coordBuffer = this._toMap( [ - [ this._anchor[ 0 ] - d, this._anchor[ 1 ] + ( image ? -d : d ) ], - [ this._anchor[ 0 ] + d, this._anchor[ 1 ] + ( image ? d : -d ) ] - ] ); - - triggerShape = { - type: "Polygon", - coordinates: [ this._toMap( this._drawPixels ) ], - bbox: [ coordBuffer[ 0 ][ 0 ], coordBuffer[ 0 ][ 1 ], coordBuffer[ 1 ][ 0 ], coordBuffer[ 1 ][ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - - this._resetDrawing(); - } else { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - break; - - case "drawPoint": - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - var geomap = this; - this._drawTimeout = setTimeout(function () { - if (geomap._drawTimeout) { - geomap._trigger("shape", e, { type: "Point", coordinates: geomap.toMap(current) }); - geomap._inOp = false; - geomap._drawTimeout = null; - } - }, 250); - } - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (wasToolPan) { - this._panFinalize(); - } else { - i = (this._drawCoords.length === 0 ? 0 : this._drawCoords.length - 1); - - this._drawCoords[i] = this._toMap(current); - this._drawPixels[i] = current; - - if (i < 2 || !(this._drawCoords[i][0] == this._drawCoords[i-1][0] && - this._drawCoords[i][1] == this._drawCoords[i-1][1])) { - this._drawCoords[i + 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[i + 1] = current; - } - - this._refreshDrawing(); - } - break; - - default: - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - this._inOp = false; - } - } - break; - } - - this._clickDate = clickDate; - - if (this._softDblClick && this._isDbltap) { - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - this._$eventTarget.trigger("dblclick", e); - return false; - } - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _eventTarget_mousewheel: function (e, delta) { - if ( this._options[ "mode" ] === "static" || this._options[ "scroll" ] === "off" ) { - return; - } - - e.preventDefault(); - - if ( this._mouseDown ) { - return false; - } - - if (delta !== 0) { - this._clearInteractiveTimeout( ); - - if ( delta > 0 ) { - delta = Math.ceil( delta ); - } else { - delta = Math.floor( delta ); - } - - var offset = $(e.currentTarget).offset(); - this._anchor = [e.pageX - offset.left, e.pageY - offset.top]; - - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, this._options[ "tilingScheme" ] !== null ), - service, - i = 0; - - this._setInteractiveCenterAndSize( wheelCenterAndSize.center, wheelCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - this._setInteractiveTimeout( true ); - } - - return false; - } - } - ); -}(jQuery)); - - -(function ($, undefined) { - $.geo._serviceTypes.tiled = (function () { - return { - create: function (map, serviceContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0, - reloadTiles: false - }; - - var scHtml = '
    '; - - serviceContainer.append(scHtml); - - serviceState.serviceContainer = serviceContainer.children( ":last" ); - - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - //console.log( "tiled.interactiveTransform( " + center.join( ", " ) + ", " + pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ), - tilingScheme = map.options[ "tilingScheme" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( i ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data("pixelSize"), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapCoord = $scaleContainer.data("scaleOrigin"), - newPixelPoint = map._toPixel(oldMapCoord, center, pixelSize); - - $scaleContainer.css( { - left: Math.round(newPixelPoint[0]) + "px", - top: Math.round(newPixelPoint[1]) + "px", - width: tilingScheme.tileWidth * scaleRatio, - height: tilingScheme.tileHeight * scaleRatio - } ); - - /* - if ( $("body")[0].filters !== undefined ) { - $scaleContainer.children().each( function ( i ) { - $( this ).css( "filter", "progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11=" + scaleRatio + ",M22=" + scaleRatio + ",sizingmethod='auto expand')" ); - } ); - } - */ - } - }); - } - }, - - refresh: function (map, service, force) { - //console.log( "tiled.refresh( " + map._center.join( ", " ) + ", " + map._pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ); - - this._cancelUnloaded(map, service); - - if ( serviceState && force ) { - // if hidden atm, we want to make sure we reload this service after it becomes visible - serviceState.reloadTiles = true; - } - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - $serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - image = map.options[ "axisLayout" ] === "image", - ySign = image ? +1 : -1, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - - tileX = Math.floor((bbox[0] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.max( Math.floor( ( image ? bbox[1] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 3 ] ) / (pixelSize * tileHeight) ), 0 ), - tileX2 = Math.ceil((bbox[2] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil( ( image ? bbox[3] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 1 ] ) / (pixelSize * tileHeight) ), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] + ySign * bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMinOrMaxY = tilingScheme.origin[1] + ySign * (fullYAtScale * tileHeight) * pixelSize, - - serviceLeft = Math.round((fullXMinX - bbox[0]) / pixelSize), - serviceTop = Math.round( ( image ? fullYMinOrMaxY - bbox[1] : bbox[3] - fullYMinOrMaxY ) / pixelSize), - - scaleContainers = $serviceContainer.children().show(), - scaleContainer = scaleContainers.filter("[data-pixel-size='" + pixelSize + "']").appendTo($serviceContainer), - - opacity = service.style.opacity, - - x, y, - - loadImageDeferredDone = function( url ) { - // when a Deferred call is done, add the image to the map - // a reference to the correct img element is on the Deferred object itself - serviceObj._loadImage( $.data( this, "img" ), url, pixelSize, map, serviceState, opacity ); - }, - - loadImageDeferredFail = function( ) { - $.data( this, "img" ).remove( ); - serviceState.loadCount--; - map._requestComplete(); - }; - - if (serviceState.reloadTiles) { - scaleContainers.find("img").attr("data-dirty", "true"); - } - - if (!scaleContainer.size()) { - $serviceContainer.append("
    "); - scaleContainer = $serviceContainer.children(":last").data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - } else { - scaleContainer.css({ - left: (serviceLeft % tileWidth) + "px", - top: (serviceTop % tileHeight) + "px" - }).data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - - scaleContainer.children().each(function (i) { - var - $img = $(this), - tile = $img.attr("data-tile").split(","); - - $img.css({ - left: Math.round(((parseInt(tile[0], 10) - fullXAtScale) * 100) + (serviceLeft - (serviceLeft % tileWidth)) / tileWidth * 100) + "%", - top: Math.round(((parseInt(tile[1], 10) - fullYAtScale) * 100) + (serviceTop - (serviceTop % tileHeight)) / tileHeight * 100) + "%" - }); - - if (opacity < 1) { - $img.fadeTo(0, opacity); - } - }); - } - - for (x = tileX; x < tileX2; x++) { - for (y = tileY; y < tileY2; y++) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ($img.size() === 0 || serviceState.reloadTiles) { - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] + ySign * (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] + ySign * ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - urlProp = ( service.hasOwnProperty( "src" ) ? "src" : "getUrl" ), - urlArgs = { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl; - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - $.templates( "geoSrc", service[ urlProp ] ); - imageUrl = $.render[ "geoSrc" ]( urlArgs ); - } - - serviceState.loadCount++; - map._requestQueued(); - - if (serviceState.reloadTiles && $img.size() > 0) { - $img.attr("src", imageUrl); - } else { - var imgMarkup = ""; - - scaleContainer.append(imgMarkup); - $img = scaleContainer.children(":last"); - } - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl ) { - // assume Deferred - $.data( imageUrl, "img", $img ); - imageUrl.done( loadImageDeferredDone ).fail( loadImageDeferredFail ); - } else { - $img.remove( ); - } - } - } - } - - scaleContainers.find("[data-dirty]").remove(); - serviceState.reloadTiles = false; - } - }, - - resize: function (map, service) { - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.css( "display", service.style.visibility === "visible" ? "block" : "none" ); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery)); - -(function ($, undefined) { - $.geo._serviceTypes.shingled = (function () { - return { - create: function (map, serviceContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0 - }; - - var scHtml = '
    '; - - serviceContainer.append(scHtml); - - serviceState.serviceContainer = serviceContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - var serviceState = $.data( service, "geoServiceState" ), - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds[ "width" ], - mapHeight = contentBounds[ "height" ], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - bbox = [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( i ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data( "pixelSize" ), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin, center, pixelSize ); - - $scaleContainer.css( { - left: Math.round( newPixelPoint[ 0 ] ), - top: Math.round( newPixelPoint[ 1 ] ), - width: mapWidth * scaleRatio, - height: mapHeight * scaleRatio - } ); - } - }); - } - }, - - refresh: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - this._cancelUnloaded(map, service); - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainer = serviceContainer.children('[data-pixel-size="' + pixelSize + '"]'), - - opacity = service.style.opacity, - - $img; - - if (opacity < 1) { - serviceContainer.find("img").attr("data-keep-alive", "0"); - } - - if ( !scaleContainer.size() ) { - serviceContainer.append('
    '); - scaleContainer = serviceContainer.children(":last"); - } - - var urlProp = ( service.hasOwnProperty("src") ? "src" : "getUrl" ), - urlArgs = { - bbox: bbox, - width: mapWidth, - height: mapHeight, - zoom: map._getZoom(), - tile: null, - index: 0 - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl, - imagePos = scaleContainer.position( ); - - imagePos.left = - ( imagePos.left ); - imagePos.top = - ( imagePos.top ); - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - $.templates( "geoSrc", service[ urlProp ] ); - imageUrl = $.render[ "geoSrc" ]( urlArgs ); - } - - serviceState.loadCount++; - map._requestQueued(); - - scaleContainer.append(''); - $img = scaleContainer.children(":last").data("center", map._center); - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, map, serviceState, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - map._requestComplete(); - } ); - } - - } - }, - - resize: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState && service && service.style.visibility === "visible" ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainers = serviceContainer.children(); - - scaleContainers.attr("data-pixel-size", "0"); - - scaleContainers.each( function ( i ) { - var $scaleContainer = $(this), - position = $scaleContainer.position( ); - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin ); - - $scaleContainer.css( { - left: position.left + ( mapWidth - $scaleContainer.width( ) ) / 2, - top: position.top + ( mapHeight - $scaleContainer.height( ) ) / 2 - } ); - - } ); - - - /* - scaleContainer.css({ - left: halfWidth + 'px', - top: halfHeight + 'px' - }); - */ - } - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.css("display", service.style.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - // #newpanzoom - serviceContainer.children(':not([data-pixel-size="' + pixelSize + '"])').remove(); - - serviceContainer.find( "img[data-keep-alive]" ).remove( ); - - serviceState.loadCount = 0; - } - }).error(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery)); diff --git a/dist/jquery.geo-1.0.0-b1.5.min.js b/dist/jquery.geo-1.0.0-b1.5.min.js deleted file mode 100644 index 66237ed..0000000 --- a/dist/jquery.geo-1.0.0-b1.5.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery Geo - v1.0.0-b1.5 - 2013-01-17 - * http://jquerygeo.com - * Copyright (c) 2013 Ryan Westphal/Applied Geographics, Inc.; Licensed MIT, GPL */ -document.createElement("canvas").getContext||function(){function f(){return this.context_||(this.context_=new P(this))}function c(e,t,n){var r=l.call(arguments,2);return function(){return e.apply(t,r.concat(l.call(arguments)))}}function h(e){return String(e).replace(/&/g,"&").replace(/"/g,""")}function p(e,t,n){e.namespaces[t]||e.namespaces.add(t,n,"#default#VML")}function d(e){p(e,"g_vml_","urn:schemas-microsoft-com:vml"),p(e,"g_o_","urn:schemas-microsoft-com:office:office");if(!e.styleSheets.ex_canvas_){var t=e.createStyleSheet();t.owningElement.id="ex_canvas_",t.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function m(e){var t=e.srcElement;switch(e.propertyName){case"width":t.getContext().clearRect(),t.style.width=t.attributes.width.nodeValue+"px",t.firstChild.style.width=t.clientWidth+"px";break;case"height":t.getContext().clearRect(),t.style.height=t.attributes.height.nodeValue+"px",t.firstChild.style.height=t.clientHeight+"px"}}function g(e){var t=e.srcElement;t.firstChild&&(t.firstChild.style.width=t.clientWidth+"px",t.firstChild.style.height=t.clientHeight+"px")}function E(){return[[1,0,0],[0,1,0],[0,0,1]]}function S(e,t){var n=E();for(var r=0;r<3;r++)for(var i=0;i<3;i++){var s=0;for(var o=0;o<3;o++)s+=e[r][o]*t[o][i];n[r][i]=s}return n}function x(e,t){t.fillStyle=e.fillStyle,t.lineCap=e.lineCap,t.lineJoin=e.lineJoin,t.lineWidth=e.lineWidth,t.miterLimit=e.miterLimit,t.shadowBlur=e.shadowBlur,t.shadowColor=e.shadowColor,t.shadowOffsetX=e.shadowOffsetX,t.shadowOffsetY=e.shadowOffsetY,t.strokeStyle=e.strokeStyle,t.globalAlpha=e.globalAlpha,t.font=e.font,t.textAlign=e.textAlign,t.textBaseline=e.textBaseline,t.arcScaleX_=e.arcScaleX_,t.arcScaleY_=e.arcScaleY_,t.lineScale_=e.lineScale_}function T(e){var t=e.indexOf("(",3),n=e.indexOf(")",t+1),r=e.substring(t+1,n).split(",");if(r.length!=4||e.charAt(3)!="a")r[3]=1;return r}function N(e){return parseFloat(e)/100}function C(e,t,n){return Math.min(n,Math.max(t,e))}function k(e){var t,n,r,i,s,o;i=parseFloat(e[0])/360%360,i<0&&i++,s=C(N(e[1]),0,1),o=C(N(e[2]),0,1);if(s==0)t=n=r=o;else{var u=o<.5?o*(1+s):o+s-o*s,a=2*o-u;t=L(a,u,i+1/3),n=L(a,u,i),r=L(a,u,i-1/3)}return"#"+y[Math.floor(t*255)]+y[Math.floor(n*255)]+y[Math.floor(r*255)]}function L(e,t,n){return n<0&&n++,n>1&&n--,6*n<1?e+(t-e)*6*n:2*n<1?t:3*n<2?e+(t-e)*(2/3-n)*6:e}function O(e){if(e in A)return A[e];var t,n=1;e=String(e);if(e.charAt(0)=="#")t=e;else if(/^rgb/.test(e)){var r=T(e),t="#",i;for(var s=0;s<3;s++)r[s].indexOf("%")!=-1?i=Math.floor(N(r[s])*255):i=+r[s],t+=y[C(i,0,255)];n=+r[3]}else if(/^hsl/.test(e)){var r=T(e);t=k(r),n=r[3]}else t=e;return A[e]={color:t,alpha:n}}function D(e){return _[e]||"square"}function P(e){this.m_=E(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.strokeStyle="#000",this.fillStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=o*1,this.globalAlpha=1,this.canvas=e;var t="width:"+e.clientWidth+"px;height:"+e.clientHeight+"px;overflow:hidden;position:absolute",n=e.ownerDocument.createElement("div");n.style.cssText=t,e.appendChild(n);var r=n.cloneNode(!1);r.style.backgroundColor="red",r.style.filter="alpha(opacity=0)",e.appendChild(r),this.element_=n,this.arcScaleX_=1,this.arcScaleY_=1,this.lineScale_=1}function B(e,t,n,r){e.currentPath_.push({type:"bezierCurveTo",cp1x:t.x,cp1y:t.y,cp2x:n.x,cp2y:n.y,x:r.x,y:r.y}),e.currentX_=r.x,e.currentY_=r.y}function j(e,t){var n=O(e.strokeStyle),r=n.color,i=n.alpha*e.globalAlpha,s=e.lineScale_*e.lineWidth;s<1&&(i*=s),t.push("')}function F(e,t,n,r){var i=e.fillStyle,s=e.arcScaleX_,o=e.arcScaleY_,u=r.x-n.x,a=r.y-n.y,f=O(e.fillStyle),l=f.color,c=f.alpha*e.globalAlpha;t.push('')}function I(e,t,n){var r=e.m_;return{x:o*(t*r[0][0]+n*r[1][0]+r[2][0])-u,y:o*(t*r[0][1]+n*r[1][1]+r[2][1])-u}}function q(e){return isFinite(e[0][0])&&isFinite(e[0][1])&&isFinite(e[1][0])&&isFinite(e[1][1])&&isFinite(e[2][0])&&isFinite(e[2][1])}function R(e,t,n){if(!q(t))return;e.m_=t;if(n){var r=t[0][0]*t[1][1]-t[0][1]*t[1][0];e.lineScale_=s(i(r))}}function U(e){throw new z(e)}function z(e){this.code=this[e],this.message=e+": DOM Exception "+this.code}var e=Math,t=e.round,n=e.sin,r=e.cos,i=e.abs,s=e.sqrt,o=10,u=o/2,a=+navigator.userAgent.match(/MSIE ([\d.]+)?/)[1],l=Array.prototype.slice;d(document);var v={init:function(e){var t=e||document;t.createElement("canvas"),t.attachEvent("onreadystatechange",c(this.init_,this,t))},init_:function(e){var t=e.getElementsByTagName("canvas");for(var n=0;nf.x)f.x=c.x;if(a.y==null||c.yf.y)f.y=c.y}}n.push(' ">'),e?F(this,n,a,f):j(this,n),n.push(""),this.element_.insertAdjacentHTML("beforeEnd",n.join(""))},H.fill=function(){this.stroke(!0)},H.closePath=function(){this.currentPath_.push({type:"close"})},H.save=function(){var e={};x(this,e),this.aStack_.push(e),this.mStack_.push(this.m_),this.m_=S(E(),this.m_)},H.restore=function(){this.aStack_.length&&(x(this.aStack_.pop(),this),this.m_=this.mStack_.pop())},H.translate=function(e,t){var n=[[1,0,0],[0,1,0],[e,t,1]];R(this,S(n,this.m_),!1)},H.scale=function(e,t){this.arcScaleX_*=e,this.arcScaleY_*=t;var n=[[e,0,0],[0,t,0],[0,0,1]];R(this,S(n,this.m_),!0)};var W=z.prototype=new Error;W.INDEX_SIZE_ERR=1,W.DOMSTRING_SIZE_ERR=2,W.HIERARCHY_REQUEST_ERR=3,W.WRONG_DOCUMENT_ERR=4,W.INVALID_CHARACTER_ERR=5,W.NO_DATA_ALLOWED_ERR=6,W.NO_MODIFICATION_ALLOWED_ERR=7,W.NOT_FOUND_ERR=8,W.NOT_SUPPORTED_ERR=9,W.INUSE_ATTRIBUTE_ERR=10,W.INVALID_STATE_ERR=11,W.SYNTAX_ERR=12,W.INVALID_MODIFICATION_ERR=13,W.NAMESPACE_ERR=14,W.INVALID_ACCESS_ERR=15,W.VALIDATION_ERR=16,W.TYPE_MISMATCH_ERR=17,G_vmlCanvasManager=v,CanvasRenderingContext2D=P,DOMException=z}(),this.jsviews||this.jQuery&&jQuery.views||function(e,t){function C(e,t){var n="\\"+e.charAt(0),r="\\"+e.charAt(1),o="\\"+t.charAt(0),u="\\"+t.charAt(1);return N.rTag=i=r+"(?:(?:(\\w+(?=[\\/\\s"+o+"]))|(?:(\\w+)?(:)|(>)|(\\*)))"+"\\s*((?:[^"+o+"]|"+o+"(?!"+u+"))*?)"+"(\\/)?|(?:\\/(\\w+)))"+o,i=new RegExp(n+i+u,"g"),s=new RegExp("<.*>|"+e+".*"+t),this}function k(e){var n=this,r=n.tmpl.helpers||{};return e=(n.ctx[e]!==t?n.ctx:r[e]!==t?r:P[e]!==t?P:{})[e],typeof e!="function"?e:function(){return e.apply(n,arguments)}}function L(e,t,n){var r=t.tmpl.converters;return e=r&&r[e]||H[e],e?e.call(t,n):n}function A(e,n,r,i,s){s.props=s.props||{};var u,a=s.props.tmpl,l=n.tmpl.tags,c=n.tmpl.templates,h=arguments,p=l&&l[e]||D[e];return p?(i=i&&n.tmpl.tmpls[i-1],a=a||i||t,s.tmpl=""+a===a?c&&c[a]||_[a]||_(a):a,s.isTag=f,s.converter=r,s.view=n,s.renderContent=B,n.ctx&&o(s.ctx,n.ctx),u=p.apply(s,h.length>5?x.call(h,5):[]),u||(u==t?"":u.toString())):""}function O(e,n,i,s,o,u){var a=i.views,f={tmpl:o,path:n,parent:i,data:s,ctx:e,views:r.isArray(s)?[]:{},hlp:k};return r.isArray(a)?a.splice(f.index=u!==t?u:a.length,0,f):a[f.index="_"+g++]=f,f}function M(e,n,r,i,s){var o,a;if(r&&typeof r=="object"&&!r.nodeType){for(o in r)n(o,r[o]);return e}if(!r||i===t)s&&(i=s(t,i||r));else if(""+r===r)if(i===null)delete n[r];else if(i=s?s(r,i):i)n[r]=i;return(a=u.onStoreItem)&&a(n,r,i,s),i}function _(e,t){return M(this,_,e,t,q)}function D(e,t){return M(this,D,e,t)}function P(e,t){return M(this,P,e,t)}function H(e,t){return M(this,H,e,t)}function B(e,n,i,s,l){var c,h,p,d,v,m,g,y,b,w,E={},S=l===f,x=this,T="";x.isTag?(b=x.tmpl,n=n||x.ctx,i=i||x.view,s=s||x.path,l=l||x.index,E=x.props):b=x.jquery&&x[0]||x,i=i||N.topView,y=i.ctx,w=b.layout,e===i&&(e=i.data,w=f),n=n&&n===y?y:y?(y=o({},y),n)?o(y,n):y:n||{},E.link===a&&(n.link=a),b.fn||(b=_[b]||_(b)),v=n.link&&u.onRenderItem,m=n.link&&u.onRenderItems;if(b){if(r.isArray(e)&&!w){d=S?i:l!==t&&i||O(n,s,i,e,b,l);for(c=0,h=e.length;c-1,a+=(b===":"?w==="html"?(c=f,"e("+S):w?(g=f,'c("'+w+'",view,'+S):(h=f,"((v="+S+')!=u?v:""'):(l=f,'t("'+b+'",view,"'+(w||"")+'",'+(M?k.length:'""')+","+x+(S?",":"")+S))+")+");return a=new Function("data, view, j, b, u",E+(h?"v,":"")+(l?"t=j.tag,":"")+(g?"c=j.convert,":"")+(c?"e=j.converters.html,":"")+"ret; try{\n\n"+(C.debug?"debugger;":"")+(N?"ret=":"return ")+a.slice(0,-1)+";\n\n"+(N?"return ret;":"")+"}catch(e){return j.err(e);}"),t&&(t.fn=a,t.useVw=g||y||l),a}function I(e,t){function u(e,u,l,h,p,d,v,m,g,y,b,w,E,S,x,T){function N(e,n,r,i,s,o,u){if(n){var a=(r?'view.hlp("'+r+'")':i?"view":"data")+(u?(s?"."+s:r?"":i?"":"."+n)+(o||""):(u=r?"":i?s||"":n,""));return t&&g!=="("&&(a="b("+a+',"'+u+'")'),a+(u?"."+u:"")}return e}p=p||"",l=l||u||b,h=h||m,g=g||x||"",p=p||"";if(!d)return o?(o=!w,o?e:'"'):s?(s=!E,s?e:'"'):(l?(i++,l):"")+(T?i?"":n?(n=a,"\b"):",":v?(i&&j(),n=f,"\b"+h+":"):h?h.replace(c,N)+(g?(r[++i]=f,g):p):p?e:S?(r[i--]=a,S)+(g?(r[++i]=f,g):""):y?(r[i]||j(),","):u?"":(o=w,s=E,'"'));j()}var n,r={},i=0,s=a,o=a;return e=(e+" ").replace(h,u),e}function q(e,n,r,i){function p(t){if(""+t===t||t.nodeType>0)return a=t.nodeType>0?t:!s.test(t)&&l&&l(t)[0],a&&a.type&&(t=_[a.getAttribute(w)],t||(e=e||"_"+y++,a.setAttribute(w,e),t=q(e,a.innerHTML,r,i),_[e]=t)),t}var u,a,f,c,h;u=p(n),i=i||(n.markup?n:{}),i.name=e,c=i.templates,!u&&n.markup&&(u=p(n.markup))&&u.fn&&(u.debug!==n.debug||u.allowCode!==n.allowCode)&&(u=u.markup);if(u!==t){e&&!r&&(T[e]=function(){return n.render.apply(n,arguments)}),u.fn||n.fn?u.fn&&(e&&e!==u.name?n=o(o({},u),i):n=u):(n=R(u,i,r,0),F(u,n));for(f in c)h=c[f],h.name!==f&&(c[f]=q(f,h,n));return n}}function R(e,t,n,r){function i(e){n[e]&&(s[e]=o(o({},n[e]),t[e]))}t=t||{};var s={markup:e,tmpls:[],links:[],render:B};return n&&(n.templates&&(s.templates=o(o({},n.templates),t.templates)),s.parent=n,s.name=n.name+"["+r+"]",s.index=r),o(s,t),n&&(i("templates"),i("tags"),i("helpers"),i("converters")),s}function U(e){return b[e]||(b[e]="&#"+e.charCodeAt(0)+";")}var n="v1.0pre",r,i,s,o,u={},a=!1,f=!0,l=e.jQuery,c=/^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g,h=/(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,p=/\r?\n/g,d=/\\(['"])/g,v=/\\?(['"])/g,m=/\x08(~)?([^\x08]+)\x08/g,g=0,y=0,b={"&":"&","<":"<",">":">"},w="data-jsv-tmpl",E="var j=j||"+(l?"jQuery.":"js")+"views,",S=/[\x00"&'<>]/g,x=Array.prototype.slice,T={},N={jsviews:n,sub:u,debugMode:f,err:function(e){return N.debugMode?"
    Error: "+(e.message||e)+". ":'""'},tmplFn:F,render:T,templates:_,tags:D,helpers:P,converters:H,View:O,convert:L,delimiters:C,tag:A};l?(r=l,r.templates=_,r.render=T,r.views=N,r.fn.render=B):(r=e.jsviews=N,r.extend=function(e,t){var n;e=e||{};for(n in t)e[n]=t[n];return e},r.isArray=Array&&Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"}),o=r.extend,N.topView={views:{},tmpl:{},hlp:k,ctx:N.helpers},D({"if":function(){var e=this,n=e.view;return n.onElse=function(e,r){var i=0,s=r.length;while(s&&!r[i++])if(i===s)return"";return n.onElse=t,e.path="",e.renderContent(n)},n.onElse(this,arguments)},"else":function(){var e=this.view;return e.onElse?e.onElse(this,arguments):""},"for":function(){var e,t=this,n="",r=arguments,i=r.length;t.props.layout&&(t.tmpl.layout=f);for(e=0;e1&&!e.isArray(t[0]))return t[0]>=-180&&t[0]<=180&&t[1]>=-85&&t[1]<=85;t=t[0]}return!1},center:function(t,n){var r=!1;!n&&e.geo.proj&&this._isGeodetic(t)&&(r=!0,t=e.geo.proj.fromGeodetic(t));var i=[(t[0]+t[2])/2,(t[1]+t[3])/2];return r?e.geo.proj.toGeodetic(i):i},expandBy:function(t,n,r,i){var s=!1;return!i&&e.geo.proj&&this._isGeodetic(t)&&(s=!0,t=e.geo.proj.fromGeodetic(t)),t=[t[0]-n,t[1]-r,t[2]+n,t[3]+r],s?e.geo.proj.toGeodetic(t):t},height:function(t,n){return!n&&e.geo.proj&&this._isGeodetic(t)&&(t=e.geo.proj.fromGeodetic(t)),t[3]-t[1]},_in:function(e,t){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[2]&&e[3]>=t[3]},_bboxDisjoint:function(e,t){return t[0]>e[2]||t[2]e[3]||t[3]0&&(s/o>n?(a=s/2,f=a/n):(f=o/2,a=f*n),t=[u[0]-a,u[1]-f,u[0]+a,u[1]+f]),i?e.geo.proj.toGeodetic(t):t},recenter:function(t,n,r){var i=!1;!r&&e.geo.proj&&(this._isGeodetic(t)&&(i=!0,t=e.geo.proj.fromGeodetic(t)),this._isGeodetic(n)&&(n=e.geo.proj.fromGeodetic(n)));var s=(t[2]-t[0])/2,o=(t[3]-t[1])/2;return t=[n[0]-s,n[1]-o,n[0]+s,n[1]+o],i?e.geo.proj.toGeodetic(t):t},scaleBy:function(t,n,r){var i=!1;!r&&e.geo.proj&&this._isGeodetic(t)&&(i=!0,t=e.geo.proj.fromGeodetic(t));var s=this.center(t,!0),o=(t[2]-t[0])*n/2,u=(t[3]-t[1])*n/2;return t=[s[0]-o,s[1]-u,s[0]+o,s[1]+u],i?e.geo.proj.toGeodetic(t):t},width:function(t,n){return!n&&e.geo.proj&&this._isGeodetic(t)&&(t=e.geo.proj.fromGeodetic(t)),t[2]-t[0]},bbox:function(t,s){var o,u=!1;if(!t)return n;if(t.bbox)o=!s&&e.geo.proj&&this._isGeodetic(t.bbox)?e.geo.proj.fromGeodetic(t.bbox):t.bbox;else{o=[r,r,i,i];var a=this._allCoordinates(t),f=0;if(a.length===0)return n;!s&&e.geo.proj&&this._isGeodetic(a)&&(u=!0,a=e.geo.proj.fromGeodetic(a));for(;f0?(u[0]=Math.min(Math.max(a[0][0],h[0]),h[2]),u[1]=Math.min(Math.max(a[0][1],h[1]),h[3]),{type:"Point",coordinates:p?e.geo.proj.toGeodetic(u):u}):n;return o*=3,u[0]=Math.min(Math.max(u[0]/o,h[0]),h[2]),u[1]=Math.min(Math.max(u[1]/o,h[1]),h[3]),{type:"Point",coordinates:p?e.geo.proj.toGeodetic(u):u}}return n},contains:function(e,t){if(e.type!="Polygon")return!1;switch(t.type){case"Point":return this._containsPolygonPoint(e.coordinates,t.coordinates);case"LineString":return this._containsPolygonLineString(e.coordinates,t.coordinates);case"Polygon":return this._containsPolygonLineString(e.coordinates,t.coordinates[0]);default:return!1}},_containsPolygonPoint:function(e,t){if(e.length===0||e[0].length<4)return!1;var n=0,r=e[0][0],i=1,s,o;for(;it[0]&&n++;r=s}return n%2==1},_containsPolygonLineString:function(e,t){for(var n=0;n0){var i=e[0],s=t[0]-i[0],o=t[1]-i[1];if(e.length==1)return Math.sqrt(s*s+o*o);for(var u=1;u=u?i*i+s*s:n*n+r*r-o*o/u},_distanceLineStringLineString:function(e,t){var n=r;for(var i=0;i2?{type:"Point",coordinates:[parseFloat(t[1]),parseFloat(t[2])]}:null}function v(e){var t=e.match(/\s*\((.*)\)/),n=[],r,i,s=0;if(t&&t.length>1){r=t[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);for(;s1){r=t[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);for(;s0){for(;s
    ";while(n[0]);return e>6?e:!e}();e.widget("geo.geographics",{_$elem:t,_options:{},_trueCanvas:!0,_trueDoubleBuffer:!0,_width:0,_height:0,_$canvas:t,_context:t,_$canvasSceneFront:t,_$canvasSceneBack:t,_timeoutEnd:null,_requireFlip:!1,_blitcanvas:t,_blitcontext:t,_$labelsContainerFront:t,_$labelsContainerBack:t,_labelsHtml:"",options:{style:{borderRadius:"8px",color:"#7f0000",fillOpacity:.2,height:"8px",opacity:1,strokeOpacity:1,strokeWidth:"2px",visibility:"visible",width:"8px"},doubleBuffer:!0},_create:function(){this._$elem=this.element,this._options=this.options,this._$elem.css({webkitTransform:"translateZ(0)",display:"inline-block",overflow:"hidden",textAlign:"left"}),this._$elem.css("position")=="static"&&this._$elem.css("position","relative"),this._$elem.addClass("geo-graphics"),this._width=this._$elem.width(),this._height=this._$elem.height();if(!this._width||!this._height)this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10);var t="position:absolute;left:0;top:0;margin:0;padding:0;",r="width:"+this._width+"px;height:"+this._height+"px;",i='width="'+this._width+'" height="'+this._height+'"';this._blitcanvas=document.createElement("canvas"),this._blitcanvas.getContext?(this._$canvas=e("'),this._blitcanvas.width=1,this._blitcanvas.height=1,this._trueDoubleBuffer=this._blitcanvas.toDataURL().length>6,(!this._options.doubleBuffer||!this._trueDoubleBuffer)&&this._$elem.append(this._$canvas),this._context=this._$canvas[0].getContext("2d"),this._blitcanvas.width=this._width,this._blitcanvas.height=this._height,this._blitcontext=this._blitcanvas.getContext("2d"),this._$canvasSceneFront=e(''),this._$canvasSceneBack=e('')):n<=8&&(this._trueCanvas=!1,this._$elem.append("
    '),this._$canvas=this._$elem.children(":last"),G_vmlCanvasManager.initElement(this._$canvas[0]),this._context=this._$canvas[0].getContext("2d"),this._$canvas.children().css({backgroundColor:"transparent",width:this._width,height:this._height})),this._$labelsContainerFront=e('
    '),this._$labelsContainerBack=e('
    ')},_setOption:function(t,n){t=="style"&&(n=e.extend({},this._options.style,n)),e.Widget.prototype._setOption.apply(this,arguments)},destroy:function(){e.Widget.prototype.destroy.apply(this,arguments),this._$elem.html(""),this._$elem.removeClass("geo-graphics")},clear:function(){this._context.clearRect(0,0,this._width,this._height),this._labelsHtml="",this._end()},drawArc:function(e,t,n,r){r=this._getGraphicStyle(r);if(r.visibility!="hidden"&&r.opacity>0&&r.widthValue>0&&r.heightValue>0){var i=Math.min(r.widthValue,r.heightValue)/2;t=t*Math.PI/180,n=n*Math.PI/180,this._context.save(),this._context.translate(e[0],e[1]),r.widthValue>r.heightValue?this._context.scale(r.widthValue/r.heightValue,1):this._context.scale(1,r.heightValue/r.widthValue),this._context.beginPath(),this._context.arc(0,0,i,t,n,!1),this._trueCanvas&&this._context.restore(),r.doFill&&(this._context.fillStyle=r.fill,this._context.globalAlpha=r.opacity*r.fillOpacity,this._context.fill()),r.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=r.strokeWidthValue,this._context.strokeStyle=r.stroke,this._context.globalAlpha=r.opacity*r.strokeOpacity,this._context.stroke()),this._trueCanvas||this._context.restore()}this._end()},drawPoint:function(e,t){t=this._getGraphicStyle(t),t.widthValue==t.heightValue&&t.heightValue==t.borderRadiusValue?this.drawArc(e,0,360,t):t.visibility!="hidden"&&t.opacity>0&&(t.borderRadiusValue=Math.min(Math.min(t.widthValue,t.heightValue)/2,t.borderRadiusValue),e[0]-=t.widthValue/2,e[1]-=t.heightValue/2,this._context.beginPath(),this._context.moveTo(e[0]+t.borderRadiusValue,e[1]),this._context.lineTo(e[0]+t.widthValue-t.borderRadiusValue,e[1]),this._context.quadraticCurveTo(e[0]+t.widthValue,e[1],e[0]+t.widthValue,e[1]+t.borderRadiusValue),this._context.lineTo(e[0]+t.widthValue,e[1]+t.heightValue-t.borderRadiusValue),this._context.quadraticCurveTo(e[0]+t.widthValue,e[1]+t.heightValue,e[0]+t.widthValue-t.borderRadiusValue,e[1]+t.heightValue),this._context.lineTo(e[0]+t.borderRadiusValue,e[1]+t.heightValue),this._context.quadraticCurveTo(e[0],e[1]+t.heightValue,e[0],e[1]+t.heightValue-t.borderRadiusValue),this._context.lineTo(e[0],e[1]+t.borderRadiusValue),this._context.quadraticCurveTo(e[0],e[1],e[0]+t.borderRadiusValue,e[1]),this._context.closePath(),t.doFill&&(this._context.fillStyle=t.fill,this._context.globalAlpha=t.opacity*t.fillOpacity,this._context.fill()),t.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=t.strokeWidthValue,this._context.strokeStyle=t.stroke,this._context.globalAlpha=t.opacity*t.strokeOpacity,this._context.stroke()),this._end())},drawLineString:function(e,t){this._drawLines([e],!1,t)},drawPolygon:function(e,t){if(!this._trueCanvas||e.length==1)this._drawLines(e,!0,t);else{if(!e||!e.length||e[0].length<3)return;t=this._getGraphicStyle(t);var n,r,i;if(t.visibility!="hidden"&&t.opacity>0){this._blitcontext.clearRect(0,0,this._width,this._height);if(t.doFill&&e.length>1){this._blitcontext.globalCompositeOperation="source-out",this._blitcontext.globalAlpha=1;for(r=1;r1)for(r=1;r'+t+""},resize:function(){this._width=this._$elem.width(),this._height=this._$elem.height();if(!this._width||!this._height)this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10);this._trueCanvas?(this._$canvas[0].width=this._width,this._$canvas[0].height=this._height,this._$canvasSceneFront.css({width:this._width,height:this._height}),this._$canvasSceneBack.css({width:this._width,height:this._height})):this._$canvas.css({width:this._width,height:this._height}),this._$labelsContainerFront.css({width:this._width,height:this._height}),this._$labelsContainerBack.css({width:this._width,height:this._height})},interactiveTransform:function(e,t){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null);if(this._trueCanvas)if(this._options.doubleBuffer&&this._trueDoubleBuffer){if(this._requireFlip){var n=this,r=n._$canvasSceneFront;n._$canvasSceneFront=n._$canvasSceneBack.css({left:0,top:0,width:n._width,height:n._height}).prop("src",n._$canvas[0].toDataURL()).prependTo(n._$elem),n._$canvasSceneBack=r.detach(),n._requireFlip=!1}this._$canvasSceneFront.css({left:Math.round(e[0]),top:Math.round(e[1]),width:this._width*t,height:this._height*t})}else this._context.clearRect(0,0,this._width,this._height);else this._context.clearRect(0,0,this._width,this._height);this._$labelsContainerFront.css({left:Math.round(e[0]),top:Math.round(e[1]),width:this._width*t,height:this._height*t})},_end:function(){function t(){if(!e._timeoutEnd)return;e._trueCanvas&&e._options.doubleBuffer&&e._trueDoubleBuffer&&e._$canvasSceneBack.prop("src","").one("load",function(t){e._requireFlip=!1;var n=e._$canvasSceneFront;e._$canvasSceneFront=e._$canvasSceneBack.css({left:0,top:0,width:e._width,height:e._height}).prependTo(e._$elem),e._$canvasSceneBack=n.detach()}).prop("src",e._$canvas[0].toDataURL()),e._$labelsContainerBack.html(e._labelsHtml).find("a").css({position:"relative",zIndex:100,display:"inline-block",webkitTransform:"translateZ(0)"});var t=e._$labelsContainerFront;e._$labelsContainerFront=e._$labelsContainerBack.css({left:0,top:0,width:e._width,height:e._height}).prependTo(e._$elem),e._$labelsContainerBack=t.detach(),e._timeoutEnd=null}this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._requireFlip=!0;var e=this;this._timeoutEnd=setTimeout(t,20)},_getGraphicStyle:function(t){function n(e){return e=parseInt(e,10),+e+""===e?+e:e}return t=e.extend({},this._options.style,t),t.borderRadiusValue=n(t.borderRadius),t.fill=t.fill||t.color,t.doFill=t.fill&&t.fillOpacity>0,t.stroke=t.stroke||t.color,t.strokeWidthValue=n(t.strokeWidth),t.doStroke=t.stroke&&t.strokeOpacity>0&&t.strokeWidthValue>0,t.widthValue=n(t.width),t.heightValue=n(t.height),t},_drawLines:function(e,t,n){if(!e||!e.length||e[0].length<2)return;var r,i;n=this._getGraphicStyle(n);if(n.visibility!="hidden"&&n.opacity>0){this._context.beginPath();for(r=0;r
    ";while(n[0]);return e>6?e:!e}(),i={bbox:[-180,-85,180,85],bboxMax:[-180,-85,180,85],center:[0,0],cursors:{"static":"default",pan:"url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move",zoom:"crosshair",dragBox:"crosshair",dragCircle:"crosshair",drawPoint:"crosshair",drawLineString:"crosshair",drawPolygon:"crosshair",measureLength:"crosshair",measureArea:"crosshair"},measureLabels:{length:"{{:length.toFixed( 2 )}} m",area:"{{:area.toFixed( 2 )}} sq m"},drawStyle:{},shapeStyle:{},mode:"pan",pannable:!0,scroll:"default",shift:"default",services:[{"class":"osm",type:"tiled",src:function(e){return"http://otile"+(e.index%4+1)+".mqcdn.com/tiles/1.0.0/osm/"+e.zoom+"/"+e.tile.column+"/"+e.tile.row+".png"},attr:"Tiles Courtesy of MapQuest "}],tilingScheme:{tileWidth:256,tileHeight:256,levels:18,basePixelSize:156543.03392799935,origin:[-20037508.342787,20037508.342787]},axisLayout:"map",zoom:0,zoomMin:0,zoomMax:Number.POSITIVE_INFINITY,pixelSize:0};e.widget("geo.geomap",{_$elem:t,_map:t,_created:!1,_createdGraphics:!1,_widgetId:0,_tmplLengthId:"",_tmplAreaId:"",_contentBounds:{},_$resizeContainer:t,_$eventTarget:t,_$contentFrame:t,_$existingChildren:t,_$attrList:t,_$servicesContainer:t,_$shapesContainers:t,_$panContainer:t,_$shapesContainer:t,_$drawContainer:t,_$measureContainer:t,_$measureLabel:t,_dpi:96,_currentServices:[],_center:t,_pixelSize:t,_centerMax:t,_pixelSizeMax:t,_userGeodetic:!0,_centerInteractive:t,_pixelSizeInteractive:t,_timeoutInteractive:null,_triggerInteractive:!1,_timeoutRefreshShapes:null,_loadCount:0,_wheelTimeout:null,_wheelLevel:0,_zoomFactor:2,_fullZoomFactor:2,_partialZoomFactor:1.18920711500273,_mouseDown:t,_inOp:t,_toolPan:t,_shiftDown:t,_anchor:t,_current:t,_downDate:t,_moveDate:t,_clickDate:t,_lastMove:t,_lastDrag:t,_windowHandler:null,_resizeTimeout:null,_panning:t,_velocity:t,_friction:t,_supportTouch:t,_softDblClick:t,_isTap:t,_isDbltap:t,_isMultiTouch:t,_multiTouchAnchor:[],_multiTouchAnchorBbox:t,_multiTouchCurrentBbox:t,_drawTimeout:null,_drawPixels:[],_drawCoords:[],_graphicShapes:[],_initOptions:{},_options:{},options:e.extend({},i),_createWidget:function(t,r){this._$elem=e(r);if(this._$elem.is(".geo-service")){this._graphicShapes=[],e.Widget.prototype._createWidget.apply(this,arguments);return}this._widgetId=n++,this._tmplLengthId="geoMeasureLength"+this._widgetId,this._tmplAreaId="geoMeasureArea"+this._widgetId,this._$elem.addClass("geo-map").css({webkitTransform:"translateZ(0)"}),this._initOptions=t||{},this._forcePosition(this._$elem),this._$elem.css("text-align","left");var i=this._findMapSize();this._contentBounds={x:parseInt(this._$elem.css("padding-left"),10),y:parseInt(this._$elem.css("padding-top"),10),width:i.width,height:i.height},this._createChildren(),this._center=[0,0],this._centerMax=[0,0],this._centerInteractive=[0,0],this.options.pixelSize=this._pixelSize=this._pixelSizeMax=156543.03392799935,this._mouseDown=this._inOp=this._toolPan=this._shiftDown=this._panning=this._isTap=this._isDbltap=!1,this._anchor=[0,0],this._current=[0,0],this._lastMove=[0,0],this._lastDrag=[0,0],this._velocity=[0,0],this._friction=[.8,.8],this._downDate=this._moveDate=this._clickDate=0,this._drawPixels=[],this._drawCoords=[],this._graphicShapes=[],e.Widget.prototype._createWidget.apply(this,arguments)},_create:function(){this._options=this.options;if(this._$elem.is(".geo-service")){this._map=this._$elem.data("geoMap"),this._$elem.data("geoService",this);return}this._map=this,this._supportTouch="ontouchend"in document,this._softDblClick=this._supportTouch||r==7;var n=this,i=this._supportTouch?"touchstart":"mousedown",s=this._supportTouch?"touchend touchcancel":"mouseup",o=this._supportTouch?"touchmove":"mousemove";e(document).keydown(e.proxy(this._document_keydown,this)),this._$eventTarget.dblclick(e.proxy(this._eventTarget_dblclick,this)),this._$eventTarget.bind(i,e.proxy(this._eventTarget_touchstart,this));var u=this._$eventTarget[0].setCapture?this._$eventTarget:e(document);u.bind(o,e.proxy(this._dragTarget_touchmove,this)),u.bind(s,e.proxy(this._dragTarget_touchstop,this)),this._$eventTarget.mousewheel(e.proxy(this._eventTarget_mousewheel,this)),this._windowHandler=function(){n._resizeTimeout&&clearTimeout(n._resizeTimeout),n._resizeTimeout=setTimeout(function(){n._created&&n._$elem.geomap("resize",!0)},500)},e(window).resize(this._windowHandler),this._$drawContainer.geographics({style:this._initOptions.drawStyle||{},doubleBuffer:!1}),this._options.drawStyle=this._$drawContainer.geographics("option","style"),this._$shapesContainer.geographics({style:this._initOptions.shapeStyle||{}}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style"),this._initOptions&&(this._initOptions.tilingScheme!==t&&this._setOption("tilingScheme",this._initOptions.tilingScheme||null,!1),this._initOptions.services&&(this._options.services=e.merge([],this._initOptions.services)),this._initOptions.bboxMax&&(this._setOption("bboxMax",this._initOptions.bboxMax,!1),this._setOption("bbox",this._initOptions.bboxMax,!1)),this._initOptions.zoomMin!==t&&this._setOption("zoomMin",this._initOptions.zoomMin,!1),this._initOptions.zoomMax!==t&&this._setOption("zoomMax",this._initOptions.zoomMax,!1),this._initOptions.bbox&&this._setOption("bbox",this._initOptions.bbox,!1),this._initOptions.center&&this._setOption("center",this._initOptions.center,!1),this._initOptions.zoom!==t&&this._setOption("zoom",this._initOptions.zoom,!1)),e.templates(this._tmplLengthId,this._options.measureLabels.length),e.templates(this._tmplAreaId,this._options.measureLabels.area),this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._createServices(),this._refresh(),this._created=!0},_setOption:function(n,r,i){if(n=="pixelSize")return;i=i===t||i,this._$elem.is(".geo-map")&&this._panFinalize();var s,o,u,a;switch(n){case"bbox":this._created&&this._clearInteractiveTimeout(),this._userGeodetic=e.geo.proj&&e.geo._isGeodetic(r),this._userGeodetic&&(r=e.geo.proj.fromGeodetic(r)),s=[r[0]+(r[2]-r[0])/2,r[1]+(r[3]-r[1])/2],o=Math.max(e.geo.width(r,!0)/this._contentBounds.width,e.geo.height(r,!0)/this._contentBounds.height),a=this._getZoom(s,o),this._options.tilingScheme?o=this._getPixelSize(Math.min(Math.max(a,this._options.zoomMin),this._options.zoomMax)):athis._options.zoomMax&&(o=this._getPixelSize(this._options.zoomMax)),this._created?(this._setInteractiveCenterAndSize(s,o),this._setInteractiveTimeout(!1)):this._setCenterAndSize(s,o,!1,i),r=this._getBbox(s,o);break;case"bboxMax":this._userGeodetic=e.geo.proj&&e.geo._isGeodetic(r);break;case"center":this._created&&this._clearInteractiveTimeout(),this._userGeodetic=e.geo.proj&&e.geo._isGeodetic(r),this._userGeodetic&&(r=e.geo.proj.fromGeodetic(r)),this._created?(this._setInteractiveCenterAndSize(r,this._pixelSizeInteractive),this._interactiveTransform(),this._setInteractiveTimeout(!1)):this._setCenterAndSize(r,this._pixelSize,!1,i);break;case"measureLabels":r=e.extend(this._options.measureLabels,r),e.templates(this._tmplLengthId,this._options.measureLabels.length),e.templates(this._tmplAreaId,this._options.measureLabels.area);break;case"drawStyle":this._$drawContainer&&(this._$drawContainer.geographics("option","style",r),r=this._$drawContainer.geographics("option","style"));break;case"shapeStyle":this._$elem.is(".geo-service")&&!this._createdGraphics&&this._createServiceGraphics(),this._createdGraphics&&(this._$shapesContainer.geographics("option","style",r),r=this._$shapesContainer.geographics("option","style"));break;case"mode":this._resetDrawing(),this._$eventTarget.css("cursor",this._options.cursors[r]);break;case"zoom":this._created?this._setZoom(r,!1,i):(r=Math.max(r,0),this._setCenterAndSize(this._center,this._getPixelSize(r),!1,i))}e.Widget.prototype._setOption.apply(this,arguments);switch(n){case"bbox":case"center":this._userGeodetic&&(this._options.bbox=e.geo.proj.toGeodetic(this._options.bbox),this._options.center=e.geo.proj.toGeodetic(this._center));break;case"tilingScheme":r!==null&&(this._pixelSizeMax=this._getPixelSize(0),this._centerMax=[r.origin[0]+this._pixelSizeMax*r.tileWidth/2,r.origin[1]+this._pixelSizeMax*r.tileHeight/2]);break;case"bboxMax":e.geo.proj&&e.geo._isGeodetic(r)?u=e.geo.proj.fromGeodetic(r):u=r,this._centerMax=e.geo.center(u),this._pixelSizeMax=Math.max(e.geo.width(u,!0)/this._contentBounds.width,e.geo.height(u,!0)/this._contentBounds.height);break;case"services":this._createServices(),i&&(this._refresh(),this._refreshAllShapes());break;case"shapeStyle":i&&this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))}},destroy:function(){if(this._$elem.is(".geo-service"))this._createdGraphics&&(this._$shapesContainer.geographics("destroy"),this._$shapesContainer=t,this._createdGraphics=!1);else{clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,this._created=!1,e(window).unbind("resize",this._windowHandler);for(var n=0;n=0||t<=1)for(var r=0;r0)){this._createdGraphics||this._createServiceGraphics();var o,u,a,f,l,c;e.isArray(n)?o=n:n.type=="FeatureCollection"?o=n.features:o=[n];for(a=1;a0)){var i=e.isArray(n)?n:[n],s;for(var o=0;o=0&&(e.removeData(n,"geoBbox"),s=this._graphicShapes.slice(o+1),this._graphicShapes.length=o,this._graphicShapes.push.apply(this._graphicShapes,s),o--);if(r===t||r)this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh(),this._refreshAllShapes()}},_getBbox:function(e,t){e=e||this._center,t=t||this._pixelSize;var n=this._contentBounds.width/2*t,r=this._contentBounds.height/2*t;return[e[0]-n,e[1]-r,e[0]+n,e[1]+r]},_setBbox:function(t,n,r){var i=[t[0]+(t[2]-t[0])/2,t[1]+(t[3]-t[1])/2],s=Math.max(e.geo.width(t,!0)/this._contentBounds.width,e.geo.height(t,!0)/this._contentBounds.height),o=this._getZoom(i,s);this._options.tilingScheme?s=this._getPixelSize(Math.min(Math.max(o,this._options.zoomMin),this._options.zoomMax)):othis._options.zoomMax&&(s=this._getPixelSize(this._options.zoomMax)),this._setInteractiveCenterAndSize(i,s),this._interactiveTransform()},_getBboxMax:function(){var e=this._contentBounds.width/2*this._pixelSizeMax,t=this._contentBounds.height/2*this._pixelSizeMax;return[this._centerMax[0]-e,this._centerMax[1]-t,this._centerMax[0]+e,this._centerMax[1]+t]},_getCenter:function(){return this._center},_getContentBounds:function(){return this._contentBounds},_getServicesContainer:function(){return this._$servicesContainer},_getZoom:function(t,n){t=t||this._center,n=n||this._pixelSize;var r=this._options.tilingScheme;if(r){if(r.pixelSizes){var i=Math.floor(n*1e3),s=r.pixelSizes.length,o=s-1;for(;o>=0;o--)if(Math.floor(r.pixelSizes[o]*1e3)>=i)return o;return 0}return Math.round(Math.log(r.basePixelSize/n)/Math.log(2))}var u=this._contentBounds.width/this._contentBounds.height,a=e.geo.reaspect(this._getBbox(t,n),u,!0),f=e.geo.reaspect(this._getBboxMax(),u,!0);return Math.round(Math.log(e.geo.width(f,!0)/e.geo.width(a,!0))/Math.log(this._zoomFactor))},_setZoom:function(e,t,n){this._clearInteractiveTimeout(),e=Math.min(Math.max(e,this._options.zoomMin),this._options.zoomMax),this._setInteractiveCenterAndSize(this._centerInteractive,this._getPixelSize(e)),this._interactiveTransform(),this._setInteractiveTimeout(t)},_createChildren:function(){this._$existingChildren=this._$elem.children(),this._forcePosition(this._$existingChildren),this._$existingChildren.detach().css({mozUserSelect:"none"});var t="width:"+this._contentBounds.width+"px; height:"+this._contentBounds.height+"px; margin:0; padding:0;",n="position:absolute; left:0; top:0;";this._$elem.prepend('
    '),this._$eventTarget=this._$contentFrame=this._$elem.children(":first"),this._$contentFrame.append('
    '),this._$servicesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
      '),this._$attrList=this._$contentFrame.children(":last"),this._$contentFrame.append('
      '),this._$drawContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
      '),this._$measureContainer=this._$contentFrame.children(":last"),this._$measureLabel=this._$measureContainer.children(),this._$contentFrame.append('
      '),this._$shapesContainer=this._$contentFrame.children(":last"),this._$panContainer=e([this._$shapesContainer[0],this._$drawContainer[0],this._$measureContainer[0]]),this._$resizeContainer=e([this._$contentFrame[0],this._$servicesContainer[0],this._$eventTarget[0],this._$measureContainer[0]]),this._$contentFrame.append(this._$existingChildren),e("#geo-measure-style").length||e("head").prepend('")},_createServices:function(){var t,n;for(n=0;n',o;this._$servicesContainer.append(s),serviceContainer=this._$servicesContainer.children(":last"),t.serviceContainer=serviceContainer,e.geo._serviceTypes[t.type].create(this,serviceContainer,t,n),serviceContainer.data("geoMap",this).geomap(),t.attr&&this._$attrList.append("
    • "+t.attr+"
    • ")}this._$shapesContainers=this._$shapesContainer,this._$attrList.find("a").css({position:"relative",zIndex:100})},_createServiceGraphics:function(){var e=this._$elem.closest(".geo-content-frame");this._$elem.append('
      '),this._$shapesContainer=this._$elem.children(":last"),this._map._$shapesContainers=this._map._$shapesContainers.add(this._$shapesContainer),this._$shapesContainer.geographics(),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style")},_refreshDrawing:function(){this._$drawContainer.geographics("clear");if(this._drawPixels.length>0){var t=this._options.mode,n=this._drawPixels,r=this._drawCoords,i,s,o,u,a;switch(t){case"measureLength":t="drawLineString",s={type:"LineString",coordinates:r},i=e.render[this._tmplLengthId]({length:e.geo.length(s,!0)}),o=e.merge([],n[n.length-1]);break;case"measureArea":t="drawPolygon",s={type:"Polygon",coordinates:[e.merge([],r)]},s.coordinates[0].push(r[0]),i=e.render[this._tmplAreaId]({area:e.geo.area(s,!0)}),o=this._toPixel(e.geo.centroid(s).coordinates),n=[n];break;case"drawPolygon":n=[n]}this._$drawContainer.geographics(t,n),i&&(this._$measureLabel.html(i),u=this._contentBounds.width-(this._$measureLabel.outerWidth(!0)+o[0]),a=this._contentBounds.height-(this._$measureLabel.outerHeight(!0)+o[1]),u<0&&(o[0]+=u),a<0&&(o[1]+=a),this._$measureLabel.css({left:Math.max(o[0],0),top:Math.max(o[1],0)}).show())}},_resetDrawing:function(){this._drawPixels=[],this._drawCoords=[],this._$drawContainer.geographics("clear"),this._$measureLabel.hide()},_refreshAllShapes:function(){this._timeoutRefreshShapes=null;var e,t,n=0;for(;n0&&t._refreshShapes(t._$shapesContainer,t._graphicShapes,t._graphicShapes,t._graphicShapes));this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._graphicShapes.length>0&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))},_refreshShapes:function(n,r,i,s,o,u){var a,f,l,c,h,p,d,v,m=this._map._getBbox(o,u);for(a=0;a0&&e.height>0)){e={width:t.width(),height:t.height()};if(e.width<=0||e.height<=0)e={width:parseInt(t.css("width"),10),height:parseInt(t.css("height"),10)};t=t.parent()}return e},_forcePosition:function(e){var t=e.css("position");t!="relative"&&t!="absolute"&&t!="fixed"&&e.css("position","relative")},_getPixelSize:function(t){var n=this._options.tilingScheme;if(n!==null){if(t===0)return n.pixelSizes?n.pixelSizes[0]:n.basePixelSize;t=Math.round(t),t=Math.max(t,0);var r=n.pixelSizes?n.pixelSizes.length:n.levels;return t=Math.min(t,r-1),n.pixelSizes?n.pixelSizes[t]:n.basePixelSize/Math.pow(2,t)}var i=e.geo.scaleBy(this._getBboxMax(),1/Math.pow(this._zoomFactor,t),!0);return Math.max(e.geo.width(i,!0)/this._contentBounds.width,e.geo.height(i,!0)/this._contentBounds.height)},_getZoomCenterAndSize:function(e,t,n){var r=n?this._fullZoomFactor:this._partialZoomFactor,i=Math.pow(r,-t),s=this._pixelSizeInteractive*i,o=this._getZoom(this._centerInteractive,s);n&&this._options.tilingScheme?s=this._getPixelSize(Math.min(Math.max(o,this._options.zoomMin),this._options.zoomMax)):t<0&&o0&&o>this._options.zoomMax&&(s=this._pixelSizeInteractive);var u=s/this._pixelSizeInteractive,a=this._toMap(e,this._centerInteractive,this._pixelSizeInteractive),f=[(this._centerInteractive[0]-a[0])*u,(this._centerInteractive[1]-a[1])*u],l=[a[0]+f[0],a[1]+f[1]];return{pixelSize:s,center:l}},_mouseWheelFinish:function(e){this._wheelTimeout=null;if(this._wheelLevel!==0){var t=this._getZoomCenterAndSize(this._anchor,this._wheelLevel,this._options.tilingScheme!==null);this._wheelLevel=0}else e&&(this._refresh(),this._refreshAllShapes())},_panFinalize:function(){if(this._panning){this._velocity=[0,0];var e=this._current[0]-this._anchor[0],t=this._current[1]-this._anchor[1],n=this._options.axisLayout==="image",r=-e*this._pixelSize,i=(n?-1:1)*t*this._pixelSize;this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._inOp=!1,this._anchor=this._current,this._mouseDown=this._toolPan=this._panning=!1}},_panMove:function(){if(!this._options.pannable)return;var e=this._current[0]-this._lastDrag[0],t=this._current[1]-this._lastDrag[1],n=0,r,i;if(this._toolPan||e>3||e<-3||t>3||t<-3){this._toolPan||(this._toolPan=!0,this._$eventTarget.css("cursor",this._options.cursors.pan)),this._mouseDown&&(this._velocity=[e,t]);if(e!==0||t!==0)this._panning=!0,this._lastDrag=this._current,this._centerInteractive[0]-=e*this._pixelSizeInteractive,this._centerInteractive[1]+=(this._options.axisLayout==="image"?-1:1)*t*this._pixelSizeInteractive,this._setInteractiveCenterAndSize(this._centerInteractive,this._pixelSizeInteractive),this._interactiveTransform()}},_clearInteractiveTimeout:function(){return this._timeoutRefreshShapes&&(clearTimeout(this._timeoutRefreshShapes),this._timeoutRefreshShapes=null),this._timeoutInteractive?(clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,!0):(this._centerInteractive[0]=this._center[0],this._centerInteractive[1]=this._center[1],this._pixelSizeInteractive=this._pixelSize,!1)},_interactiveTransform:function(){var t=this._contentBounds.width,n=this._contentBounds.height,r=t/2,i=n/2,s=[this._centerInteractive[0]-r,this._centerInteractive[1]-i,this._centerInteractive[0]+r,this._centerInteractive[1]+i],o=this._pixelSize,u=o/this._pixelSizeInteractive;if(o>0){u=Math.round(u*1e3)/1e3;var a=this._toMap([0,0]),f=this._toPixel(a,this._centerInteractive,this._pixelSizeInteractive);this._$shapesContainers.geographics("interactiveTransform",f,u)}for(var l=0;l0&&(this._drawPixels=this._toPixel(this._drawCoords,this._centerInteractive,this._pixelSizeInteractive),this._refreshDrawing())},_interactiveTimeout:function(){this._isMultiTouch?this._timeoutInteractive=setTimeout(e.proxy(interactiveTimeout,this),128):this._created&&this._timeoutInteractive&&(this._setCenterAndSize(this._centerInteractive,this._pixelSizeInteractive,this._triggerInteractive,!0),this._timeoutInteractive=null,this._triggerInteractive=!1,this._timeoutRefreshShapes=setTimeout(e.proxy(this._refreshAllShapes,this),128))},_setInteractiveTimeout:function(t){this._timeoutInteractive=setTimeout(e.proxy(this._interactiveTimeout,this),128),this._triggerInteractive|=t},_refresh:function(t,n){var r,i=0;for(;ithis._options.zoomMax&&(this._pixelSizeInteractive=n=this._getPixelSize(this._options.zoomMax)),this._center[0]=t[0],this._center[1]=t[1],this._options.pixelSize=this._pixelSize=n,this._userGeodetic?(this._options.bbox=e.geo.proj.toGeodetic(this._getBbox()),this._options.center=e.geo.proj.toGeodetic(this._center)):(this._options.bbox=this._getBbox(),this._options.center=e.merge([],t)),this._options.zoom=s,r&&this._trigger("bboxchange",window.event,{bbox:e.merge([],this._options.bbox)}),i&&(this._refresh(),this._refreshAllShapes(),this._refreshDrawing())},_requestQueued:function(){this._loadCount===0&&this._trigger("loadstart",window.event),this._loadCount++},_requestComplete:function(){this._loadCount--,this._loadCount<=0&&(this._loadCount=0,this._trigger("loadend",window.event))},_toMap:function(t,n,r){n=n||this._center,r=r||this._pixelSize;var i=e.isArray(t[0]),s=i&&e.isArray(t[0][0]),o=s&&e.isArray(t[0][0][0]),u=this._contentBounds.width,a=this._contentBounds.height,f=u/2*r,l=a/2*r,c=[n[0]-f,n[1]-l,n[0]+f,n[1]+l],h=e.geo.width(c,!0)/u,p=e.geo.height(c,!0)/a,d,v=this._options.axisLayout==="image",m=[],g,y,b;o||(s||(i||(t=[t]),t=[t]),t=[t]);for(g=0;g0&&t.which==27&&(n<=2?(this._resetDrawing(),this._inOp=!1):(this._drawCoords[n-2]=e.merge([],this._drawCoords[n-1]),this._drawPixels[n-2]=e.merge([],this._drawPixels[n-1]),this._drawCoords.length--,this._drawPixels.length--,this._refreshDrawing()))},_eventTarget_dblclick_zoom:function(e){var t=this._clearInteractiveTimeout();this._trigger("dblclick",e,{type:"Point",coordinates:this._toMap(this._current,this._centerInteractive,this._pixelSizeInteractive)});if(!e.isDefaultPrevented()){var n=this._getZoomCenterAndSize(this._current,1,!0);this._setInteractiveCenterAndSize(n.center,n.pixelSize),this._interactiveTransform(),t=!0}t&&this._setInteractiveTimeout(!0)},_eventTarget_dblclick:function(t){if(this._options.mode==="static")return;this._drawTimeout&&(window.clearTimeout(this._drawTimeout),this._drawTimeout=null);var n=e(t.currentTarget).offset();switch(this._options.mode){case"drawLineString":case"measureLength":this._drawCoords.length>1&&(this._drawCoords[0][0]!=this._drawCoords[1][0]||this._drawCoords[0][1]!=this._drawCoords[1][1])?(this._drawCoords.length--,this._trigger("shape",t,{type:"LineString",coordinates:this._userGeodetic?e.geo.proj.toGeodetic(this._drawCoords):this._drawCoords})):this._eventTarget_dblclick_zoom(t),this._resetDrawing();break;case"drawPolygon":case"measureArea":if(this._drawCoords.length>1&&(this._drawCoords[0][0]!=this._drawCoords[1][0]||this._drawCoords[0][1]!=this._drawCoords[1][1])){var r=this._drawCoords.length-1;r>2&&(this._drawCoords[r]=e.merge([],this._drawCoords[0]),this._trigger("shape",t,{type:"Polygon",coordinates:[this._userGeodetic?e.geo.proj.toGeodetic(this._drawCoords):this._drawCoords]}))}else this._eventTarget_dblclick_zoom(t);this._resetDrawing();break;default:this._eventTarget_dblclick_zoom(t)}this._inOp=!1},_eventTarget_touchstart:function(t){if(typeof document.elementFromPoint!="undefined"&&document.elementFromPoint(t.pageX,t.pageY).nodeName==="A")return;var n=this._options.mode,r=this._options.shift,i=n==="dragBox"?"dragBox":"zoom";if(n==="static")return;if(!this._supportTouch&&t.which!=1)return;var s=this._clearInteractiveTimeout(),o=e(t.currentTarget).offset(),u=t.originalEvent.changedTouches;this._supportTouch?(this._multiTouchAnchor=e.merge([],u),this._isMultiTouch=this._multiTouchAnchor.length>1,this._isMultiTouch?(this._multiTouchCurrentBbox=[u[0].pageX-o.left,u[0].pageY-o.top,u[1].pageX-o.left,u[1].pageY-o.top],this._multiTouchAnchorBbox=e.merge([],this._multiTouchCurrentBbox),this._current=e.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchCurrentBbox=[u[0].pageX-o.left,u[0].pageY-o.top,NaN,NaN],this._current=[u[0].pageX-o.left,u[0].pageY-o.top])):this._current=[t.pageX-o.left,t.pageY-o.top];if(this._softDblClick){var a=e.now();if(a-this._downDate<750){if(this._isTap){var f=this._current[0]-this._anchor[0],l=this._current[1]-this._anchor[1],c=Math.sqrt(f*f+l*l);c>8?this._isTap=!1:this._current=e.merge([],this._anchor)}this._isDbltap?this._isDbltap=!1:this._isDbltap=this._isTap}else this._isDbltap=!1;this._isTap=!0,this._downDate=a}return this._mouseDown=!0,this._anchor=e.merge([],this._current),!this._inOp&&t.shiftKey&&r!=="off"?(this._shiftDown=!0,this._$eventTarget.css("cursor",this._options.cursors[r==="default"?i:r])):!this._isMultiTouch&&(this._options.pannable||n==="dragBox"||n==="dragCircle")&&(this._inOp=!0,n!=="zoom"&&n!=="dragBox"&&n!=="dragCircle"&&(this._lastDrag=this._current,t.currentTarget.setCapture&&t.currentTarget.setCapture())),t.preventDefault(),s&&this._setInteractiveTimeout(!0),!1},_dragTarget_touchmove:function(t){if(this._options.mode==="static")return;var n=!1;this._mouseDown&&(n=this._clearInteractiveTimeout());var i=this._$eventTarget.offset(),s=this._drawCoords.length,o=t.originalEvent.changedTouches,u,a,f=0;if(this._supportTouch){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&o[0].identifier!==this._multiTouchAnchor[0].identifier)return this._mouseDown=!1,this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(o[0]),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-i.left,this._multiTouchAnchor[1].pageY-i.top],this._multiTouchAnchorBbox=e.merge([],this._multiTouchCurrentBbox),this._mouseDown=!0,this._anchor=this._current=e.geo.center(this._multiTouchCurrentBbox,!0),n&&this._setInteractiveTimeout(!0),!1;if(this._isMultiTouch){for(;f0?h*=5:h*=10;var p=h-this._wheelLevel;this._wheelLevel=h;var d=this._getZoomCenterAndSize(this._anchor,p,!1);this._setInteractiveCenterAndSize(d.center,d.pixelSize),this._interactiveTransform(),n=!0,u=e.geo.center(this._multiTouchCurrentBbox,!0)}else u=[t.originalEvent.changedTouches[0].pageX-i.left,t.originalEvent.changedTouches[0].pageY-i.top]}else u=[t.pageX-i.left,t.pageY-i.top];if(u[0]===this._lastMove[0]&&u[1]===this._lastMove[1]&&this._inOp)return t.preventDefault(),n&&this._setInteractiveTimeout(!0),!1;r==7&&(this._isDbltap=this._isTap=!1),this._mouseDown&&(this._current=u,this._moveDate=e.now());if(this._isMultiTouch)return t.preventDefault(),this._isDbltap=this._isTap=!1,n&&this._setInteractiveTimeout(!0),!1;var v=this._options.mode,m=this._options.shift,g=v==="dragBox"?"dragBox":"zoom",y,b,w;this._shiftDown&&(v=m==="default"?g:m);switch(v){case"zoom":case"dragBox":this._mouseDown?(this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawBbox",[this._anchor[0],this._anchor[1],u[0],u[1]])):this._trigger("move",t,{type:"Point",coordinates:this.toMap(u)});break;case"dragCircle":this._mouseDown?(y=u[0]-this._anchor[0],b=u[1]-this._anchor[1],w=Math.sqrt(y*y+b*b)*2,this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawArc",this._anchor,0,360,{width:w,height:w})):this._trigger("move",t,{type:"Point",coordinates:this.toMap(u)});break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":this._mouseDown||this._toolPan?(this._panMove(),n=!0):(s>0&&(this._drawCoords[s-1]=this._toMap(u,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[s-1]=u,this._refreshDrawing()),this._trigger("move",t,{type:"Point",coordinates:this.toMap(u)}));break;default:this._mouseDown||this._toolPan?(this._panMove(),n=!0):this._trigger("move",t,{type:"Point",coordinates:this.toMap(u)})}this._lastMove=u,n&&this._setInteractiveTimeout(!0);if(this._inOp)return t.preventDefault(),!1},_dragTarget_touchstop:function(t){if(this._options.mode==="static")return;if(!this._mouseDown){if(r!=7)return;this._eventTarget_touchstart(t)}var n=this._clearInteractiveTimeout(),i=this._mouseDown,s=this._toolPan,o=this._$eventTarget.offset(),u=this._options.mode,a=this._options.shift,f=u==="dragBox"?"dragBox":"zoom",l,c,h,p,d,v,m;this._shiftDown&&(u=a==="default"?f:a),this._supportTouch?(l=[t.originalEvent.changedTouches[0].pageX-o.left,t.originalEvent.changedTouches[0].pageY-o.top],this._multiTouchAnchor=[],this._inOp=!1):l=[t.pageX-o.left,t.pageY-o.top],this._softDblClick&&this._isTap&&(p=l[0]-this._anchor[0],d=l[1]-this._anchor[1],Math.sqrt(p*p+d*d)<=8&&(l=e.merge([],this._anchor))),p=l[0]-this._anchor[0],d=l[1]-this._anchor[1],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._shiftDown=this._mouseDown=this._toolPan=!1;if(this._isMultiTouch){t.preventDefault(),this._isMultiTouch=!1,this._wheelLevel=0,n&&this._setInteractiveTimeout(!0);return}document.releaseCapture&&document.releaseCapture();if(i){h=e.now(),this._current=l;switch(u){case"zoom":case"dragBox":if(p!==0||d!==0){var g=this._pixelSize*6,y=this._toMap([[Math.min(this._anchor[0],l[0]),Math.max(this._anchor[1],l[1])],[Math.max(this._anchor[0],l[0]),Math.min(this._anchor[1],l[1])]]),b=[y[0][0],y[0][1],y[1][0],y[1][1]];u==="zoom"?(b[2]-b[0]100){var T=this;this._drawTimeout=setTimeout(function(){T._drawTimeout&&(T._trigger("shape",t,{type:"Point",coordinates:T.toMap(l)}),T._inOp=!1,T._drawTimeout=null)},250)}break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":if(s)this._panFinalize();else{c=this._drawCoords.length===0?0:this._drawCoords.length-1,this._drawCoords[c]=this._toMap(l),this._drawPixels[c]=l;if(c<2||this._drawCoords[c][0]!=this._drawCoords[c-1][0]||this._drawCoords[c][1]!=this._drawCoords[c-1][1])this._drawCoords[c+1]=this._toMap(l,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[c+1]=l;this._refreshDrawing()}break;default:s?this._panFinalize():h-this._clickDate>100&&(this._trigger("click",t,{type:"Point",coordinates:this.toMap(l)}),this._inOp=!1)}this._clickDate=h;if(this._softDblClick&&this._isDbltap)return this._isDbltap=this._isTap=!1,n&&this._setInteractiveTimeout(!0),this._$eventTarget.trigger("dblclick",t),!1}n&&this._setInteractiveTimeout(!0);if(this._inOp)return t.preventDefault(),!1},_eventTarget_mousewheel:function(t,n){if(this._options.mode==="static"||this._options.scroll==="off")return;t.preventDefault();if(this._mouseDown)return!1;if(n!==0){this._clearInteractiveTimeout(),n>0?n=Math.ceil(n):n=Math.floor(n);var r=e(t.currentTarget).offset();this._anchor=[t.pageX-r.left,t.pageY-r.top];var i=this._getZoomCenterAndSize(this._anchor,n,this._options.tilingScheme!==null),s,o=0;this._setInteractiveCenterAndSize(i.center,i.pixelSize),this._interactiveTransform(),this._setInteractiveTimeout(!0)}return!1}})}(jQuery),function(e,t){e.geo._serviceTypes.tiled=function(){return{create:function(t,n,r,i){var s=e.data(r,"geoServiceState");if(!s){s={loadCount:0,reloadTiles:!1};var o='
      ';n.append(o),s.serviceContainer=n.children(":last"),e.data(r,"geoServiceState",s)}return s.serviceContainer},destroy:function(t,n,r){var i=e.data(r,"geoServiceState");i.serviceContainer.remove(),e.removeData(r,"geoServiceState")},interactiveTransform:function(t,n,r,i){var s=e.data(n,"geoServiceState"),o=t.options.tilingScheme;s&&(this._cancelUnloaded(t,n),s.serviceContainer.children().each(function(n){var s=e(this),u=s.data("pixelSize"),a=u/i;if(u>0){a=Math.round(a*1e3)/1e3;var f=s.data("scaleOrigin"),l=t._toPixel(f,r,i);s.css({left:Math.round(l[0])+"px",top:Math.round(l[1])+"px",width:o.tileWidth*a,height:o.tileHeight*a})}}))},refresh:function(t,n,r){var i=e.data(n,"geoServiceState");this._cancelUnloaded(t,n),i&&r&&(i.reloadTiles=!0);if(i&&n&&n.style.visibility==="visible"&&!i.serviceContainer.is(":hidden")){var s=t._getBbox(),o=t._pixelSize,u=this,a=i.serviceContainer,f=t._getContentBounds(),l=f.width,c=f.height,h=t.options.axisLayout==="image",p=h?1:-1,d=t.options.tilingScheme,v=d.tileWidth,m=d.tileHeight,g=Math.floor((s[0]-d.origin[0])/(o*v)),y=Math.max(Math.floor((h?s[1]-d.origin[1]:d.origin[1]-s[3])/(o*m)),0),b=Math.ceil((s[2]-d.origin[0])/(o*v)),w=Math.ceil((h?s[3]-d.origin[1]:d.origin[1]-s[1])/(o*m)),E=t._getBboxMax(),S=t._getPixelSize(0),x=S/o,T=Math.floor((E[0]-d.origin[0])/(S*v))*x,N=Math.floor((d.origin[1]+p*E[3])/(S*m))*x,C=d.origin[0]+T*v*o,k=d.origin[1]+p*N*m*o,L=Math.round((C-s[0])/o),A=Math.round((h?k-s[1]:s[3]-k)/o),O=a.children().show(),M=O.filter("[data-pixel-size='"+o+"']").appendTo(a),_=n.style.opacity,D,P,H=function(n){u._loadImage(e.data(this,"img"),n,o,t,i,_)},B=function(){e.data(this,"img").remove(),i.loadCount--,t._requestComplete()};i.reloadTiles&&O.find("img").attr("data-dirty","true"),M.size()?(M.css({left:L%v+"px",top:A%m+"px"}).data("scaleOrigin",t._toMap([L%v,A%m])),M.children().each(function(t){var n=e(this),r=n.attr("data-tile").split(",");n.css({left:Math.round((parseInt(r[0],10)-T)*100+(L-L%v)/v*100)+"%",top:Math.round((parseInt(r[1],10)-N)*100+(A-A%m)/m*100)+"%"}),_<1&&n.fadeTo(0,_)})):(a.append("
      "),M=a.children(":last").data("scaleOrigin",t._toMap([L%v,A%m])));for(D=g;D0)F.attr("src",X);else{var V="",M.append(V),F=M.children(":last")}typeof X=="string"?u._loadImage(F,X,o,t,i,_):X?(e.data(X,"img",F),X.done(H).fail(B)):F.remove()}}O.find("[data-dirty]").remove(),i.reloadTiles=!1}},resize:function(e,t){},opacity:function(t,n){var r=e.data(n,"geoServiceState");r.serviceContainer.find("img").stop(!0).fadeTo("fast",n.style.opacity)},toggle:function(t,n){var r=e.data(n,"geoServiceState");r.serviceContainer.css("display",n.style.visibility==="visible"?"block":"none")},_cancelUnloaded:function(t,n){var r=e.data(n,"geoServiceState");if(r&&r.loadCount>0){r.serviceContainer.find("img:hidden").remove();while(r.loadCount>0)r.loadCount--,t._requestComplete()}},_loadImage:function(t,n,r,i,s,o){var u=s.serviceContainer;t.load(function(t){o<1?e(t.target).fadeTo(0,o):e(t.target).show(),s.loadCount--,i._requestComplete(),s.loadCount<=0&&(u.children(":not([data-pixel-size='"+r+"'])").remove(),s.loadCount=0)}).error(function(t){e(t.target).remove(),s.loadCount--,i._requestComplete(),s.loadCount<=0&&(u.children(":not([data-pixel-size='"+r+"'])").remove(),s.loadCount=0)}).attr("src",n)}}}()}(jQuery),function(e,t){e.geo._serviceTypes.shingled=function(){return{create:function(t,n,r,i){var s=e.data(r,"geoServiceState");if(!s){s={loadCount:0};var o='
      ';n.append(o),s.serviceContainer=n.children(":last"),e.data(r,"geoServiceState",s)}return s.serviceContainer},destroy:function(t,n,r){var i=e.data(r,"geoServiceState");i.serviceContainer.remove(),e.removeData(r,"geoServiceState")},interactiveTransform:function(t,n,r,i){var s=e.data(n,"geoServiceState"),o=t._getContentBounds(),u=o.width,a=o.height,f=u/2,l=a/2,c=[r[0]-f,r[1]-l,r[0]+f,r[1]+l];s&&(this._cancelUnloaded(t,n),s.serviceContainer.children().each(function(n){var s=e(this),o=s.data("pixelSize"),f=o/i;if(o>0){f=Math.round(f*1e3)/1e3;var l=s.data("origin"),c=t._toPixel(l,r,i);s.css({left:Math.round(c[0]),top:Math.round(c[1]),width:u*f,height:a*f})}}))},refresh:function(t,n){var r=e.data(n,"geoServiceState");this._cancelUnloaded(t,n);if(r&&n&&n.style.visibility==="visible"&&!r.serviceContainer.is(":hidden")){var i=t._getBbox(),s=t._pixelSize,o=this,u=r.serviceContainer,a=t._getContentBounds(),f=a.width,l=a.height,c=u.children('[data-pixel-size="'+s+'"]'),h=n.style.opacity,p;h<1&&u.find("img").attr("data-keep-alive","0"),c.size()||(u.append('
      '),c=u.children(":last"));var d=n.hasOwnProperty("src")?"src":"getUrl",v={bbox:i,width:f,height:l,zoom:t._getZoom(),tile:null,index:0},m=e.isFunction(n[d]),g,y=c.position();y.left=-y.left,y.top=-y.top,m?g=n[d](v):(e.templates("geoSrc",n[d]),g=e.render.geoSrc(v)),r.loadCount++,t._requestQueued(),c.append(''),p=c.children(":last").data("center",t._center),typeof g=="string"?o._loadImage(p,g,s,t,r,h):g.done(function(e){o._loadImage(p,e,s,t,r,h)}).fail(function(){p.remove(),r.loadCount--,t._requestComplete()})}},resize:function(t,n){var r=e.data(n,"geoServiceState");if(r&&n&&n.style.visibility==="visible"){this._cancelUnloaded(t,n);var i=r.serviceContainer,s=t._getContentBounds(),o=s.width,u=s.height,a=i.children();a.attr("data-pixel-size","0"),a.each(function(n){var r=e(this),i=r.position(),s=r.data("origin"),a=t._toPixel(s);r.css({left:i.left+(o-r.width())/2,top:i.top+(u-r.height())/2})})}},opacity:function(t,n){var r=e.data(n,"geoServiceState");r.serviceContainer.find("img").stop(!0).fadeTo("fast",n.style.opacity)},toggle:function(t,n){var r=e.data(n,"geoServiceState");r.serviceContainer.css("display",n.style.visibility==="visible"?"block":"none")},_cancelUnloaded:function(t,n){var r=e.data(n,"geoServiceState");if(r&&r.loadCount>0){r.serviceContainer.find("img:hidden").remove();while(r.loadCount>0)r.loadCount--,t._requestComplete()}},_loadImage:function(t,n,r,i,s,o){var u=s.serviceContainer;t.load(function(t){if(!e.contains(document.body,t.target.jquery?t.target[0]:t.target))return;o<1?e(t.target).fadeTo(0,o):e(t.target).show(),s.loadCount--,i._requestComplete(),s.loadCount<=0&&(u.children(':not([data-pixel-size="'+r+'"])').remove(),u.find("img[data-keep-alive]").remove(),s.loadCount=0)}).error(function(t){if(!e.contains(document.body,t.target.jquery?t.target[0]:t.target))return;e(t.target).remove(),s.loadCount--,i._requestComplete(),s.loadCount<=0&&(u.children(":not([data-pixel-size='"+r+"'])").remove(),s.loadCount=0)}).attr("src",n)}}}()}(jQuery); \ No newline at end of file diff --git a/dist/jquery.geo-1.0.0-b2.js b/dist/jquery.geo-1.0.0-b2.js deleted file mode 100644 index ee66914..0000000 --- a/dist/jquery.geo-1.0.0-b2.js +++ /dev/null @@ -1,7245 +0,0 @@ -/*! jQuery Geo - v1.0.0-b2 - 2014-09-16 -* http://jquerygeo.com -* Copyright (c) 2014 Ryan Westphal; Licensed MIT */ -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -// Known Issues: -// -// * Patterns only support repeat. -// * Radial gradient are not implemented. The VML version of these look very -// different from the canvas one. -// * Clipping paths are not implemented. -// * Coordsize. The width and height attribute have higher priority than the -// width and height style values which isn't correct. -// * Painting mode isn't implemented. -// * Canvas width/height should is using content-box by default. IE in -// Quirks mode will draw the canvas using border-box. Either change your -// doctype to HTML5 -// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) -// or use Box Sizing Behavior from WebFX -// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) -// * Non uniform scaling does not correctly scale strokes. -// * Optimize. There is always room for speed improvements. - -// Only add this code if we do not already have a canvas implementation -if (!document.createElement('canvas').getContext) { - - (function () { - - // alias some functions to make (compiled) code shorter - var m = Math; - var mr = m.round; - var ms = m.sin; - var mc = m.cos; - var abs = m.abs; - var sqrt = m.sqrt; - - // this is used for sub pixel precision - var Z = 10; - var Z2 = Z / 2; - - var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; - - /** - * This funtion is assigned to the elements as element.getContext(). - * @this {HTMLElement} - * @return {CanvasRenderingContext2D_} - */ - function getContext() { - return this.context_ || - (this.context_ = new CanvasRenderingContext2D_(this)); - } - - var slice = Array.prototype.slice; - - /** - * Binds a function to an object. The returned function will always use the - * passed in {@code obj} as {@code this}. - * - * Example: - * - * g = bind(f, obj, a, b) - * g(c, d) // will do f.call(obj, a, b, c, d) - * - * @param {Function} f The function to bind the object to - * @param {Object} obj The object that should act as this when the function - * is called - * @param {*} var_args Rest arguments that will be used as the initial - * arguments when the function is called - * @return {Function} A new function that has bound this - */ - function bind(f, obj, var_args) { - var a = slice.call(arguments, 2); - return function () { - return f.apply(obj, a.concat(slice.call(arguments))); - }; - } - - function encodeHtmlAttribute(s) { - return String(s).replace(/&/g, '&').replace(/"/g, '"'); - } - - function addNamespace(doc, prefix, urn) { - if (!doc.namespaces[prefix]) { - doc.namespaces.add(prefix, urn, '#default#VML'); - } - } - - function addNamespacesAndStylesheet(doc) { - addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); - addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); - - // Setup default CSS. Only add one style sheet per document - if (!doc.styleSheets['ex_canvas_']) { - var ss = doc.createStyleSheet(); - ss.owningElement.id = 'ex_canvas_'; - ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + - // default size is 300x150 in Gecko and Opera - 'text-align:left;width:300px;height:150px}'; - } - } - - // Add namespaces and stylesheet at startup. - addNamespacesAndStylesheet(document); - - var G_vmlCanvasManager_ = { - init: function (opt_doc) { - var doc = opt_doc || document; - // Create a dummy element so that IE will allow canvas elements to be - // recognized. - doc.createElement('canvas'); - doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); - }, - - init_: function (doc) { - // find all canvas elements - var els = doc.getElementsByTagName('canvas'); - for (var i = 0; i < els.length; i++) { - this.initElement(els[i]); - } - }, - - /** - * Public initializes a canvas element so that it can be used as canvas - * element from now on. This is called automatically before the page is - * loaded but if you are creating elements using createElement you need to - * make sure this is called on the element. - * @param {HTMLElement} el The canvas element to initialize. - * @return {HTMLElement} the element that was created. - */ - initElement: function (el) { - if (!el.getContext) { - el.getContext = getContext; - - // Add namespaces and stylesheet to document of the element. - addNamespacesAndStylesheet(el.ownerDocument); - - // Remove fallback content. There is no way to hide text nodes so we - // just remove all childNodes. We could hide all elements and remove - // text nodes but who really cares about the fallback content. - el.innerHTML = ''; - - // do not use inline function because that will leak memory - el.attachEvent('onpropertychange', onPropertyChange); - el.attachEvent('onresize', onResize); - - var attrs = el.attributes; - if (attrs.width && attrs.width.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setWidth_(attrs.width.nodeValue); - el.style.width = attrs.width.nodeValue + 'px'; - } else { - el.width = el.clientWidth; - } - if (attrs.height && attrs.height.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setHeight_(attrs.height.nodeValue); - el.style.height = attrs.height.nodeValue + 'px'; - } else { - el.height = el.clientHeight; - } - //el.getContext().setCoordsize_() - } - return el; - } - }; - - function onPropertyChange(e) { - var el = e.srcElement; - - switch (e.propertyName) { - case 'width': - el.getContext().clearRect(); - el.style.width = el.attributes.width.nodeValue + 'px'; - // In IE8 this does not trigger onresize. - el.firstChild.style.width = el.clientWidth + 'px'; - break; - case 'height': - el.getContext().clearRect(); - el.style.height = el.attributes.height.nodeValue + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - break; - } - } - - function onResize(e) { - var el = e.srcElement; - if (el.firstChild) { - el.firstChild.style.width = el.clientWidth + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - } - } - - G_vmlCanvasManager_.init(); - - // precompute "00" to "FF" - var decToHex = []; - for (var i = 0; i < 16; i++) { - for (var j = 0; j < 16; j++) { - decToHex[i * 16 + j] = i.toString(16) + j.toString(16); - } - } - - function createMatrixIdentity() { - return [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1] - ]; - } - - function matrixMultiply(m1, m2) { - var result = createMatrixIdentity(); - - for (var x = 0; x < 3; x++) { - for (var y = 0; y < 3; y++) { - var sum = 0; - - for (var z = 0; z < 3; z++) { - sum += m1[x][z] * m2[z][y]; - } - - result[x][y] = sum; - } - } - return result; - } - - function copyState(o1, o2) { - o2.fillStyle = o1.fillStyle; - o2.lineCap = o1.lineCap; - o2.lineJoin = o1.lineJoin; - o2.lineWidth = o1.lineWidth; - o2.miterLimit = o1.miterLimit; - o2.shadowBlur = o1.shadowBlur; - o2.shadowColor = o1.shadowColor; - o2.shadowOffsetX = o1.shadowOffsetX; - o2.shadowOffsetY = o1.shadowOffsetY; - o2.strokeStyle = o1.strokeStyle; - o2.globalAlpha = o1.globalAlpha; - o2.font = o1.font; - o2.textAlign = o1.textAlign; - o2.textBaseline = o1.textBaseline; - o2.arcScaleX_ = o1.arcScaleX_; - o2.arcScaleY_ = o1.arcScaleY_; - o2.lineScale_ = o1.lineScale_; - } - - // var colorData = { - // aliceblue: '#F0F8FF', - // antiquewhite: '#FAEBD7', - // aquamarine: '#7FFFD4', - // azure: '#F0FFFF', - // beige: '#F5F5DC', - // bisque: '#FFE4C4', - // black: '#000000', - // blanchedalmond: '#FFEBCD', - // blueviolet: '#8A2BE2', - // brown: '#A52A2A', - // burlywood: '#DEB887', - // cadetblue: '#5F9EA0', - // chartreuse: '#7FFF00', - // chocolate: '#D2691E', - // coral: '#FF7F50', - // cornflowerblue: '#6495ED', - // cornsilk: '#FFF8DC', - // crimson: '#DC143C', - // cyan: '#00FFFF', - // darkblue: '#00008B', - // darkcyan: '#008B8B', - // darkgoldenrod: '#B8860B', - // darkgray: '#A9A9A9', - // darkgreen: '#006400', - // darkgrey: '#A9A9A9', - // darkkhaki: '#BDB76B', - // darkmagenta: '#8B008B', - // darkolivegreen: '#556B2F', - // darkorange: '#FF8C00', - // darkorchid: '#9932CC', - // darkred: '#8B0000', - // darksalmon: '#E9967A', - // darkseagreen: '#8FBC8F', - // darkslateblue: '#483D8B', - // darkslategray: '#2F4F4F', - // darkslategrey: '#2F4F4F', - // darkturquoise: '#00CED1', - // darkviolet: '#9400D3', - // deeppink: '#FF1493', - // deepskyblue: '#00BFFF', - // dimgray: '#696969', - // dimgrey: '#696969', - // dodgerblue: '#1E90FF', - // firebrick: '#B22222', - // floralwhite: '#FFFAF0', - // forestgreen: '#228B22', - // gainsboro: '#DCDCDC', - // ghostwhite: '#F8F8FF', - // gold: '#FFD700', - // goldenrod: '#DAA520', - // grey: '#808080', - // greenyellow: '#ADFF2F', - // honeydew: '#F0FFF0', - // hotpink: '#FF69B4', - // indianred: '#CD5C5C', - // indigo: '#4B0082', - // ivory: '#FFFFF0', - // khaki: '#F0E68C', - // lavender: '#E6E6FA', - // lavenderblush: '#FFF0F5', - // lawngreen: '#7CFC00', - // lemonchiffon: '#FFFACD', - // lightblue: '#ADD8E6', - // lightcoral: '#F08080', - // lightcyan: '#E0FFFF', - // lightgoldenrodyellow: '#FAFAD2', - // lightgreen: '#90EE90', - // lightgrey: '#D3D3D3', - // lightpink: '#FFB6C1', - // lightsalmon: '#FFA07A', - // lightseagreen: '#20B2AA', - // lightskyblue: '#87CEFA', - // lightslategray: '#778899', - // lightslategrey: '#778899', - // lightsteelblue: '#B0C4DE', - // lightyellow: '#FFFFE0', - // limegreen: '#32CD32', - // linen: '#FAF0E6', - // magenta: '#FF00FF', - // mediumaquamarine: '#66CDAA', - // mediumblue: '#0000CD', - // mediumorchid: '#BA55D3', - // mediumpurple: '#9370DB', - // mediumseagreen: '#3CB371', - // mediumslateblue: '#7B68EE', - // mediumspringgreen: '#00FA9A', - // mediumturquoise: '#48D1CC', - // mediumvioletred: '#C71585', - // midnightblue: '#191970', - // mintcream: '#F5FFFA', - // mistyrose: '#FFE4E1', - // moccasin: '#FFE4B5', - // navajowhite: '#FFDEAD', - // oldlace: '#FDF5E6', - // olivedrab: '#6B8E23', - // orange: '#FFA500', - // orangered: '#FF4500', - // orchid: '#DA70D6', - // palegoldenrod: '#EEE8AA', - // palegreen: '#98FB98', - // paleturquoise: '#AFEEEE', - // palevioletred: '#DB7093', - // papayawhip: '#FFEFD5', - // peachpuff: '#FFDAB9', - // peru: '#CD853F', - // pink: '#FFC0CB', - // plum: '#DDA0DD', - // powderblue: '#B0E0E6', - // rosybrown: '#BC8F8F', - // royalblue: '#4169E1', - // saddlebrown: '#8B4513', - // salmon: '#FA8072', - // sandybrown: '#F4A460', - // seagreen: '#2E8B57', - // seashell: '#FFF5EE', - // sienna: '#A0522D', - // skyblue: '#87CEEB', - // slateblue: '#6A5ACD', - // slategray: '#708090', - // slategrey: '#708090', - // snow: '#FFFAFA', - // springgreen: '#00FF7F', - // steelblue: '#4682B4', - // tan: '#D2B48C', - // thistle: '#D8BFD8', - // tomato: '#FF6347', - // turquoise: '#40E0D0', - // violet: '#EE82EE', - // wheat: '#F5DEB3', - // whitesmoke: '#F5F5F5', - // yellowgreen: '#9ACD32' - // }; - - - function getRgbHslContent(styleString) { - var start = styleString.indexOf('(', 3); - var end = styleString.indexOf(')', start + 1); - var parts = styleString.substring(start + 1, end).split(','); - // add alpha if needed - if (parts.length != 4 || styleString.charAt(3) != 'a') { - parts[3] = 1; - } - return parts; - } - - function percent(s) { - return parseFloat(s) / 100; - } - - function clamp(v, min, max) { - return Math.min(max, Math.max(min, v)); - } - - function hslToRgb(parts) { - var r, g, b, h, s, l; - h = parseFloat(parts[0]) / 360 % 360; - if (h < 0) - h++; - s = clamp(percent(parts[1]), 0, 1); - l = clamp(percent(parts[2]), 0, 1); - if (s == 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1 / 3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1 / 3); - } - - return '#' + decToHex[Math.floor(r * 255)] + - decToHex[Math.floor(g * 255)] + - decToHex[Math.floor(b * 255)]; - } - - function hueToRgb(m1, m2, h) { - if (h < 0) - h++; - if (h > 1) - h--; - - if (6 * h < 1) - return m1 + (m2 - m1) * 6 * h; - else if (2 * h < 1) - return m2; - else if (3 * h < 2) - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - else - return m1; - } - - var processStyleCache = {}; - - function processStyle(styleString) { - if (styleString in processStyleCache) { - return processStyleCache[styleString]; - } - - var str, alpha = 1; - - styleString = String(styleString); - if (styleString.charAt(0) == '#') { - str = styleString; - } else if (/^rgb/.test(styleString)) { - var parts = getRgbHslContent(styleString); - var str = '#', n; - for (var i = 0; i < 3; i++) { - if (parts[i].indexOf('%') != -1) { - n = Math.floor(percent(parts[i]) * 255); - } else { - n = +parts[i]; - } - str += decToHex[clamp(n, 0, 255)]; - } - alpha = +parts[3]; - } else if (/^hsl/.test(styleString)) { - var parts = getRgbHslContent(styleString); - str = hslToRgb(parts); - alpha = parts[3]; - } else { - str = /*colorData[styleString] ||*/styleString; - } - return processStyleCache[styleString] = { color: str, alpha: alpha }; - } - - var DEFAULT_STYLE = { - style: 'normal', - variant: 'normal', - weight: 'normal', - size: 10, - family: 'sans-serif' - }; - - // Internal text style cache - // var fontStyleCache = {}; - - // function processFontStyle(styleString) { - // if (fontStyleCache[styleString]) { - // return fontStyleCache[styleString]; - // } - - // var el = document.createElement('div'); - // var style = el.style; - // try { - // style.font = styleString; - // } catch (ex) { - // // Ignore failures to set to invalid font. - // } - - // return fontStyleCache[styleString] = { - // style: style.fontStyle || DEFAULT_STYLE.style, - // variant: style.fontVariant || DEFAULT_STYLE.variant, - // weight: style.fontWeight || DEFAULT_STYLE.weight, - // size: style.fontSize || DEFAULT_STYLE.size, - // family: style.fontFamily || DEFAULT_STYLE.family - // }; - // } - - // function getComputedStyle(style, element) { - // var computedStyle = {}; - - // for (var p in style) { - // computedStyle[p] = style[p]; - // } - - // // Compute the size - // var canvasFontSize = parseFloat(element.currentStyle.fontSize), - // fontSize = parseFloat(style.size); - - // if (typeof style.size == 'number') { - // computedStyle.size = style.size; - // } else if (style.size.indexOf('px') != -1) { - // computedStyle.size = fontSize; - // } else if (style.size.indexOf('em') != -1) { - // computedStyle.size = canvasFontSize * fontSize; - // } else if(style.size.indexOf('%') != -1) { - // computedStyle.size = (canvasFontSize / 100) * fontSize; - // } else if (style.size.indexOf('pt') != -1) { - // computedStyle.size = fontSize / .75; - // } else { - // computedStyle.size = canvasFontSize; - // } - - // // Different scaling between normal text and VML text. This was found using - // // trial and error to get the same size as non VML text. - // computedStyle.size *= 0.981; - - // return computedStyle; - // } - - // function buildStyle(style) { - // return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + - // style.size + 'px ' + style.family; - // } - - var lineCapMap = { - 'butt': 'flat', - 'round': 'round' - }; - - function processLineCap(lineCap) { - return lineCapMap[lineCap] || 'square'; - } - - /** - * This class implements CanvasRenderingContext2D interface as described by - * the WHATWG. - * @param {HTMLElement} canvasElement The element that the 2D context should - * be associated with - */ - function CanvasRenderingContext2D_(canvasElement) { - this.m_ = createMatrixIdentity(); - - this.mStack_ = []; - this.aStack_ = []; - this.currentPath_ = []; - - // Canvas context properties - this.strokeStyle = '#000'; - this.fillStyle = '#000'; - - this.lineWidth = 1; - this.lineJoin = 'miter'; - this.lineCap = 'butt'; - this.miterLimit = Z * 1; - this.globalAlpha = 1; - //this.font = '10px sans-serif'; - //this.textAlign = 'left'; - //this.textBaseline = 'alphabetic'; - this.canvas = canvasElement; - - var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + - canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; - var el = canvasElement.ownerDocument.createElement('div'); - el.style.cssText = cssText; - canvasElement.appendChild(el); - - var overlayEl = el.cloneNode(false); - // Use a non transparent background. - overlayEl.style.backgroundColor = 'red'; - overlayEl.style.filter = 'alpha(opacity=0)'; - canvasElement.appendChild(overlayEl); - - this.element_ = el; - this.arcScaleX_ = 1; - this.arcScaleY_ = 1; - this.lineScale_ = 1; - } - - var contextPrototype = CanvasRenderingContext2D_.prototype; - contextPrototype.clearRect = function () { - if (this.textMeasureEl_) { - this.textMeasureEl_.removeNode(true); - this.textMeasureEl_ = null; - } - this.element_.innerHTML = ''; - }; - - contextPrototype.beginPath = function () { - // TODO: Branch current matrix so that save/restore has no effect - // as per safari docs. - this.currentPath_ = []; - }; - - contextPrototype.moveTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'moveTo', x: p.x, y: p.y }); - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.lineTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'lineTo', x: p.x, y: p.y }); - - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY) { - var p = getCoords(this, aX, aY); - var cp1 = getCoords(this, aCP1x, aCP1y); - var cp2 = getCoords(this, aCP2x, aCP2y); - bezierCurveTo(this, cp1, cp2, p); - }; - - // Helper function that takes the already fixed cordinates. - function bezierCurveTo(self, cp1, cp2, p) { - self.currentPath_.push({ - type: 'bezierCurveTo', - cp1x: cp1.x, - cp1y: cp1.y, - cp2x: cp2.x, - cp2y: cp2.y, - x: p.x, - y: p.y - }); - self.currentX_ = p.x; - self.currentY_ = p.y; - } - - contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { - // the following is lifted almost directly from - // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes - - var cp = getCoords(this, aCPx, aCPy); - var p = getCoords(this, aX, aY); - - var cp1 = { - x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), - y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) - }; - var cp2 = { - x: cp1.x + (p.x - this.currentX_) / 3.0, - y: cp1.y + (p.y - this.currentY_) / 3.0 - }; - - bezierCurveTo(this, cp1, cp2, p); - }; - - contextPrototype.arc = function (aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise) { - aRadius *= Z; - var arcType = aClockwise ? 'at' : 'wa'; - - var xStart = aX + mc(aStartAngle) * aRadius - Z2; - var yStart = aY + ms(aStartAngle) * aRadius - Z2; - - var xEnd = aX + mc(aEndAngle) * aRadius - Z2; - var yEnd = aY + ms(aEndAngle) * aRadius - Z2; - - // IE won't render arches drawn counter clockwise if xStart == xEnd. - if (xStart == xEnd && !aClockwise) { - xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something - // that can be represented in binary - } - - var p = getCoords(this, aX, aY); - var pStart = getCoords(this, xStart, yStart); - var pEnd = getCoords(this, xEnd, yEnd); - - this.currentPath_.push({ type: arcType, - x: p.x, - y: p.y, - radius: aRadius, - xStart: pStart.x, - yStart: pStart.y, - xEnd: pEnd.x, - yEnd: pEnd.y - }); - - }; - - // contextPrototype.rect = function(aX, aY, aWidth, aHeight) { - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // }; - - // contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.stroke(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.fill(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { - // var gradient = new CanvasGradient_('gradient'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // return gradient; - // }; - - // contextPrototype.createRadialGradient = function(aX0, aY0, aR0, - // aX1, aY1, aR1) { - // var gradient = new CanvasGradient_('gradientradial'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.r0_ = aR0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // gradient.r1_ = aR1; - // return gradient; - // }; - - // contextPrototype.drawImage = function(image, var_args) { - // var dx, dy, dw, dh, sx, sy, sw, sh; - - // // to find the original width we overide the width and height - // var oldRuntimeWidth = image.runtimeStyle.width; - // var oldRuntimeHeight = image.runtimeStyle.height; - // image.runtimeStyle.width = 'auto'; - // image.runtimeStyle.height = 'auto'; - - // // get the original size - // var w = image.width; - // var h = image.height; - - // // and remove overides - // image.runtimeStyle.width = oldRuntimeWidth; - // image.runtimeStyle.height = oldRuntimeHeight; - - // if (arguments.length == 3) { - // dx = arguments[1]; - // dy = arguments[2]; - // sx = sy = 0; - // sw = dw = w; - // sh = dh = h; - // } else if (arguments.length == 5) { - // dx = arguments[1]; - // dy = arguments[2]; - // dw = arguments[3]; - // dh = arguments[4]; - // sx = sy = 0; - // sw = w; - // sh = h; - // } else if (arguments.length == 9) { - // sx = arguments[1]; - // sy = arguments[2]; - // sw = arguments[3]; - // sh = arguments[4]; - // dx = arguments[5]; - // dy = arguments[6]; - // dw = arguments[7]; - // dh = arguments[8]; - // } else { - // throw Error('Invalid number of arguments'); - // } - - // var d = getCoords(this, dx, dy); - - // var w2 = sw / 2; - // var h2 = sh / 2; - - // var vmlStr = []; - - // var W = 10; - // var H = 10; - - // // For some reason that I've now forgotten, using divs didn't work - // vmlStr.push(' ' , - // '', - // ''); - - // this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); - // }; - - contextPrototype.stroke = function (aFill) { - var lineStr = []; - var lineOpen = false; - - var W = 10; - var H = 10; - - lineStr.push(''); - - if (!aFill) { - appendStroke(this, lineStr); - } else { - appendFill(this, lineStr, min, max); - } - - lineStr.push(''); - - this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - }; - - function appendStroke(ctx, lineStr) { - var a = processStyle(ctx.strokeStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - var lineWidth = ctx.lineScale_ * ctx.lineWidth; - - // VML cannot correctly render a line if the width is less than 1px. - // In that case, we dilute the color to make the line look thinner. - if (lineWidth < 1) { - opacity *= lineWidth; - } - - lineStr.push( - '' - ); - } - - function appendFill(ctx, lineStr, min, max) { - var fillStyle = ctx.fillStyle; - var arcScaleX = ctx.arcScaleX_; - var arcScaleY = ctx.arcScaleY_; - var width = max.x - min.x; - var height = max.y - min.y; - // if (fillStyle instanceof CanvasGradient_) { - // // TODO: Gradients transformed with the transformation matrix. - // var angle = 0; - // var focus = {x: 0, y: 0}; - - // // additional offset - // var shift = 0; - // // scale factor for offset - // var expansion = 1; - - // if (fillStyle.type_ == 'gradient') { - // var x0 = fillStyle.x0_ / arcScaleX; - // var y0 = fillStyle.y0_ / arcScaleY; - // var x1 = fillStyle.x1_ / arcScaleX; - // var y1 = fillStyle.y1_ / arcScaleY; - // var p0 = getCoords(ctx, x0, y0); - // var p1 = getCoords(ctx, x1, y1); - // var dx = p1.x - p0.x; - // var dy = p1.y - p0.y; - // angle = Math.atan2(dx, dy) * 180 / Math.PI; - - // // The angle should be a non-negative number. - // if (angle < 0) { - // angle += 360; - // } - - // // Very small angles produce an unexpected result because they are - // // converted to a scientific notation string. - // if (angle < 1e-6) { - // angle = 0; - // } - // } else { - // var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); - // focus = { - // x: (p0.x - min.x) / width, - // y: (p0.y - min.y) / height - // }; - - // width /= arcScaleX * Z; - // height /= arcScaleY * Z; - // var dimension = m.max(width, height); - // shift = 2 * fillStyle.r0_ / dimension; - // expansion = 2 * fillStyle.r1_ / dimension - shift; - // } - - // // We need to sort the color stops in ascending order by offset, - // // otherwise IE won't interpret it correctly. - // var stops = fillStyle.colors_; - // stops.sort(function(cs1, cs2) { - // return cs1.offset - cs2.offset; - // }); - - // var length = stops.length; - // var color1 = stops[0].color; - // var color2 = stops[length - 1].color; - // var opacity1 = stops[0].alpha * ctx.globalAlpha; - // var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; - - // var colors = []; - // for (var i = 0; i < length; i++) { - // var stop = stops[i]; - // colors.push(stop.offset * expansion + shift + ' ' + stop.color); - // } - - // // When colors attribute is used, the meanings of opacity and o:opacity2 - // // are reversed. - // lineStr.push(''); - // } else if (fillStyle instanceof CanvasPattern_) { - // if (width && height) { - // var deltaLeft = -min.x; - // var deltaTop = -min.y; - // lineStr.push(''); - // } - // } else { - var a = processStyle(ctx.fillStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - lineStr.push(''); - // } - } - - contextPrototype.fill = function () { - this.stroke(true); - }; - - contextPrototype.closePath = function () { - this.currentPath_.push({ type: 'close' }); - }; - - function getCoords(ctx, aX, aY) { - var m = ctx.m_; - return { - x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, - y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 - }; - }; - - contextPrototype.save = function () { - var o = {}; - copyState(this, o); - this.aStack_.push(o); - this.mStack_.push(this.m_); - this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); - }; - - contextPrototype.restore = function () { - if (this.aStack_.length) { - copyState(this.aStack_.pop(), this); - this.m_ = this.mStack_.pop(); - } - }; - - function matrixIsFinite(m) { - return isFinite(m[0][0]) && isFinite(m[0][1]) && - isFinite(m[1][0]) && isFinite(m[1][1]) && - isFinite(m[2][0]) && isFinite(m[2][1]); - } - - function setM(ctx, m, updateLineScale) { - if (!matrixIsFinite(m)) { - return; - } - ctx.m_ = m; - - if (updateLineScale) { - // Get the line scale. - // Determinant of this.m_ means how much the area is enlarged by the - // transformation. So its square root can be used as a scale factor - // for width. - var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; - ctx.lineScale_ = sqrt(abs(det)); - } - } - - contextPrototype.translate = function (aX, aY) { - var m1 = [ - [1, 0, 0], - [0, 1, 0], - [aX, aY, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), false); - }; - - // contextPrototype.rotate = function(aRot) { - // var c = mc(aRot); - // var s = ms(aRot); - - // var m1 = [ - // [c, s, 0], - // [-s, c, 0], - // [0, 0, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), false); - // }; - - contextPrototype.scale = function (aX, aY) { - this.arcScaleX_ *= aX; - this.arcScaleY_ *= aY; - var m1 = [ - [aX, 0, 0], - [0, aY, 0], - [0, 0, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), true); - }; - - // contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { - // var m1 = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), true); - // }; - - // contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { - // var m = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, m, true); - // }; - - /** - * The text drawing function. - * The maxWidth argument isn't taken in account, since no browser supports - * it yet. - */ - // contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { - // var m = this.m_, - // delta = 1000, - // left = 0, - // right = delta, - // offset = {x: 0, y: 0}, - // lineStr = []; - - // var fontStyle = getComputedStyle(processFontStyle(this.font), - // this.element_); - - // var fontStyleString = buildStyle(fontStyle); - - // var elementStyle = this.element_.currentStyle; - // var textAlign = this.textAlign.toLowerCase(); - // switch (textAlign) { - // case 'left': - // case 'center': - // case 'right': - // break; - // case 'end': - // textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; - // break; - // case 'start': - // textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; - // break; - // default: - // textAlign = 'left'; - // } - - // // 1.75 is an arbitrary number, as there is no info about the text baseline - // switch (this.textBaseline) { - // case 'hanging': - // case 'top': - // offset.y = fontStyle.size / 1.75; - // break; - // case 'middle': - // break; - // default: - // case null: - // case 'alphabetic': - // case 'ideographic': - // case 'bottom': - // offset.y = -fontStyle.size / 2.25; - // break; - // } - - // switch(textAlign) { - // case 'right': - // left = delta; - // right = 0.05; - // break; - // case 'center': - // left = right = delta / 2; - // break; - // } - - // var d = getCoords(this, x + offset.x, y + offset.y); - - // lineStr.push(''); - - // if (stroke) { - // appendStroke(this, lineStr); - // } else { - // // TODO: Fix the min and max params. - // appendFill(this, lineStr, {x: -left, y: 0}, - // {x: right, y: fontStyle.size}); - // } - - // var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + - // m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; - - // var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); - - // lineStr.push('', - // '', - // ''); - - // this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - // }; - - // contextPrototype.fillText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, false); - // }; - - // contextPrototype.strokeText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, true); - // }; - - // contextPrototype.measureText = function(text) { - // if (!this.textMeasureEl_) { - // var s = ''; - // this.element_.insertAdjacentHTML('beforeEnd', s); - // this.textMeasureEl_ = this.element_.lastChild; - // } - // var doc = this.element_.ownerDocument; - // this.textMeasureEl_.innerHTML = ''; - // this.textMeasureEl_.style.font = this.font; - // // Don't use innerHTML or innerText because they allow markup/whitespace. - // this.textMeasureEl_.appendChild(doc.createTextNode(text)); - // return {width: this.textMeasureEl_.offsetWidth}; - // }; - - /******** STUBS ********/ - // contextPrototype.clip = function() { - // // TODO: Implement - // }; - - // contextPrototype.arcTo = function() { - // // TODO: Implement - // }; - - // contextPrototype.createPattern = function(image, repetition) { - // return new CanvasPattern_(image, repetition); - // }; - - // // Gradient / Pattern Stubs - // function CanvasGradient_(aType) { - // this.type_ = aType; - // this.x0_ = 0; - // this.y0_ = 0; - // this.r0_ = 0; - // this.x1_ = 0; - // this.y1_ = 0; - // this.r1_ = 0; - // this.colors_ = []; - // } - - // CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { - // aColor = processStyle(aColor); - // this.colors_.push({offset: aOffset, - // color: aColor.color, - // alpha: aColor.alpha}); - // }; - - // function CanvasPattern_(image, repetition) { - // assertImageIsValid(image); - // switch (repetition) { - // case 'repeat': - // case null: - // case '': - // this.repetition_ = 'repeat'; - // break - // case 'repeat-x': - // case 'repeat-y': - // case 'no-repeat': - // this.repetition_ = repetition; - // break; - // default: - // throwException('SYNTAX_ERR'); - // } - - // this.src_ = image.src; - // this.width_ = image.width; - // this.height_ = image.height; - // } - - function throwException(s) { - throw new DOMException_(s); - } - - // function assertImageIsValid(img) { - // if (!img || img.nodeType != 1 || img.tagName != 'IMG') { - // throwException('TYPE_MISMATCH_ERR'); - // } - // if (img.readyState != 'complete') { - // throwException('INVALID_STATE_ERR'); - // } - // } - - function DOMException_(s) { - this.code = this[s]; - this.message = s + ': DOM Exception ' + this.code; - } - var p = DOMException_.prototype = new Error; - p.INDEX_SIZE_ERR = 1; - p.DOMSTRING_SIZE_ERR = 2; - p.HIERARCHY_REQUEST_ERR = 3; - p.WRONG_DOCUMENT_ERR = 4; - p.INVALID_CHARACTER_ERR = 5; - p.NO_DATA_ALLOWED_ERR = 6; - p.NO_MODIFICATION_ALLOWED_ERR = 7; - p.NOT_FOUND_ERR = 8; - p.NOT_SUPPORTED_ERR = 9; - p.INUSE_ATTRIBUTE_ERR = 10; - p.INVALID_STATE_ERR = 11; - p.SYNTAX_ERR = 12; - p.INVALID_MODIFICATION_ERR = 13; - p.NAMESPACE_ERR = 14; - p.INVALID_ACCESS_ERR = 15; - p.VALIDATION_ERR = 16; - p.TYPE_MISMATCH_ERR = 17; - - // set up externs - G_vmlCanvasManager = G_vmlCanvasManager_; - CanvasRenderingContext2D = CanvasRenderingContext2D_; - //CanvasGradient = CanvasGradient_; - //CanvasPattern = CanvasPattern_; - DOMException = DOMException_; - })(); - -} // if - -/*! JsRender v1.0pre: http://github.com/BorisMoore/jsrender */ -/* - * Optimized version of jQuery Templates, for rendering to string. - * Does not require jQuery, or HTML DOM - * Integrates with JsViews (http://github.com/BorisMoore/jsviews) - * Copyright 2012, Boris Moore - * Released under the MIT License. - */ -// informal pre beta commit counter: 3 - -this.jsviews || this.jQuery && jQuery.views || (function( window, undefined ) { - -//========================== Top-level vars ========================== - -var versionNumber = "v1.0pre", - - $, rTag, rTmplString, extend, - sub = {}, - FALSE = false, TRUE = true, - jQuery = window.jQuery, - - rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // nil object helper view viewProperty pathTokens leafToken string - - rParams = /(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - - rNewLine = /\r?\n/g, - rUnescapeQuotes = /\\(['"])/g, - rEscapeQuotes = /\\?(['"])/g, - rBuildHash = /\x08(~)?([^\x08]+)\x08/g, - - autoViewKey = 0, - autoTmplName = 0, - escapeMapForHtml = { - "&": "&", - "<": "<", - ">": ">" - }, - tmplAttr = "data-jsv-tmpl", - fnDeclStr = "var j=j||" + (jQuery ? "jQuery." : "js") + "views,", - htmlSpecialChar = /[\x00"&'<>]/g, - slice = Array.prototype.slice, - - render = {}, - - // jsviews object ($.views if jQuery is loaded) - jsv = { - jsviews: versionNumber, - sub: sub, // subscription, e.g. JsViews integration - debugMode: TRUE, - err: function( e ) { - return jsv.debugMode ? ("
      Error: " + (e.message || e) + ". ") : '""'; - }, - tmplFn: tmplFn, - render: render, - templates: templates, - tags: tags, - helpers: helpers, - converters: converters, - View: View, - convert: convert, - delimiters: setDelimiters, - tag: renderTag - }; - -//========================== Top-level functions ========================== - -//=================== -// jsviews.delimiters -//=================== - -function setDelimiters( openChars, closeChars ) { - // Set the tag opening and closing delimiters. Default is "{{" and "}}" - // openChar, closeChars: opening and closing strings, each with two characters - var firstOpenChar = "\\" + openChars.charAt( 0 ), // Escape the characters - since they could be regex special characters - secondOpenChar = "\\" + openChars.charAt( 1 ), - firstCloseChar = "\\" + closeChars.charAt( 0 ), - secondCloseChar = "\\" + closeChars.charAt( 1 ); - // Build regex with new delimiters - jsv.rTag = rTag // make rTag available to JsViews (or other components) for parsing binding expressions - = secondOpenChar - // tag (followed by / space or }) or colon or html or code - + "(?:(?:(\\w+(?=[\\/\\s" + firstCloseChar + "]))|(?:(\\w+)?(:)|(>)|(\\*)))" - // params - + "\\s*((?:[^" + firstCloseChar + "]|" + firstCloseChar + "(?!" + secondCloseChar + "))*?)" - // slash or closeBlock - + "(\\/)?|(?:\\/(\\w+)))" - // }} - + firstCloseChar; - - // Default rTag: tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/\s\}]))|(?:(\w+)?(:)|(>)|(\*)))\s*((?:[^}]|}(?!\}))*?)(\/)?|(?:\/(\w+)))}} - - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - rTag = new RegExp( firstOpenChar + rTag + secondCloseChar, "g" ); - rTmplString = new RegExp( "<.*>|" + openChars + ".*" + closeChars ); - return this; -} - -//================= -// View.hlp -//================= - -function getHelper( helper ) { - // Helper method called as view.hlp() from compiled template, for helper functions or template parameters ~foo - var view = this, - tmplHelpers = view.tmpl.helpers || {}; - helper = (view.ctx[ helper ] !== undefined ? view.ctx : tmplHelpers[ helper ] !== undefined ? tmplHelpers : helpers[ helper ] !== undefined ? helpers : {})[ helper ]; - return typeof helper !== "function" ? helper : function() { - return helper.apply(view, arguments); - }; -} - -//================= -// jsviews.convert -//================= - -function convert( converter, view, text ) { - var tmplConverters = view.tmpl.converters; - converter = tmplConverters && tmplConverters[ converter ] || converters[ converter ]; - return converter ? converter.call( view, text ) : text; -} - -//================= -// jsviews.tag -//================= - -function renderTag( tag, parentView, converter, content, tagObject ) { - // Called from within compiled template function, to render a nested tag - // Returns the rendered tag - tagObject.props = tagObject.props || {}; - var ret, - tmpl = tagObject.props.tmpl, - tmplTags = parentView.tmpl.tags, - nestedTemplates = parentView.tmpl.templates, - args = arguments, - tagFn = tmplTags && tmplTags[ tag ] || tags[ tag ]; - - if ( !tagFn ) { - return ""; - } - // Set the tmpl property to the content of the block tag, unless set as an override property on the tag - content = content && parentView.tmpl.tmpls[ content - 1 ]; - tmpl = tmpl || content || undefined; - tagObject.tmpl = - "" + tmpl === tmpl // if a string - ? nestedTemplates && nestedTemplates[ tmpl ] || templates[ tmpl ] || templates( tmpl ) - : tmpl; - - tagObject.isTag = TRUE; - tagObject.converter = converter; - tagObject.view = parentView; - tagObject.renderContent = renderContent; - if ( parentView.ctx ) { - extend( tagObject.ctx, parentView.ctx); - } - - ret = tagFn.apply( tagObject, args.length > 5 ? slice.call( args, 5 ) : [] ); - return ret || ( ret == undefined ? "" : ret.toString()); // (If ret is the value 0 or false, will render to string) -} - -//================= -// View constructor -//================= - -function View( context, path, parentView, data, template, index ) { - // Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded) - var views = parentView.views, -// TODO: add this, as part of smart re-linking on existing content ($.link method), or remove completely -// self = parentView.views[ index ]; -// if ( !self ) { ... } - self = { - tmpl: template, - path: path, - parent: parentView, - data: data, - ctx: context, - views: $.isArray( data ) ? [] : {}, - hlp: getHelper - }; - - if ( $.isArray( views )) { - views.splice( - self.index = index !== undefined - ? index - : views.length, 0, self - ); - } else { - views[ self.index = "_" + autoViewKey++ ] = self; - } - return self; -} - -//================= -// Registration -//================= - -function addToStore( self, store, name, item, process ) { - // Add item to named store such as templates, helpers, converters... - var key, onStore; - if ( name && typeof name === "object" && !name.nodeType ) { - // If name is a map, iterate over map and call store for key - for ( key in name ) { - store( key, name[ key ]); - } - return self; - } - if ( !name || item === undefined ) { - if ( process ) { - item = process( undefined, item || name ); - } - } else if ( "" + name === name ) { // name must be a string - if ( item === null ) { - // If item is null, delete this entry - delete store[name]; - } else if ( item = process ? process( name, item ) : item ) { - store[ name ] = item; - } - } - if ( onStore = sub.onStoreItem ) { - // e.g. JsViews integration - onStore( store, name, item, process ); - } - return item; -} - -function templates( name, tmpl ) { - // Register templates - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, templates, name, tmpl, compile ); -} - -function tags( name, tagFn ) { - // Register template tags - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, tags, name, tagFn ); -} - -function helpers( name, helperFn ) { - // Register helper functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.helpers( name, helperFn ) or $.view.helpers({ name: helperFn, ... }) to add additional helpers to the registered helpers collection. - // Getter: Use var helperFn = $.views.helpers( name ) or $.views.helpers[name] or $.views.helpers.name to return the function. - // Remove: Use $.view.helpers( name, null ) to remove a registered helper function from $.view.helpers. - // Within a template, access the helper using the syntax: {{... ~myHelper(...) ...}}. - return addToStore( this, helpers, name, helperFn ); -} - -function converters( name, converterFn ) { - // Register converter functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.converters( name, converterFn ) or $.view.converters({ name: converterFn, ... }) to add additional converters to the registered converters collection. - // Getter: Use var converterFn = $.views.converters( name ) or $.views.converters[name] or $.views.converters.name to return the converter function. - // Remove: Use $.view.converters( name, null ) to remove a registered converter from $.view.converters. - // Within a template, access the converter using the syntax: {{myConverter:...}}. - return addToStore( this, converters, name, converterFn ); -} - -//================= -// renderContent -//================= - -function renderContent( data, context, parentView, path, index ) { - // Render template against data as a tree of subviews (nested template), or as a string (top-level template). - // tagName parameter for internal use only. Used for rendering templates registered as tags (which may have associated presenter objects) - var i, l, dataItem, newView, itemWrap, itemsWrap, itemResult, parentContext, tmpl, layout, - props = {}, - swapContent = index === TRUE, - self = this, - result = ""; - - if ( self.isTag ) { - // This is a call from renderTag - tmpl = self.tmpl; - context = context || self.ctx; - parentView = parentView || self.view; - path = path || self.path; - index = index || self.index; - props = self.props; - } else { - tmpl = self.jquery && self[0] // This is a call $.fn.render - || self; // This is a call from tmpl.render - } - parentView = parentView || jsv.topView; - parentContext = parentView.ctx; - layout = tmpl.layout; - if ( data === parentView ) { - // Inherit the data from the parent view. - // This may be the contents of an {{if}} block - data = parentView.data; - layout = TRUE; - } - - // Set additional context on views created here, (as modified context inherited from the parent, and be inherited by child views) - // Note: If no jQuery, extend does not support chained copies - so limit extend() to two parameters - context = (context && context === parentContext) - ? parentContext - : (parentContext - // if parentContext, make copy - ? ((parentContext = extend( {}, parentContext ), context) - // If context, merge context with copied parentContext - ? extend( parentContext, context ) - : parentContext) - // if no parentContext, use context, or default to {} - : context || {}); - - if ( props.link === FALSE ) { - // Override inherited value of link by an explicit setting in props: link=false - // The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect. - context.link = FALSE; - } - if ( !tmpl.fn ) { - tmpl = templates[ tmpl ] || templates( tmpl ); - } - itemWrap = context.link && sub.onRenderItem; - itemsWrap = context.link && sub.onRenderItems; - - if ( tmpl ) { - if ( $.isArray( data ) && !layout ) { - // Create a view for the array, whose child views correspond to each data item. - // (Note: if index and parentView are passed in along with parent view, treat as - // insert -e.g. from view.addViews - so parentView is already the view item for array) - newView = swapContent ? parentView : (index !== undefined && parentView) || View( context, path, parentView, data, tmpl, index ); - - for ( i = 0, l = data.length; i < l; i++ ) { - // Create a view for each data item. - dataItem = data[ i ]; - itemResult = tmpl.fn( dataItem, View( context, path, newView, dataItem, tmpl, (index||0) + i ), jsv ); - result += itemWrap ? itemWrap( itemResult, props ) : itemResult; - } - } else { - // Create a view for singleton data object. - newView = swapContent ? parentView : View( context, path, parentView, data, tmpl, index ); - result += (data || layout) ? tmpl.fn( data, newView, jsv ) : ""; - } - parentView.topKey = newView.index; - return itemsWrap ? itemsWrap( result, path, newView.index, tmpl, props ) : result; - } - return ""; // No tmpl. Could throw... -} - -//=========================== -// Build and compile template -//=========================== - -// Generate a reusable function that will serve to render a template against data -// (Compile AST then build template function) - -function syntaxError() { - throw "Syntax error"; -} - -function tmplFn( markup, tmpl, bind ) { - // Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes - // Used for compiling templates, and also by JsViews to build functions for data link expressions - var newNode, node, i, l, code, hasTag, hasEncoder, getsValue, hasConverter, hasViewPath, tag, converter, params, hash, nestedTmpl, allowCode, - tmplOptions = tmpl ? { - allowCode: allowCode = tmpl.allowCode, - debug: tmpl.debug - } : {}, - nested = tmpl && tmpl.tmpls, - astTop = [], - loc = 0, - stack = [], - content = astTop, - current = [,,,astTop], - nestedIndex = 0; - - //==== nested functions ==== - function pushPreceedingContent( shift ) { - shift -= loc; - if ( shift ) { - content.push( markup.substr( loc, shift ).replace( rNewLine, "\\n" )); - } - } - - function parseTag( all, tagName, converter, colon, html, code, params, slash, closeBlock, index ) { - // tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(?:(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - // Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, contentMarkup ] - if ( html ) { - colon = ":"; - converter = "html"; - } - var hash = "", - passedCtx = "", - block = !slash && !colon; // Block tag if not self-closing and not {{:}} or {{>}} (special case) - - //==== nested helper function ==== - - tagName = tagName || colon; - pushPreceedingContent( index ); - loc = index + all.length; // location marker - parsed up to here - if ( code ) { - if ( allowCode ) { - content.push([ "*", params.replace( rUnescapeQuotes, "$1" ) ]); - } - } else if ( tagName ) { - if ( tagName === "else" ) { - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - content = current[ 3 ]; - block = TRUE; - } - params = (params - ? parseParams( params, bind ) - .replace( rBuildHash, function( all, isCtx, keyValue ) { - if ( isCtx ) { - passedCtx += keyValue + ","; - } else { - hash += keyValue + ","; - } - return ""; - }) - : ""); - hash = hash.slice( 0, -1 ); - params = params.slice( 0, -1 ); - newNode = [ - tagName, - converter || "", - params, - block && [], - "{" + (hash ? ("props:{" + hash + "},"): "") + "path:'" + params + "'" + (passedCtx ? ",ctx:{" + passedCtx.slice( 0, -1 ) + "}" : "") + "}" - ]; - if ( block ) { - stack.push( current ); - current = newNode; - current[ 5 ] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag - } - content.push( newNode ); - } else if ( closeBlock ) { - //if ( closeBlock !== current[ 0 ]) { - // throw "unmatched close tag: /" + closeBlock + ". Expected /" + current[ 0 ]; - //} - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - } - if ( !current ) { - throw "Expected block tag"; - } - content = current[ 3 ]; - } - //==== /end of nested functions ==== - - markup = markup.replace( rEscapeQuotes, "\\$1" ); - - // Build the AST (abstract syntax tree) under astTop - markup.replace( rTag, parseTag ); - - pushPreceedingContent( markup.length ); - - // Use the AST (astTop) to build the template function - l = astTop.length; - code = (l ? "" : '"";'); - - for ( i = 0; i < l; i++ ) { - // AST nodes: [ tagName, converter, params, content, hash, contentMarkup ] - node = astTop[ i ]; - if ( node[ 0 ] === "*" ) { - code = code.slice( 0, i ? -1 : -3 ) + ";" + node[ 1 ] + (i + 1 < l ? "ret+=" : ""); - } else if ( "" + node === node ) { // type string - code += '"' + node + '"+'; - } else { - tag = node[ 0 ]; - converter = node[ 1 ]; - params = node[ 2 ]; - content = node[ 3 ]; - hash = node[ 4 ]; - markup = node[ 5 ]; - if ( content ) { - // Create template object for nested template - nestedTmpl = TmplObject( markup, tmplOptions, tmpl, nestedIndex++ ); - // Compile to AST and then to compiled function - tmplFn( markup, nestedTmpl); - nested.push( nestedTmpl ); - } - hasViewPath = hasViewPath || hash.indexOf( "view" ) > -1; - code += (tag === ":" - ? (converter === "html" - ? (hasEncoder = TRUE, "e(" + params) - : converter - ? (hasConverter = TRUE, 'c("' + converter + '",view,' + params) - : (getsValue = TRUE, "((v=" + params + ')!=u?v:""') - ) - : (hasTag = TRUE, 't("' + tag + '",view,"' + (converter || "") + '",' - + (content ? nested.length : '""') // For block tags, pass in the key (nested.length) to the nested content template - + "," + hash + (params ? "," : "") + params)) - + ")+"; - } - } - code = new Function( "data, view, j, b, u", fnDeclStr - + (getsValue ? "v," : "") - + (hasTag ? "t=j.tag," : "") - + (hasConverter ? "c=j.convert," : "") - + (hasEncoder ? "e=j.converters.html," : "") - + "ret; try{\n\n" - + (tmplOptions.debug ? "debugger;" : "") - + (allowCode ? 'ret=' : 'return ') - + code.slice( 0, -1 ) + ";\n\n" - + (allowCode ? "return ret;" : "") - + "}catch(e){return j.err(e);}" - ); - - // Include only the var references that are needed in the code - if ( tmpl ) { - tmpl.fn = code; - tmpl.useVw = hasConverter || hasViewPath || hasTag; - } - return code; -} - -function parseParams( params, bind ) { - var named, - fnCall = {}, - parenDepth = 0, - quoted = FALSE, // boolean for string content in double quotes - aposed = FALSE; // or in single quotes - - function parseTokens( all, lftPrn0, lftPrn, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, prn2, space ) { - // rParams = /(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn path operator err eq path2 prn comma lftPrn3 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - operator = operator || ""; - lftPrn = lftPrn || lftPrn0 || lftPrn2; - path = path || path2; - prn = prn || prn2 || ""; - operator = operator || ""; - - function parsePath( all, object, helper, view, viewProperty, pathTokens, leafToken ) { - // rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // object helper view viewProperty pathTokens leafToken string - if ( object ) { - var ret = (helper - ? 'view.hlp("' + helper + '")' - : view - ? "view" - : "data") - + (leafToken - ? (viewProperty - ? "." + viewProperty - : helper - ? "" - : (view ? "" : "." + object) - ) + (pathTokens || "") - : (leafToken = helper ? "" : view ? viewProperty || "" : object, "")); - - if ( bind && prn !== "(" ) { - ret = "b(" + ret + ',"' + leafToken + '")'; - } - return ret + (leafToken ? "." + leafToken : ""); - } - return all; - } - - if ( err ) { - syntaxError(); - } else { - return (aposed - // within single-quoted string - ? (aposed = !apos, (aposed ? all : '"')) - : quoted - // within double-quoted string - ? (quoted = !quot, (quoted ? all : '"')) - : - ( - (lftPrn - ? (parenDepth++, lftPrn) - : "") - + (space - ? (parenDepth - ? "" - : named - ? (named = FALSE, "\b") - : "," - ) - : eq - // named param - ? (parenDepth && syntaxError(), named = TRUE, '\b' + path + ':') - : path - // path - ? (path.replace( rPath, parsePath ) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : operator) - ) - : operator - ? all - : rtPrn - // function - ? ((fnCall[ parenDepth-- ] = FALSE, rtPrn) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : "") - ) - : comma - ? (fnCall[ parenDepth ] || syntaxError(), ",") // We don't allow top-level literal arrays or objects - : lftPrn0 - ? "" - : (aposed = apos, quoted = quot, '"') - )) - ); - } - } - params = (params + " " ).replace( rParams, parseTokens ); - return params; -} - -function compile( name, tmpl, parent, options ) { - // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object - // options is the set of template properties, c - var tmplOrMarkup, elem, key, nested, nestedItem; - - //==== nested functions ==== - function tmplOrMarkupFromStr( value ) { - // If value is of type string - treat as selector, or name of compiled template - // Return the template object, if already compiled, or the markup string - - if ( ("" + value === value) || value.nodeType > 0 ) { - // If selector is valid and returns at least one element, get first element - elem = value.nodeType > 0 ? value : !rTmplString.test( value ) && jQuery && jQuery( value )[0]; - if ( elem && elem.type ) { - // It is a script element - // Create a name for data linking if none provided - value = templates[ elem.getAttribute( tmplAttr )]; - if ( !value ) { - // Not already compiled and cached, so compile and cache the name - name = name || "_" + autoTmplName++; - elem.setAttribute( tmplAttr, name ); - value = compile( name, elem.innerHTML, parent, options ); // Use tmpl as options - templates[ name ] = value; - } - } - return value; - } - // If value is not a string or dom element, return undefined - } - - //==== Compile the template ==== - tmplOrMarkup = tmplOrMarkupFromStr( tmpl ); - - // If tmpl is a template object, use it for options - options = options || (tmpl.markup ? tmpl : {}); - options.name = name; - nested = options.templates; - - // If tmpl is not a markup string or a selector string, then it must be a template object - // In that case, get it from the markup property of the object - if ( !tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr( tmpl.markup ))) { - if ( tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode )) { - // if the string references a compiled template object, but the debug or allowCode props are different, need to recompile - tmplOrMarkup = tmplOrMarkup.markup; - } - } - if ( tmplOrMarkup !== undefined ) { - if ( name && !parent ) { - render[ name ] = function() { - return tmpl.render.apply( tmpl, arguments ); - }; - } - if ( tmplOrMarkup.fn || tmpl.fn ) { - // tmpl is already compiled, so use it, or if different name is provided, clone it - if ( tmplOrMarkup.fn ) { - if ( name && name !== tmplOrMarkup.name ) { - tmpl = extend( extend( {}, tmplOrMarkup ), options); - } else { - tmpl = tmplOrMarkup; - } - } - } else { - // tmplOrMarkup is a markup string, not a compiled template - // Create template object - tmpl = TmplObject( tmplOrMarkup, options, parent, 0 ); - // Compile to AST and then to compiled function - tmplFn( tmplOrMarkup, tmpl ); - } - for ( key in nested ) { - // compile nested template declarations - nestedItem = nested[ key ]; - if ( nestedItem.name !== key ) { - nested[ key ] = compile( key, nestedItem, tmpl ); - } - } - return tmpl; - } -} -//==== /end of function compile ==== - -function TmplObject( markup, options, parent, index ) { - // Template object constructor - - // nested helper function - function extendStore( storeName ) { - if ( parent[ storeName ]) { - // Include parent items except if overridden by item of same name in options - tmpl[ storeName ] = extend( extend( {}, parent[ storeName ] ), options[ storeName ] ); - } - } - - options = options || {}; - var tmpl = { - markup: markup, - tmpls: [], - links: [], - render: renderContent - }; - if ( parent ) { - if ( parent.templates ) { - tmpl.templates = extend( extend( {}, parent.templates ), options.templates ); - } - tmpl.parent = parent; - tmpl.name = parent.name + "[" + index + "]"; - tmpl.index = index; - } - - extend( tmpl, options ); - if ( parent ) { - extendStore( "templates" ); - extendStore( "tags" ); - extendStore( "helpers" ); - extendStore( "converters" ); - } - return tmpl; -} - -//========================== Initialize ========================== - -if ( jQuery ) { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is loaded, so make $ the jQuery object - $ = jQuery; - $.templates = templates; - $.render = render; - $.views = jsv; - $.fn.render = renderContent; - -} else { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is not loaded. - - $ = window.jsviews = jsv; - $.extend = function( target, source ) { - var name; - target = target || {}; - for ( name in source ) { - target[ name ] = source[ name ]; - } - return target; - }; - - $.isArray = Array && Array.isArray || function( obj ) { - return Object.prototype.toString.call( obj ) === "[object Array]"; - }; -} - -extend = $.extend; - -jsv.topView = { views: {}, tmpl: {}, hlp: getHelper, ctx: jsv.helpers }; - -function replacerForHtml( ch ) { - // Original code from Mike Samuel - return escapeMapForHtml[ ch ] - // Intentional assignment that caches the result of encoding ch. - || (escapeMapForHtml[ ch ] = "&#" + ch.charCodeAt( 0 ) + ";"); -} - -//========================== Register tags ========================== - -tags({ - "if": function() { - var ifTag = this, - view = ifTag.view; - - view.onElse = function( tagObject, args ) { - var i = 0, - l = args.length; - - while ( l && !args[ i++ ]) { - // Only render content if args.length === 0 (i.e. this is an else with no condition) or if a condition argument is truey - if ( i === l ) { - return ""; - } - } - view.onElse = undefined; // If condition satisfied, so won't run 'else'. - tagObject.path = ""; - return tagObject.renderContent( view ); - // Test is satisfied, so render content, while remaining in current data context - // By passing the view, we inherit data context from the parent view, and the content is treated as a layout template - // (so if the data is an array, it will not iterate over the data - }; - return view.onElse( this, arguments ); - }, - "else": function() { - var view = this.view; - return view.onElse ? view.onElse( this, arguments ) : ""; - }, - "for": function() { - var i, - self = this, - result = "", - args = arguments, - l = args.length; - if ( self.props.layout ) { - self.tmpl.layout = TRUE; - } - for ( i = 0; i < l; i++ ) { - result += self.renderContent( args[ i ]); - } - return result; - }, - "=": function( value ) { - return value; - }, - "*": function( value ) { - return value; - } -}); - -//========================== Register global helpers ========================== - -// helpers({ // Global helper functions -// // TODO add any useful built-in helper functions -// }); - -//========================== Register converters ========================== - -converters({ - html: function( text ) { - // HTML encoding helper: Replace < > & and ' and " by corresponding entities. - // inspired by Mike Samuel - return text != undefined ? String( text ).replace( htmlSpecialChar, replacerForHtml ) : ""; - } -}); - -//========================== Define default delimiters ========================== -setDelimiters( "{{", "}}" ); - -})( this ); - -/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) - * Licensed under the MIT License (LICENSE.txt). - * - * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. - * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. - * Thanks to: Seamus Leahy for adding deltaX and deltaY - * - * Version: 3.0.6 - * - * Requires: 1.2.2+ - */ - -(function($) { - -var types = ['DOMMouseScroll', 'mousewheel']; - -if ($.event.fixHooks) { - for ( var i=types.length; i; ) { - $.event.fixHooks[ types[--i] ] = $.event.mouseHooks; - } -} - -$.event.special.mousewheel = { - setup: function() { - if ( this.addEventListener ) { - for ( var i=types.length; i; ) { - this.addEventListener( types[--i], handler, false ); - } - } else { - this.onmousewheel = handler; - } - }, - - teardown: function() { - if ( this.removeEventListener ) { - for ( var i=types.length; i; ) { - this.removeEventListener( types[--i], handler, false ); - } - } else { - this.onmousewheel = null; - } - } -}; - -$.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); - }, - - unmousewheel: function(fn) { - return this.unbind("mousewheel", fn); - } -}); - - -function handler(event) { - var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0; - event = $.event.fix(orgEvent); - event.type = "mousewheel"; - - // Old school scrollwheel delta - if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; } - if ( orgEvent.detail ) { delta = -orgEvent.detail/3; } - - // New school multidimensional scroll (touchpads) deltas - deltaY = delta; - - // Gecko - if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { - deltaY = 0; - deltaX = -1*delta; - } - - // Webkit - if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; } - if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; } - - // Add event and delta to the front of the arguments - args.unshift(event, delta, deltaX, deltaY); - - return ($.event.dispatch || $.event.handle).apply(this, args); -} - -})(jQuery); - -/*! - * jQuery UI Widget 1.8.18 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ - -if ( ! $.widget ) { - -(function( $, undefined ) { - -// jQuery 1.4+ -if ( $.cleanData ) { - var _cleanData = $.cleanData; - $.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); - }; -} else { - var _remove = $.fn.remove; - $.fn.remove = function( selector, keepData ) { - return this.each(function() { - if ( !keepData ) { - if ( !selector || $.filter( selector, [ this ] ).length ) { - $( "*", this ).add( [ this ] ).each(function() { - try { - $( this ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - }); - } - } - return _remove.call( $(this), selector, keepData ); - }); - }; -} - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from -// $.each( basePrototype, function( key, val ) { -// if ( $.isPlainObject(val) ) { -// basePrototype[ key ] = $.extend( {}, val ); -// } -// }); - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = Array.prototype.slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - // prevent calls to internal methods - if ( isMethodCall && options.charAt( 0 ) === "_" ) { - return returnValue; - } - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ), - methodValue = instance && $.isFunction( instance[options] ) ? - instance[ options ].apply( instance, args ) : - instance; - // TODO: add this back in 1.9 and use $.error() (see #5972) -// if ( !instance ) { -// throw "cannot call methods on " + name + " prior to initialization; " + -// "attempted to call method '" + options + "'"; -// } -// if ( !$.isFunction( instance[options] ) ) { -// throw "no such method '" + options + "' for " + name + " widget instance"; -// } -// var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, name, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - // $.widget.bridge stores the plugin instance, but we do it anyway - // so that it's stored even before the _create function runs - $.data( element, this.widgetName, this ); - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - var self = this; - this.element.bind( "remove." + this.widgetName, function() { - self.destroy(); - }); - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: function() {}, - _init: function() {}, - - destroy: function() { - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - }, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - [ value ? "addClass" : "removeClass"]( - this.widgetBaseClass + "-disabled" + " " + - "ui-state-disabled" ) - .attr( "aria-disabled", value ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - - return !( $.isFunction(callback) && - callback.call( this.element[0], event, data ) === false || - event.isDefaultPrevented() ); - } -}; - -})( jQuery ); - -}; - - -(function ($, window, undefined) { - window.toStaticHTML = window.toStaticHTML || function ( x ) { return x; }; - - var pos_oo = Number.POSITIVE_INFINITY, - neg_oo = Number.NEGATIVE_INFINITY; - - $.geo = { - // - // utility functions - // - - _allCoordinates: function (geom) { - // return array of all positions in all geometries of geom - // not in JTS - var geometries = this._flatten(geom), - curGeom = 0, - result = []; - - for (; curGeom < geometries.length; curGeom++) { - var coordinates = geometries[curGeom].coordinates, - isArray = coordinates && $.isArray(coordinates[0]), - isDblArray = isArray && $.isArray(coordinates[0][0]), - isTriArray = isDblArray && $.isArray(coordinates[0][0][0]), - i, j, k; - - if (!isTriArray) { - if (!isDblArray) { - if (!isArray) { - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - for (k = 0; k < coordinates[i][j].length; k++) { - result.push(coordinates[i][j][k]); - } - } - } - } - return result; - }, - - _isGeodetic: function( coords ) { - // returns true if the first coordinate it can find is geodetic - - while ( $.isArray( coords ) ) { - if ( coords.length > 1 && ! $.isArray( coords[ 0 ] ) ) { - return ( coords[ 0 ] >= -180.001 && coords[ 0 ] <= 180.001 && coords[ 1 ] >= -90.001 && coords[ 1 ] <= 90.001 ); - } else { - coords = coords[ 0 ]; - } - } - - return false; - }, - - // - // bbox functions - // - - center: function (bbox, _ignoreGeo /* Internal Use Only */) { - // Envelope.centre in JTS - // bbox only, use centroid for geom - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return wasGeodetic ? $.geo.proj.toGeodetic(center) : center; - }, - - expandBy: function (bbox, dx, dy, _ignoreGeo /* Internal Use Only */) { - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - bbox = [bbox[0] - dx, bbox[1] - dy, bbox[2] + dx, bbox[3] + dy]; - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - height: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[3] - bbox[1]; - }, - - _in: function(bbox1, bbox2) { - return bbox1[0] <= bbox2[0] && - bbox1[1] <= bbox2[1] && - bbox1[2] >= bbox2[2] && - bbox1[3] >= bbox2[3]; - }, - - _bboxDisjoint: function( bbox1, bbox2 ) { - return bbox2[ 0 ] > bbox1[ 2 ] || - bbox2[ 2 ] < bbox1[ 0 ] || - bbox2[ 1 ] > bbox1[ 3 ] || - bbox2[ 3 ] < bbox1[ 1 ]; - }, - - include: function( bbox, value, _ignoreGeo /* Internal Use Only */ ) { - // similar to Envelope.expandToInclude in JTS - if ( !value || !$.isArray( value ) ) { - return bbox; - } - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox || value ) ) { - wasGeodetic = true; - } - - if ( !bbox ) { - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - } else if ( wasGeodetic ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - - if ( value.length === 2 ) { - value = [ value[ 0 ], value[ 1 ], value[ 0 ], value[ 1 ] ]; - } - - if ( $.geo.proj ) { - value = $.geo.proj.fromGeodetic( value ); - } - - bbox[0] = Math.min( value[ 0 ], bbox[ 0 ] ); - bbox[1] = Math.min( value[ 1 ], bbox[ 1 ] ); - bbox[2] = Math.max( value[ 2 ], bbox[ 2 ] ); - bbox[3] = Math.max( value[ 3 ], bbox[ 3 ] ); - - return wasGeodetic ? $.geo.proj.toGeodetic( bbox ) : bbox; - }, - - polygonize: function( bbox, _ignoreGeo /* Internal Use Only */ ) { - // adaptation of Polygonizer class in JTS for use with bboxes - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var polygon = { - type: "Polygon", - coordinates: [ [ - [ bbox[ 0 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 1 ] ] - ] ] - }; - - if ( wasGeodetic ) { - polygon.coordinates = $.geo.proj.toGeodetic( polygon.coordinates ); - } - - return polygon; - }, - - reaspect: function (bbox, ratio, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var width = this.width(bbox, true), - height = this.height(bbox, true), - center = this.center(bbox, true), - dx, dy; - - if (width !== 0 && height !== 0 && ratio > 0) { - if (width / height > ratio) { - dx = width / 2; - dy = dx / ratio; - } else { - dy = height / 2; - dx = dy * ratio; - } - - bbox = [center[0] - dx, center[1] - dy, center[0] + dx, center[1] + dy]; - } - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - recenter: function( bbox, center, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj ) { - if ( this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - if ( this._isGeodetic( center ) ) { - center = $.geo.proj.fromGeodetic(center); - } - } - - var halfWidth = ( bbox[ 2 ] - bbox[ 0 ] ) / 2, - halfHeight = ( bbox[ 3 ] - bbox[ 1 ] ) / 2; - - bbox = [ - center[ 0 ] - halfWidth, - center[ 1 ] - halfHeight, - center[ 0 ] + halfWidth, - center[ 1 ] + halfHeight - ]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - scaleBy: function ( bbox, scale, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var c = this.center(bbox, true), - dx = (bbox[2] - bbox[0]) * scale / 2, - dy = (bbox[3] - bbox[1]) * scale / 2; - - bbox = [c[0] - dx, c[1] - dy, c[0] + dx, c[1] + dy]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - width: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[2] - bbox[0]; - }, - - // - // geometry functions - // - - // bbox (Geometry.getEnvelope in JTS) - - bbox: function ( geom, _ignoreGeo /* Internal Use Only */ ) { - var result, wasGeodetic = false; - if ( !geom ) { - return undefined; - } else if ( geom.bbox ) { - result = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.bbox ) ) ? $.geo.proj.fromGeodetic( geom.bbox ) : geom.bbox; - } else { - result = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var coordinates = this._allCoordinates( geom ), - curCoord = 0; - - if ( coordinates.length === 0 ) { - return undefined; - } - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coordinates ) ) { - wasGeodetic = true; - coordinates = $.geo.proj.fromGeodetic( coordinates ); - } - - for ( ; curCoord < coordinates.length; curCoord++ ) { - result[0] = Math.min(coordinates[curCoord][0], result[0]); - result[1] = Math.min(coordinates[curCoord][1], result[1]); - result[2] = Math.max(coordinates[curCoord][0], result[2]); - result[3] = Math.max(coordinates[curCoord][1], result[3]); - } - } - - return wasGeodetic ? $.geo.proj.toGeodetic(result) : result; - }, - - // centroid - - centroid: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var c; //< temp storage for any coordinate during centroid op - - switch (geom.type) { - case "Point": - return $.extend({}, geom); - - case "LineString": - case "Polygon": - var a = 0, - coords = $.merge( [ ], geom.type === "Polygon" ? geom.coordinates[0] : geom.coordinates ), - i = 1, j, n, - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - c = [ 0, 0 ]; - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coords ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic(coords); - } - - //if (coords[0][0] != coords[coords.length - 1][0] || coords[0][1] != coords[coords.length - 1][1]) { - // coords.push(coords[0]); - //} - - for (; i <= coords.length; i++) { - j = i % coords.length; - - bbox[0] = Math.min(coords[j][0], bbox[0]); - bbox[1] = Math.min(coords[j][1], bbox[1]); - bbox[2] = Math.max(coords[j][0], bbox[2]); - bbox[3] = Math.max(coords[j][1], bbox[3]); - - n = (coords[i - 1][0] * coords[j][1]) - (coords[j][0] * coords[i - 1][1]); - a += n; - c[0] += (coords[i - 1][0] + coords[j][0]) * n; - c[1] += (coords[i - 1][1] + coords[j][1]) * n; - } - - if (a === 0) { - if (coords.length > 0) { - c[0] = Math.min( Math.max( coords[0][0], bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( coords[0][1], bbox[ 1 ] ), bbox[ 3 ] ); - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } else { - return undefined; - } - } - - a *= 3; - //c[0] /= a; - //c[1] /= a; - - c[0] = Math.min( Math.max( c[0] / a, bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( c[1] / a, bbox[ 1 ] ), bbox[ 3 ] ); - - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - - case "MultiPoint": - // should return center of mass for point cluster but just return first point for now - if ( geom.coordinates.length > 0 ) { - c = geom.coordinates[ 0 ]; - return { - type: "Point", - coordinates: [ c[ 0 ], c[ 1 ] ] - }; - } - break; - - case "MultiLineString": - case "MultiPolygon": - if ( geom.coordinates.length > 0 ) { - return this.centroid( { - type: geom.type.substr( 5 ), - coordinates: geom.coordinates[ 0 ] - }, _ignoreGeo ); - } - break; - - } - return undefined; - }, - - // contains - - contains: function (geom1, geom2) { - if (geom1.type !== "Polygon") { - return false; - } - - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1.coordinates, geom2.coordinates); - - case "LineString": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates); - - case "Polygon": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates[0]); - - default: - return false; - } - }, - - _containsPolygonPoint: function (polygonCoordinates, pointCoordinate) { - if (polygonCoordinates.length === 0 || polygonCoordinates[0].length < 4) { - return false; - } - - var rayCross = 0, - a = polygonCoordinates[0][0], - i = 1, - b, - x; - - for (; i < polygonCoordinates[0].length; i++) { - b = polygonCoordinates[0][i]; - - if ((a[1] <= pointCoordinate[1] && pointCoordinate[1] < b[1]) || (b[1] <= pointCoordinate[1] && pointCoordinate[1] < a[1]) && (pointCoordinate[0] < a[0] || pointCoordinate[0] < b[0])) { - x = a[0] + (b[0] - a[0]) * (pointCoordinate[1] - a[1]) / (b[1] - a[1]); - - if (x > pointCoordinate[0]) { - rayCross++; - } - } - - a = b; - } - - return rayCross % 2 === 1; - }, - - _containsPolygonLineString: function (polygonCoordinates, lineStringCoordinates) { - for (var i = 0; i < lineStringCoordinates.length; i++) { - if (!this._containsPolygonPoint(polygonCoordinates, lineStringCoordinates[i])) { - return false; - } - } - return true; - }, - - // distance - - distance: function ( geom1, geom2, _ignoreGeo /* Internal Use Only */ ) { - var geom1CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom1.coordinates ) ) ? $.geo.proj.fromGeodetic(geom1.coordinates) : geom1.coordinates, - geom2CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom2.coordinates ) ) ? $.geo.proj.fromGeodetic(geom2.coordinates) : geom2.coordinates; - - switch (geom1.type) { - case "Point": - switch (geom2.type) { - case "Point": - return this._distancePointPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "LineString": - return this._distanceLineStringPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "Polygon": - return this._containsPolygonPoint(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "LineString": - switch (geom2.type) { - case "Point": - return this._distanceLineStringPoint(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "LineString": - return this._distanceLineStringLineString(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "Polygon": - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "LineString": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected[0]) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected[0]); - default: - return undefined; - } - break; - } - }, - - _distancePointPoint: function (coordinate1, coordinate2) { - var dx = coordinate2[0] - coordinate1[0], - dy = coordinate2[1] - coordinate1[1]; - return Math.sqrt((dx * dx) + (dy * dy)); - }, - - _distanceLineStringPoint: function (lineStringCoordinates, pointCoordinate) { - var minDist = pos_oo; - - if (lineStringCoordinates.length > 0) { - var a = lineStringCoordinates[0], - - apx = pointCoordinate[0] - a[0], - apy = pointCoordinate[1] - a[1]; - - if (lineStringCoordinates.length === 1) { - return Math.sqrt(apx * apx + apy * apy); - } else { - for (var i = 1; i < lineStringCoordinates.length; i++) { - var b = lineStringCoordinates[i], - - abx = b[0] - a[0], - aby = b[1] - a[1], - bpx = pointCoordinate[0] - b[0], - bpy = pointCoordinate[1] - b[1], - - d = this._distanceSegmentPoint(abx, aby, apx, apy, bpx, bpy); - - if (d === 0) { - return 0; - } - - if (d < minDist) { - minDist = d; - } - - a = b; - apx = bpx; - apy = bpy; - } - } - } - - return Math.sqrt(minDist); - }, - - _distanceSegmentPoint: function (abx, aby, apx, apy, bpx, bpy) { - var dot1 = abx * apx + aby * apy; - - if (dot1 <= 0) { - return apx * apx + apy * apy; - } - - var dot2 = abx * abx + aby * aby; - - if (dot1 >= dot2) { - return bpx * bpx + bpy * bpy; - } - - return apx * apx + apy * apy - dot1 * dot1 / dot2; - }, - - _distanceLineStringLineString: function (lineStringCoordinates1, lineStringCoordinates2) { - var minDist = pos_oo; - for (var i = 0; i < lineStringCoordinates2.length; i++) { - minDist = Math.min(minDist, this._distanceLineStringPoint(lineStringCoordinates1, lineStringCoordinates2[i])); - } - return minDist; - }, - - // buffer - - _buffer: function( geom, distance, _ignoreGeo /* Internal Use Only */ ) { - var wasGeodetic = false, - coords = geom.coordinates; - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.coordinates ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic( geom.coordinates ); - } - - if ( geom.type === "Point" ) { - var resultCoords = [], - slices = 180, - i = 0, - a; - - for ( ; i <= slices; i++ ) { - a = ( i * 360 / slices ) * ( Math.PI / 180 ); - resultCoords.push( [ - coords[ 0 ] + Math.cos( a ) * distance, - coords[ 1 ] + Math.sin( a ) * distance - ] ); - } - - return { - type: "Polygon", - coordinates: [ ( wasGeodetic ? $.geo.proj.toGeodetic( resultCoords ) : resultCoords ) ] - }; - } else { - return undefined; - } - }, - - - // - // feature - // - - _basic: function( geom ) { - // return an array of all basic geometries - // e.g., MultiPolygons become multiple Polygons - // coordinate arrays are kept as references for speed & should not be altered - // not in JTS - var geometries = [ ]; - var multiType; - var i = 0; - var j; - - var flat = this._flatten( geom ); - - for ( ; i < flat.length; i++ ) { - if ( flat[ i ].type.substring( 0, 5 ) === "Multi" ) { - multiType = flat[ i ].type.substring( 5 ); - - for ( j = 0; j < flat[ i ].coordinates.length; j++ ) { - geometries.push( { - type: multiType, - coordinates: flat[ i ].coordinates[ j ] - } ); - } - } else { - geometries.push( flat[ i ] ); - } - } - - return geometries; - }, - - _flatten: function (geom) { - // return an array of only geometries - // will extract geometries from Feature, FeatureCollection, & GeometryCollection - // not in JTS - var geometries = [], - curGeom = 0; - switch (geom.type) { - case "Feature": - $.merge(geometries, this._flatten(geom.geometry)); - break; - - case "FeatureCollection": - for (; curGeom < geom.features.length; curGeom++) { - $.merge(geometries, this._flatten(geom.features[curGeom].geometry)); - } - break; - - case "GeometryCollection": - for (; curGeom < geom.geometries.length; curGeom++) { - $.merge(geometries, this._flatten(geom.geometries[curGeom])); - } - break; - - default: - geometries[0] = geom; - break; - } - return geometries; - }, - - length: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - lineStringCoordinates, - i = 1, dx, dy; - - switch ( geom.type ) { - case "Point": - return 0; - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][0] - lineStringCoordinates[ i - 1 ][0]; - dy = lineStringCoordinates[ i ][1] - lineStringCoordinates[ i - 1 ][1]; - sum += Math.sqrt((dx * dx) + (dy * dy)); - } - - return sum; - } - - // return undefined; - }, - - area: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - polygonCoordinates, - i = 1, j; - - switch ( geom.type ) { - case "Point": - case "LineString": - return 0; - - case "Polygon": - polygonCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( polygonCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( polygonCoordinates ) ) { - polygonCoordinates = $.geo.proj.fromGeodetic( polygonCoordinates ); - } - - for ( ; i <= polygonCoordinates.length; i++) { - j = i % polygonCoordinates.length; - sum += ( polygonCoordinates[ i - 1 ][ 0 ] - polygonCoordinates[ j ][ 0 ] ) * ( polygonCoordinates[ i - 1 ][ 1 ] + polygonCoordinates[ j ][ 1 ] ) / 2; - } - - return Math.abs( sum ); - } - }, - - pointAlong: function( geom, percentage, _ignoreGeo /* Internal Use Only */ ) { - var totalLength = 0, - previousPercentageSum = 0, - percentageSum = 0, - remainderPercentageSum, - len, - lineStringCoordinates, - segmentLengths = [], - i = 1, dx, dy, - c, c0, c1, - wasGeodetic = false; - - switch ( geom.type ) { - case "Point": - return $.extend( { }, geom ); - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( percentage === 0 ) { - return { - type: "Point", - coordinates: [ lineStringCoordinates[ 0 ][ 0 ], lineStringCoordinates[ 0 ][ 1 ] ] - }; - } else if ( percentage === 1 ) { - i = lineStringCoordinates.length - 1; - return { - type: "Point", - coordinates: [ lineStringCoordinates[ i ][ 0 ], lineStringCoordinates[ i ][ 1 ] ] - }; - } else { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - wasGeodetic = true; - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][ 0 ] - lineStringCoordinates[ i - 1 ][ 0 ]; - dy = lineStringCoordinates[ i ][ 1 ] - lineStringCoordinates[ i - 1 ][ 1 ]; - len = Math.sqrt((dx * dx) + (dy * dy)); - segmentLengths.push( len ); - totalLength += len; - } - - for ( i = 0; i < segmentLengths.length && percentageSum < percentage; i++ ) { - previousPercentageSum = percentageSum; - percentageSum += ( segmentLengths[ i ] / totalLength ); - } - - remainderPercentageSum = percentage - previousPercentageSum; - - c0 = lineStringCoordinates[ i - 1 ]; - c1 = lineStringCoordinates[ i ]; - - c = [ - c0[ 0 ] + ( remainderPercentageSum * ( c1[ 0 ] - c0[ 0 ] ) ), - c0[ 1 ] + ( remainderPercentageSum * ( c1[ 1 ] - c0[ 1 ] ) ) - ]; - - return { - type: "Point", - coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c - }; - } - } - }, - - // - // WKT functions - // - - WKT: (function () { - function pointToString(value) { - return "POINT " + pointToUntaggedString(value.coordinates); - } - - function pointToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - return "(" + coordinates.join(" ") + ")"; - } - } - - function lineStringToString(value) { - return "LINESTRING " + lineStringToUntaggedString(value.coordinates); - } - - function lineStringToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var points = []; - - for (var i = 0; i < coordinates.length; i++) { - points.push(coordinates[i].join(" ")); - } - - return "(" + points + ")"; - } - } - - function polygonToString(value) { - return "POLYGON " + polygonToUntaggedString(value.coordinates); - } - - function polygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMTPY"; - } else { - var lineStrings = []; - - for (var i = 0; i < coordinates.length; i++) { - lineStrings.push(lineStringToUntaggedString(coordinates[i])); - } - - return "(" + lineStrings + ")"; - } - } - - function multiPointToString(value) { - return "MULTIPOINT " + lineStringToUntaggedString(value.coordinates); - } - - function multiLineStringToString(value) { - return "MULTILINSTRING " + polygonToUntaggedString(value.coordinates); - } - - function multiPolygonToString(value) { - return "MULTIPOLYGON " + multiPolygonToUntaggedString(value.coordinates); - } - - function multiPolygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var polygons = []; - for (var i = 0; i < coordinates.length; i++) { - polygons.push(polygonToUntaggedString(coordinates[i])); - } - return "(" + polygons + ")"; - } - } - - function geometryCollectionToString(value) { - return "GEOMETRYCOLLECTION " + geometryCollectionToUntaggedString(value.geometries); - } - - function geometryCollectionToUntaggedString(geometries) { - if (!(geometries && geometries.length)) { - return "EMPTY"; - } else { - var geometryText = []; - for (var i = 0; i < geometries.length; i++) { - geometryText.push(stringify(geometries[i])); - } - return "(" + geometries + ")"; - } - } - - function stringify(value) { - if (!(value && value.type)) { - return ""; - } else { - switch (value.type) { - case "Point": - return pointToString(value); - - case "LineString": - return lineStringToString(value); - - case "Polygon": - return polygonToString(value); - - case "MultiPoint": - return multiPointToString(value); - - case "MultiLineString": - return multiLineStringToString(value); - - case "MultiPolygon": - return multiPolygonToString(value); - - case "GeometryCollection": - return geometryCollectionToString(value); - - default: - return ""; - } - } - } - - function pointParseUntagged(wkt) { - var pointString = wkt.match( /\(\s*([\d\.\-]+)\s+([\d\.\-]+)\s*\)/ ); - return pointString && pointString.length > 2 ? { - type: "Point", - coordinates: [ - parseFloat(pointString[1]), - parseFloat(pointString[2]) - ] - } : null; - } - - function lineStringParseUntagged(wkt) { - var lineString = wkt.match( /\s*\((.*)\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( lineString && lineString.length > 1 ) { - pointStrings = lineString[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "LineString", - coordinates: coords - }; - } else { - return null; - } - } - - function polygonParseUntagged(wkt) { - var polygon = wkt.match( /\s*\(\s*\((.*)\)\s*\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( polygon && polygon.length > 1 ) { - pointStrings = polygon[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "Polygon", - coordinates: [ coords ] - }; - } else { - return null; - } - } - - function multiPointParseUntagged(wkt) { - var multiSomething; - - if ( wkt.indexOf( "((" ) === -1 ) { - multiSomething = lineStringParseUntagged( wkt ); - } else { - multiSomething = multiLineStringParseUntagged( wkt ); - multiSomething.coordinates = $.geo._allCoordinates( multiSomething ); - } - - multiSomething.type = "MultiPoint"; - - return multiSomething; - } - - function multiLineStringParseUntagged(wkt) { - var lineStringsWkt = wkt.substr( 2, wkt.length - 4 ), - lineString, - lineStrings = lineStringsWkt.split( /\),\s*\(/ ), - i = 0, - multiLineString = { - type: "MultiLineString", - coordinates: [ ] - }; - - for ( ; i < lineStrings.length; i++ ) { - lineString = lineStringParseUntagged( "(" + lineStrings[ i ] + ")" ); - if ( lineString ) { - multiLineString.coordinates.push( lineString.coordinates ); - } - } - - return multiLineString; - } - - function multiPolygonParseUntagged(wkt) { - var polygonsWkt = wkt.substr( 1, wkt.length - 2 ), - polygon, - polygons = polygonsWkt.split( /\),\s*\(/ ), - i = 0, - multiPolygon = { - type: "MultiPolygon", - coordinates: [ ] - }; - - for ( ; i < polygons.length; i++ ) { - polygon = polygonParseUntagged( "(" + polygons[ i ] + ")" ); - if ( polygon ) { - multiPolygon.coordinates.push( polygon.coordinates ); - } - } - - return multiPolygon; - } - - function geometryCollectionParseUntagged( wkt ) { - var geometriesWkt = wkt.substr( 1, wkt.length - 2 ), - geometries = geometriesWkt.match( /\),[a-zA-Z]/g ), - geometryCollection = { - type: "GeometryCollection", - geometries: [ ] - }, - curGeom, - i = 0, curStart = 0, curLen; - - if ( geometries && geometries.length > 0 ) { - for ( ; i < geometries.length; i++ ) { - curLen = geometriesWkt.indexOf( geometries[ i ], curStart ) - curStart + 1; - curGeom = parse( geometriesWkt.substr( curStart, curLen ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - curStart += curLen + 1; - } - - // one more - curGeom = parse( geometriesWkt.substr( curStart ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - - return geometryCollection; - } else { - return null; - } - } - - function parse(wkt) { - wkt = $.trim(wkt); - - var typeIndex = wkt.indexOf( "(" ), - untagged = wkt.substr( typeIndex ); - - switch ($.trim(wkt.substr(0, typeIndex)).toUpperCase()) { - case "POINT": - return pointParseUntagged( untagged ); - - case "LINESTRING": - return lineStringParseUntagged( untagged ); - - case "POLYGON": - return polygonParseUntagged( untagged ); - - case "MULTIPOINT": - return multiPointParseUntagged( untagged ); - - case "MULTILINESTRING": - return multiLineStringParseUntagged( untagged ); - - case "MULTIPOLYGON": - return multiPolygonParseUntagged( untagged ); - - case "GEOMETRYCOLLECTION": - return geometryCollectionParseUntagged( untagged ); - - default: - return null; - } - } - - return { - stringify: stringify, - - parse: parse - }; - }()), - - // - // projection functions - // - - proj: (function () { - var halfPi = 1.5707963267948966192, - quarterPi = 0.7853981633974483096, - radiansPerDegree = 0.0174532925199432958, - degreesPerRadian = 57.295779513082320877, - semiMajorAxis = 6378137; - - return { - fromGeodeticPos: function (coordinate) { - return [ - semiMajorAxis * coordinate[ 0 ] * radiansPerDegree, - semiMajorAxis * Math.log(Math.tan(quarterPi + coordinate[ 1 ] * radiansPerDegree / 2)) - ]; - }, - - fromGeodetic: function ( coordinates ) { - if ( ! $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - fromGeodeticPos = this.fromGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length === 4) { - // bbox - var min = fromGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = fromGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = fromGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - }, - - toGeodeticPos: function (coordinate) { - return [ - (coordinate[ 0 ] / semiMajorAxis) * degreesPerRadian, - (halfPi - 2 * Math.atan(1 / Math.exp(coordinate[ 1 ] / semiMajorAxis))) * degreesPerRadian - ]; - }, - - toGeodetic: function (coordinates) { - if ( $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - toGeodeticPos = this.toGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length === 4) { - // bbox - var min = toGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = toGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = toGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - } - }; - }()), - - // - // service types (defined in other files) - // - - _serviceTypes: {} - }; -}(jQuery, this)); - -(function ($, window, undefined) { - var _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ); - - $.widget("geo.geographics", { - _$elem: undefined, - _options: {}, - _trueCanvas: true, - _trueDoubleBuffer: true, - - _width: 0, - _height: 0, - - _$canvas: undefined, - _context: undefined, - - _$canvasSceneFront: undefined, //< if _trueCanvas, where canvas images get written (front buffer) - _$canvasSceneBack: undefined, //< if _trueCanvas, where canvas images get written (back buffer) - _timeoutEnd: null, - _requireFlip: false, - - _blitcanvas: undefined, - _blitcontext: undefined, - - _$labelsContainerFront: undefined, - _$labelsContainerBack: undefined, - _labelsHtml: "", - - options: { - style: { - borderRadius: "8px", - color: "#7f0000", - //fill: undefined, - fillOpacity: 0.2, - height: "8px", - opacity: 1, - //stroke: undefined, - strokeOpacity: 1, - strokeWidth: "2px", - visibility: "visible", - width: "8px" - }, - - doubleBuffer: true - }, - - _create: function () { - this._$elem = this.element; - this._options = this.options; - - this._$elem.css( { - webkitTransform: "translateZ(0)", - display: "inline-block", - overflow: "hidden", - textAlign: "left" - } ); - - if (this._$elem.css("position") === "static") { - this._$elem.css("position", "relative"); - } - - this._$elem.addClass( "geo-graphics" ); - - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - var posCss = 'position:absolute;left:0;top:0;margin:0;padding:0;', - sizeCss = 'width:' + this._width + 'px;height:' + this._height + 'px;', - sizeAttr = 'width="' + this._width + '" height="' + this._height + '"'; - - this._blitcanvas = document.createElement( "canvas" ); - - if ( this._blitcanvas.getContext ) { - this._$canvas = $( window.toStaticHTML( '' ) ); - - // test _trueDoubleBuffer - this._blitcanvas.width = 1; - this._blitcanvas.height = 1; - this._trueDoubleBuffer = this._blitcanvas.toDataURL().length > 6; - - if ( !(this._options.doubleBuffer && this._trueDoubleBuffer) ) { - this._$elem.append( this._$canvas ); - } - - this._context = this._$canvas[0].getContext("2d"); - - this._blitcanvas.width = this._width; - this._blitcanvas.height = this._height; - this._blitcontext = this._blitcanvas.getContext("2d"); - - // create our front & back buffers - // though, at any time either one can be in front - this._$canvasSceneFront = $( window.toStaticHTML( '' ) ); //.load($.proxy(this._canvasSceneLoad, this)); - this._$canvasSceneBack = $( window.toStaticHTML( '' ) ); //.load($.proxy(this._canvasSceneLoad, this)); - - } else if (_ieVersion <= 8) { - this._trueCanvas = false; - this._$elem.append( '
      '); - this._$canvas = this._$elem.children(':last'); - - G_vmlCanvasManager.initElement(this._$canvas[0]); - this._context = this._$canvas[0].getContext("2d"); - this._$canvas.children().css({ backgroundColor: "transparent", width: this._width, height: this._height }); - } - - // create our front & back label containers - this._$labelsContainerFront = $( window.toStaticHTML( '
      ' ) ); - this._$labelsContainerBack = $( window.toStaticHTML( '
      ' ) ); - }, - - _setOption: function (key, value) { - if (key === "style") { - value = $.extend({}, this._options.style, value); - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - destroy: function () { - $.Widget.prototype.destroy.apply(this, arguments); - this._$elem.html(""); - this._$elem.removeClass( "geo-graphics" ); - }, - - clear: function () { - this._context.clearRect(0, 0, this._width, this._height); - this._labelsHtml = ""; - this._end( ); - }, - - drawArc: function (coordinates, startAngle, sweepAngle, style) { - style = this._getGraphicStyle(style); - - if (style.visibility !== "hidden" && style.opacity > 0 && style.widthValue > 0 && style.heightValue > 0) { - var r = Math.min(style.widthValue, style.heightValue) / 2; - - startAngle = (startAngle * Math.PI / 180); - sweepAngle = (sweepAngle * Math.PI / 180); - - this._context.save(); - this._context.translate(coordinates[0], coordinates[1]); - if (style.widthValue > style.heightValue) { - this._context.scale(style.widthValue / style.heightValue, 1); - } else { - this._context.scale(1, style.heightValue / style.widthValue); - } - - this._context.beginPath(); - this._context.arc(0, 0, r, startAngle, sweepAngle, false); - - if (this._trueCanvas) { - this._context.restore(); - } - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - if (!this._trueCanvas) { - this._context.restore(); - } - } - - this._end( ); - }, - - drawPoint: function (coordinates, style) { - style = this._getGraphicStyle(style); - if (style.widthValue === style.heightValue && style.heightValue === style.borderRadiusValue) { - this.drawArc(coordinates, 0, 360, style); - } else if (style.visibility !== "hidden" && style.opacity > 0) { - style.borderRadiusValue = Math.min(Math.min(style.widthValue, style.heightValue) / 2, style.borderRadiusValue); - coordinates[0] -= style.widthValue / 2; - coordinates[1] -= style.heightValue / 2; - this._context.beginPath(); - this._context.moveTo(coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.lineTo(coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1]); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1], coordinates[0] + style.widthValue, coordinates[1] + style.borderRadiusValue); - this._context.lineTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue, coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.lineTo(coordinates[0] + style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1] + style.heightValue, coordinates[0], coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.lineTo(coordinates[0], coordinates[1] + style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1], coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.closePath(); - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - - this._context.stroke(); - } - - this._end( ); - } - }, - - drawLineString: function (coordinates, style) { - this._drawLines([coordinates], false, style); - }, - - drawPolygon: function (coordinates, style) { - if ( !this._trueCanvas || coordinates.length === 1 ) { - // either we don't have fancy rendering or there's no need for it (no holes) - this._drawLines( coordinates, true, style ); - } else { - if ( !coordinates || !coordinates.length || coordinates[ 0 ].length < 3 ) { - // this is not a Polygon or it doesn't have a proper outer ring - return; - } - - style = this._getGraphicStyle(style); - - var pixelBbox, i, j; - - if ( style.visibility !== "hidden" && style.opacity > 0 ) { - this._blitcontext.clearRect(0, 0, this._width, this._height); - - if ( style.doFill ) { - if ( coordinates.length > 1 ) { - // stencil inner rings - this._blitcontext.globalCompositeOperation = "source-out"; - this._blitcontext.globalAlpha = 1; - - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.fill( ); - } - } - } - - // path outer ring - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ 0 ][ 0 ][ 0 ], coordinates[ 0 ][ 0 ][ 1 ] ); - - pixelBbox = [ coordinates[ 0 ][ 0 ][ 0 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 0 ] + style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] + style.strokeWidthValue ]; - - for ( i = 1; i < coordinates[ 0 ].length - 1; i++ ) { - this._blitcontext.lineTo( coordinates[ 0 ][ i ][ 0 ], coordinates[ 0 ][ i ][ 1 ] ); - - pixelBbox[ 0 ] = Math.min( coordinates[ 0 ][ i ][ 0 ] - style.strokeWidthValue, pixelBbox[ 0 ] ); - pixelBbox[ 1 ] = Math.min( coordinates[ 0 ][ i ][ 1 ] - style.strokeWidthValue, pixelBbox[ 1 ] ); - pixelBbox[ 2 ] = Math.max( coordinates[ 0 ][ i ][ 0 ] + style.strokeWidthValue, pixelBbox[ 2 ] ); - pixelBbox[ 3 ] = Math.max( coordinates[ 0 ][ i ][ 1 ] + style.strokeWidthValue, pixelBbox[ 3 ] ); - } - - this._blitcontext.closePath(); - - this._blitcontext.globalCompositeOperation = "source-out"; - if ( style.doFill ) { - // fill outer ring - this._blitcontext.fillStyle = style.fill; - this._blitcontext.globalAlpha = style.opacity * style.fillOpacity; - this._blitcontext.fill( ); - } - - this._blitcontext.globalCompositeOperation = "source-over"; - if ( style.doStroke ) { - // stroke outer ring - this._blitcontext.lineCap = this._blitcontext.lineJoin = "round"; - this._blitcontext.lineWidth = style.strokeWidthValue; - this._blitcontext.strokeStyle = style.stroke; - - this._blitcontext.globalAlpha = style.opacity * style.strokeOpacity; - this._blitcontext.stroke( ); - - if ( coordinates.length > 1 ) { - // stroke inner rings - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.stroke( ); - } - } - } - - // blit - pixelBbox[ 0 ] = Math.min( Math.max( pixelBbox[ 0 ], 0), this._width ); - pixelBbox[ 1 ] = Math.min( Math.max( pixelBbox[ 1 ], 0), this._height ); - pixelBbox[ 2 ] = Math.min( Math.max( pixelBbox[ 2 ], 0), this._width ); - pixelBbox[ 3 ] = Math.min( Math.max( pixelBbox[ 3 ], 0), this._height ); - - if ( pixelBbox[ 0 ] !== pixelBbox[ 2 ] && pixelBbox[ 1 ] !== pixelBbox[ 3 ] ) { - this._context.drawImage(this._blitcanvas, pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ], pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ] ); - - this._end( ); - } - } - } - }, - - drawBbox: function (bbox, style) { - this._drawLines([[ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ]], true, style); - }, - - drawLabel: function( coordinates, label ) { - this._labelsHtml += '
      ' + label + '
      '; - }, - - resize: function( dx, dy ) { - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - if ( this._trueCanvas ) { - this._$canvas[0].width = this._width; - this._$canvas[0].height = this._height; - - this._$canvasSceneFront.css( { - left: dx, - top: dy - } ); - - this._$canvasSceneBack.css( { - width: this._width, - height: this._height - } ); - } else { - this._$canvas.css( { - width: this._width, - height: this._height - } ); - } - - var labelPositionFront = this._$labelsContainerFront.position(); - - this._$labelsContainerFront.css( { - left: labelPositionFront.left + dx, - top: labelPositionFront.top + dy, - width: this._width, - height: this._height - } ); - - this._$labelsContainerBack.css( { - width: this._width, - height: this._height - } ); - }, - - interactiveTransform: function( origin, scale ) { - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - if ( this._trueCanvas ) { - if ( this._options.doubleBuffer && this._trueDoubleBuffer ) { - - var geographics = this; - - if ( this._requireFlip ) { - geographics._requireFlip = false; - - var oldCanvasScene = geographics._$canvasSceneFront; - - geographics._$canvasSceneFront = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ).prependTo( geographics._$elem ); - - geographics._$canvasSceneBack = oldCanvasScene.prop( "src", "" ).detach(); - } - - // transform a finished scene, can assume no drawing during these calls - this._$canvasSceneFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - - // transform labels - this._$labelsContainerFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - }, - - _canvasSceneLoad: function() { - var geographics = this; - if ( geographics._requireFlip ) { - geographics._requireFlip = false; - var oldCanvasScene = geographics._$canvasSceneFront; - - geographics._$canvasSceneFront = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prependTo( geographics._$elem ); - - geographics._$canvasSceneBack = oldCanvasScene.prop( "src", "" ).detach(); - } - }, - - _endCallback: function() { - var geographics = this; - - if ( !geographics._timeoutEnd ) { - // something has canceled the draw - return; - } - - if ( geographics._trueCanvas && geographics._options.doubleBuffer && geographics._trueDoubleBuffer ) { - geographics._$canvasSceneBack.prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ); - this._canvasSceneLoad( ); - } - - - geographics._$labelsContainerBack.html( window.toStaticHTML( geographics._labelsHtml ) ).find("a").css({ - position: "relative", - zIndex: 1, - display: "inline-block", - webkitTransform: "translateZ(0)" - }); - - var oldLabelsContainer = geographics._$labelsContainerFront; - - geographics._$labelsContainerFront = geographics._$labelsContainerBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).appendTo( geographics._$elem ); - - geographics._$labelsContainerBack = oldLabelsContainer.detach(); - - geographics._timeoutEnd = null; - }, - - _end: function( ) { - // end/finalize a scene - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - this._requireFlip = true; - - this._timeoutEnd = setTimeout( $.proxy(this._endCallback, this), 20 ); - }, - - _getGraphicStyle: function (style) { - function safeParse(value) { - value = parseInt(value, 10); - return (+value + '') === value ? +value : value; - } - - style = $.extend({}, this._options.style, style); - style.borderRadiusValue = safeParse(style.borderRadius); - style.fill = style.fill || style.color; - style.doFill = style.fill && style.fillOpacity > 0; - style.stroke = style.stroke || style.color; - style.strokeWidthValue = safeParse(style.strokeWidth); - style.doStroke = style.stroke && style.strokeOpacity > 0 && style.strokeWidthValue > 0; - style.widthValue = safeParse(style.width); - style.heightValue = safeParse(style.height); - return style; - }, - - _drawLines: function (coordinates, close, style) { - if (!coordinates || !coordinates.length || coordinates[0].length < 2) { - return; - } - - var i, j; - style = this._getGraphicStyle(style); - - if (style.visibility !== "hidden" && style.opacity > 0) { - this._context.beginPath(); - - for (i = 0; i < coordinates.length; i++) { - this._context.moveTo(coordinates[i][0][0], coordinates[i][0][1]); - for (j = 1; j < coordinates[i].length; j++) { - this._context.lineTo(coordinates[i][j][0], coordinates[i][j][1]); - } - } - - if (close) { - this._context.closePath(); - } - - if (close && style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineCap = this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - this._end( ); - } - } - }); -}(jQuery, window)); - - -(function ($, window, undefined) { - var _widgetIdSeed = 0, - _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ), - - _defaultOptions = { - bbox: [-180, -85, 180, 85], - bboxMax: [-180, -85, 180, 85], - center: [0, 0], - cursors: { - "static": "default", - pan: "url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move", - click: "crosshair", - zoom: "crosshair", - dragBox: "crosshair", - dragCircle: "crosshair", - drawPoint: "crosshair", - drawLineString: "crosshair", - drawPolygon: "crosshair", - measureLength: "crosshair", - measureArea: "crosshair" - }, - measureLabels: { - length: "{{:length.toFixed( 2 )}} m", - area: "{{:area.toFixed( 2 )}} sq m" - }, - drawStyle: {}, - shapeStyle: {}, - mode: "pan", - pannable: true, - scroll: "default", - shift: "default", - services: [ - { - "class": "osm", - type: "tiled", - src: function (view) { - return "//otile" + ((view.index % 4) + 1) + ((location.protocol === 'https:') ? "-s" : "") + ".mqcdn.com/tiles/1.0.0/osm/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; - }, - attr: "Tiles Courtesy of MapQuest " - } - ], - tilingScheme: { - tileWidth: 256, - tileHeight: 256, - levels: 18, - basePixelSize: 156543.03392799936, - origin: [-20037508.342787, 20037508.342787] - }, - axisLayout: "map", - zoom: 0, - zoomMin: 0, - zoomMax: Number.POSITIVE_INFINITY, - zoomFactor: 2, //< determines what a zoom level means - pixelSize: 0 - }; - - $.widget("geo.geomap", { - // private widget members - _$elem: undefined, //< map div for maps, service div for services - _map: undefined, //< only defined in services - _created: false, - _createdGraphics: false, - _widgetId: 0, - _tmplLengthId: "", - _tmplAreaId: "", - - _contentBounds: {}, - - _$resizeContainer: undefined, //< all elements that should match _contentBounds' size - - _$eventTarget: undefined, - _$contentFrame: undefined, - _$existingChildren: undefined, - _$attrList: undefined, - _$servicesContainer: undefined, - _$shapesContainers: undefined, //< all shapesContainer divs (map only) - - _$panContainer: undefined, //< all non-service elements that move while panning - _$shapesContainer: undefined, //< just "our" shapesContainer div (map & service) - _$drawContainer: undefined, - _$measureContainer: undefined, - _$measureLabel: undefined, - - _dpi: 96, - - _currentServices: [], //< internal copy - - _center: undefined, - _pixelSize: undefined, - _centerMax: undefined, - _pixelSizeMax: undefined, - _pixelSizeMin: undefined, - - _userGeodetic: true, - - _centerInteractive: undefined, - _pixelSizeInteractive: undefined, - _timeoutInteractive: null, - _triggerInteractive: false, - - _timeoutRefreshShapes: null, - - _loadCount: 0, - - _wheelLevel: 0, - - _fullZoomFactor: 2, //< interactiveScale factor needed to zoom a whole level - _partialZoomFactor: 1.18920711500273, //< interactiveScale factor needed to zoom a fraction of a level (the fourth root of 2) - - _mouseDown: undefined, - _inOp: undefined, - _toolPan: undefined, - _shiftDown: undefined, - _anchor: undefined, - _current: undefined, - _downDate: undefined, - _moveDate: undefined, - _clickDate: undefined, - _lastMove: undefined, - _lastDrag: undefined, - - _windowHandler: null, - _resizeTimeout: null, - - _panning: undefined, - _velocity: undefined, - _friction: undefined, - - _supportTouch: undefined, - _softDblClick: undefined, - _isTap: undefined, - _isDbltap: undefined, - - _isMultiTouch: undefined, - _multiTouchAnchor: [], //< TouchList - _multiTouchAnchorBbox: undefined, //< bbox - _multiTouchCurrentBbox: undefined, //< bbox - - _drawTimeout: null, //< used in drawPoint mode so we don't send two shape events on dbltap - _drawPixels: [], //< an array of coordinate arrays for drawing lines & polygons, in pixel coordinates - _drawCoords: [], - - _graphicShapes: [], //< an array of objects containing style object refs & GeoJSON object refs - - _initOptions: {}, - - _options: {}, - - options: $.extend({}, _defaultOptions), - - _createWidget: function (options, element) { - this._$elem = $(element); - - if (this._$elem.is(".geo-service")) { - this._graphicShapes = []; - $.Widget.prototype._createWidget.apply(this, arguments); - return; - } - - this._widgetId = _widgetIdSeed++; - this._serviceIdSeed = 0; - this._tmplLengthId = "geoMeasureLength" + this._widgetId; - this._tmplAreaId = "geoMeasureArea" + this._widgetId; - - this._$elem.addClass("geo-map").css( { - webkitTransform: "translateZ(0)" - } ); - - - this._initOptions = options || {}; - - this._forcePosition(this._$elem); - - this._$elem.css("text-align", "left"); - - var size = this._findMapSize(); - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._createChildren(); - - this._center = [ 0, 0 ]; - this._centerMax = [ 0, 0 ]; - this._centerInteractive = [ 0, 0 ]; - - this.options["pixelSize"] = this._pixelSize = this._pixelSizeMax = 156543.03392799936; - this._pixelSizeMin = this._pixelSizeMax / Math.pow( 2, 17 ); - - this._mouseDown = - this._inOp = - this._toolPan = - this._shiftDown = - this._panning = - this._isTap = - this._isDbltap = false; - - this._anchor = [ 0, 0 ]; /* mouse down */ - this._current = [ 0, 0 ]; /* mouse move no matter what */ - this._lastMove = [ 0, 0 ]; - this._lastDrag = [ 0, 0 ]; - this._velocity = [ 0, 0 ]; - - this._friction = [0.8, 0.8]; - - this._downDate = - this._moveDate = - this._clickDate = 0; - - this._drawPixels = []; - this._drawCoords = []; - this._graphicShapes = []; - - - $.Widget.prototype._createWidget.apply(this, arguments); - }, - - _create: function () { - this._options = this.options; - - if (this._$elem.is(".geo-service")) { - this._map = this._$elem.data( "geoMap" ); - this._$elem.data( "geoService", this ); - return; - } - - this._map = this; - - this._supportTouch = "ontouchend" in document; - this._softDblClick = this._supportTouch || _ieVersion === 7; - - var geomap = this, - touchStartEvent = this._supportTouch ? "touchstart mousedown" : "mousedown", - touchStopEvent = this._supportTouch ? "touchend touchcancel mouseup" : "mouseup", - touchMoveEvent = this._supportTouch ? "touchmove mousemove" : "mousemove"; - - $(document).keydown($.proxy(this._document_keydown, this)); - - this._$eventTarget.dblclick($.proxy(this._eventTarget_dblclick, this)); - - this._$eventTarget.bind(touchStartEvent, $.proxy(this._eventTarget_touchstart, this)); - - var dragTarget = (this._$eventTarget[0].setCapture) ? this._$eventTarget : $(document); - dragTarget.bind(touchMoveEvent, $.proxy(this._dragTarget_touchmove, this)); - dragTarget.bind(touchStopEvent, $.proxy(this._dragTarget_touchstop, this)); - - this._$eventTarget.mousewheel($.proxy(this._eventTarget_mousewheel, this)); - - this._windowHandler = function () { - if (geomap._resizeTimeout) { - clearTimeout(geomap._resizeTimeout); - } - geomap._resizeTimeout = setTimeout(function () { - if (geomap._created) { - geomap._$elem.geomap( "resize", true ); - } - }, 500); - }; - - $(window).resize(this._windowHandler); - - this._$drawContainer.geographics({ style: this._initOptions.drawStyle || {}, doubleBuffer: false }); - this._options["drawStyle"] = this._$drawContainer.geographics("option", "style"); - - this._$shapesContainer.geographics( { style: this._initOptions.shapeStyle || { } } ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - - if (this._initOptions) { - // always init tilingScheme right away, even if it's null - if ( this._initOptions.tilingScheme !== undefined ) { - this._setOption("tilingScheme", this._initOptions.tilingScheme || null, false); - } - - if ( this._initOptions.services ) { - // jQuery UI Widget Factory merges user services with our default, we want to clobber the default - this._options[ "services" ] = $.merge( [ ], this._initOptions.services ); - } - if (this._initOptions.bboxMax) { - this._setOption("bboxMax", this._initOptions.bboxMax, false); - this._setOption("bbox", this._initOptions.bboxMax, false); - } - if (this._initOptions.zoomMin !== undefined) { - this._setOption("zoomMin", this._initOptions.zoomMin, false); - } - if (this._initOptions.zoomMax !== undefined) { - this._setOption("zoomMax", this._initOptions.zoomMax, false); - } - if (this._initOptions.zoomFactor !== undefined) { - this._setOption("zoomFactor", this._initOptions.zoomFactor, false); - this._fullZoomFactor = this._initOptions.zoomFactor; - this._partialZoomFactor = Math.pow(4, 1 / this._fullZoomFactor); // 4th root of full - } - if (this._initOptions.bbox) { - this._setOption("bbox", this._initOptions.bbox, false); - } - if (this._initOptions.center) { - this._setOption("center", this._initOptions.center, false); - } - if (this._initOptions.zoom !== undefined) { - this._setOption("zoom", this._initOptions.zoom, false); - } - } - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._createServices(); - this._refresh(); - - this._created = true; - }, - - _setOption: function (key, value, refresh) { - if ( key === "pixelSize" ) { - return; - } - - refresh = (refresh === undefined || refresh); - - if ( this._$elem.is( ".geo-map" ) ) { - this._panFinalize(); - } - - var center, pixelSize, bbox, zoom; - - switch (key) { - case "bbox": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2]; - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height); - - // clamp to zoom - zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( center, pixelSize ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( center, pixelSize, false, refresh ); - } - - value = this._getBbox( center, pixelSize ); - break; - - case "bboxMax": - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - break; - - case "center": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( value, this._pixelSizeInteractive ); - this._interactiveTransform( ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( value, this._pixelSize, false, refresh ); - } - break; - - case "measureLabels": - value = $.extend( this._options[ "measureLabels" ], value ); - - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - break; - - case "drawStyle": - if (this._$drawContainer) { - this._$drawContainer.geographics("option", "style", value); - value = this._$drawContainer.geographics("option", "style"); - } - break; - - case "shapeStyle": - if ( this._$elem.is( ".geo-service" ) && !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("option", "style", value); - value = this._$shapesContainer.geographics("option", "style"); - } - break; - - case "mode": - this._resetDrawing( ); - this._$eventTarget.css("cursor", this._options["cursors"][value]); - break; - - case "zoom": - if ( this._created ) { - this._setZoom(value, false, refresh); - } else { - value = Math.max( value, 0 ); - this._setCenterAndSize( this._center, this._getPixelSize( value ), false, refresh ); - } - break; - } - - $.Widget.prototype._setOption.apply(this, arguments); - - switch ( key ) { - case "bbox": - case "center": - if ( this._userGeodetic ) { - this._options[ "bbox" ] = $.geo.proj.toGeodetic( this._options[ "bbox" ] ); - this._options[ "center" ] = $.geo.proj.toGeodetic( this._center ); - } - break; - - case "tilingScheme": - if ( value !== null ) { - this._pixelSizeMax = this._getPixelSize( 0 ); - this._pixelSizeMin = this._getPixelSize( value.pixelSizes ? value.pixelSizes.length - 1 : value.levels - 1 ); - this._centerMax = [ - value.origin[ 0 ] + this._pixelSizeMax * value.tileWidth / 2, - value.origin[ 1 ] + this._pixelSizeMax * value.tileHeight / 2 - ]; - } - break; - - case "bboxMax": - if ( this._userGeodetic ) { - bbox = $.geo.proj.fromGeodetic( value ); - } else { - bbox = value; - } - - this._centerMax = $.geo.center( bbox ); - this._pixelSizeMax = Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - this._pixelSizeMin = 1; - break; - - case "services": - this._createServices(); - if (refresh) { - this._refresh(); - this._refreshAllShapes(); - } - break; - - case "shapeStyle": - if ( refresh && this._createdGraphics ) { - this._$shapesContainer.geographics("clear"); - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - break; - } - }, - - destroy: function () { - if ( this._$elem.is(".geo-service") ) { - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - } - } else { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - - this._created = false; - - $(window).unbind("resize", this._windowHandler); - - for ( var i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - - this._$drawContainer.geographics("destroy"); - this._$drawContainer = undefined; - - this._$existingChildren.detach(); - this._$elem.html(""); - this._$elem.append(this._$existingChildren); - this._$elem.removeClass("geo-map"); - } - - $.Widget.prototype.destroy.apply(this, arguments); - }, - - toMap: function (p) { - p = this._toMap(p); - return this._userGeodetic ? $.geo.proj.toGeodetic(p) : p; - }, - - toPixel: function ( p, _center /* Internal Use Only */, _pixelSize /* Internal Use Only */ ) { - return this._toPixel( $.geo.proj ? $.geo.proj.fromGeodetic( p ) : p, _center, _pixelSize ); - }, - - opacity: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "opacity", value, this._$elem ); - } else { - if ( value >= 0 || value <= 1 ) { - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - service.style.opacity = value; - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - $.geo[ "_serviceTypes" ][ service.type ].opacity( this, service ); - } - } - } - } - }, - - toggle: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "toggle", value, this._$elem ); - } else { - - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - if ( value === undefined ) { - // toggle visibility - value = ( service.style.visibility !== "visible" ); - } - - service.style.visibility = ( value ? "visible" : "hidden" ); - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - service.serviceContainer.toggle( value ); - - if ( value ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service ); - } - } - } - } - }, - - zoom: function (numberOfLevels) { - if (numberOfLevels !== null) { - this._setZoom(this._options["zoom"] + numberOfLevels, false, true); - } - }, - - refresh: function ( force, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "refresh", force, this._$elem ); - } else { - this._refresh( force, _serviceContainer ); - this._refreshAllShapes( ); - } - }, - - resize: function ( _trigger /* Internal Use Only */ ) { - var size = this._findMapSize(), - dx = size["width"]/2 - this._contentBounds.width/2, - dy = size["height"]/2 - this._contentBounds.height/2, - i; - - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._$resizeContainer.css( { - width: size["width"], - height: size["height"] - } ); - - for (i = 0; i < this._currentServices.length; i++) { - $.geo["_serviceTypes"][this._currentServices[i].type].resize(this, this._currentServices[i], dx, dy); - } - - this._$elem.find( ".geo-graphics" ).css( { - width: size["width"], - height: size["height"] - }).geographics( "resize", dx, dy ); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._setCenterAndSize(this._center, this._pixelSize, _trigger, true); - }, - - append: function ( shape /* , style, label, refresh */ ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - if ( !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - var shapes, arg, i, realStyle, realLabel, realRefresh; - - if ( $.isArray( shape ) ) { - shapes = shape; - } else if ( shape.type === "FeatureCollection" ) { - shapes = shape.features; - } else { - shapes = [ shape ]; - } - - for ( i = 1; i < arguments.length; i++ ) { - arg = arguments[ i ]; - - if ( arg !== null ) { - if ( typeof arg === "object" ) { - realStyle = arg; - } else if ( typeof arg === "number" || typeof arg === "string" ) { - realLabel = arg; - } else if ( typeof arg === "boolean" ) { - realRefresh = arg; - } - } - } - - for ( i = 0; i < shapes.length; i++ ) { - if ( !$.data( shapes[ i ], "geoBbox" ) ) { - var bbox = $.geo.bbox( shapes[ i ] ); - if ( $.geo.proj && $.geo._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - $.data( shapes[ i ], "geoBbox", bbox ); - } - - this._graphicShapes.push( { - shape: shapes[ i ], - style: realStyle, - label: realLabel - } ); - } - - if ( realRefresh === undefined || realRefresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - empty: function ( refresh ) { - this._graphicShapes = []; - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - }, - - find: function ( selector, pixelTolerance ) { - var isPoint = $.isPlainObject( selector ), - //searchPixel = isPoint ? this._map.toPixel( selector.coordinates ) : undefined, - mapTol = this._map._pixelSize * pixelTolerance, - result = [], - graphicShape, - geometries, - curGeom, - i = 0; - - for ( ; i < this._graphicShapes.length; i++ ) { - graphicShape = this._graphicShapes[ i ]; - - if ( isPoint ) { - if ( graphicShape.shape.type === "Point" ) { - if ( $.geo.distance( graphicShape.shape, selector ) <= mapTol ) { - result.push( graphicShape.shape ); - } - } else { - var bbox = $.data( graphicShape.shape, "geoBbox" ), - bboxPolygon = { - type: "Polygon", - coordinates: [ [ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ] ] - }, - projectedPoint = { - type: "Point", - coordinates: $.geo.proj && $.geo._isGeodetic( selector.coordinates ) ? $.geo.proj.fromGeodetic( selector.coordinates ) : selector.coordinates - }; - - if ( $.geo.distance( bboxPolygon, projectedPoint, true ) <= mapTol ) { - geometries = $.geo._basic( graphicShape.shape ); - for ( curGeom = 0; curGeom < geometries.length; curGeom++ ) { - if ( $.geo.distance( geometries[ curGeom ], selector ) <= mapTol ) { - result.push( graphicShape.shape ); - break; - } - } - } - } - } else { - result.push( graphicShape.shape ); - } - } - - if ( this._$elem.is( ".geo-map" ) ) { - this._$elem.find( ".geo-service" ).each( function( ) { - result = $.merge( result, $( this ).geomap( "find", selector, pixelTolerance ) ); - } ); - } - - return result; - }, - - remove: function ( shape, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - var shapes = $.isArray( shape ) ? shape : [ shape ], - rest; - - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - if ( $.inArray( this._graphicShapes[ i ].shape, shapes ) >= 0 ) { - rest = this._graphicShapes.slice( i + 1 ); - this._graphicShapes.length = i; - this._graphicShapes.push.apply( this._graphicShapes, rest ); - i--; - } - } - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - _getBbox: function (center, pixelSize) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - // calculate the internal bbox - var halfWidth = this._contentBounds[ "width" ] / 2 * pixelSize, - halfHeight = this._contentBounds[ "height" ] / 2 * pixelSize; - return [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - }, - - _setBbox: function (value /* , trigger, refresh */ ) { - var center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2], - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height), - zoom = this._getZoom( center, pixelSize ); - - // clamp to zoom - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._setInteractiveCenterAndSize( center, pixelSize ); - this._interactiveTransform( ); - }, - - _getBboxMax: function () { - // calculate the internal bboxMax - var halfWidth = this._contentBounds["width"] / 2 * this._pixelSizeMax, - halfHeight = this._contentBounds["height"] / 2 * this._pixelSizeMax; - return [this._centerMax[0] - halfWidth, this._centerMax[1] - halfHeight, this._centerMax[0] + halfWidth, this._centerMax[1] + halfHeight]; - }, - - _getCenter: function () { - return this._center; - }, - - _getContentBounds: function () { - return this._contentBounds; - }, - - _getServicesContainer: function () { - return this._$servicesContainer; - }, - - _getZoom: function ( center, pixelSize ) { - // calculate the internal zoom level, vs. public zoom property - // this does not take zoomMin or zoomMax into account - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var tilingScheme = this._options["tilingScheme"]; - if ( tilingScheme ) { - if ( tilingScheme.pixelSizes ) { - var roundedPixelSize = Math.floor(pixelSize * 1000), - levels = tilingScheme.pixelSizes.length, - i = levels - 1; - - for ( ; i >= 0; i-- ) { - if ( Math.floor( tilingScheme.pixelSizes[ i ] * 1000 ) >= roundedPixelSize ) { - return i; - } - } - - return 0; - } else { - return Math.round( Math.log( tilingScheme.basePixelSize / pixelSize) / Math.log( 2 ) ); - } - } else { - var ratio = this._contentBounds["width"] / this._contentBounds["height"], - bbox = $.geo.reaspect( this._getBbox( center, pixelSize ), ratio, true ), - bboxMax = $.geo.reaspect(this._getBboxMax(), ratio, true); - - return Math.round( Math.log($.geo.width(bboxMax, true) / $.geo.width(bbox, true)) / Math.log(this._fullZoomFactor) ); - } - }, - - _setZoom: function ( value, trigger /* , refresh */ ) { - // set the map widget's zoom, taking zoomMin and zoomMax into account - this._clearInteractiveTimeout( ); - - value = Math.min( Math.max( value, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ); - - this._setInteractiveCenterAndSize( this._centerInteractive, this._getPixelSize( value ) ); - this._interactiveTransform( ); - this._setInteractiveTimeout( trigger ); - }, - - _createChildren: function () { - this._$existingChildren = this._$elem.children(); - - this._forcePosition(this._$existingChildren); - - this._$existingChildren.detach().css( { - mozUserSelect: "none" - } ); - - - var contentSizeCss = "width:" + this._contentBounds["width"] + "px; height:" + this._contentBounds["height"] + "px; margin:0; padding:0;", - contentPosCss = "position:absolute; left:0; top:0;"; - - this._$elem.prepend( window.toStaticHTML( '
      ' ) ); - this._$eventTarget = this._$contentFrame = this._$elem.children(':first'); - - this._$contentFrame.append('
      '); - this._$servicesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append( '
        ' ); - this._$attrList = this._$contentFrame.children( ":last" ); - - this._$contentFrame.append('
        '); - this._$drawContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
        '); - this._$measureContainer = this._$contentFrame.children(':last'); - this._$measureLabel = this._$measureContainer.children(); - - this._$contentFrame.append('
        '); - this._$shapesContainer = this._$contentFrame.children(':last'); - - this._$panContainer = $( [ this._$shapesContainer[ 0 ], this._$drawContainer[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$resizeContainer = $( [ this._$contentFrame[ 0 ], this._$servicesContainer[ 0 ], this._$eventTarget[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$contentFrame.append(this._$existingChildren); - - if ( ! $("#geo-measure-style").length ) { - $("head").prepend( window.toStaticHTML( '' ) ); - } - }, - - _createServices: function () { - var service, i; - - for ( i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap( "destroy" ); - $.geo[ "_serviceTypes" ][ this._currentServices[ i ].type ].destroy( this, this._$servicesContainer, this._currentServices[ i ] ); - } - - this._currentServices = [ ]; - this._$servicesContainer.html( "" ); - this._$attrList.html( "" ); - - for ( i = 0; i < this._options[ "services" ].length; i++ ) { - service = this._currentServices[ i ] = $.extend( { }, this._options[ "services" ][ i ] ); - - // keep a reference to the original - service.serviceObject = this._options[ "services" ][ i ]; - - // default the service style property on our copy - service.style = $.extend( { - visibility: "visible", - opacity: 1 - }, service.style ); - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = 'class="geo-service ' + ( service["class"] ? service["class"] : '' ) + '"', - scHtml = '
        ', - serviceContainer; - - this._$servicesContainer.append( window.toStaticHTML( scHtml ) ); - serviceContainer = this._$servicesContainer.children( ":last" ); - service.serviceContainer = serviceContainer; - - $.geo[ "_serviceTypes" ][ service.type ].create( this, serviceContainer, service, i ); - - serviceContainer.data( "geoMap", this ).geomap(); - - if ( service.attr ) { - this._$attrList.append( '
      • ' + service.attr + '
      • ' ); - } - } - - // start with our map-level shapesContainer - this._$shapesContainers = this._$shapesContainer; - - this._$attrList.find( "a" ).css( { - position: "relative", - zIndex: 1, - display: "inline-block", - webkitTransform: "translateZ(0)" - } ); - }, - - _createServiceGraphics: function( ) { - // only called in the context of a service-level geomap - var $contentFrame = this._$elem.closest( ".geo-content-frame" ); - this._$elem.append('
        '); - this._$shapesContainer = this._$elem.children(':last'); - - this._map._$shapesContainers = this._map._$shapesContainers.add( this._$shapesContainer ); - - this._$shapesContainer.geographics( ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - }, - - _refreshDrawing: function ( ) { - this._$drawContainer.geographics("clear"); - - if ( this._drawPixels.length > 0 ) { - var mode = this._options[ "mode" ], - pixels = this._drawPixels, - coords = this._drawCoords, - label, - labelShape, - labelPixel, - widthOver, - heightOver; - - switch ( mode ) { - case "measureLength": - mode = "drawLineString"; - labelShape = { - type: "LineString", - coordinates: coords - }; - label = $.render[ this._tmplLengthId ]( { length: $.geo.length( labelShape, true ) } ); - labelPixel = $.merge( [], pixels[ pixels.length - 1 ] ); - break; - - case "measureArea": - mode = "drawPolygon"; - - labelShape = { - type: "Polygon", - coordinates: [ $.merge( [ ], coords ) ] - }; - labelShape.coordinates[ 0 ].push( coords[ 0 ] ); - - label = $.render[ this._tmplAreaId ]( { area: $.geo.area( labelShape, true ) } ); - labelPixel = this._toPixel( $.geo.centroid( labelShape ).coordinates ); - pixels = [ pixels ]; - break; - - case "drawPolygon": - pixels = [ pixels ]; - break; - } - - this._$drawContainer.geographics( mode, pixels ); - - if ( label ) { - this._$measureLabel.html( label ); - - widthOver = this._contentBounds.width - ( this._$measureLabel.outerWidth( true ) + labelPixel[ 0 ] ); - heightOver = this._contentBounds.height - ( this._$measureLabel.outerHeight( true ) + labelPixel[ 1 ] ); - - if ( widthOver < 0 ) { - labelPixel[ 0 ] += widthOver; - } - - if ( heightOver < 0 ) { - labelPixel[ 1 ] += heightOver; - } - - this._$measureLabel.css( { - left: Math.max( labelPixel[ 0 ], 0 ), - top: Math.max( labelPixel[ 1 ], 0 ) - } ).show(); - } - } - }, - - _resetDrawing: function () { - this._drawPixels = []; - this._drawCoords = []; - this._$drawContainer.geographics("clear"); - this._$measureLabel.hide(); - }, - - _refreshAllShapes: function ( ) { - this._timeoutRefreshShapes = null; - - var service, - geoService, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - geoService = service.serviceContainer.data( "geoService" ); - - if ( geoService._createdGraphics ) { - geoService._$shapesContainer.geographics( "clear" ); - if ( geoService._graphicShapes.length > 0 ) { - geoService._refreshShapes( geoService._$shapesContainer, geoService._graphicShapes, geoService._graphicShapes, geoService._graphicShapes ); - } - } - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics( "clear" ); - if ( this._graphicShapes.length > 0 ) { - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - } - }, - - - _refreshShapes: function (geographics, shapes, styles, labels, center, pixelSize) { - var i, mgi, - shape, - shapeBbox, - style, - label, - hasLabel, - labelPixel, - centroid, - bbox = this._map._getBbox(center, pixelSize); - - for (i = 0; i < shapes.length; i++) { - shape = shapes[i].shape || shapes[i]; - shape = shape.geometry || shape; - shapeBbox = $.data(shape, "geoBbox"); - - if ( shapeBbox && $.geo._bboxDisjoint( bbox, shapeBbox ) ) { - continue; - } - - style = $.isArray(styles) ? styles[i].style : styles; - label = $.isArray(labels) ? labels[i].label : labels; - hasLabel = ( label !== undefined ); - labelPixel = undefined; - centroid = $.geo.centroid( shape ); - - switch (shape.type) { - case "Point": - labelPixel = this._map.toPixel( shape.coordinates, center, pixelSize ); - this._$shapesContainer.geographics("drawPoint", labelPixel, style); - break; - case "LineString": - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.pointAlong( shape, 0.5 ).coordinates, center, pixelSize ); - } - break; - case "Polygon": - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiPoint": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPoint", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiLineString": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiPolygon": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - - case "GeometryCollection": - this._refreshShapes(geographics, shape.geometries, style, label, center, pixelSize); - break; - } - - if ( hasLabel && labelPixel ) { - this._$shapesContainer.geographics( "drawLabel", labelPixel, label ); - } - } - }, - - _findMapSize: function () { - // really, really attempt to find a size for this thing - // even if it's hidden (look at parents) - var size = { width: 0, height: 0 }, - sizeContainer = this._$elem; - - while (sizeContainer.size() && !(size["width"] > 0 && size["height"] > 0)) { - size = { width: sizeContainer.width(), height: sizeContainer.height() }; - if (size["width"] <= 0 || size["height"] <= 0) { - size = { width: parseInt(sizeContainer.css("width"), 10), height: parseInt(sizeContainer.css("height"), 10) }; - } - sizeContainer = sizeContainer.parent(); - } - return size; - }, - - _forcePosition: function (elem) { - var cssPosition = elem.css("position"); - if (cssPosition !== "relative" && cssPosition !== "absolute" && cssPosition !== "fixed") { - elem.css("position", "relative"); - } - }, - - _getPixelSize: function ( zoom ) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme !== null) { - if (zoom === 0) { - return tilingScheme.pixelSizes ? tilingScheme.pixelSizes[0] : tilingScheme.basePixelSize; - } - - zoom = Math.round(zoom); - zoom = Math.max(zoom, 0); - var levels = tilingScheme.pixelSizes ? tilingScheme.pixelSizes.length : tilingScheme.levels; - zoom = Math.min(zoom, levels - 1); - - if ( tilingScheme.pixelSizes ) { - return tilingScheme.pixelSizes[zoom]; - } else { - return tilingScheme.basePixelSize / Math.pow(2, zoom); - } - } else { - var bbox = $.geo.scaleBy( this._getBboxMax(), 1 / Math.pow( this._fullZoomFactor, zoom ), true ); - return Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - } - }, - - _getZoomCenterAndSize: function ( anchor, zoomDelta, full ) { - var zoomFactor = ( full ? this._fullZoomFactor : this._partialZoomFactor ), - scale = Math.pow( zoomFactor, -zoomDelta ), - pixelSize = this._pixelSizeInteractive * scale; - - // clamp to min/max pixelSize - pixelSize = Math.min( Math.max( pixelSize, this._pixelSizeMin ), this._pixelSizeMax ); - - var zoom = this._getZoom(this._centerInteractive, pixelSize); - - // clamp to zoom - if ( full && this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoomDelta < 0 && zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._pixelSizeInteractive; - } else if ( zoomDelta > 0 && zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._pixelSizeInteractive; - } - } - - var ratio = pixelSize / this._pixelSizeInteractive, - anchorMapCoord = this._toMap( anchor, this._centerInteractive, this._pixelSizeInteractive ), - centerDelta = [(this._centerInteractive[0] - anchorMapCoord[0]) * ratio, (this._centerInteractive[1] - anchorMapCoord[1]) * ratio], - scaleCenter = [anchorMapCoord[0] + centerDelta[0], anchorMapCoord[1] + centerDelta[1]]; - - return { pixelSize: pixelSize, center: scaleCenter }; - }, - - _panFinalize: function () { - if (this._panning) { - this._velocity = [0, 0]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._inOp = false; - this._anchor = this._current; - this._mouseDown = this._toolPan = this._panning = false; - } - }, - - _panMove: function () { - if ( ! this._options[ "pannable" ] ) { - return; - } - - var dx = this._current[0] - this._lastDrag[0], - dy = this._current[1] - this._lastDrag[1]; - - if (this._toolPan || dx > 3 || dx < -3 || dy > 3 || dy < -3) { - if (!this._toolPan) { - this._toolPan = true; - this._$eventTarget.css("cursor", this._options["cursors"]["pan"]); - } - - if (this._mouseDown) { - this._velocity = [dx, dy]; - } - - if (dx !== 0 || dy !== 0) { - this._panning = true; - this._lastDrag = this._current; - - this._centerInteractive[ 0 ] -= ( dx * this._pixelSizeInteractive ); - this._centerInteractive[ 1 ] += ( ( this._options[ "axisLayout" ] === "image" ? -1 : 1 ) * dy * this._pixelSizeInteractive ); - this._setInteractiveCenterAndSize( this._centerInteractive, this._pixelSizeInteractive ); - this._interactiveTransform( ); - } - } - }, - - _clearInteractiveTimeout: function() { - if ( this._timeoutRefreshShapes ) { - clearTimeout( this._timeoutRefreshShapes ); - this._timeoutRefreshShapes = null; - } - - if ( this._timeoutInteractive ) { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - return true; - } else { - this._centerInteractive[ 0 ] = this._center[ 0 ]; - this._centerInteractive[ 1 ] = this._center[ 1 ]; - this._pixelSizeInteractive = this._pixelSize; - return false; - } - }, - - _interactiveTransform: function( ) { - var service, - - scalePixelSize = this._pixelSize, - scaleRatio = scalePixelSize / this._pixelSizeInteractive; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = this._toMap( [ 0, 0 ] ), - newPixelPoint = this._toPixel( oldMapOrigin, this._centerInteractive, this._pixelSizeInteractive ); - - - this._$shapesContainers.geographics("interactiveTransform", newPixelPoint, scaleRatio); - } - - for ( var i = 0; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo[ "_serviceTypes" ][ service.type ].interactiveTransform( this, service, this._centerInteractive, this._pixelSizeInteractive ); - } - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel( this._drawCoords, this._centerInteractive, this._pixelSizeInteractive ); - this._refreshDrawing(); - } - }, - - _interactiveTimeout: function( ) { - if ( this._isMultiTouch ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - } else if ( this._created && this._timeoutInteractive ) { - this._setCenterAndSize( this._centerInteractive, this._pixelSizeInteractive, this._triggerInteractive, true ); - this._timeoutInteractive = null; - this._triggerInteractive = false; - - this._timeoutRefreshShapes = setTimeout( $.proxy( this._refreshAllShapes, this ), 128 ); - } - }, - - _setInteractiveTimeout: function( trigger ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - this._triggerInteractive |= trigger; - }, - - _refresh: function ( force, _serviceContainer ) { - var service, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service, force ); - } - } - }, - - _setInteractiveCenterAndSize: function ( center, pixelSize ) { - // set the temporary (interactive) center & size - // also, update the public-facing options - // this does not take zoomMin or zoomMax into account - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - this._pixelSizeInteractive = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox( center, pixelSize ) ); - this._options["center"] = $.geo.proj.toGeodetic( center ); - } else { - this._options["bbox"] = this._getBbox( center, pixelSize ); - this._options["center"][ 0 ] = center[ 0 ]; - this._options["center"][ 1 ] = center[ 1 ]; - } - - this._options["pixelSize"] = pixelSize; - this._options["zoom"] = this._getZoom( center, pixelSize ); - }, - - _setCenterAndSize: function (center, pixelSize, trigger, refresh) { - if ( ! $.isArray( center ) || center.length !== 2 || typeof center[ 0 ] !== "number" || typeof center[ 1 ] !== "number" ) { - return; - } - - // the final call during any extent change - // only called by timeoutInteractive & resize - // clamp to zoom - var zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - - if ( this._created ) { - // one last interactiveTransform to put pinched map into place - this._interactiveTransform( ); - } - - this._options["pixelSize"] = this._pixelSize = pixelSize; - - this._center[ 0 ] = center[ 0 ]; - this._center[ 1 ] = center[ 1 ]; - - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox() ); - this._options["center"] = $.geo.proj.toGeodetic( this._center ); - } else { - this._options["bbox"] = this._getBbox(); - this._options["center"] = $.merge( [ ], center ); - } - - this._options["zoom"] = zoom; - - if (trigger) { - this._trigger("bboxchange", window.event, { bbox: $.merge( [ ], this._options["bbox"] ) }); - } - - if (refresh) { - this._refresh(); - this._refreshAllShapes( ); - this._refreshDrawing(); - } - }, - - _requestQueued: function ( ) { - if ( this._loadCount === 0 ) { - this._trigger( "loadstart", window.event ); - } - this._loadCount++; - }, - - _requestComplete: function ( ) { - this._loadCount--; - if ( this._loadCount <= 0 ) { - this._loadCount = 0; - this._trigger( "loadend", window.event ); - } - }, - - _toMap: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - xRatio = $.geo.width(bbox, true) / width, - yRatio = $.geo.height(bbox, true) / height, - yOffset, - image = this._options[ "axisLayout" ] === "image", - result = [], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - yOffset = (p[ i ][ j ][ k ][1] * yRatio); - result[ i ][ j ][ k ] = [ - bbox[ 0 ] + ( p[ i ][ j ][ k ][ 0 ] * xRatio ), - image ? bbox[ 1 ] + yOffset : bbox[ 3 ] - yOffset - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _toPixel: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - bboxWidth = $.geo.width(bbox, true), - bboxHeight = $.geo.height(bbox, true), - image = this._options[ "axisLayout" ] === "image", - xRatio = width / bboxWidth, - yRatio = height / bboxHeight, - result = [ ], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = [ - Math.round( ( p[ i ][ j ][ k ][ 0 ] - bbox[ 0 ] ) * xRatio ), - Math.round( ( image ? p[ i ][ j ][ k ][ 1 ] - bbox[ 1 ] : bbox[ 3 ] - p[ i ][ j ][ k ][ 1 ] ) * yRatio ) - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _document_keydown: function (e) { - var len = this._drawCoords.length; - if (len > 0 && e.which === 27) { - if (len <= 2) { - this._resetDrawing(); - this._inOp = false; - } else { - this._drawCoords[len - 2] = $.merge( [], this._drawCoords[ len - 1 ] ); - this._drawPixels[len - 2] = $.merge( [], this._drawPixels[ len - 1 ] ); - - this._drawCoords.length--; - this._drawPixels.length--; - - this._refreshDrawing(); - } - } - }, - - _eventTarget_dblclick_zoom: function(e) { - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - this._trigger("dblclick", e, { type: "Point", coordinates: this._toMap(this._current, this._centerInteractive, this._pixelSizeInteractive ) }); - - if (!e.isDefaultPrevented()) { - var centerAndSize = this._getZoomCenterAndSize(this._current, 1, true ); - - this._setInteractiveCenterAndSize( centerAndSize.center, centerAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - }, - - _eventTarget_dblclick: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - switch (this._options["mode"]) { - case "drawLineString": - case "measureLength": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] === this._drawCoords[1][0] && - this._drawCoords[0][1] === this._drawCoords[1][1] ) ) { - this._drawCoords.length--; - this._trigger( "shape", e, { - type: "LineString", - coordinates: this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords - } ); - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "drawPolygon": - case "measureArea": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] === this._drawCoords[1][0] && - this._drawCoords[0][1] === this._drawCoords[1][1] ) ) { - var endIndex = this._drawCoords.length - 1; - if (endIndex > 2) { - this._drawCoords[endIndex] = $.merge( [], this._drawCoords[0] ); - this._trigger( "shape", e, { - type: "Polygon", - coordinates: [ this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords ] - } ); - } - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - default: - this._eventTarget_dblclick_zoom(e); - break; - } - - this._inOp = false; - }, - - _eventTarget_touchstart: function (e) { - if ( typeof( document.elementFromPoint ) !== "undefined" ) { - var elFromPt = document.elementFromPoint( e.pageX, e.pageY ); - if ( elFromPt && elFromPt.nodeName === "A" ) { - return; - } - } - - var mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ); - - if ( mode === "static" ) { - return; - } - - if ( !this._supportTouch && e.which !== 1 ) { - return; - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var offset = $(e.currentTarget).offset(), - touches = e.originalEvent.changedTouches; - - if ( this._supportTouch && touches ) { - this._multiTouchAnchor = $.merge( [ ], touches ); - - this._isMultiTouch = this._multiTouchAnchor.length > 1; - - if ( this._isMultiTouch ) { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - touches[1].pageX - offset.left, - touches[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ touches[0].pageX - offset.left, touches[0].pageY - offset.top ]; - } - } else { - this._current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - var downDate = $.now(); - if (downDate - this._downDate < 750) { - if (this._isTap) { - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance > 8) { - this._isTap = false; - } else { - this._current = $.merge( [ ], this._anchor ); - } - } - - if (this._isDbltap) { - this._isDbltap = false; - } else { - this._isDbltap = this._isTap; - } - } else { - this._isDbltap = false; - } - this._isTap = true; - this._downDate = downDate; - } - - this._mouseDown = true; - this._anchor = $.merge( [ ], this._current ); - - if (!this._inOp && e.shiftKey && shift !== "off") { - this._shiftDown = true; - this._$eventTarget.css( "cursor", this._options[ "cursors" ][ shift === "default" ? defaultShift : shift ] ); - } else if ( !this._isMultiTouch && ( this._options[ "pannable" ] || mode === "dragBox" || mode === "dragCircle" ) ) { - this._inOp = true; - - if ( mode !== "zoom" && mode !== "dragBox" && mode !== "dragCircle" ) { - this._lastDrag = this._current; - - if (e.currentTarget.setCapture) { - e.currentTarget.setCapture(); - } - } - } - - e.preventDefault(); - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - }, - - _dragTarget_touchmove: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - var doInteractiveTimeout = false; - if ( this._mouseDown ) { - doInteractiveTimeout = this._clearInteractiveTimeout( ); - } - - var offset = this._$eventTarget.offset(), - drawCoordsLen = this._drawCoords.length, - touches = e.originalEvent.changedTouches, - current, - i = 0; - - if ( this._supportTouch && touches ) { - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 && touches[ 0 ].identifier !== this._multiTouchAnchor[ 0 ].identifier ) { - // switch to multitouch - this._mouseDown = false; - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( touches[ 0 ] ); - - - - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._mouseDown = true; - this._anchor = this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - if ( this._isMultiTouch ) { - - for ( ; i < touches.length; i++ ) { - if ( touches[ i ].identifier === this._multiTouchAnchor[ 0 ].identifier ) { - this._multiTouchCurrentBbox[ 0 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = touches[ i ].pageY - offset.top; - } else if ( touches[ i ].identifier === this._multiTouchAnchor[ 1 ].identifier ) { - this._multiTouchCurrentBbox[ 2 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = touches[ i ].pageY - offset.top; - } - } - - var anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ), - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - var wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - var delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - var pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (current[0] === this._lastMove[0] && current[1] === this._lastMove[1]) { - if ( this._inOp ) { - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } else { - // fixes: [bug] highlight pop - return false; - } - } - - if ( _ieVersion === 7 ) { - this._isDbltap = this._isTap = false; - } - - if (this._mouseDown) { - this._current = current; - this._moveDate = $.now(); - } - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - var mode = this._options["mode"], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - dx, dy, circleSize; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - switch (mode) { - case "zoom": - case "dragBox": - if ( this._mouseDown ) { - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawBbox", [ - this._anchor[ 0 ], - this._anchor[ 1 ], - current[ 0 ], - current[ 1 ] - ] ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "dragCircle": - if ( this._mouseDown ) { - dx = current[ 0 ] - this._anchor[ 0 ]; - dy = current[ 1 ] - this._anchor[ 1 ]; - circleSize = Math.sqrt( ( dx * dx) + ( dy * dy ) ) * 2; - //circleSize = Math.max( Math.abs( current[ 0 ] - this._anchor[ 0 ] ), Math.abs( current[ 1 ] - this._anchor[ 1 ] ) ) * 2; - - // not part of _refreshDrawing - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawArc", this._anchor, 0, 360, { - width: circleSize, - height: circleSize - } ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - if (drawCoordsLen > 0) { - this._drawCoords[drawCoordsLen - 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[drawCoordsLen - 1] = current; - - this._refreshDrawing(); - } - - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - default: - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - } - - this._lastMove = current; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchstop: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if ( !this._mouseDown ) { - if ( _ieVersion === 7 ) { - // ie7 doesn't appear to trigger dblclick on this._$eventTarget, - // we fake regular click here to cause soft dblclick - this._eventTarget_touchstart(e); - } else { - // Chrome & Firefox trigger a rogue mouseup event when doing a dblclick maximize in Windows(/Linux?) - // ignore it - return; - } - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var mouseWasDown = this._mouseDown, - wasToolPan = this._toolPan, - offset = this._$eventTarget.offset(), - mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - current, i, clickDate, - dx, dy, - coordBuffer, - triggerShape; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - if (this._supportTouch && e.originalEvent.changedTouches) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - this._multiTouchAnchor = []; - this._inOp = false; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - if (this._isTap) { - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - if (Math.sqrt((dx * dx) + (dy * dy)) <= 8) { - current = $.merge( [ ], this._anchor ); - } - } - } - - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._shiftDown = this._mouseDown = this._toolPan = false; - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isMultiTouch = false; - - this._wheelLevel = 0; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return; - } - - if (document.releaseCapture) { - document.releaseCapture(); - } - - if (mouseWasDown) { - clickDate = $.now(); - this._current = current; - - switch ( mode ) { - case "zoom": - case "dragBox": - if ( dx !== 0 || dy !== 0 ) { - var minSize = this._pixelSize * 6, - bboxCoords = this._toMap( [ [ - Math.min( this._anchor[ 0 ], current[ 0 ] ), - Math.max( this._anchor[ 1 ], current[ 1 ] ) - ], [ - Math.max( this._anchor[ 0 ], current[ 0 ] ), - Math.min( this._anchor[ 1 ], current[ 1 ] ) - ] - ] ), - bbox = [ - bboxCoords[0][0], - bboxCoords[0][1], - bboxCoords[1][0], - bboxCoords[1][1] - ]; - - if ( mode === "zoom" ) { - if ( ( bbox[2] - bbox[0] ) < minSize && ( bbox[3] - bbox[1] ) < minSize ) { - bbox = $.geo.scaleBy( this._getBbox( $.geo.center( bbox, true ) ), 0.5, true ); - } - - this._setBbox(bbox, true, true); - doInteractiveTimeout = true; - } else { - triggerShape = $.geo.polygonize( bbox, true ); - triggerShape.bbox = bbox; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - this._trigger( "shape", e, triggerShape ); - } - } else { - if ( mode === "dragBox" ) { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - } - - this._resetDrawing(); - break; - - case "dragCircle": - if ( dx !== 0 || dy !== 0 ) { - var image = this._options[ "axisLayout" ] === "image", - d = Math.sqrt( ( dx * dx) + ( dy * dy ) ), - n = 180, - a; - - this._drawPixels.length = n + 1; - - for ( i = 0; i < n; i++ ) { - a = ( i * 360 / n ) * ( Math.PI / 180 ); - this._drawPixels[ i ] = [ - this._anchor[ 0 ] + Math.cos( a ) * d, - this._anchor[ 1 ] + Math.sin( a ) * d - ]; - } - - this._drawPixels[ n ] = [ - this._drawPixels[ 0 ][ 0 ], - this._drawPixels[ 0 ][ 1 ] - ]; - - // using coordBuffer for bbox coords - coordBuffer = this._toMap( [ - [ this._anchor[ 0 ] - d, this._anchor[ 1 ] + ( image ? -d : d ) ], - [ this._anchor[ 0 ] + d, this._anchor[ 1 ] + ( image ? d : -d ) ] - ] ); - - triggerShape = { - type: "Polygon", - coordinates: [ this._toMap( this._drawPixels ) ], - bbox: [ coordBuffer[ 0 ][ 0 ], coordBuffer[ 0 ][ 1 ], coordBuffer[ 1 ][ 0 ], coordBuffer[ 1 ][ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - - this._resetDrawing(); - } else { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - break; - - case "drawPoint": - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - var geomap = this; - this._drawTimeout = setTimeout(function () { - if (geomap._drawTimeout) { - geomap._trigger("shape", e, { type: "Point", coordinates: geomap.toMap(current) }); - geomap._inOp = false; - geomap._drawTimeout = null; - } - }, 250); - } - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (wasToolPan) { - this._panFinalize(); - } else { - i = (this._drawCoords.length === 0 ? 0 : this._drawCoords.length - 1); - - this._drawCoords[i] = this._toMap(current); - this._drawPixels[i] = current; - - if (i < 2 || !(this._drawCoords[i][0] === this._drawCoords[i-1][0] && - this._drawCoords[i][1] === this._drawCoords[i-1][1])) { - this._drawCoords[i + 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[i + 1] = current; - } - - this._refreshDrawing(); - } - break; - - default: - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - this._inOp = false; - } - } - break; - } - - this._clickDate = clickDate; - - if (this._softDblClick && this._isDbltap) { - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - this._$eventTarget.trigger("dblclick", e); - return false; - } - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _eventTarget_mousewheel: function (e, delta) { - if ( this._options[ "mode" ] === "static" || this._options[ "scroll" ] === "off" ) { - return; - } - - e.preventDefault(); - - if ( this._mouseDown ) { - return false; - } - - if (delta !== 0) { - var tiledFull = Math.abs( delta ) >= 1; - this._clearInteractiveTimeout( ); - - if ( delta > 0 ) { - delta = Math.ceil( delta ); - } else { - delta = Math.floor( delta ); - } - - var offset = $(e.currentTarget).offset(); - this._anchor = [e.pageX - offset.left, e.pageY - offset.top]; - - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, this._options[ "tilingScheme" ] !== null ? tiledFull : false ); - - this._setInteractiveCenterAndSize( wheelCenterAndSize.center, wheelCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - this._setInteractiveTimeout( true ); - } - - return false; - } - } - ); -}(jQuery, window)); - - -(function ($, window, undefined) { - $.geo._serviceTypes.tiled = (function () { - var rTmplString = new RegExp( "<.*>|{{.*}}" ); - - return { - _serviceId: 0, - _tmplGeoSrcId: "", - - - create: function (map, serviceContainer, service /* , index */) { - this._serviceId = map._serviceIdSeed++; - this._tmplGeoSrcId = "geoSrc" + this._serviceId; - - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0, - reloadTiles: false - }; - - var scHtml = '
        '; - - serviceContainer.append( window.toStaticHTML( scHtml ) ); - - serviceState.serviceContainer = serviceContainer.children( ":last" ); - - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - //console.log( "tiled.interactiveTransform( " + center.join( ", " ) + ", " + pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ), - tilingScheme = map.options[ "tilingScheme" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data("pixelSize"), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapCoord = $scaleContainer.data("scaleOrigin"), - newPixelPoint = map._toPixel(oldMapCoord, center, pixelSize); - - $scaleContainer.css( { - left: Math.round(newPixelPoint[0]) + "px", - top: Math.round(newPixelPoint[1]) + "px", - width: tilingScheme.tileWidth * scaleRatio, - height: tilingScheme.tileHeight * scaleRatio - } ); - - /* - if ( $("body")[0].filters !== undefined ) { - $scaleContainer.children().each( function ( i ) { - $( this ).css( "filter", "progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11=" + scaleRatio + ",M22=" + scaleRatio + ",sizingmethod='auto expand')" ); - } ); - } - */ - } - }); - } - }, - - refresh: function (map, service, force) { - //console.log( "tiled.refresh( " + map._center.join( ", " ) + ", " + map._pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ); - - this._cancelUnloaded(map, service); - - if ( serviceState && force ) { - // if hidden atm, we want to make sure we reload this service after it becomes visible - serviceState.reloadTiles = true; - } - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - $serviceContainer = serviceState.serviceContainer, - - image = map.options[ "axisLayout" ] === "image", - ySign = image ? +1 : -1, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - - tileX = Math.floor((bbox[0] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.max( Math.floor( ( image ? bbox[1] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 3 ] ) / (pixelSize * tileHeight) ), 0 ), - tileX2 = Math.ceil((bbox[2] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil( ( image ? bbox[3] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 1 ] ) / (pixelSize * tileHeight) ), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] + ySign * bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMinOrMaxY = tilingScheme.origin[1] + ySign * (fullYAtScale * tileHeight) * pixelSize, - - serviceLeft = Math.round((fullXMinX - bbox[0]) / pixelSize), - serviceTop = Math.round( ( image ? fullYMinOrMaxY - bbox[1] : bbox[3] - fullYMinOrMaxY ) / pixelSize), - - scaleContainers = $serviceContainer.children().show(), - scaleContainer = scaleContainers.filter("[data-pixel-size='" + pixelSize + "']").appendTo($serviceContainer), - - opacity = service.style.opacity, - - x, y, - - loadImageDeferredDone = function( url ) { - // when a Deferred call is done, add the image to the map - // a reference to the correct img element is on the Deferred object itself - serviceObj._loadImage( this.img, url, pixelSize, map, serviceState, opacity ); - }, - - loadImageDeferredFail = function( ) { - delete this.img; - serviceState.loadCount--; - map._requestComplete(); - }; - - if (serviceState.reloadTiles) { - scaleContainers.find("img").attr("data-dirty", "true"); - } - - if (!scaleContainer.size()) { - $serviceContainer.append( window.toStaticHTML( "
        " ) ); - scaleContainer = $serviceContainer.children(":last").data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - } else { - scaleContainer.css({ - left: (serviceLeft % tileWidth) + "px", - top: (serviceTop % tileHeight) + "px" - }).data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - - scaleContainer.children().each( function () { - var $img = $(this), - tile = $img.attr("data-tile").split(","); - - $img.css({ - left: Math.round(((parseInt(tile[0], 10) - fullXAtScale) * 100) + (serviceLeft - (serviceLeft % tileWidth)) / tileWidth * 100) + "%", - top: Math.round(((parseInt(tile[1], 10) - fullYAtScale) * 100) + (serviceTop - (serviceTop % tileHeight)) / tileHeight * 100) + "%" - }); - - if (opacity < 1) { - $img.fadeTo(0, opacity); - } - } ); - } - - for (x = tileX; x < tileX2; x++) { - for (y = tileY; y < tileY2; y++) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ($img.size() === 0 || serviceState.reloadTiles) { - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] + ySign * (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] + ySign * ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - urlProp = ( service.hasOwnProperty( "src" ) ? "src" : "getUrl" ), - urlArgs = { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl; - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - if ( rTmplString.test( service[ urlProp ] ) ) { - $.templates( this._tmplGeoSrcId, service[ urlProp ] ); - imageUrl = $.render[ this._tmplGeoSrcId ]( urlArgs ); - } else { - imageUrl = service[ urlProp ]; - } - } - - serviceState.loadCount++; - map._requestQueued(); - - if (serviceState.reloadTiles && $img.size() > 0) { - $img.attr("src", imageUrl); - } else { - var imgMarkup = ""; - - scaleContainer.append( window.toStaticHTML( imgMarkup ) ); - $img = scaleContainer.children(":last"); - } - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl && $.isFunction( imageUrl.promise ) ) { - // assume Deferred - $.extend( imageUrl.promise( ), { img: $img } ); - imageUrl.done( loadImageDeferredDone ).fail( loadImageDeferredFail ); - } else { - $img.remove( ); - } - } - } - } - - scaleContainers.find("[data-dirty]").remove(); - serviceState.reloadTiles = false; - } - }, - - resize: function ( /* map, service, dx, dy */ ) { - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.css( "display", service.style.visibility === "visible" ? "block" : "none" ); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if (serviceState && serviceState.loadCount > 0) { - if ( window.stop !== undefined ) { - window.stop(); - } else if( document.execCommand !== undefined ) { - document.execCommand("Stop", false); - } - - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery, window)); - -(function ($, window, undefined) { - $.geo._serviceTypes.shingled = (function () { - var rTmplString = new RegExp( "<.*>|{{.*}}" ); - - return { - _serviceId: 0, - _tmplGeoSrcId: "", - - create: function ( map, serviceContainer, service /* , index */ ) { - this._serviceId = map._serviceIdSeed++; - this._tmplGeoSrcId = "geoSrc" + this._serviceId; - - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0 - }; - - var scHtml = '
        '; - - serviceContainer.append( window.toStaticHTML( scHtml ) ); - - serviceState.serviceContainer = serviceContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - var serviceState = $.data( service, "geoServiceState" ), - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds[ "width" ], - mapHeight = contentBounds[ "height" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data( "pixelSize" ), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin, center, pixelSize ); - - $scaleContainer.css( { - left: Math.round( newPixelPoint[ 0 ] ), - top: Math.round( newPixelPoint[ 1 ] ), - width: mapWidth * scaleRatio, - height: mapHeight * scaleRatio - } ); - } - }); - } - }, - - refresh: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - this._cancelUnloaded(map, service); - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainer = serviceContainer.children('[data-pixel-size="' + pixelSize + '"]'), - - opacity = service.style.opacity, - - $img; - - if (opacity < 1) { - serviceContainer.find("img").attr("data-keep-alive", "0"); - } - - if ( !scaleContainer.size() ) { - serviceContainer.append( window.toStaticHTML( '
        ' ) ); - scaleContainer = serviceContainer.children(":last"); - } - - var urlProp = ( service.hasOwnProperty("src") ? "src" : "getUrl" ), - urlArgs = { - bbox: bbox, - width: mapWidth, - height: mapHeight, - zoom: map._getZoom(), - tile: null, - index: 0 - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl, - imagePos = scaleContainer.position( ); - - imagePos.left = - ( imagePos.left ); - imagePos.top = - ( imagePos.top ); - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - if ( rTmplString.test( service[ urlProp ] ) ) { - $.templates( this._tmplGeoSrcId, service[ urlProp ] ); - imageUrl = $.render[ this._tmplGeoSrcId ]( urlArgs ); - } else { - imageUrl = service[ urlProp ]; - } - } - - serviceState.loadCount++; - map._requestQueued(); - - scaleContainer.append( window.toStaticHTML( '' ) ); - $img = scaleContainer.children(":last").data("center", map._center); - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, map, serviceState, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - map._requestComplete(); - } ); - } - - } - }, - - resize: function ( map, service /* , dx, dy */ ) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState && service && service.style.visibility === "visible" ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainers = serviceContainer.children(); - - scaleContainers.attr("data-pixel-size", "0"); - - scaleContainers.each( function ( ) { - var $scaleContainer = $(this), - position = $scaleContainer.position( ); - - $scaleContainer.css( { - left: position.left + ( mapWidth - $scaleContainer.width( ) ) / 2, - top: position.top + ( mapHeight - $scaleContainer.height( ) ) / 2 - } ); - - } ); - } - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.css("display", service.style.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - // #newpanzoom - serviceContainer.children(':not([data-pixel-size="' + pixelSize + '"])').remove(); - - serviceContainer.find( "img[data-keep-alive]" ).remove( ); - - serviceState.loadCount = 0; - } - }).error(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery, window)); diff --git a/dist/jquery.geo-1.0.0-b2.min.js b/dist/jquery.geo-1.0.0-b2.min.js deleted file mode 100644 index 3391cd1..0000000 --- a/dist/jquery.geo-1.0.0-b2.min.js +++ /dev/null @@ -1,6 +0,0 @@ -/*! jQuery Geo - v1.0.0-b2 - 2014-09-16 -* http://jquerygeo.com -* Copyright (c) 2014 Ryan Westphal; Licensed MIT */ -document.createElement("canvas").getContext||function(){function t(){return this.context_||(this.context_=new m(this))}function e(t,e){var i=k.call(arguments,2);return function(){return t.apply(e,i.concat(k.call(arguments)))}}function i(t,e,i){t.namespaces[e]||t.namespaces.add(e,i,"#default#VML")}function s(t){if(i(t,"g_vml_","urn:schemas-microsoft-com:vml"),i(t,"g_o_","urn:schemas-microsoft-com:office:office"),!t.styleSheets.ex_canvas_){var e=t.createStyleSheet();e.owningElement.id="ex_canvas_",e.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function o(t){var e=t.srcElement;switch(t.propertyName){case"width":e.getContext().clearRect(),e.style.width=e.attributes.width.nodeValue+"px",e.firstChild.style.width=e.clientWidth+"px";break;case"height":e.getContext().clearRect(),e.style.height=e.attributes.height.nodeValue+"px",e.firstChild.style.height=e.clientHeight+"px"}}function n(t){var e=t.srcElement;e.firstChild&&(e.firstChild.style.width=e.clientWidth+"px",e.firstChild.style.height=e.clientHeight+"px")}function r(){return[[1,0,0],[0,1,0],[0,0,1]]}function a(t,e){for(var i=r(),s=0;3>s;s++)for(var o=0;3>o;o++){for(var n=0,a=0;3>a;a++)n+=t[s][a]*e[a][o];i[s][o]=n}return i}function h(t,e){e.fillStyle=t.fillStyle,e.lineCap=t.lineCap,e.lineJoin=t.lineJoin,e.lineWidth=t.lineWidth,e.miterLimit=t.miterLimit,e.shadowBlur=t.shadowBlur,e.shadowColor=t.shadowColor,e.shadowOffsetX=t.shadowOffsetX,e.shadowOffsetY=t.shadowOffsetY,e.strokeStyle=t.strokeStyle,e.globalAlpha=t.globalAlpha,e.font=t.font,e.textAlign=t.textAlign,e.textBaseline=t.textBaseline,e.arcScaleX_=t.arcScaleX_,e.arcScaleY_=t.arcScaleY_,e.lineScale_=t.lineScale_}function c(t){var e=t.indexOf("(",3),i=t.indexOf(")",e+1),s=t.substring(e+1,i).split(",");return(4!=s.length||"a"!=t.charAt(3))&&(s[3]=1),s}function l(t){return parseFloat(t)/100}function _(t,e,i){return Math.min(i,Math.max(e,t))}function u(t){var e,i,s,o,n,r;if(o=parseFloat(t[0])/360%360,0>o&&o++,n=_(l(t[1]),0,1),r=_(l(t[2]),0,1),0==n)e=i=s=r;else{var a=.5>r?r*(1+n):r+n-r*n,h=2*r-a;e=d(h,a,o+1/3),i=d(h,a,o),s=d(h,a,o-1/3)}return"#"+G[Math.floor(255*e)]+G[Math.floor(255*i)]+G[Math.floor(255*s)]}function d(t,e,i){return 0>i&&i++,i>1&&i--,1>6*i?t+6*(e-t)*i:1>2*i?e:2>3*i?t+6*(e-t)*(2/3-i):t}function p(t){if(t in D)return D[t];var e,i=1;if(t+="","#"==t.charAt(0))e=t;else if(/^rgb/.test(t)){for(var s,o=c(t),e="#",n=0;3>n;n++)s=-1!=o[n].indexOf("%")?Math.floor(255*l(o[n])):+o[n],e+=G[_(s,0,255)];i=+o[3]}else if(/^hsl/.test(t)){var o=c(t);e=u(o),i=o[3]}else e=t;return D[t]={color:e,alpha:i}}function g(t){return j[t]||"square"}function m(t){this.m_=r(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.strokeStyle="#000",this.fillStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=1*z,this.globalAlpha=1,this.canvas=t;var e="width:"+t.clientWidth+"px;height:"+t.clientHeight+"px;overflow:hidden;position:absolute",i=t.ownerDocument.createElement("div");i.style.cssText=e,t.appendChild(i);var s=i.cloneNode(!1);s.style.backgroundColor="red",s.style.filter="alpha(opacity=0)",t.appendChild(s),this.element_=i,this.arcScaleX_=1,this.arcScaleY_=1,this.lineScale_=1}function f(t,e,i,s){t.currentPath_.push({type:"bezierCurveTo",cp1x:e.x,cp1y:e.y,cp2x:i.x,cp2y:i.y,x:s.x,y:s.y}),t.currentX_=s.x,t.currentY_=s.y}function v(t,e){var i=p(t.strokeStyle),s=i.color,o=i.alpha*t.globalAlpha,n=t.lineScale_*t.lineWidth;1>n&&(o*=n),e.push("')}function x(t,e,i,s){t.fillStyle,t.arcScaleX_,t.arcScaleY_,s.x-i.x,s.y-i.y;var o=p(t.fillStyle),n=o.color,r=o.alpha*t.globalAlpha;e.push('')}function y(t,e,i){var s=t.m_;return{x:z*(e*s[0][0]+i*s[1][0]+s[2][0])-I,y:z*(e*s[0][1]+i*s[1][1]+s[2][1])-I}}function b(t){return isFinite(t[0][0])&&isFinite(t[0][1])&&isFinite(t[1][0])&&isFinite(t[1][1])&&isFinite(t[2][0])&&isFinite(t[2][1])}function w(t,e,i){if(b(e)&&(t.m_=e,i)){var s=e[0][0]*e[1][1]-e[0][1]*e[1][0];t.lineScale_=$(P(s))}}function S(t){this.code=this[t],this.message=t+": DOM Exception "+this.code}var A=Math,C=A.round,T=A.sin,M=A.cos,P=A.abs,$=A.sqrt,z=10,I=z/2;+navigator.userAgent.match(/MSIE ([\d.]+)?/)[1];var k=Array.prototype.slice;s(document);var L={init:function(t){var i=t||document;i.createElement("canvas"),i.attachEvent("onreadystatechange",e(this.init_,this,i))},init_:function(t){for(var e=t.getElementsByTagName("canvas"),i=0;e.length>i;i++)this.initElement(e[i])},initElement:function(e){if(!e.getContext){e.getContext=t,s(e.ownerDocument),e.innerHTML="",e.attachEvent("onpropertychange",o),e.attachEvent("onresize",n);var i=e.attributes;i.width&&i.width.specified?e.style.width=i.width.nodeValue+"px":e.width=e.clientWidth,i.height&&i.height.specified?e.style.height=i.height.nodeValue+"px":e.height=e.clientHeight}return e}};L.init();for(var G=[],O=0;16>O;O++)for(var B=0;16>B;B++)G[16*O+B]=O.toString(16)+B.toString(16);var D={},j={butt:"flat",round:"round"},E=m.prototype;E.clearRect=function(){this.textMeasureEl_&&(this.textMeasureEl_.removeNode(!0),this.textMeasureEl_=null),this.element_.innerHTML=""},E.beginPath=function(){this.currentPath_=[]},E.moveTo=function(t,e){var i=y(this,t,e);this.currentPath_.push({type:"moveTo",x:i.x,y:i.y}),this.currentX_=i.x,this.currentY_=i.y},E.lineTo=function(t,e){var i=y(this,t,e);this.currentPath_.push({type:"lineTo",x:i.x,y:i.y}),this.currentX_=i.x,this.currentY_=i.y},E.bezierCurveTo=function(t,e,i,s,o,n){var r=y(this,o,n),a=y(this,t,e),h=y(this,i,s);f(this,a,h,r)},E.quadraticCurveTo=function(t,e,i,s){var o=y(this,t,e),n=y(this,i,s),r={x:this.currentX_+2/3*(o.x-this.currentX_),y:this.currentY_+2/3*(o.y-this.currentY_)},a={x:r.x+(n.x-this.currentX_)/3,y:r.y+(n.y-this.currentY_)/3};f(this,r,a,n)},E.arc=function(t,e,i,s,o,n){i*=z;var r=n?"at":"wa",a=t+M(s)*i-I,h=e+T(s)*i-I,c=t+M(o)*i-I,l=e+T(o)*i-I;a!=c||n||(a+=.125);var _=y(this,t,e),u=y(this,a,h),d=y(this,c,l);this.currentPath_.push({type:r,x:_.x,y:_.y,radius:i,xStart:u.x,yStart:u.y,xEnd:d.x,yEnd:d.y})},E.stroke=function(t){var e=[],i=10,s=10;e.push("n.x)&&(n.x=h.x),(null==o.y||h.yn.y)&&(n.y=h.y))}e.push(' ">'),t?x(this,e,o,n):v(this,e),e.push(""),this.element_.insertAdjacentHTML("beforeEnd",e.join(""))},E.fill=function(){this.stroke(!0)},E.closePath=function(){this.currentPath_.push({type:"close"})},E.save=function(){var t={};h(this,t),this.aStack_.push(t),this.mStack_.push(this.m_),this.m_=a(r(),this.m_)},E.restore=function(){this.aStack_.length&&(h(this.aStack_.pop(),this),this.m_=this.mStack_.pop())},E.translate=function(t,e){var i=[[1,0,0],[0,1,0],[t,e,1]];w(this,a(i,this.m_),!1)},E.scale=function(t,e){this.arcScaleX_*=t,this.arcScaleY_*=e;var i=[[t,0,0],[0,e,0],[0,0,1]];w(this,a(i,this.m_),!0)};var F=S.prototype=Error();F.INDEX_SIZE_ERR=1,F.DOMSTRING_SIZE_ERR=2,F.HIERARCHY_REQUEST_ERR=3,F.WRONG_DOCUMENT_ERR=4,F.INVALID_CHARACTER_ERR=5,F.NO_DATA_ALLOWED_ERR=6,F.NO_MODIFICATION_ALLOWED_ERR=7,F.NOT_FOUND_ERR=8,F.NOT_SUPPORTED_ERR=9,F.INUSE_ATTRIBUTE_ERR=10,F.INVALID_STATE_ERR=11,F.SYNTAX_ERR=12,F.INVALID_MODIFICATION_ERR=13,F.NAMESPACE_ERR=14,F.INVALID_ACCESS_ERR=15,F.VALIDATION_ERR=16,F.TYPE_MISMATCH_ERR=17,G_vmlCanvasManager=L,CanvasRenderingContext2D=m,DOMException=S}(),this.jsviews||this.jQuery&&jQuery.views||function(t,e){function i(t,e){var i="\\"+t.charAt(0),s="\\"+t.charAt(1),o="\\"+e.charAt(0),n="\\"+e.charAt(1);return V.rTag=y=s+"(?:(?:(\\w+(?=[\\/\\s"+o+"]))|(?:(\\w+)?(:)|(>)|(\\*)))"+"\\s*((?:[^"+o+"]|"+o+"(?!"+n+"))*?)"+"(\\/)?|(?:\\/(\\w+)))"+o,y=RegExp(i+y+n,"g"),b=RegExp("<.*>|"+t+".*"+e),this}function s(t){var i=this,s=i.tmpl.helpers||{};return t=(i.ctx[t]!==e?i.ctx:s[t]!==e?s:l[t]!==e?l:{})[t],"function"!=typeof t?t:function(){return t.apply(i,arguments)}}function o(t,e,i){var s=e.tmpl.converters;return t=s&&s[t]||_[t],t?t.call(e,i):i}function n(t,i,s,o,n){n.props=n.props||{};var r,a=n.props.tmpl,l=i.tmpl.tags,_=i.tmpl.templates,d=arguments,p=l&&l[t]||c[t];return p?(o=o&&i.tmpl.tmpls[o-1],a=a||o||e,n.tmpl=""+a===a?_&&_[a]||h[a]||h(a):a,n.isTag=T,n.converter=s,n.view=i,n.renderContent=u,i.ctx&&w(n.ctx,i.ctx),r=p.apply(n,d.length>5?F.call(d,5):[]),r||(r==e?"":""+r)):""}function r(t,i,o,n,r,a){var h=o.views,c={tmpl:r,path:i,parent:o,data:n,ctx:t,views:x.isArray(n)?[]:{},hlp:s};return x.isArray(h)?h.splice(c.index=a!==e?a:h.length,0,c):h[c.index="_"+G++]=c,c}function a(t,i,s,o,n){var r,a;if(s&&"object"==typeof s&&!s.nodeType){for(r in s)i(r,s[r]);return t}return s&&o!==e?""+s===s&&(null===o?delete i[s]:(o=n?n(s,o):o)&&(i[s]=o)):n&&(o=n(e,o||s)),(a=A.onStoreItem)&&a(i,s,o,n),o}function h(t,e){return a(this,h,t,e,m)}function c(t,e){return a(this,c,t,e)}function l(t,e){return a(this,l,t,e)}function _(t,e){return a(this,_,t,e)}function u(t,i,s,o,n){var a,c,l,_,u,d,p,g,m,f,v={},y=n===T,b=this,S="";if(b.isTag?(m=b.tmpl,i=i||b.ctx,s=s||b.view,o=o||b.path,n=n||b.index,v=b.props):m=b.jquery&&b[0]||b,s=s||V.topView,g=s.ctx,f=m.layout,t===s&&(t=s.data,f=T),i=i&&i===g?g:g?(g=w({},g),i?w(g,i):g):i||{},v.link===C&&(i.link=C),m.fn||(m=h[m]||h(m)),u=i.link&&A.onRenderItem,d=i.link&&A.onRenderItems,m){if(x.isArray(t)&&!f)for(_=y?s:n!==e&&s||r(i,o,s,t,m,n),a=0,c=t.length;c>a;a++)l=t[a],p=m.fn(l,r(i,o,_,l,m,(n||0)+a),V),S+=u?u(p,v):p;else _=y?s:r(i,o,s,t,m,n),S+=t||f?m.fn(t,_,V):"";return s.topKey=_.index,d?d(S,o,_.index,m,v):S}return""}function d(){throw"Syntax error"}function p(t,e,i){function s(e){e-=$,e&&O.push(t.substr($,e).replace(z,"\\n"))}function o(e,o,r,a,h,c,l,_,u,d){h&&(a=":",r="html");var p="",m="",f=!_&&!a;if(o=o||a,s(d),$=d+e.length,c?A&&O.push(["*",l.replace(I,"$1")]):o?("else"===o&&(B[5]=t.substring(B[5],d),B=G.pop(),O=B[3],f=T),l=l?g(l,i).replace(L,function(t,e,i){return e?m+=i+",":p+=i+",",""}):"",p=p.slice(0,-1),l=l.slice(0,-1),n=[o,r||"",l,f&&[],"{"+(p?"props:{"+p+"},":"")+"path:'"+l+"'"+(m?",ctx:{"+m.slice(0,-1)+"}":"")+"}"],f&&(G.push(B),B=n,B[5]=$),O.push(n)):u&&(B[5]=t.substring(B[5],d),B=G.pop()),!B)throw"Expected block tag";O=B[3]}var n,r,a,h,c,l,_,u,d,m,v,x,b,w,S,A,C=e?{allowCode:A=e.allowCode,debug:e.debug}:{},M=e&&e.tmpls,P=[],$=0,G=[],O=P,B=[,,,P],D=0;for(t=t.replace(k,"\\$1"),t.replace(y,o),s(t.length),h=P.length,c=h?"":'"";',a=0;h>a;a++)r=P[a],"*"===r[0]?c=c.slice(0,a?-1:-3)+";"+r[1]+(h>a+1?"ret+=":""):""+r===r?c+='"'+r+'"+':(v=r[0],x=r[1],b=r[2],O=r[3],w=r[4],t=r[5],O&&(S=f(t,C,e,D++),p(t,S),M.push(S)),m=m||w.indexOf("view")>-1,c+=(":"===v?"html"===x?(_=T,"e("+b):x?(d=T,'c("'+x+'",view,'+b):(u=T,"((v="+b+')!=u?v:""'):(l=T,'t("'+v+'",view,"'+(x||"")+'",'+(O?M.length:'""')+","+w+(b?",":"")+b))+")+");return c=Function("data, view, j, b, u",j+(u?"v,":"")+(l?"t=j.tag,":"")+(d?"c=j.convert,":"")+(_?"e=j.converters.html,":"")+"ret; try{\n\n"+(C.debug?"debugger;":"")+(A?"ret=":"return ")+c.slice(0,-1)+";\n\n"+(A?"return ret;":"")+"}catch(e){return j.err(e);}"),e&&(e.fn=c,e.useVw=d||m||l),c}function g(t,i){function s(t,s,c,l,_,u,p,g,m,f,v,x,y,b,w,S){function A(t,e,s,o,n,r,a){if(e){var h=(s?'view.hlp("'+s+'")':o?"view":"data")+(a?(n?"."+n:s?"":o?"":"."+e)+(r||""):(a=s?"":o?n||"":e,""));return i&&"("!==m&&(h="b("+h+',"'+a+'")'),h+(a?"."+a:"")}return t}return _=_||"",c=c||s||v,l=l||g,m=m||w||"",_=_||"",u?(d(),e):h?(h=!x,h?t:'"'):a?(a=!y,a?t:'"'):(c?(r++,c):"")+(S?r?"":o?(o=C,"\b"):",":p?(r&&d(),o=T,"\b"+l+":"):l?l.replace(P,A)+(m?(n[++r]=T,m):_):_?t:b?(n[r--]=C,b+(m?(n[++r]=T,m):"")):f?(n[r]||d(),","):s?"":(h=x,a=y,'"'))}var o,n={},r=0,a=C,h=C;return t=(t+" ").replace($,s)}function m(t,i,s,o){function n(i){return""+i===i||i.nodeType>0?(a=i.nodeType>0?i:!b.test(i)&&M&&M(i)[0],a&&a.type&&(i=h[a.getAttribute(D)],i||(t=t||"_"+O++,a.setAttribute(D,t),i=m(t,a.innerHTML,s,o),h[t]=i)),i):e}var r,a,c,l,_;if(r=n(i),o=o||(i.markup?i:{}),o.name=t,l=o.templates,!r&&i.markup&&(r=n(i.markup))&&(!r.fn||r.debug===i.debug&&r.allowCode===i.allowCode||(r=r.markup)),r!==e){t&&!s&&(R[t]=function(){return i.render.apply(i,arguments)}),r.fn||i.fn?r.fn&&(i=t&&t!==r.name?w(w({},r),o):r):(i=f(r,o,s,0),p(r,i));for(c in l)_=l[c],_.name!==c&&(l[c]=m(c,_,i));return i}}function f(t,e,i,s){function o(t){i[t]&&(n[t]=w(w({},i[t]),e[t]))}e=e||{};var n={markup:t,tmpls:[],links:[],render:u};return i&&(i.templates&&(n.templates=w(w({},i.templates),e.templates)),n.parent=i,n.name=i.name+"["+s+"]",n.index=s),w(n,e),i&&(o("templates"),o("tags"),o("helpers"),o("converters")),n}function v(t){return B[t]||(B[t]="&#"+t.charCodeAt(0)+";")}var x,y,b,w,S="v1.0pre",A={},C=!1,T=!0,M=t.jQuery,P=/^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g,$=/(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,z=/\r?\n/g,I=/\\(['"])/g,k=/\\?(['"])/g,L=/\x08(~)?([^\x08]+)\x08/g,G=0,O=0,B={"&":"&","<":"<",">":">"},D="data-jsv-tmpl",j="var j=j||"+(M?"jQuery.":"js")+"views,",E=/[\x00"&'<>]/g,F=Array.prototype.slice,R={},V={jsviews:S,sub:A,debugMode:T,err:function(t){return V.debugMode?"
        Error: "+(t.message||t)+". ":'""'},tmplFn:p,render:R,templates:h,tags:c,helpers:l,converters:_,View:r,convert:o,delimiters:i,tag:n};M?(x=M,x.templates=h,x.render=R,x.views=V,x.fn.render=u):(x=t.jsviews=V,x.extend=function(t,e){var i;t=t||{};for(i in e)t[i]=e[i];return t},x.isArray=Array&&Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}),w=x.extend,V.topView={views:{},tmpl:{},hlp:s,ctx:V.helpers},c({"if":function(){var t=this,i=t.view;return i.onElse=function(t,s){for(var o=0,n=s.length;n&&!s[o++];)if(o===n)return"";return i.onElse=e,t.path="",t.renderContent(i)},i.onElse(this,arguments)},"else":function(){var t=this.view;return t.onElse?t.onElse(this,arguments):""},"for":function(){var t,e=this,i="",s=arguments,o=s.length;for(e.props.layout&&(e.tmpl.layout=T),t=0;o>t;t++)i+=e.renderContent(s[t]);return i},"=":function(t){return t},"*":function(t){return t}}),_({html:function(t){return t!=e?(t+"").replace(E,v):""}}),i("{{","}}")}(this),function(t){function e(e){var i=e||window.event,s=[].slice.call(arguments,1),o=0,n=0,r=0;return e=t.event.fix(i),e.type="mousewheel",i.wheelDelta&&(o=i.wheelDelta/120),i.detail&&(o=-i.detail/3),r=o,void 0!==i.axis&&i.axis===i.HORIZONTAL_AXIS&&(r=0,n=-1*o),void 0!==i.wheelDeltaY&&(r=i.wheelDeltaY/120),void 0!==i.wheelDeltaX&&(n=-1*i.wheelDeltaX/120),s.unshift(e,o,n,r),(t.event.dispatch||t.event.handle).apply(this,s)}var i=["DOMMouseScroll","mousewheel"];if(t.event.fixHooks)for(var s=i.length;s;)t.event.fixHooks[i[--s]]=t.event.mouseHooks;t.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var t=i.length;t;)this.addEventListener(i[--t],e,!1);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var t=i.length;t;)this.removeEventListener(i[--t],e,!1);else this.onmousewheel=null}},t.fn.extend({mousewheel:function(t){return t?this.bind("mousewheel",t):this.trigger("mousewheel")},unmousewheel:function(t){return this.unbind("mousewheel",t)}})}(jQuery),$.widget||function(t,e){if(t.cleanData){var i=t.cleanData;t.cleanData=function(e){for(var s,o=0;null!=(s=e[o]);o++)try{t(s).triggerHandler("remove")}catch(n){}i(e)}}else{var s=t.fn.remove;t.fn.remove=function(e,i){return this.each(function(){return i||(!e||t.filter(e,[this]).length)&&t("*",this).add([this]).each(function(){try{t(this).triggerHandler("remove")}catch(e){}}),s.call(t(this),e,i)})}}t.widget=function(e,i,s){var o,n=e.split(".")[0];e=e.split(".")[1],o=n+"-"+e,s||(s=i,i=t.Widget),t.expr[":"][o]=function(i){return!!t.data(i,e)},t[n]=t[n]||{},t[n][e]=function(t,e){arguments.length&&this._createWidget(t,e)};var r=new i;r.options=t.extend(!0,{},r.options),t[n][e].prototype=t.extend(!0,r,{namespace:n,widgetName:e,widgetEventPrefix:t[n][e].prototype.widgetEventPrefix||e,widgetBaseClass:o},s),t.widget.bridge(e,t[n][e])},t.widget.bridge=function(i,s){t.fn[i]=function(o){var n="string"==typeof o,r=Array.prototype.slice.call(arguments,1),a=this;return o=!n&&r.length?t.extend.apply(null,[!0,o].concat(r)):o,n&&"_"===o.charAt(0)?a:(n?this.each(function(){var s=t.data(this,i),n=s&&t.isFunction(s[o])?s[o].apply(s,r):s;return n!==s&&n!==e?(a=n,!1):e}):this.each(function(){var e=t.data(this,i);e?e.option(o||{})._init():t.data(this,i,new s(o,this))}),a)}},t.Widget=function(t,e){arguments.length&&this._createWidget(t,e)},t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(e,i){t.data(i,this.widgetName,this),this.element=t(i),this.options=t.extend(!0,{},this.options,this._getCreateOptions(),e);var s=this;this.element.bind("remove."+this.widgetName,function(){s.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return t.metadata&&t.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled "+"ui-state-disabled")},widget:function(){return this.element},option:function(i,s){var o=i;if(0===arguments.length)return t.extend({},this.options);if("string"==typeof i){if(s===e)return this.options[i];o={},o[i]=s}return this._setOptions(o),this},_setOptions:function(e){var i=this;return t.each(e,function(t,e){i._setOption(t,e)}),this},_setOption:function(t,e){return this.options[t]=e,"disabled"===t&&this.widget()[e?"addClass":"removeClass"](this.widgetBaseClass+"-disabled"+" "+"ui-state-disabled").attr("aria-disabled",e),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(e,i,s){var o,n,r=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],n=i.originalEvent)for(o in n)o in i||(i[o]=n[o]);return this.element.trigger(i,s),!(t.isFunction(r)&&r.call(this.element[0],i,s)===!1||i.isDefaultPrevented())}}}(jQuery),function(t,e,i){e.toStaticHTML=e.toStaticHTML||function(t){return t};var s=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;t.geo={_allCoordinates:function(e){for(var i=this._flatten(e),s=0,o=[];i.length>s;s++){var n,r,a,h=i[s].coordinates,c=h&&t.isArray(h[0]),l=c&&t.isArray(h[0][0]),_=l&&t.isArray(h[0][0][0]);for(_||(l||(c||(h=[h]),h=[h]),h=[h]),n=0;h.length>n;n++)for(r=0;h[n].length>r;r++)for(a=0;h[n][r].length>a;a++)o.push(h[n][r][a])}return o},_isGeodetic:function(e){for(;t.isArray(e);){if(e.length>1&&!t.isArray(e[0]))return e[0]>=-180.001&&180.001>=e[0]&&e[1]>=-90.001&&90.001>=e[1];e=e[0]}return!1},center:function(e,i){var s=!1;!i&&t.geo.proj&&this._isGeodetic(e)&&(s=!0,e=t.geo.proj.fromGeodetic(e));var o=[(e[0]+e[2])/2,(e[1]+e[3])/2];return s?t.geo.proj.toGeodetic(o):o},expandBy:function(e,i,s,o){var n=!1;return!o&&t.geo.proj&&this._isGeodetic(e)&&(n=!0,e=t.geo.proj.fromGeodetic(e)),e=[e[0]-i,e[1]-s,e[2]+i,e[3]+s],n?t.geo.proj.toGeodetic(e):e},height:function(e,i){return!i&&t.geo.proj&&this._isGeodetic(e)&&(e=t.geo.proj.fromGeodetic(e)),e[3]-e[1]},_in:function(t,e){return t[0]<=e[0]&&t[1]<=e[1]&&t[2]>=e[2]&&t[3]>=e[3]},_bboxDisjoint:function(t,e){return e[0]>t[2]||e[2]t[3]||e[3]0&&(a/h>i?(n=a/2,r=n/i):(r=h/2,n=r*i),e=[c[0]-n,c[1]-r,c[0]+n,c[1]+r]),o?t.geo.proj.toGeodetic(e):e},recenter:function(e,i,s){var o=!1;!s&&t.geo.proj&&(this._isGeodetic(e)&&(o=!0,e=t.geo.proj.fromGeodetic(e)),this._isGeodetic(i)&&(i=t.geo.proj.fromGeodetic(i)));var n=(e[2]-e[0])/2,r=(e[3]-e[1])/2;return e=[i[0]-n,i[1]-r,i[0]+n,i[1]+r],o?t.geo.proj.toGeodetic(e):e},scaleBy:function(e,i,s){var o=!1;!s&&t.geo.proj&&this._isGeodetic(e)&&(o=!0,e=t.geo.proj.fromGeodetic(e));var n=this.center(e,!0),r=(e[2]-e[0])*i/2,a=(e[3]-e[1])*i/2;return e=[n[0]-r,n[1]-a,n[0]+r,n[1]+a],o?t.geo.proj.toGeodetic(e):e},width:function(e,i){return!i&&t.geo.proj&&this._isGeodetic(e)&&(e=t.geo.proj.fromGeodetic(e)),e[2]-e[0]},bbox:function(e,n){var r,a=!1;if(!e)return i;if(e.bbox)r=!n&&t.geo.proj&&this._isGeodetic(e.bbox)?t.geo.proj.fromGeodetic(e.bbox):e.bbox;else{r=[s,s,o,o];var h=this._allCoordinates(e),c=0;if(0===h.length)return i;for(!n&&t.geo.proj&&this._isGeodetic(h)&&(a=!0,h=t.geo.proj.fromGeodetic(h));h.length>c;c++)r[0]=Math.min(h[c][0],r[0]),r[1]=Math.min(h[c][1],r[1]),r[2]=Math.max(h[c][0],r[2]),r[3]=Math.max(h[c][1],r[3])}return a?t.geo.proj.toGeodetic(r):r},centroid:function(e,n){var r;switch(e.type){case"Point":return t.extend({},e);case"LineString":case"Polygon":var a,h,c=0,l=t.merge([],"Polygon"===e.type?e.coordinates[0]:e.coordinates),_=1,u=[s,s,o,o];r=[0,0];var d=!1;for(!n&&t.geo.proj&&this._isGeodetic(l)&&(d=!0,l=t.geo.proj.fromGeodetic(l));l.length>=_;_++)a=_%l.length,u[0]=Math.min(l[a][0],u[0]),u[1]=Math.min(l[a][1],u[1]),u[2]=Math.max(l[a][0],u[2]),u[3]=Math.max(l[a][1],u[3]),h=l[_-1][0]*l[a][1]-l[a][0]*l[_-1][1],c+=h,r[0]+=(l[_-1][0]+l[a][0])*h,r[1]+=(l[_-1][1]+l[a][1])*h;return 0===c?l.length>0?(r[0]=Math.min(Math.max(l[0][0],u[0]),u[2]),r[1]=Math.min(Math.max(l[0][1],u[1]),u[3]),{type:"Point",coordinates:d?t.geo.proj.toGeodetic(r):r}):i:(c*=3,r[0]=Math.min(Math.max(r[0]/c,u[0]),u[2]),r[1]=Math.min(Math.max(r[1]/c,u[1]),u[3]),{type:"Point",coordinates:d?t.geo.proj.toGeodetic(r):r});case"MultiPoint":if(e.coordinates.length>0)return r=e.coordinates[0],{type:"Point",coordinates:[r[0],r[1]]};break;case"MultiLineString":case"MultiPolygon":if(e.coordinates.length>0)return this.centroid({type:e.type.substr(5),coordinates:e.coordinates[0]},n)}return i},contains:function(t,e){if("Polygon"!==t.type)return!1;switch(e.type){case"Point":return this._containsPolygonPoint(t.coordinates,e.coordinates);case"LineString":return this._containsPolygonLineString(t.coordinates,e.coordinates);case"Polygon":return this._containsPolygonLineString(t.coordinates,e.coordinates[0]);default:return!1}},_containsPolygonPoint:function(t,e){if(0===t.length||4>t[0].length)return!1;for(var i,s,o=0,n=t[0][0],r=1;t[0].length>r;r++)i=t[0][r],(n[1]<=e[1]&&e[1]e[0]&&o++),n=i;return 1===o%2},_containsPolygonLineString:function(t,e){for(var i=0;e.length>i;i++)if(!this._containsPolygonPoint(t,e[i]))return!1;return!0},distance:function(e,s,o){var n=!o&&t.geo.proj&&this._isGeodetic(e.coordinates)?t.geo.proj.fromGeodetic(e.coordinates):e.coordinates,r=!o&&t.geo.proj&&this._isGeodetic(s.coordinates)?t.geo.proj.fromGeodetic(s.coordinates):s.coordinates;switch(e.type){case"Point":switch(s.type){case"Point":return this._distancePointPoint(r,n);case"LineString":return this._distanceLineStringPoint(r,n);case"Polygon":return this._containsPolygonPoint(r,n)?0:this._distanceLineStringPoint(r[0],n);default:return i}break;case"LineString":switch(s.type){case"Point":return this._distanceLineStringPoint(n,r);case"LineString":return this._distanceLineStringLineString(n,r);case"Polygon":return this._containsPolygonLineString(r,n)?0:this._distanceLineStringLineString(r[0],n);default:return i}break;case"Polygon":switch(s.type){case"Point":return this._containsPolygonPoint(n,r)?0:this._distanceLineStringPoint(n[0],r);case"LineString":return this._containsPolygonLineString(n,r)?0:this._distanceLineStringLineString(n[0],r);case"Polygon":return this._containsPolygonLineString(n,r[0])?0:this._distanceLineStringLineString(n[0],r[0]);default:return i}}},_distancePointPoint:function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},_distanceLineStringPoint:function(t,e){var i=s;if(t.length>0){var o=t[0],n=e[0]-o[0],r=e[1]-o[1];if(1===t.length)return Math.sqrt(n*n+r*r);for(var a=1;t.length>a;a++){var h=t[a],c=h[0]-o[0],l=h[1]-o[1],_=e[0]-h[0],u=e[1]-h[1],d=this._distanceSegmentPoint(c,l,n,r,_,u);if(0===d)return 0;i>d&&(i=d),o=h,n=_,r=u}}return Math.sqrt(i)},_distanceSegmentPoint:function(t,e,i,s,o,n){var r=t*i+e*s;if(0>=r)return i*i+s*s;var a=t*t+e*e;return r>=a?o*o+n*n:i*i+s*s-r*r/a},_distanceLineStringLineString:function(t,e){for(var i=s,o=0;e.length>o;o++)i=Math.min(i,this._distanceLineStringPoint(t,e[o]));return i},_buffer:function(e,s,o){var n=!1,r=e.coordinates;if(!o&&t.geo.proj&&this._isGeodetic(e.coordinates)&&(n=!0,r=t.geo.proj.fromGeodetic(e.coordinates)),"Point"===e.type){for(var a,h=[],c=180,l=0;c>=l;l++)a=360*l/c*(Math.PI/180),h.push([r[0]+Math.cos(a)*s,r[1]+Math.sin(a)*s]);return{type:"Polygon",coordinates:[n?t.geo.proj.toGeodetic(h):h]}}return i},_basic:function(t){for(var e,i,s=[],o=0,n=this._flatten(t);n.length>o;o++)if("Multi"===n[o].type.substring(0,5))for(e=n[o].type.substring(5),i=0;n[o].coordinates.length>i;i++)s.push({type:e,coordinates:n[o].coordinates[i]});else s.push(n[o]);return s},_flatten:function(e){var i=[],s=0;switch(e.type){case"Feature":t.merge(i,this._flatten(e.geometry));break;case"FeatureCollection":for(;e.features.length>s;s++)t.merge(i,this._flatten(e.features[s].geometry));break;case"GeometryCollection":for(;e.geometries.length>s;s++)t.merge(i,this._flatten(e.geometries[s]));break;default:i[0]=e}return i},length:function(e,i){var s,o,n,r=0,a=1;switch(e.type){case"Point":return 0;case"LineString":s=e.coordinates;break;case"Polygon":s=e.coordinates[0]}if(s){for(!i&&t.geo.proj&&this._isGeodetic(s)&&(s=t.geo.proj.fromGeodetic(s));s.length>a;a++)o=s[a][0]-s[a-1][0],n=s[a][1]-s[a-1][1],r+=Math.sqrt(o*o+n*n);return r}},area:function(e,i){var s,o,n=0,r=1;switch(e.type){case"Point":case"LineString":return 0;case"Polygon":s=e.coordinates[0]}if(s){for(!i&&t.geo.proj&&this._isGeodetic(s)&&(s=t.geo.proj.fromGeodetic(s));s.length>=r;r++)o=r%s.length,n+=(s[r-1][0]-s[o][0])*(s[r-1][1]+s[o][1])/2;return Math.abs(n)}},pointAlong:function(e,i,s){var o,n,r,a,h,c,l,_,u=0,d=0,p=0,g=[],m=1,f=!1;switch(e.type){case"Point":return t.extend({},e);case"LineString":r=e.coordinates;break;case"Polygon":r=e.coordinates[0]}if(r){if(0===i)return{type:"Point",coordinates:[r[0][0],r[0][1]]};if(1===i)return m=r.length-1,{type:"Point",coordinates:[r[m][0],r[m][1]]};for(!s&&t.geo.proj&&this._isGeodetic(r)&&(f=!0,r=t.geo.proj.fromGeodetic(r));r.length>m;m++)a=r[m][0]-r[m-1][0],h=r[m][1]-r[m-1][1],n=Math.sqrt(a*a+h*h),g.push(n),u+=n;for(m=0;g.length>m&&i>p;m++)d=p,p+=g[m]/u;return o=i-d,l=r[m-1],_=r[m],c=[l[0]+o*(_[0]-l[0]),l[1]+o*(_[1]-l[1])],{type:"Point",coordinates:f?t.geo.proj.toGeodetic(c):c}}},WKT:function(){function e(t){return"POINT "+i(t.coordinates)}function i(t){return t&&t.length?"("+t.join(" ")+")":"EMPTY"}function s(t){return"LINESTRING "+o(t.coordinates)}function o(t){if(t&&t.length){for(var e=[],i=0;t.length>i;i++)e.push(t[i].join(" "));return"("+e+")"}return"EMPTY"}function n(t){return"POLYGON "+r(t.coordinates)}function r(t){if(t&&t.length){for(var e=[],i=0;t.length>i;i++)e.push(o(t[i]));return"("+e+")"}return"EMTPY"}function a(t){return"MULTIPOINT "+o(t.coordinates)}function h(t){return"MULTILINSTRING "+r(t.coordinates)}function c(t){return"MULTIPOLYGON "+l(t.coordinates)}function l(t){if(t&&t.length){for(var e=[],i=0;t.length>i;i++)e.push(r(t[i]));return"("+e+")"}return"EMPTY"}function _(t){return"GEOMETRYCOLLECTION "+u(t.geometries)}function u(t){if(t&&t.length){for(var e=[],i=0;t.length>i;i++)e.push(d(t[i]));return"("+t+")"}return"EMPTY"}function d(t){if(!t||!t.type)return"";switch(t.type){case"Point":return e(t);case"LineString":return s(t);case"Polygon":return n(t);case"MultiPoint":return a(t);case"MultiLineString":return h(t);case"MultiPolygon":return c(t);case"GeometryCollection":return _(t);default:return""}}function p(t){var e=t.match(/\(\s*([\d\.\-]+)\s+([\d\.\-]+)\s*\)/);return e&&e.length>2?{type:"Point",coordinates:[parseFloat(e[1]),parseFloat(e[2])]}:null}function g(t){var e,i,s=t.match(/\s*\((.*)\)/),o=[],n=0;if(s&&s.length>1){for(e=s[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);e.length>n;n++)i=e[n].match(/\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/),o[n]=[parseFloat(i[1]),parseFloat(i[2])];return{type:"LineString",coordinates:o}}return null}function m(t){var e,i,s=t.match(/\s*\(\s*\((.*)\)\s*\)/),o=[],n=0;if(s&&s.length>1){for(e=s[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);e.length>n;n++)i=e[n].match(/\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/),o[n]=[parseFloat(i[1]),parseFloat(i[2])];return{type:"Polygon",coordinates:[o]}}return null}function f(e){var i;return-1===e.indexOf("((")?i=g(e):(i=v(e),i.coordinates=t.geo._allCoordinates(i)),i.type="MultiPoint",i}function v(t){for(var e,i=t.substr(2,t.length-4),s=i.split(/\),\s*\(/),o=0,n={type:"MultiLineString",coordinates:[]};s.length>o;o++)e=g("("+s[o]+")"),e&&n.coordinates.push(e.coordinates);return n}function x(t){for(var e,i=t.substr(1,t.length-2),s=i.split(/\),\s*\(/),o=0,n={type:"MultiPolygon",coordinates:[]};s.length>o;o++)e=m("("+s[o]+")"),e&&n.coordinates.push(e.coordinates);return n}function y(t){var e,i,s=t.substr(1,t.length-2),o=s.match(/\),[a-zA-Z]/g),n={type:"GeometryCollection",geometries:[]},r=0,a=0;if(o&&o.length>0){for(;o.length>r;r++)i=s.indexOf(o[r],a)-a+1,e=b(s.substr(a,i)),e&&n.geometries.push(e),a+=i+1;return e=b(s.substr(a)),e&&n.geometries.push(e),n}return null}function b(e){e=t.trim(e);var i=e.indexOf("("),s=e.substr(i);switch(t.trim(e.substr(0,i)).toUpperCase()){case"POINT":return p(s);case"LINESTRING":return g(s);case"POLYGON":return m(s);case"MULTIPOINT":return f(s);case"MULTILINESTRING":return v(s);case"MULTIPOLYGON":return x(s);case"GEOMETRYCOLLECTION":return y(s);default:return null}}return{stringify:d,parse:b}}(),proj:function(){var e=1.5707963267948966,i=.7853981633974483,s=.017453292519943295,o=57.29577951308232,n=6378137;return{fromGeodeticPos:function(t){return[n*t[0]*s,n*Math.log(Math.tan(i+t[1]*s/2))]},fromGeodetic:function(e){if(!t.geo._isGeodetic(e))return e;var i=t.isArray(e[0]),s=this.fromGeodeticPos;if(i||4!==e.length){var o,n,r,a=i&&t.isArray(e[0][0]),h=a&&t.isArray(e[0][0][0]),c=[];for(h||(a||(i||(e=[e]),e=[e]),e=[e]),o=0;e.length>o;o++)for(c[o]=[],n=0;e[o].length>n;n++)for(c[o][n]=[],r=0;e[o][n].length>r;r++)c[o][n][r]=s(e[o][n][r]);return h?c:a?c[0]:i?c[0][0]:c[0][0][0]}var l=s([e[0],e[1]]),_=s([e[2],e[3]]);return[l[0],l[1],_[0],_[1]]},toGeodeticPos:function(t){return[t[0]/n*o,(e-2*Math.atan(1/Math.exp(t[1]/n)))*o] -},toGeodetic:function(e){if(t.geo._isGeodetic(e))return e;var i=t.isArray(e[0]),s=this.toGeodeticPos;if(i||4!==e.length){var o,n,r,a=i&&t.isArray(e[0][0]),h=a&&t.isArray(e[0][0][0]),c=[];for(h||(a||(i||(e=[e]),e=[e]),e=[e]),o=0;e.length>o;o++)for(c[o]=[],n=0;e[o].length>n;n++)for(c[o][n]=[],r=0;e[o][n].length>r;r++)c[o][n][r]=s(e[o][n][r]);return h?c:a?c[0]:i?c[0][0]:c[0][0][0]}var l=s([e[0],e[1]]),_=s([e[2],e[3]]);return[l[0],l[1],_[0],_[1]]}}}(),_serviceTypes:{}}}(jQuery,this),function(t,e,i){var s=function(){var t=5,e=document.createElement("div"),i=e.all||[];do e.innerHTML="";while(i[0]);return t>6?t:!t}();t.widget("geo.geographics",{_$elem:i,_options:{},_trueCanvas:!0,_trueDoubleBuffer:!0,_width:0,_height:0,_$canvas:i,_context:i,_$canvasSceneFront:i,_$canvasSceneBack:i,_timeoutEnd:null,_requireFlip:!1,_blitcanvas:i,_blitcontext:i,_$labelsContainerFront:i,_$labelsContainerBack:i,_labelsHtml:"",options:{style:{borderRadius:"8px",color:"#7f0000",fillOpacity:.2,height:"8px",opacity:1,strokeOpacity:1,strokeWidth:"2px",visibility:"visible",width:"8px"},doubleBuffer:!0},_create:function(){this._$elem=this.element,this._options=this.options,this._$elem.css({webkitTransform:"translateZ(0)",display:"inline-block",overflow:"hidden",textAlign:"left"}),"static"===this._$elem.css("position")&&this._$elem.css("position","relative"),this._$elem.addClass("geo-graphics"),this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10));var i="position:absolute;left:0;top:0;margin:0;padding:0;",o="width:"+this._width+"px;height:"+this._height+"px;",n='width="'+this._width+'" height="'+this._height+'"';this._blitcanvas=document.createElement("canvas"),this._blitcanvas.getContext?(this._$canvas=t(e.toStaticHTML("')),this._blitcanvas.width=1,this._blitcanvas.height=1,this._trueDoubleBuffer=this._blitcanvas.toDataURL().length>6,this._options.doubleBuffer&&this._trueDoubleBuffer||this._$elem.append(this._$canvas),this._context=this._$canvas[0].getContext("2d"),this._blitcanvas.width=this._width,this._blitcanvas.height=this._height,this._blitcontext=this._blitcanvas.getContext("2d"),this._$canvasSceneFront=t(e.toStaticHTML('')),this._$canvasSceneBack=t(e.toStaticHTML(''))):8>=s&&(this._trueCanvas=!1,this._$elem.append("
        '),this._$canvas=this._$elem.children(":last"),G_vmlCanvasManager.initElement(this._$canvas[0]),this._context=this._$canvas[0].getContext("2d"),this._$canvas.children().css({backgroundColor:"transparent",width:this._width,height:this._height})),this._$labelsContainerFront=t(e.toStaticHTML('
        ')),this._$labelsContainerBack=t(e.toStaticHTML('
        '))},_setOption:function(e,i){"style"===e&&(i=t.extend({},this._options.style,i)),t.Widget.prototype._setOption.apply(this,arguments)},destroy:function(){t.Widget.prototype.destroy.apply(this,arguments),this._$elem.html(""),this._$elem.removeClass("geo-graphics")},clear:function(){this._context.clearRect(0,0,this._width,this._height),this._labelsHtml="",this._end()},drawArc:function(t,e,i,s){if(s=this._getGraphicStyle(s),"hidden"!==s.visibility&&s.opacity>0&&s.widthValue>0&&s.heightValue>0){var o=Math.min(s.widthValue,s.heightValue)/2;e=e*Math.PI/180,i=i*Math.PI/180,this._context.save(),this._context.translate(t[0],t[1]),s.widthValue>s.heightValue?this._context.scale(s.widthValue/s.heightValue,1):this._context.scale(1,s.heightValue/s.widthValue),this._context.beginPath(),this._context.arc(0,0,o,e,i,!1),this._trueCanvas&&this._context.restore(),s.doFill&&(this._context.fillStyle=s.fill,this._context.globalAlpha=s.opacity*s.fillOpacity,this._context.fill()),s.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=s.strokeWidthValue,this._context.strokeStyle=s.stroke,this._context.globalAlpha=s.opacity*s.strokeOpacity,this._context.stroke()),this._trueCanvas||this._context.restore()}this._end()},drawPoint:function(t,e){e=this._getGraphicStyle(e),e.widthValue===e.heightValue&&e.heightValue===e.borderRadiusValue?this.drawArc(t,0,360,e):"hidden"!==e.visibility&&e.opacity>0&&(e.borderRadiusValue=Math.min(Math.min(e.widthValue,e.heightValue)/2,e.borderRadiusValue),t[0]-=e.widthValue/2,t[1]-=e.heightValue/2,this._context.beginPath(),this._context.moveTo(t[0]+e.borderRadiusValue,t[1]),this._context.lineTo(t[0]+e.widthValue-e.borderRadiusValue,t[1]),this._context.quadraticCurveTo(t[0]+e.widthValue,t[1],t[0]+e.widthValue,t[1]+e.borderRadiusValue),this._context.lineTo(t[0]+e.widthValue,t[1]+e.heightValue-e.borderRadiusValue),this._context.quadraticCurveTo(t[0]+e.widthValue,t[1]+e.heightValue,t[0]+e.widthValue-e.borderRadiusValue,t[1]+e.heightValue),this._context.lineTo(t[0]+e.borderRadiusValue,t[1]+e.heightValue),this._context.quadraticCurveTo(t[0],t[1]+e.heightValue,t[0],t[1]+e.heightValue-e.borderRadiusValue),this._context.lineTo(t[0],t[1]+e.borderRadiusValue),this._context.quadraticCurveTo(t[0],t[1],t[0]+e.borderRadiusValue,t[1]),this._context.closePath(),e.doFill&&(this._context.fillStyle=e.fill,this._context.globalAlpha=e.opacity*e.fillOpacity,this._context.fill()),e.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=e.strokeWidthValue,this._context.strokeStyle=e.stroke,this._context.globalAlpha=e.opacity*e.strokeOpacity,this._context.stroke()),this._end())},drawLineString:function(t,e){this._drawLines([t],!1,e)},drawPolygon:function(t,e){if(this._trueCanvas&&1!==t.length){if(!t||!t.length||3>t[0].length)return;e=this._getGraphicStyle(e);var i,s,o;if("hidden"!==e.visibility&&e.opacity>0){if(this._blitcontext.clearRect(0,0,this._width,this._height),e.doFill&&t.length>1)for(this._blitcontext.globalCompositeOperation="source-out",this._blitcontext.globalAlpha=1,s=1;t.length>s;s++){for(this._blitcontext.beginPath(),this._blitcontext.moveTo(t[s][0][0],t[s][0][1]),o=1;t[s].length>o;o++)this._blitcontext.lineTo(t[s][o][0],t[s][o][1]);this._blitcontext.closePath(),this._blitcontext.fill()}for(this._blitcontext.beginPath(),this._blitcontext.moveTo(t[0][0][0],t[0][0][1]),i=[t[0][0][0]-e.strokeWidthValue,t[0][0][1]-e.strokeWidthValue,t[0][0][0]+e.strokeWidthValue,t[0][0][1]+e.strokeWidthValue],s=1;t[0].length-1>s;s++)this._blitcontext.lineTo(t[0][s][0],t[0][s][1]),i[0]=Math.min(t[0][s][0]-e.strokeWidthValue,i[0]),i[1]=Math.min(t[0][s][1]-e.strokeWidthValue,i[1]),i[2]=Math.max(t[0][s][0]+e.strokeWidthValue,i[2]),i[3]=Math.max(t[0][s][1]+e.strokeWidthValue,i[3]);if(this._blitcontext.closePath(),this._blitcontext.globalCompositeOperation="source-out",e.doFill&&(this._blitcontext.fillStyle=e.fill,this._blitcontext.globalAlpha=e.opacity*e.fillOpacity,this._blitcontext.fill()),this._blitcontext.globalCompositeOperation="source-over",e.doStroke&&(this._blitcontext.lineCap=this._blitcontext.lineJoin="round",this._blitcontext.lineWidth=e.strokeWidthValue,this._blitcontext.strokeStyle=e.stroke,this._blitcontext.globalAlpha=e.opacity*e.strokeOpacity,this._blitcontext.stroke(),t.length>1))for(s=1;t.length>s;s++){for(this._blitcontext.beginPath(),this._blitcontext.moveTo(t[s][0][0],t[s][0][1]),o=1;t[s].length>o;o++)this._blitcontext.lineTo(t[s][o][0],t[s][o][1]);this._blitcontext.closePath(),this._blitcontext.stroke()}i[0]=Math.min(Math.max(i[0],0),this._width),i[1]=Math.min(Math.max(i[1],0),this._height),i[2]=Math.min(Math.max(i[2],0),this._width),i[3]=Math.min(Math.max(i[3],0),this._height),i[0]!==i[2]&&i[1]!==i[3]&&(this._context.drawImage(this._blitcanvas,i[0],i[1],i[2]-i[0],i[3]-i[1],i[0],i[1],i[2]-i[0],i[3]-i[1]),this._end())}}else this._drawLines(t,!0,e)},drawBbox:function(t,e){this._drawLines([[[t[0],t[1]],[t[0],t[3]],[t[2],t[3]],[t[2],t[1]],[t[0],t[1]]]],!0,e)},drawLabel:function(t,e){this._labelsHtml+='
        '+e+"
        "},resize:function(t,e){this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10)),this._trueCanvas?(this._$canvas[0].width=this._width,this._$canvas[0].height=this._height,this._$canvasSceneFront.css({left:t,top:e}),this._$canvasSceneBack.css({width:this._width,height:this._height})):this._$canvas.css({width:this._width,height:this._height});var i=this._$labelsContainerFront.position();this._$labelsContainerFront.css({left:i.left+t,top:i.top+e,width:this._width,height:this._height}),this._$labelsContainerBack.css({width:this._width,height:this._height})},interactiveTransform:function(t,e){if(this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._trueCanvas)if(this._options.doubleBuffer&&this._trueDoubleBuffer){var i=this;if(this._requireFlip){i._requireFlip=!1;var s=i._$canvasSceneFront;i._$canvasSceneFront=i._$canvasSceneBack.css({left:0,top:0,width:i._width,height:i._height}).prop("src",i._$canvas[0].toDataURL()).prependTo(i._$elem),i._$canvasSceneBack=s.prop("src","").detach()}this._$canvasSceneFront.css({left:Math.round(t[0]),top:Math.round(t[1]),width:this._width*e,height:this._height*e})}else this._context.clearRect(0,0,this._width,this._height);else this._context.clearRect(0,0,this._width,this._height);this._$labelsContainerFront.css({left:Math.round(t[0]),top:Math.round(t[1]),width:this._width*e,height:this._height*e})},_canvasSceneLoad:function(){var t=this;if(t._requireFlip){t._requireFlip=!1;var e=t._$canvasSceneFront;t._$canvasSceneFront=t._$canvasSceneBack.css({left:0,top:0,width:t._width,height:t._height}).prependTo(t._$elem),t._$canvasSceneBack=e.prop("src","").detach()}},_endCallback:function(){var t=this;if(t._timeoutEnd){t._trueCanvas&&t._options.doubleBuffer&&t._trueDoubleBuffer&&(t._$canvasSceneBack.prop("src",t._$canvas[0].toDataURL()),this._canvasSceneLoad()),t._$labelsContainerBack.html(e.toStaticHTML(t._labelsHtml)).find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"});var i=t._$labelsContainerFront;t._$labelsContainerFront=t._$labelsContainerBack.css({left:0,top:0,width:t._width,height:t._height}).appendTo(t._$elem),t._$labelsContainerBack=i.detach(),t._timeoutEnd=null}},_end:function(){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._requireFlip=!0,this._timeoutEnd=setTimeout(t.proxy(this._endCallback,this),20)},_getGraphicStyle:function(e){function i(t){return t=parseInt(t,10),+t+""===t?+t:t}return e=t.extend({},this._options.style,e),e.borderRadiusValue=i(e.borderRadius),e.fill=e.fill||e.color,e.doFill=e.fill&&e.fillOpacity>0,e.stroke=e.stroke||e.color,e.strokeWidthValue=i(e.strokeWidth),e.doStroke=e.stroke&&e.strokeOpacity>0&&e.strokeWidthValue>0,e.widthValue=i(e.width),e.heightValue=i(e.height),e},_drawLines:function(t,e,i){if(t&&t.length&&!(2>t[0].length)){var s,o;if(i=this._getGraphicStyle(i),"hidden"!==i.visibility&&i.opacity>0){for(this._context.beginPath(),s=0;t.length>s;s++)for(this._context.moveTo(t[s][0][0],t[s][0][1]),o=1;t[s].length>o;o++)this._context.lineTo(t[s][o][0],t[s][o][1]);e&&this._context.closePath(),e&&i.doFill&&(this._context.fillStyle=i.fill,this._context.globalAlpha=i.opacity*i.fillOpacity,this._context.fill()),i.doStroke&&(this._context.lineCap=this._context.lineJoin="round",this._context.lineWidth=i.strokeWidthValue,this._context.strokeStyle=i.stroke,this._context.globalAlpha=i.opacity*i.strokeOpacity,this._context.stroke()),this._end()}}}})}(jQuery,window),function(t,e,i){var s=0,o=function(){var t=5,e=document.createElement("div"),i=e.all||[];do e.innerHTML="";while(i[0]);return t>6?t:!t}(),n={bbox:[-180,-85,180,85],bboxMax:[-180,-85,180,85],center:[0,0],cursors:{"static":"default",pan:"url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move",click:"crosshair",zoom:"crosshair",dragBox:"crosshair",dragCircle:"crosshair",drawPoint:"crosshair",drawLineString:"crosshair",drawPolygon:"crosshair",measureLength:"crosshair",measureArea:"crosshair"},measureLabels:{length:"{{:length.toFixed( 2 )}} m",area:"{{:area.toFixed( 2 )}} sq m"},drawStyle:{},shapeStyle:{},mode:"pan",pannable:!0,scroll:"default",shift:"default",services:[{"class":"osm",type:"tiled",src:function(t){return"//otile"+(t.index%4+1)+("https:"===location.protocol?"-s":"")+".mqcdn.com/tiles/1.0.0/osm/"+t.zoom+"/"+t.tile.column+"/"+t.tile.row+".png"},attr:"Tiles Courtesy of MapQuest "}],tilingScheme:{tileWidth:256,tileHeight:256,levels:18,basePixelSize:156543.03392799935,origin:[-20037508.342787,20037508.342787]},axisLayout:"map",zoom:0,zoomMin:0,zoomMax:Number.POSITIVE_INFINITY,zoomFactor:2,pixelSize:0};t.widget("geo.geomap",{_$elem:i,_map:i,_created:!1,_createdGraphics:!1,_widgetId:0,_tmplLengthId:"",_tmplAreaId:"",_contentBounds:{},_$resizeContainer:i,_$eventTarget:i,_$contentFrame:i,_$existingChildren:i,_$attrList:i,_$servicesContainer:i,_$shapesContainers:i,_$panContainer:i,_$shapesContainer:i,_$drawContainer:i,_$measureContainer:i,_$measureLabel:i,_dpi:96,_currentServices:[],_center:i,_pixelSize:i,_centerMax:i,_pixelSizeMax:i,_pixelSizeMin:i,_userGeodetic:!0,_centerInteractive:i,_pixelSizeInteractive:i,_timeoutInteractive:null,_triggerInteractive:!1,_timeoutRefreshShapes:null,_loadCount:0,_wheelLevel:0,_fullZoomFactor:2,_partialZoomFactor:1.18920711500273,_mouseDown:i,_inOp:i,_toolPan:i,_shiftDown:i,_anchor:i,_current:i,_downDate:i,_moveDate:i,_clickDate:i,_lastMove:i,_lastDrag:i,_windowHandler:null,_resizeTimeout:null,_panning:i,_velocity:i,_friction:i,_supportTouch:i,_softDblClick:i,_isTap:i,_isDbltap:i,_isMultiTouch:i,_multiTouchAnchor:[],_multiTouchAnchorBbox:i,_multiTouchCurrentBbox:i,_drawTimeout:null,_drawPixels:[],_drawCoords:[],_graphicShapes:[],_initOptions:{},_options:{},options:t.extend({},n),_createWidget:function(e,o){if(this._$elem=t(o),this._$elem.is(".geo-service"))return this._graphicShapes=[],t.Widget.prototype._createWidget.apply(this,arguments),i;this._widgetId=s++,this._serviceIdSeed=0,this._tmplLengthId="geoMeasureLength"+this._widgetId,this._tmplAreaId="geoMeasureArea"+this._widgetId,this._$elem.addClass("geo-map").css({webkitTransform:"translateZ(0)"}),this._initOptions=e||{},this._forcePosition(this._$elem),this._$elem.css("text-align","left");var n=this._findMapSize();this._contentBounds={x:parseInt(this._$elem.css("padding-left"),10),y:parseInt(this._$elem.css("padding-top"),10),width:n.width,height:n.height},this._createChildren(),this._center=[0,0],this._centerMax=[0,0],this._centerInteractive=[0,0],this.options.pixelSize=this._pixelSize=this._pixelSizeMax=156543.03392799935,this._pixelSizeMin=this._pixelSizeMax/Math.pow(2,17),this._mouseDown=this._inOp=this._toolPan=this._shiftDown=this._panning=this._isTap=this._isDbltap=!1,this._anchor=[0,0],this._current=[0,0],this._lastMove=[0,0],this._lastDrag=[0,0],this._velocity=[0,0],this._friction=[.8,.8],this._downDate=this._moveDate=this._clickDate=0,this._drawPixels=[],this._drawCoords=[],this._graphicShapes=[],t.Widget.prototype._createWidget.apply(this,arguments)},_create:function(){if(this._options=this.options,this._$elem.is(".geo-service"))return this._map=this._$elem.data("geoMap"),this._$elem.data("geoService",this),i;this._map=this,this._supportTouch="ontouchend"in document,this._softDblClick=this._supportTouch||7===o;var s=this,n=this._supportTouch?"touchstart mousedown":"mousedown",r=this._supportTouch?"touchend touchcancel mouseup":"mouseup",a=this._supportTouch?"touchmove mousemove":"mousemove";t(document).keydown(t.proxy(this._document_keydown,this)),this._$eventTarget.dblclick(t.proxy(this._eventTarget_dblclick,this)),this._$eventTarget.bind(n,t.proxy(this._eventTarget_touchstart,this));var h=this._$eventTarget[0].setCapture?this._$eventTarget:t(document);h.bind(a,t.proxy(this._dragTarget_touchmove,this)),h.bind(r,t.proxy(this._dragTarget_touchstop,this)),this._$eventTarget.mousewheel(t.proxy(this._eventTarget_mousewheel,this)),this._windowHandler=function(){s._resizeTimeout&&clearTimeout(s._resizeTimeout),s._resizeTimeout=setTimeout(function(){s._created&&s._$elem.geomap("resize",!0)},500)},t(e).resize(this._windowHandler),this._$drawContainer.geographics({style:this._initOptions.drawStyle||{},doubleBuffer:!1}),this._options.drawStyle=this._$drawContainer.geographics("option","style"),this._$shapesContainer.geographics({style:this._initOptions.shapeStyle||{}}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style"),this._initOptions&&(this._initOptions.tilingScheme!==i&&this._setOption("tilingScheme",this._initOptions.tilingScheme||null,!1),this._initOptions.services&&(this._options.services=t.merge([],this._initOptions.services)),this._initOptions.bboxMax&&(this._setOption("bboxMax",this._initOptions.bboxMax,!1),this._setOption("bbox",this._initOptions.bboxMax,!1)),this._initOptions.zoomMin!==i&&this._setOption("zoomMin",this._initOptions.zoomMin,!1),this._initOptions.zoomMax!==i&&this._setOption("zoomMax",this._initOptions.zoomMax,!1),this._initOptions.zoomFactor!==i&&(this._setOption("zoomFactor",this._initOptions.zoomFactor,!1),this._fullZoomFactor=this._initOptions.zoomFactor,this._partialZoomFactor=Math.pow(4,1/this._fullZoomFactor)),this._initOptions.bbox&&this._setOption("bbox",this._initOptions.bbox,!1),this._initOptions.center&&this._setOption("center",this._initOptions.center,!1),this._initOptions.zoom!==i&&this._setOption("zoom",this._initOptions.zoom,!1)),t.templates(this._tmplLengthId,this._options.measureLabels.length),t.templates(this._tmplAreaId,this._options.measureLabels.area),this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._createServices(),this._refresh(),this._created=!0},_setOption:function(e,s,o){if("pixelSize"!==e){o=o===i||o,this._$elem.is(".geo-map")&&this._panFinalize();var n,r,a,h;switch(e){case"bbox":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&t.geo.proj&&t.geo._isGeodetic(s),this._userGeodetic&&(s=t.geo.proj.fromGeodetic(s)),n=[s[0]+(s[2]-s[0])/2,s[1]+(s[3]-s[1])/2],r=Math.max(t.geo.width(s,!0)/this._contentBounds.width,t.geo.height(s,!0)/this._contentBounds.height),h=this._getZoom(n,r),this._options.tilingScheme?r=this._getPixelSize(Math.min(Math.max(h,this._options.zoomMin),this._options.zoomMax)):this._options.zoomMin>h?r=this._getPixelSize(this._options.zoomMin):h>this._options.zoomMax&&(r=this._getPixelSize(this._options.zoomMax)),this._created?(this._setInteractiveCenterAndSize(n,r),this._setInteractiveTimeout(!1)):this._setCenterAndSize(n,r,!1,o),s=this._getBbox(n,r);break;case"bboxMax":this._userGeodetic="map"===this._options.axisLayout&&t.geo.proj&&t.geo._isGeodetic(s);break;case"center":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&t.geo.proj&&t.geo._isGeodetic(s),this._userGeodetic&&(s=t.geo.proj.fromGeodetic(s)),this._created?(this._setInteractiveCenterAndSize(s,this._pixelSizeInteractive),this._interactiveTransform(),this._setInteractiveTimeout(!1)):this._setCenterAndSize(s,this._pixelSize,!1,o);break;case"measureLabels":s=t.extend(this._options.measureLabels,s),t.templates(this._tmplLengthId,this._options.measureLabels.length),t.templates(this._tmplAreaId,this._options.measureLabels.area);break;case"drawStyle":this._$drawContainer&&(this._$drawContainer.geographics("option","style",s),s=this._$drawContainer.geographics("option","style"));break;case"shapeStyle":this._$elem.is(".geo-service")&&!this._createdGraphics&&this._createServiceGraphics(),this._createdGraphics&&(this._$shapesContainer.geographics("option","style",s),s=this._$shapesContainer.geographics("option","style"));break;case"mode":this._resetDrawing(),this._$eventTarget.css("cursor",this._options.cursors[s]);break;case"zoom":this._created?this._setZoom(s,!1,o):(s=Math.max(s,0),this._setCenterAndSize(this._center,this._getPixelSize(s),!1,o))}switch(t.Widget.prototype._setOption.apply(this,arguments),e){case"bbox":case"center":this._userGeodetic&&(this._options.bbox=t.geo.proj.toGeodetic(this._options.bbox),this._options.center=t.geo.proj.toGeodetic(this._center));break;case"tilingScheme":null!==s&&(this._pixelSizeMax=this._getPixelSize(0),this._pixelSizeMin=this._getPixelSize(s.pixelSizes?s.pixelSizes.length-1:s.levels-1),this._centerMax=[s.origin[0]+this._pixelSizeMax*s.tileWidth/2,s.origin[1]+this._pixelSizeMax*s.tileHeight/2]);break;case"bboxMax":a=this._userGeodetic?t.geo.proj.fromGeodetic(s):s,this._centerMax=t.geo.center(a),this._pixelSizeMax=Math.max(t.geo.width(a,!0)/this._contentBounds.width,t.geo.height(a,!0)/this._contentBounds.height),this._pixelSizeMin=1;break;case"services":this._createServices(),o&&(this._refresh(),this._refreshAllShapes());break;case"shapeStyle":o&&this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))}}},destroy:function(){if(this._$elem.is(".geo-service"))this._createdGraphics&&(this._$shapesContainer.geographics("destroy"),this._$shapesContainer=i,this._createdGraphics=!1);else{clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,this._created=!1,t(e).unbind("resize",this._windowHandler);for(var s=0;this._currentServices.length>s;s++)this._currentServices[s].serviceContainer.geomap("destroy"),t.geo._serviceTypes[this._currentServices[s].type].destroy(this,this._$servicesContainer,this._currentServices[s]);this._$shapesContainer.geographics("destroy"),this._$shapesContainer=i,this._createdGraphics=!1,this._$drawContainer.geographics("destroy"),this._$drawContainer=i,this._$existingChildren.detach(),this._$elem.html(""),this._$elem.append(this._$existingChildren),this._$elem.removeClass("geo-map")}t.Widget.prototype.destroy.apply(this,arguments)},toMap:function(e){return e=this._toMap(e),this._userGeodetic?t.geo.proj.toGeodetic(e):e},toPixel:function(e,i,s){return this._toPixel(t.geo.proj?t.geo.proj.fromGeodetic(e):e,i,s)},opacity:function(e,i){if(this._$elem.is(".geo-service"))this._$elem.closest(".geo-map").geomap("opacity",e,this._$elem);else if(e>=0||1>=e)for(var s=0;this._currentServices.length>s;s++){var o=this._currentServices[s];i&&o.serviceContainer[0]!==i[0]||(o.style.opacity=e,o.serviceObject.style=t.extend({},o.serviceObject.style,o.style),t.geo._serviceTypes[o.type].opacity(this,o))}},toggle:function(e,s){if(this._$elem.is(".geo-service"))this._$elem.closest(".geo-map").geomap("toggle",e,this._$elem);else for(var o=0;this._currentServices.length>o;o++){var n=this._currentServices[o];s&&n.serviceContainer[0]!==s[0]||(e===i&&(e="visible"!==n.style.visibility),n.style.visibility=e?"visible":"hidden",n.serviceObject.style=t.extend({},n.serviceObject.style,n.style),n.serviceContainer.toggle(e),e&&t.geo._serviceTypes[n.type].refresh(this,n))}},zoom:function(t){null!==t&&this._setZoom(this._options.zoom+t,!1,!0)},refresh:function(t,e){this._$elem.is(".geo-service")?this._$elem.closest(".geo-map").geomap("refresh",t,this._$elem):(this._refresh(t,e),this._refreshAllShapes())},resize:function(e){var i,s=this._findMapSize(),o=s.width/2-this._contentBounds.width/2,n=s.height/2-this._contentBounds.height/2;for(this._contentBounds={x:parseInt(this._$elem.css("padding-left"),10),y:parseInt(this._$elem.css("padding-top"),10),width:s.width,height:s.height},this._$resizeContainer.css({width:s.width,height:s.height}),i=0;this._currentServices.length>i;i++)t.geo._serviceTypes[this._currentServices[i].type].resize(this,this._currentServices[i],o,n);for(this._$elem.find(".geo-graphics").css({width:s.width,height:s.height}).geographics("resize",o,n),i=0;this._drawPixels.length>i;i++)this._drawPixels[i][0]+=o,this._drawPixels[i][1]+=n;this._setCenterAndSize(this._center,this._pixelSize,e,!0)},append:function(e){if(e&&(t.isPlainObject(e)||t.isArray(e)&&e.length>0)){this._createdGraphics||this._createServiceGraphics();var s,o,n,r,a,h;for(s=t.isArray(e)?e:"FeatureCollection"===e.type?e.features:[e],n=1;arguments.length>n;n++)o=arguments[n],null!==o&&("object"==typeof o?r=o:"number"==typeof o||"string"==typeof o?a=o:"boolean"==typeof o&&(h=o));for(n=0;s.length>n;n++){if(!t.data(s[n],"geoBbox")){var c=t.geo.bbox(s[n]);t.geo.proj&&t.geo._isGeodetic(c)&&(c=t.geo.proj.fromGeodetic(c)),t.data(s[n],"geoBbox",c)}this._graphicShapes.push({shape:s[n],style:r,label:a})}(h===i||h)&&(this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh(),this._refreshAllShapes())}},empty:function(t){this._graphicShapes=[],(t===i||t)&&(this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh(),this._refreshAllShapes())},find:function(e,i){for(var s,o,n,r=t.isPlainObject(e),a=this._map._pixelSize*i,h=[],c=0;this._graphicShapes.length>c;c++)if(s=this._graphicShapes[c],r)if("Point"===s.shape.type)a>=t.geo.distance(s.shape,e)&&h.push(s.shape);else{var l=t.data(s.shape,"geoBbox"),_={type:"Polygon",coordinates:[[[l[0],l[1]],[l[0],l[3]],[l[2],l[3]],[l[2],l[1]],[l[0],l[1]]]]},u={type:"Point",coordinates:t.geo.proj&&t.geo._isGeodetic(e.coordinates)?t.geo.proj.fromGeodetic(e.coordinates):e.coordinates};if(a>=t.geo.distance(_,u,!0))for(o=t.geo._basic(s.shape),n=0;o.length>n;n++)if(a>=t.geo.distance(o[n],e)){h.push(s.shape);break}}else h.push(s.shape);return this._$elem.is(".geo-map")&&this._$elem.find(".geo-service").each(function(){h=t.merge(h,t(this).geomap("find",e,i))}),h},remove:function(e,s){if(e&&(t.isPlainObject(e)||t.isArray(e)&&e.length>0)){for(var o,n=t.isArray(e)?e:[e],r=0;this._graphicShapes.length>r;r++)t.inArray(this._graphicShapes[r].shape,n)>=0&&(o=this._graphicShapes.slice(r+1),this._graphicShapes.length=r,this._graphicShapes.push.apply(this._graphicShapes,o),r--);(s===i||s)&&(this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh(),this._refreshAllShapes())}},_getBbox:function(t,e){t=t||this._center,e=e||this._pixelSize;var i=this._contentBounds.width/2*e,s=this._contentBounds.height/2*e;return[t[0]-i,t[1]-s,t[0]+i,t[1]+s]},_setBbox:function(e){var i=[e[0]+(e[2]-e[0])/2,e[1]+(e[3]-e[1])/2],s=Math.max(t.geo.width(e,!0)/this._contentBounds.width,t.geo.height(e,!0)/this._contentBounds.height),o=this._getZoom(i,s);this._options.tilingScheme?s=this._getPixelSize(Math.min(Math.max(o,this._options.zoomMin),this._options.zoomMax)):this._options.zoomMin>o?s=this._getPixelSize(this._options.zoomMin):o>this._options.zoomMax&&(s=this._getPixelSize(this._options.zoomMax)),this._setInteractiveCenterAndSize(i,s),this._interactiveTransform()},_getBboxMax:function(){var t=this._contentBounds.width/2*this._pixelSizeMax,e=this._contentBounds.height/2*this._pixelSizeMax;return[this._centerMax[0]-t,this._centerMax[1]-e,this._centerMax[0]+t,this._centerMax[1]+e]},_getCenter:function(){return this._center},_getContentBounds:function(){return this._contentBounds},_getServicesContainer:function(){return this._$servicesContainer},_getZoom:function(e,i){e=e||this._center,i=i||this._pixelSize;var s=this._options.tilingScheme;if(s){if(s.pixelSizes){for(var o=Math.floor(1e3*i),n=s.pixelSizes.length,r=n-1;r>=0;r--)if(Math.floor(1e3*s.pixelSizes[r])>=o)return r;return 0}return Math.round(Math.log(s.basePixelSize/i)/Math.log(2))}var a=this._contentBounds.width/this._contentBounds.height,h=t.geo.reaspect(this._getBbox(e,i),a,!0),c=t.geo.reaspect(this._getBboxMax(),a,!0);return Math.round(Math.log(t.geo.width(c,!0)/t.geo.width(h,!0))/Math.log(this._fullZoomFactor))},_setZoom:function(t,e){this._clearInteractiveTimeout(),t=Math.min(Math.max(t,this._options.zoomMin),this._options.zoomMax),this._setInteractiveCenterAndSize(this._centerInteractive,this._getPixelSize(t)),this._interactiveTransform(),this._setInteractiveTimeout(e)},_createChildren:function(){this._$existingChildren=this._$elem.children(),this._forcePosition(this._$existingChildren),this._$existingChildren.detach().css({mozUserSelect:"none"});var i="width:"+this._contentBounds.width+"px; height:"+this._contentBounds.height+"px; margin:0; padding:0;",s="position:absolute; left:0; top:0;";this._$elem.prepend(e.toStaticHTML('
        ')),this._$eventTarget=this._$contentFrame=this._$elem.children(":first"),this._$contentFrame.append('
        '),this._$servicesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
          '),this._$attrList=this._$contentFrame.children(":last"),this._$contentFrame.append('
          '),this._$drawContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
          '),this._$measureContainer=this._$contentFrame.children(":last"),this._$measureLabel=this._$measureContainer.children(),this._$contentFrame.append('
          '),this._$shapesContainer=this._$contentFrame.children(":last"),this._$panContainer=t([this._$shapesContainer[0],this._$drawContainer[0],this._$measureContainer[0]]),this._$resizeContainer=t([this._$contentFrame[0],this._$servicesContainer[0],this._$eventTarget[0],this._$measureContainer[0]]),this._$contentFrame.append(this._$existingChildren),t("#geo-measure-style").length||t("head").prepend(e.toStaticHTML('"))},_createServices:function(){var i,s;for(s=0;this._currentServices.length>s;s++)this._currentServices[s].serviceContainer.geomap("destroy"),t.geo._serviceTypes[this._currentServices[s].type].destroy(this,this._$servicesContainer,this._currentServices[s]);for(this._currentServices=[],this._$servicesContainer.html(""),this._$attrList.html(""),s=0;this._options.services.length>s;s++){i=this._currentServices[s]=t.extend({},this._options.services[s]),i.serviceObject=this._options.services[s],i.style=t.extend({visibility:"visible",opacity:1},i.style);var o,n=i.id?' id="'+i.id+'"':"",r='class="geo-service '+(i["class"]?i["class"]:"")+'"',a="
          ';this._$servicesContainer.append(e.toStaticHTML(a)),o=this._$servicesContainer.children(":last"),i.serviceContainer=o,t.geo._serviceTypes[i.type].create(this,o,i,s),o.data("geoMap",this).geomap(),i.attr&&this._$attrList.append("
        • "+i.attr+"
        • ") -}this._$shapesContainers=this._$shapesContainer,this._$attrList.find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"})},_createServiceGraphics:function(){var t=this._$elem.closest(".geo-content-frame");this._$elem.append('
          '),this._$shapesContainer=this._$elem.children(":last"),this._map._$shapesContainers=this._map._$shapesContainers.add(this._$shapesContainer),this._$shapesContainer.geographics(),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style")},_refreshDrawing:function(){if(this._$drawContainer.geographics("clear"),this._drawPixels.length>0){var e,i,s,o,n,r=this._options.mode,a=this._drawPixels,h=this._drawCoords;switch(r){case"measureLength":r="drawLineString",i={type:"LineString",coordinates:h},e=t.render[this._tmplLengthId]({length:t.geo.length(i,!0)}),s=t.merge([],a[a.length-1]);break;case"measureArea":r="drawPolygon",i={type:"Polygon",coordinates:[t.merge([],h)]},i.coordinates[0].push(h[0]),e=t.render[this._tmplAreaId]({area:t.geo.area(i,!0)}),s=this._toPixel(t.geo.centroid(i).coordinates),a=[a];break;case"drawPolygon":a=[a]}this._$drawContainer.geographics(r,a),e&&(this._$measureLabel.html(e),o=this._contentBounds.width-(this._$measureLabel.outerWidth(!0)+s[0]),n=this._contentBounds.height-(this._$measureLabel.outerHeight(!0)+s[1]),0>o&&(s[0]+=o),0>n&&(s[1]+=n),this._$measureLabel.css({left:Math.max(s[0],0),top:Math.max(s[1],0)}).show())}},_resetDrawing:function(){this._drawPixels=[],this._drawCoords=[],this._$drawContainer.geographics("clear"),this._$measureLabel.hide()},_refreshAllShapes:function(){this._timeoutRefreshShapes=null;for(var t,e,i=0;this._currentServices.length>i;i++)t=this._currentServices[i],e=t.serviceContainer.data("geoService"),e._createdGraphics&&(e._$shapesContainer.geographics("clear"),e._graphicShapes.length>0&&e._refreshShapes(e._$shapesContainer,e._graphicShapes,e._graphicShapes,e._graphicShapes));this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._graphicShapes.length>0&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))},_refreshShapes:function(e,s,o,n,r,a){var h,c,l,_,u,d,p,g,m,f=this._map._getBbox(r,a);for(h=0;s.length>h;h++)if(l=s[h].shape||s[h],l=l.geometry||l,_=t.data(l,"geoBbox"),!_||!t.geo._bboxDisjoint(f,_)){switch(u=t.isArray(o)?o[h].style:o,d=t.isArray(n)?n[h].label:n,p=d!==i,g=i,m=t.geo.centroid(l),l.type){case"Point":g=this._map.toPixel(l.coordinates,r,a),this._$shapesContainer.geographics("drawPoint",g,u);break;case"LineString":this._$shapesContainer.geographics("drawLineString",this._map.toPixel(l.coordinates,r,a),u),p&&(g=this._map.toPixel(t.geo.pointAlong(l,.5).coordinates,r,a));break;case"Polygon":this._$shapesContainer.geographics("drawPolygon",this._map.toPixel(l.coordinates,r,a),u),p&&m&&(g=this._map.toPixel(m.coordinates,r,a));break;case"MultiPoint":for(c=0;l.coordinates.length>c;c++)this._$shapesContainer.geographics("drawPoint",this._map.toPixel(l.coordinates[c],r,a),u);p&&m&&(g=this._map.toPixel(m.coordinates,r,a));break;case"MultiLineString":for(c=0;l.coordinates.length>c;c++)this._$shapesContainer.geographics("drawLineString",this._map.toPixel(l.coordinates[c],r,a),u);p&&m&&(g=this._map.toPixel(m.coordinates,r,a));break;case"MultiPolygon":for(c=0;l.coordinates.length>c;c++)this._$shapesContainer.geographics("drawPolygon",this._map.toPixel(l.coordinates[c],r,a),u);p&&m&&(g=this._map.toPixel(m.coordinates,r,a));break;case"GeometryCollection":this._refreshShapes(e,l.geometries,u,d,r,a)}p&&g&&this._$shapesContainer.geographics("drawLabel",g,d)}},_findMapSize:function(){for(var t={width:0,height:0},e=this._$elem;e.size()&&!(t.width>0&&t.height>0);)t={width:e.width(),height:e.height()},(0>=t.width||0>=t.height)&&(t={width:parseInt(e.css("width"),10),height:parseInt(e.css("height"),10)}),e=e.parent();return t},_forcePosition:function(t){var e=t.css("position");"relative"!==e&&"absolute"!==e&&"fixed"!==e&&t.css("position","relative")},_getPixelSize:function(e){var i=this._options.tilingScheme;if(null!==i){if(0===e)return i.pixelSizes?i.pixelSizes[0]:i.basePixelSize;e=Math.round(e),e=Math.max(e,0);var s=i.pixelSizes?i.pixelSizes.length:i.levels;return e=Math.min(e,s-1),i.pixelSizes?i.pixelSizes[e]:i.basePixelSize/Math.pow(2,e)}var o=t.geo.scaleBy(this._getBboxMax(),1/Math.pow(this._fullZoomFactor,e),!0);return Math.max(t.geo.width(o,!0)/this._contentBounds.width,t.geo.height(o,!0)/this._contentBounds.height)},_getZoomCenterAndSize:function(t,e,i){var s=i?this._fullZoomFactor:this._partialZoomFactor,o=Math.pow(s,-e),n=this._pixelSizeInteractive*o;n=Math.min(Math.max(n,this._pixelSizeMin),this._pixelSizeMax);var r=this._getZoom(this._centerInteractive,n);i&&this._options.tilingScheme?n=this._getPixelSize(Math.min(Math.max(r,this._options.zoomMin),this._options.zoomMax)):0>e&&this._options.zoomMin>r?n=this._pixelSizeInteractive:e>0&&r>this._options.zoomMax&&(n=this._pixelSizeInteractive);var a=n/this._pixelSizeInteractive,h=this._toMap(t,this._centerInteractive,this._pixelSizeInteractive),c=[(this._centerInteractive[0]-h[0])*a,(this._centerInteractive[1]-h[1])*a],l=[h[0]+c[0],h[1]+c[1]];return{pixelSize:n,center:l}},_panFinalize:function(){this._panning&&(this._velocity=[0,0],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._inOp=!1,this._anchor=this._current,this._mouseDown=this._toolPan=this._panning=!1)},_panMove:function(){if(this._options.pannable){var t=this._current[0]-this._lastDrag[0],e=this._current[1]-this._lastDrag[1];(this._toolPan||t>3||-3>t||e>3||-3>e)&&(this._toolPan||(this._toolPan=!0,this._$eventTarget.css("cursor",this._options.cursors.pan)),this._mouseDown&&(this._velocity=[t,e]),(0!==t||0!==e)&&(this._panning=!0,this._lastDrag=this._current,this._centerInteractive[0]-=t*this._pixelSizeInteractive,this._centerInteractive[1]+=("image"===this._options.axisLayout?-1:1)*e*this._pixelSizeInteractive,this._setInteractiveCenterAndSize(this._centerInteractive,this._pixelSizeInteractive),this._interactiveTransform()))}},_clearInteractiveTimeout:function(){return this._timeoutRefreshShapes&&(clearTimeout(this._timeoutRefreshShapes),this._timeoutRefreshShapes=null),this._timeoutInteractive?(clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,!0):(this._centerInteractive[0]=this._center[0],this._centerInteractive[1]=this._center[1],this._pixelSizeInteractive=this._pixelSize,!1)},_interactiveTransform:function(){var e,i=this._pixelSize,s=i/this._pixelSizeInteractive;if(i>0){s=Math.round(1e3*s)/1e3;var o=this._toMap([0,0]),n=this._toPixel(o,this._centerInteractive,this._pixelSizeInteractive);this._$shapesContainers.geographics("interactiveTransform",n,s)}for(var r=0;this._currentServices.length>r;r++)e=this._currentServices[r],t.geo._serviceTypes[e.type].interactiveTransform(this,e,this._centerInteractive,this._pixelSizeInteractive);this._drawCoords.length>0&&(this._drawPixels=this._toPixel(this._drawCoords,this._centerInteractive,this._pixelSizeInteractive),this._refreshDrawing())},_interactiveTimeout:function(){this._isMultiTouch?this._timeoutInteractive=setTimeout(t.proxy(this._interactiveTimeout,this),128):this._created&&this._timeoutInteractive&&(this._setCenterAndSize(this._centerInteractive,this._pixelSizeInteractive,this._triggerInteractive,!0),this._timeoutInteractive=null,this._triggerInteractive=!1,this._timeoutRefreshShapes=setTimeout(t.proxy(this._refreshAllShapes,this),128))},_setInteractiveTimeout:function(e){this._timeoutInteractive=setTimeout(t.proxy(this._interactiveTimeout,this),128),this._triggerInteractive|=e},_refresh:function(e,i){for(var s,o=0;this._currentServices.length>o;o++)s=this._currentServices[o],i&&s.serviceContainer[0]!==i[0]||t.geo._serviceTypes[s.type].refresh(this,s,e)},_setInteractiveCenterAndSize:function(e,i){this._centerInteractive[0]=e[0],this._centerInteractive[1]=e[1],this._pixelSizeInteractive=i,this._userGeodetic?(this._options.bbox=t.geo.proj.toGeodetic(this._getBbox(e,i)),this._options.center=t.geo.proj.toGeodetic(e)):(this._options.bbox=this._getBbox(e,i),this._options.center[0]=e[0],this._options.center[1]=e[1]),this._options.pixelSize=i,this._options.zoom=this._getZoom(e,i)},_setCenterAndSize:function(i,s,o,n){if(t.isArray(i)&&2===i.length&&"number"==typeof i[0]&&"number"==typeof i[1]){var r=this._getZoom(i,s);this._options.tilingScheme?this._pixelSizeInteractive=s=this._getPixelSize(Math.min(Math.max(r,this._options.zoomMin),this._options.zoomMax)):this._options.zoomMin>r?this._pixelSizeInteractive=s=this._getPixelSize(this._options.zoomMin):r>this._options.zoomMax&&(this._pixelSizeInteractive=s=this._getPixelSize(this._options.zoomMax)),this._centerInteractive[0]=i[0],this._centerInteractive[1]=i[1],this._created&&this._interactiveTransform(),this._options.pixelSize=this._pixelSize=s,this._center[0]=i[0],this._center[1]=i[1],this._userGeodetic?(this._options.bbox=t.geo.proj.toGeodetic(this._getBbox()),this._options.center=t.geo.proj.toGeodetic(this._center)):(this._options.bbox=this._getBbox(),this._options.center=t.merge([],i)),this._options.zoom=r,o&&this._trigger("bboxchange",e.event,{bbox:t.merge([],this._options.bbox)}),n&&(this._refresh(),this._refreshAllShapes(),this._refreshDrawing())}},_requestQueued:function(){0===this._loadCount&&this._trigger("loadstart",e.event),this._loadCount++},_requestComplete:function(){this._loadCount--,0>=this._loadCount&&(this._loadCount=0,this._trigger("loadend",e.event))},_toMap:function(e,i,s){i=i||this._center,s=s||this._pixelSize;var o,n,r,a,h=t.isArray(e[0]),c=h&&t.isArray(e[0][0]),l=c&&t.isArray(e[0][0][0]),_=this._contentBounds.width,u=this._contentBounds.height,d=_/2*s,p=u/2*s,g=[i[0]-d,i[1]-p,i[0]+d,i[1]+p],m=t.geo.width(g,!0)/_,f=t.geo.height(g,!0)/u,v="image"===this._options.axisLayout,x=[];for(l||(c||(h||(e=[e]),e=[e]),e=[e]),n=0;e.length>n;n++)for(x[n]=[],r=0;e[n].length>r;r++)for(x[n][r]=[],a=0;e[n][r].length>a;a++)o=e[n][r][a][1]*f,x[n][r][a]=[g[0]+e[n][r][a][0]*m,v?g[1]+o:g[3]-o];return l?x:c?x[0]:h?x[0][0]:x[0][0][0]},_toPixel:function(e,i,s){i=i||this._center,s=s||this._pixelSize;var o,n,r,a=t.isArray(e[0]),h=a&&t.isArray(e[0][0]),c=h&&t.isArray(e[0][0][0]),l=this._contentBounds.width,_=this._contentBounds.height,u=l/2*s,d=_/2*s,p=[i[0]-u,i[1]-d,i[0]+u,i[1]+d],g=t.geo.width(p,!0),m=t.geo.height(p,!0),f="image"===this._options.axisLayout,v=l/g,x=_/m,y=[];for(c||(h||(a||(e=[e]),e=[e]),e=[e]),o=0;e.length>o;o++)for(y[o]=[],n=0;e[o].length>n;n++)for(y[o][n]=[],r=0;e[o][n].length>r;r++)y[o][n][r]=[Math.round((e[o][n][r][0]-p[0])*v),Math.round((f?e[o][n][r][1]-p[1]:p[3]-e[o][n][r][1])*x)];return c?y:h?y[0]:a?y[0][0]:y[0][0][0]},_document_keydown:function(e){var i=this._drawCoords.length;i>0&&27===e.which&&(2>=i?(this._resetDrawing(),this._inOp=!1):(this._drawCoords[i-2]=t.merge([],this._drawCoords[i-1]),this._drawPixels[i-2]=t.merge([],this._drawPixels[i-1]),this._drawCoords.length--,this._drawPixels.length--,this._refreshDrawing()))},_eventTarget_dblclick_zoom:function(t){var e=this._clearInteractiveTimeout();if(this._trigger("dblclick",t,{type:"Point",coordinates:this._toMap(this._current,this._centerInteractive,this._pixelSizeInteractive)}),!t.isDefaultPrevented()){var i=this._getZoomCenterAndSize(this._current,1,!0);this._setInteractiveCenterAndSize(i.center,i.pixelSize),this._interactiveTransform(),e=!0}e&&this._setInteractiveTimeout(!0)},_eventTarget_dblclick:function(i){if("static"!==this._options.mode){switch(this._drawTimeout&&(e.clearTimeout(this._drawTimeout),this._drawTimeout=null),this._options.mode){case"drawLineString":case"measureLength":this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])?(this._drawCoords.length--,this._trigger("shape",i,{type:"LineString",coordinates:this._userGeodetic?t.geo.proj.toGeodetic(this._drawCoords):this._drawCoords})):this._eventTarget_dblclick_zoom(i),this._resetDrawing();break;case"drawPolygon":case"measureArea":if(this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])){var s=this._drawCoords.length-1;s>2&&(this._drawCoords[s]=t.merge([],this._drawCoords[0]),this._trigger("shape",i,{type:"Polygon",coordinates:[this._userGeodetic?t.geo.proj.toGeodetic(this._drawCoords):this._drawCoords]}))}else this._eventTarget_dblclick_zoom(i);this._resetDrawing();break;default:this._eventTarget_dblclick_zoom(i)}this._inOp=!1}},_eventTarget_touchstart:function(e){if(document.elementFromPoint!==i){var s=document.elementFromPoint(e.pageX,e.pageY);if(s&&"A"===s.nodeName)return}var o=this._options.mode,n=this._options.shift,r="dragBox"===o?"dragBox":"zoom";if("static"!==o&&(this._supportTouch||1===e.which)){var a=this._clearInteractiveTimeout(),h=t(e.currentTarget).offset(),c=e.originalEvent.changedTouches;if(this._supportTouch&&c?(this._multiTouchAnchor=t.merge([],c),this._isMultiTouch=this._multiTouchAnchor.length>1,this._isMultiTouch?(this._multiTouchCurrentBbox=[c[0].pageX-h.left,c[0].pageY-h.top,c[1].pageX-h.left,c[1].pageY-h.top],this._multiTouchAnchorBbox=t.merge([],this._multiTouchCurrentBbox),this._current=t.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchCurrentBbox=[c[0].pageX-h.left,c[0].pageY-h.top,0/0,0/0],this._current=[c[0].pageX-h.left,c[0].pageY-h.top])):this._current=[e.pageX-h.left,e.pageY-h.top],this._softDblClick){var l=t.now();if(750>l-this._downDate){if(this._isTap){var _=this._current[0]-this._anchor[0],u=this._current[1]-this._anchor[1],d=Math.sqrt(_*_+u*u);d>8?this._isTap=!1:this._current=t.merge([],this._anchor)}this._isDbltap=this._isDbltap?!1:this._isTap}else this._isDbltap=!1;this._isTap=!0,this._downDate=l}return this._mouseDown=!0,this._anchor=t.merge([],this._current),!this._inOp&&e.shiftKey&&"off"!==n?(this._shiftDown=!0,this._$eventTarget.css("cursor",this._options.cursors["default"===n?r:n])):this._isMultiTouch||!this._options.pannable&&"dragBox"!==o&&"dragCircle"!==o||(this._inOp=!0,"zoom"!==o&&"dragBox"!==o&&"dragCircle"!==o&&(this._lastDrag=this._current,e.currentTarget.setCapture&&e.currentTarget.setCapture())),e.preventDefault(),a&&this._setInteractiveTimeout(!0),!1}},_dragTarget_touchmove:function(e){if("static"!==this._options.mode){var s=!1;this._mouseDown&&(s=this._clearInteractiveTimeout());var n,r=this._$eventTarget.offset(),a=this._drawCoords.length,h=e.originalEvent.changedTouches,c=0;if(this._supportTouch&&h){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&h[0].identifier!==this._multiTouchAnchor[0].identifier)return this._mouseDown=!1,this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(h[0]),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-r.left,this._multiTouchAnchor[1].pageY-r.top],this._multiTouchAnchorBbox=t.merge([],this._multiTouchCurrentBbox),this._mouseDown=!0,this._anchor=this._current=t.geo.center(this._multiTouchCurrentBbox,!0),s&&this._setInteractiveTimeout(!0),!1;if(this._isMultiTouch){for(;h.length>c;c++)h[c].identifier===this._multiTouchAnchor[0].identifier?(this._multiTouchCurrentBbox[0]=h[c].pageX-r.left,this._multiTouchCurrentBbox[1]=h[c].pageY-r.top):h[c].identifier===this._multiTouchAnchor[1].identifier&&(this._multiTouchCurrentBbox[2]=h[c].pageX-r.left,this._multiTouchCurrentBbox[3]=h[c].pageY-r.top);var l=t.geo._distancePointPoint([this._multiTouchAnchorBbox[0],this._multiTouchAnchorBbox[1]],[this._multiTouchAnchorBbox[2],this._multiTouchAnchorBbox[3]]),_=t.geo._distancePointPoint([this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1]],[this._multiTouchCurrentBbox[2],this._multiTouchCurrentBbox[3]]);n=t.geo.center(this._multiTouchCurrentBbox,!0);var u=(_-l)/l;u*=u>0?5:10;var d=u-this._wheelLevel;this._wheelLevel=u;var p=this._getZoomCenterAndSize(this._anchor,d,!1);this._setInteractiveCenterAndSize(p.center,p.pixelSize),this._interactiveTransform(),s=!0,n=t.geo.center(this._multiTouchCurrentBbox,!0)}else n=[e.originalEvent.changedTouches[0].pageX-r.left,e.originalEvent.changedTouches[0].pageY-r.top]}else n=[e.pageX-r.left,e.pageY-r.top];if(n[0]===this._lastMove[0]&&n[1]===this._lastMove[1])return this._inOp?(e.preventDefault(),s&&this._setInteractiveTimeout(!0),!1):!1;if(7===o&&(this._isDbltap=this._isTap=!1),this._mouseDown&&(this._current=n,this._moveDate=t.now()),this._isMultiTouch)return e.preventDefault(),this._isDbltap=this._isTap=!1,s&&this._setInteractiveTimeout(!0),!1;var g,m,f,v=this._options.mode,x=this._options.shift,y="dragBox"===v?"dragBox":"zoom";switch(this._shiftDown&&(v="default"===x?y:x),v){case"zoom":case"dragBox":this._mouseDown?(this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawBbox",[this._anchor[0],this._anchor[1],n[0],n[1]])):this._trigger("move",e,{type:"Point",coordinates:this.toMap(n)});break;case"dragCircle":this._mouseDown?(g=n[0]-this._anchor[0],m=n[1]-this._anchor[1],f=2*Math.sqrt(g*g+m*m),this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawArc",this._anchor,0,360,{width:f,height:f})):this._trigger("move",e,{type:"Point",coordinates:this.toMap(n)});break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":this._mouseDown||this._toolPan?(this._panMove(),s=!0):(a>0&&(this._drawCoords[a-1]=this._toMap(n,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[a-1]=n,this._refreshDrawing()),this._trigger("move",e,{type:"Point",coordinates:this.toMap(n)}));break;default:this._mouseDown||this._toolPan?(this._panMove(),s=!0):this._trigger("move",e,{type:"Point",coordinates:this.toMap(n)})}return this._lastMove=n,s&&this._setInteractiveTimeout(!0),this._inOp?(e.preventDefault(),!1):i}},_dragTarget_touchstop:function(s){if("static"!==this._options.mode){if(!this._mouseDown){if(7!==o)return;this._eventTarget_touchstart(s)}var n,r,a,h,c,l,_,u=this._clearInteractiveTimeout(),d=this._mouseDown,p=this._toolPan,g=this._$eventTarget.offset(),m=this._options.mode,f=this._options.shift,v="dragBox"===m?"dragBox":"zoom";if(this._shiftDown&&(m="default"===f?v:f),this._supportTouch&&s.originalEvent.changedTouches?(n=[s.originalEvent.changedTouches[0].pageX-g.left,s.originalEvent.changedTouches[0].pageY-g.top],this._multiTouchAnchor=[],this._inOp=!1):n=[s.pageX-g.left,s.pageY-g.top],this._softDblClick&&this._isTap&&(h=n[0]-this._anchor[0],c=n[1]-this._anchor[1],8>=Math.sqrt(h*h+c*c)&&(n=t.merge([],this._anchor))),h=n[0]-this._anchor[0],c=n[1]-this._anchor[1],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._shiftDown=this._mouseDown=this._toolPan=!1,this._isMultiTouch)return s.preventDefault(),this._isMultiTouch=!1,this._wheelLevel=0,u&&this._setInteractiveTimeout(!0),i;if(document.releaseCapture&&document.releaseCapture(),d){switch(a=t.now(),this._current=n,m){case"zoom":case"dragBox":if(0!==h||0!==c){var x=6*this._pixelSize,y=this._toMap([[Math.min(this._anchor[0],n[0]),Math.max(this._anchor[1],n[1])],[Math.max(this._anchor[0],n[0]),Math.min(this._anchor[1],n[1])]]),b=[y[0][0],y[0][1],y[1][0],y[1][1]];"zoom"===m?(x>b[2]-b[0]&&x>b[3]-b[1]&&(b=t.geo.scaleBy(this._getBbox(t.geo.center(b,!0)),.5,!0)),this._setBbox(b,!0,!0),u=!0):(_=t.geo.polygonize(b,!0),_.bbox=b,this._userGeodetic&&(_.coordinates=t.geo.proj.toGeodetic(_.coordinates),_.bbox=t.geo.proj.toGeodetic(_.bbox)),this._trigger("shape",s,_))}else"dragBox"===m&&(l=this._toMap(n),_={type:"Point",coordinates:[l[0],l[1]],bbox:[l[0],l[1],l[0],l[1]]},this._userGeodetic&&(_.coordinates=t.geo.proj.toGeodetic(_.coordinates),_.bbox=t.geo.proj.toGeodetic(_.bbox)),this._trigger("shape",s,_));this._resetDrawing();break;case"dragCircle":if(0!==h||0!==c){var w,S="image"===this._options.axisLayout,A=Math.sqrt(h*h+c*c),C=180;for(this._drawPixels.length=C+1,r=0;C>r;r++)w=360*r/C*(Math.PI/180),this._drawPixels[r]=[this._anchor[0]+Math.cos(w)*A,this._anchor[1]+Math.sin(w)*A];this._drawPixels[C]=[this._drawPixels[0][0],this._drawPixels[0][1]],l=this._toMap([[this._anchor[0]-A,this._anchor[1]+(S?-A:A)],[this._anchor[0]+A,this._anchor[1]+(S?A:-A)]]),_={type:"Polygon",coordinates:[this._toMap(this._drawPixels)],bbox:[l[0][0],l[0][1],l[1][0],l[1][1]]},this._userGeodetic&&(_.coordinates=t.geo.proj.toGeodetic(_.coordinates),_.bbox=t.geo.proj.toGeodetic(_.bbox)),this._trigger("shape",s,_),this._resetDrawing()}else l=this._toMap(n),_={type:"Point",coordinates:[l[0],l[1]],bbox:[l[0],l[1],l[0],l[1]]},this._userGeodetic&&(_.coordinates=t.geo.proj.toGeodetic(_.coordinates),_.bbox=t.geo.proj.toGeodetic(_.bbox)),this._trigger("shape",s,_);break;case"drawPoint":if(this._drawTimeout&&(e.clearTimeout(this._drawTimeout),this._drawTimeout=null),p)this._panFinalize();else if(a-this._clickDate>100){var T=this;this._drawTimeout=setTimeout(function(){T._drawTimeout&&(T._trigger("shape",s,{type:"Point",coordinates:T.toMap(n)}),T._inOp=!1,T._drawTimeout=null)},250)}break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":p?this._panFinalize():(r=0===this._drawCoords.length?0:this._drawCoords.length-1,this._drawCoords[r]=this._toMap(n),this._drawPixels[r]=n,(2>r||this._drawCoords[r][0]!==this._drawCoords[r-1][0]||this._drawCoords[r][1]!==this._drawCoords[r-1][1])&&(this._drawCoords[r+1]=this._toMap(n,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[r+1]=n),this._refreshDrawing());break;default:p?this._panFinalize():a-this._clickDate>100&&(this._trigger("click",s,{type:"Point",coordinates:this.toMap(n)}),this._inOp=!1)}if(this._clickDate=a,this._softDblClick&&this._isDbltap)return this._isDbltap=this._isTap=!1,u&&this._setInteractiveTimeout(!0),this._$eventTarget.trigger("dblclick",s),!1}return u&&this._setInteractiveTimeout(!0),this._inOp?(s.preventDefault(),!1):i}},_eventTarget_mousewheel:function(e,i){if("static"!==this._options.mode&&"off"!==this._options.scroll){if(e.preventDefault(),this._mouseDown)return!1;if(0!==i){var s=Math.abs(i)>=1;this._clearInteractiveTimeout(),i=i>0?Math.ceil(i):Math.floor(i);var o=t(e.currentTarget).offset();this._anchor=[e.pageX-o.left,e.pageY-o.top];var n=this._getZoomCenterAndSize(this._anchor,i,null!==this._options.tilingScheme?s:!1);this._setInteractiveCenterAndSize(n.center,n.pixelSize),this._interactiveTransform(),this._setInteractiveTimeout(!0)}return!1}}})}(jQuery,window),function(t,e,i){t.geo._serviceTypes.tiled=function(){var s=RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(i,s,o){this._serviceId=i._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var n=t.data(o,"geoServiceState");if(!n){n={loadCount:0,reloadTiles:!1};var r='
          ';s.append(e.toStaticHTML(r)),n.serviceContainer=s.children(":last"),t.data(o,"geoServiceState",n)}return n.serviceContainer},destroy:function(e,i,s){var o=t.data(s,"geoServiceState");o.serviceContainer.remove(),t.removeData(s,"geoServiceState")},interactiveTransform:function(e,i,s,o){var n=t.data(i,"geoServiceState"),r=e.options.tilingScheme;n&&(this._cancelUnloaded(e,i),n.serviceContainer.children().each(function(){var i=t(this),n=i.data("pixelSize"),a=n/o;if(n>0){a=Math.round(1e3*a)/1e3;var h=i.data("scaleOrigin"),c=e._toPixel(h,s,o);i.css({left:Math.round(c[0])+"px",top:Math.round(c[1])+"px",width:r.tileWidth*a,height:r.tileHeight*a})}}))},refresh:function(i,o,n){var r=t.data(o,"geoServiceState");if(this._cancelUnloaded(i,o),r&&n&&(r.reloadTiles=!0),r&&o&&"visible"===o.style.visibility&&!r.serviceContainer.is(":hidden")){var a,h,c=i._getBbox(),l=i._pixelSize,_=this,u=r.serviceContainer,d="image"===i.options.axisLayout,p=d?1:-1,g=i.options.tilingScheme,m=g.tileWidth,f=g.tileHeight,v=Math.floor((c[0]-g.origin[0])/(l*m)),x=Math.max(Math.floor((d?c[1]-g.origin[1]:g.origin[1]-c[3])/(l*f)),0),y=Math.ceil((c[2]-g.origin[0])/(l*m)),b=Math.ceil((d?c[3]-g.origin[1]:g.origin[1]-c[1])/(l*f)),w=i._getBboxMax(),S=i._getPixelSize(0),A=S/l,C=Math.floor((w[0]-g.origin[0])/(S*m))*A,T=Math.floor((g.origin[1]+p*w[3])/(S*f))*A,M=g.origin[0]+C*m*l,P=g.origin[1]+p*T*f*l,$=Math.round((M-c[0])/l),z=Math.round((d?P-c[1]:c[3]-P)/l),I=u.children().show(),k=I.filter("[data-pixel-size='"+l+"']").appendTo(u),L=o.style.opacity,G=function(t){_._loadImage(this.img,t,l,i,r,L)},O=function(){delete this.img,r.loadCount--,i._requestComplete()};for(r.reloadTiles&&I.find("img").attr("data-dirty","true"),k.size()?(k.css({left:$%m+"px",top:z%f+"px"}).data("scaleOrigin",i._toMap([$%m,z%f])),k.children().each(function(){var e=t(this),i=e.attr("data-tile").split(",");e.css({left:Math.round(100*(parseInt(i[0],10)-C)+100*(($-$%m)/m))+"%",top:Math.round(100*(parseInt(i[1],10)-T)+100*((z-z%f)/f))+"%"}),1>L&&e.fadeTo(0,L)})):(u.append(e.toStaticHTML("
          ")),k=u.children(":last").data("scaleOrigin",i._toMap([$%m,z%f]))),a=v;y>a;a++)for(h=x;b>h;h++){var B=""+a+","+h,D=k.children("[data-tile='"+B+"']").removeAttr("data-dirty");if(0===D.size()||r.reloadTiles){var j,E=[g.origin[0]+a*m*l,g.origin[1]+p*h*f*l],F=[g.origin[0]+((a+1)*m-1)*l,g.origin[1]+p*((h+1)*f-1)*l],R=[E[0],E[1],F[0],F[1]],V=o.hasOwnProperty("src")?"src":"getUrl",N={bbox:R,width:m,height:f,zoom:i._getZoom(),tile:{row:h,column:a},index:Math.abs(h+a)},H=t.isFunction(o[V]);if(H?j=o[V](N):s.test(o[V])?(t.templates(this._tmplGeoSrcId,o[V]),j=t.render[this._tmplGeoSrcId](N)):j=o[V],r.loadCount++,i._requestQueued(),r.reloadTiles&&D.size()>0)D.attr("src",j);else{var W="",k.append(e.toStaticHTML(W)),D=k.children(":last")}"string"==typeof j?_._loadImage(D,j,l,i,r,L):j&&t.isFunction(j.promise)?(t.extend(j.promise(),{img:D}),j.done(G).fail(O)):D.remove()}}I.find("[data-dirty]").remove(),r.reloadTiles=!1}},resize:function(){},opacity:function(e,i){var s=t.data(i,"geoServiceState");s.serviceContainer.find("img").stop(!0).fadeTo("fast",i.style.opacity)},toggle:function(e,i){var s=t.data(i,"geoServiceState");s.serviceContainer.css("display","visible"===i.style.visibility?"block":"none")},_cancelUnloaded:function(s,o){var n=t.data(o,"geoServiceState");if(n&&n.loadCount>0)for(e.stop!==i?e.stop():document.execCommand!==i&&document.execCommand("Stop",!1),n.serviceContainer.find("img:hidden").remove();n.loadCount>0;)n.loadCount--,s._requestComplete()},_loadImage:function(e,i,s,o,n,r){var a=n.serviceContainer;e.load(function(e){1>r?t(e.target).fadeTo(0,r):t(e.target).show(),n.loadCount--,o._requestComplete(),0>=n.loadCount&&(a.children(":not([data-pixel-size='"+s+"'])").remove(),n.loadCount=0)}).error(function(e){t(e.target).remove(),n.loadCount--,o._requestComplete(),0>=n.loadCount&&(a.children(":not([data-pixel-size='"+s+"'])").remove(),n.loadCount=0)}).attr("src",i)}}}()}(jQuery,window),function(t,e){t.geo._serviceTypes.shingled=function(){var i=RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(i,s,o){this._serviceId=i._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var n=t.data(o,"geoServiceState");if(!n){n={loadCount:0};var r='
          ';s.append(e.toStaticHTML(r)),n.serviceContainer=s.children(":last"),t.data(o,"geoServiceState",n)}return n.serviceContainer},destroy:function(e,i,s){var o=t.data(s,"geoServiceState");o.serviceContainer.remove(),t.removeData(s,"geoServiceState")},interactiveTransform:function(e,i,s,o){var n=t.data(i,"geoServiceState"),r=e._getContentBounds(),a=r.width,h=r.height;n&&(this._cancelUnloaded(e,i),n.serviceContainer.children().each(function(){var i=t(this),n=i.data("pixelSize"),r=n/o;if(n>0){r=Math.round(1e3*r)/1e3;var c=i.data("origin"),l=e._toPixel(c,s,o);i.css({left:Math.round(l[0]),top:Math.round(l[1]),width:a*r,height:h*r})}}))},refresh:function(s,o){var n=t.data(o,"geoServiceState");if(this._cancelUnloaded(s,o),n&&o&&"visible"===o.style.visibility&&!n.serviceContainer.is(":hidden")){var r,a=s._getBbox(),h=s._pixelSize,c=this,l=n.serviceContainer,_=s._getContentBounds(),u=_.width,d=_.height,p=l.children('[data-pixel-size="'+h+'"]'),g=o.style.opacity;1>g&&l.find("img").attr("data-keep-alive","0"),p.size()||(l.append(e.toStaticHTML('
          ')),p=l.children(":last"));var m,f=o.hasOwnProperty("src")?"src":"getUrl",v={bbox:a,width:u,height:d,zoom:s._getZoom(),tile:null,index:0},x=t.isFunction(o[f]),y=p.position();y.left=-y.left,y.top=-y.top,x?m=o[f](v):i.test(o[f])?(t.templates(this._tmplGeoSrcId,o[f]),m=t.render[this._tmplGeoSrcId](v)):m=o[f],n.loadCount++,s._requestQueued(),p.append(e.toStaticHTML('')),r=p.children(":last").data("center",s._center),"string"==typeof m?c._loadImage(r,m,h,s,n,g):m.done(function(t){c._loadImage(r,t,h,s,n,g)}).fail(function(){r.remove(),n.loadCount--,s._requestComplete()})}},resize:function(e,i){var s=t.data(i,"geoServiceState");if(s&&i&&"visible"===i.style.visibility){this._cancelUnloaded(e,i);var o=s.serviceContainer,n=e._getContentBounds(),r=n.width,a=n.height,h=o.children();h.attr("data-pixel-size","0"),h.each(function(){var e=t(this),i=e.position();e.css({left:i.left+(r-e.width())/2,top:i.top+(a-e.height())/2})})}},opacity:function(e,i){var s=t.data(i,"geoServiceState");s.serviceContainer.find("img").stop(!0).fadeTo("fast",i.style.opacity)},toggle:function(e,i){var s=t.data(i,"geoServiceState");s.serviceContainer.css("display","visible"===i.style.visibility?"block":"none")},_cancelUnloaded:function(e,i){var s=t.data(i,"geoServiceState");if(s&&s.loadCount>0)for(s.serviceContainer.find("img:hidden").remove();s.loadCount>0;)s.loadCount--,e._requestComplete()},_loadImage:function(e,i,s,o,n,r){var a=n.serviceContainer;e.load(function(e){t.contains(document.body,e.target.jquery?e.target[0]:e.target)&&(1>r?t(e.target).fadeTo(0,r):t(e.target).show(),n.loadCount--,o._requestComplete(),0>=n.loadCount&&(a.children(':not([data-pixel-size="'+s+'"])').remove(),a.find("img[data-keep-alive]").remove(),n.loadCount=0))}).error(function(e){t.contains(document.body,e.target.jquery?e.target[0]:e.target)&&(t(e.target).remove(),n.loadCount--,o._requestComplete(),0>=n.loadCount&&(a.children(":not([data-pixel-size='"+s+"'])").remove(),n.loadCount=0))}).attr("src",i)}}}()}(jQuery,window); \ No newline at end of file diff --git a/dist/jquery.geo-1.0.0-b3.2.js b/dist/jquery.geo-1.0.0-b3.2.js deleted file mode 100644 index ab91b17..0000000 --- a/dist/jquery.geo-1.0.0-b3.2.js +++ /dev/null @@ -1,7515 +0,0 @@ -/*! jQuery Geo - v1.0.0-b3.2 - 2016-01-16 -* http://jquerygeo.com -* Copyright (c) 2016 Ryan Morrison-Westphal; Licensed MIT */ -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -// Known Issues: -// -// * Patterns only support repeat. -// * Radial gradient are not implemented. The VML version of these look very -// different from the canvas one. -// * Clipping paths are not implemented. -// * Coordsize. The width and height attribute have higher priority than the -// width and height style values which isn't correct. -// * Painting mode isn't implemented. -// * Canvas width/height should is using content-box by default. IE in -// Quirks mode will draw the canvas using border-box. Either change your -// doctype to HTML5 -// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) -// or use Box Sizing Behavior from WebFX -// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) -// * Non uniform scaling does not correctly scale strokes. -// * Optimize. There is always room for speed improvements. - -// Only add this code if we do not already have a canvas implementation -if (!document.createElement('canvas').getContext) { - - (function () { - - // alias some functions to make (compiled) code shorter - var m = Math; - var mr = m.round; - var ms = m.sin; - var mc = m.cos; - var abs = m.abs; - var sqrt = m.sqrt; - - // this is used for sub pixel precision - var Z = 10; - var Z2 = Z / 2; - - var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; - - /** - * This funtion is assigned to the elements as element.getContext(). - * @this {HTMLElement} - * @return {CanvasRenderingContext2D_} - */ - function getContext() { - return this.context_ || - (this.context_ = new CanvasRenderingContext2D_(this)); - } - - var slice = Array.prototype.slice; - - /** - * Binds a function to an object. The returned function will always use the - * passed in {@code obj} as {@code this}. - * - * Example: - * - * g = bind(f, obj, a, b) - * g(c, d) // will do f.call(obj, a, b, c, d) - * - * @param {Function} f The function to bind the object to - * @param {Object} obj The object that should act as this when the function - * is called - * @param {*} var_args Rest arguments that will be used as the initial - * arguments when the function is called - * @return {Function} A new function that has bound this - */ - function bind(f, obj, var_args) { - var a = slice.call(arguments, 2); - return function () { - return f.apply(obj, a.concat(slice.call(arguments))); - }; - } - - function encodeHtmlAttribute(s) { - return String(s).replace(/&/g, '&').replace(/"/g, '"'); - } - - function addNamespace(doc, prefix, urn) { - if (!doc.namespaces[prefix]) { - doc.namespaces.add(prefix, urn, '#default#VML'); - } - } - - function addNamespacesAndStylesheet(doc) { - addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); - addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); - - // Setup default CSS. Only add one style sheet per document - if (!doc.styleSheets['ex_canvas_']) { - var ss = doc.createStyleSheet(); - ss.owningElement.id = 'ex_canvas_'; - ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + - // default size is 300x150 in Gecko and Opera - 'text-align:left;width:300px;height:150px}'; - } - } - - // Add namespaces and stylesheet at startup. - addNamespacesAndStylesheet(document); - - var G_vmlCanvasManager_ = { - init: function (opt_doc) { - var doc = opt_doc || document; - // Create a dummy element so that IE will allow canvas elements to be - // recognized. - doc.createElement('canvas'); - doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); - }, - - init_: function (doc) { - // find all canvas elements - var els = doc.getElementsByTagName('canvas'); - for (var i = 0; i < els.length; i++) { - this.initElement(els[i]); - } - }, - - /** - * Public initializes a canvas element so that it can be used as canvas - * element from now on. This is called automatically before the page is - * loaded but if you are creating elements using createElement you need to - * make sure this is called on the element. - * @param {HTMLElement} el The canvas element to initialize. - * @return {HTMLElement} the element that was created. - */ - initElement: function (el) { - if (!el.getContext) { - el.getContext = getContext; - - // Add namespaces and stylesheet to document of the element. - addNamespacesAndStylesheet(el.ownerDocument); - - // Remove fallback content. There is no way to hide text nodes so we - // just remove all childNodes. We could hide all elements and remove - // text nodes but who really cares about the fallback content. - el.innerHTML = ''; - - // do not use inline function because that will leak memory - el.attachEvent('onpropertychange', onPropertyChange); - el.attachEvent('onresize', onResize); - - var attrs = el.attributes; - if (attrs.width && attrs.width.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setWidth_(attrs.width.nodeValue); - el.style.width = attrs.width.nodeValue + 'px'; - } else { - el.width = el.clientWidth; - } - if (attrs.height && attrs.height.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setHeight_(attrs.height.nodeValue); - el.style.height = attrs.height.nodeValue + 'px'; - } else { - el.height = el.clientHeight; - } - //el.getContext().setCoordsize_() - } - return el; - } - }; - - function onPropertyChange(e) { - var el = e.srcElement; - - switch (e.propertyName) { - case 'width': - el.getContext().clearRect(); - el.style.width = el.attributes.width.nodeValue + 'px'; - // In IE8 this does not trigger onresize. - el.firstChild.style.width = el.clientWidth + 'px'; - break; - case 'height': - el.getContext().clearRect(); - el.style.height = el.attributes.height.nodeValue + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - break; - } - } - - function onResize(e) { - var el = e.srcElement; - if (el.firstChild) { - el.firstChild.style.width = el.clientWidth + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - } - } - - G_vmlCanvasManager_.init(); - - // precompute "00" to "FF" - var decToHex = []; - for (var i = 0; i < 16; i++) { - for (var j = 0; j < 16; j++) { - decToHex[i * 16 + j] = i.toString(16) + j.toString(16); - } - } - - function createMatrixIdentity() { - return [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1] - ]; - } - - function matrixMultiply(m1, m2) { - var result = createMatrixIdentity(); - - for (var x = 0; x < 3; x++) { - for (var y = 0; y < 3; y++) { - var sum = 0; - - for (var z = 0; z < 3; z++) { - sum += m1[x][z] * m2[z][y]; - } - - result[x][y] = sum; - } - } - return result; - } - - function copyState(o1, o2) { - o2.fillStyle = o1.fillStyle; - o2.lineCap = o1.lineCap; - o2.lineJoin = o1.lineJoin; - o2.lineWidth = o1.lineWidth; - o2.miterLimit = o1.miterLimit; - o2.shadowBlur = o1.shadowBlur; - o2.shadowColor = o1.shadowColor; - o2.shadowOffsetX = o1.shadowOffsetX; - o2.shadowOffsetY = o1.shadowOffsetY; - o2.strokeStyle = o1.strokeStyle; - o2.globalAlpha = o1.globalAlpha; - o2.font = o1.font; - o2.textAlign = o1.textAlign; - o2.textBaseline = o1.textBaseline; - o2.arcScaleX_ = o1.arcScaleX_; - o2.arcScaleY_ = o1.arcScaleY_; - o2.lineScale_ = o1.lineScale_; - } - - // var colorData = { - // aliceblue: '#F0F8FF', - // antiquewhite: '#FAEBD7', - // aquamarine: '#7FFFD4', - // azure: '#F0FFFF', - // beige: '#F5F5DC', - // bisque: '#FFE4C4', - // black: '#000000', - // blanchedalmond: '#FFEBCD', - // blueviolet: '#8A2BE2', - // brown: '#A52A2A', - // burlywood: '#DEB887', - // cadetblue: '#5F9EA0', - // chartreuse: '#7FFF00', - // chocolate: '#D2691E', - // coral: '#FF7F50', - // cornflowerblue: '#6495ED', - // cornsilk: '#FFF8DC', - // crimson: '#DC143C', - // cyan: '#00FFFF', - // darkblue: '#00008B', - // darkcyan: '#008B8B', - // darkgoldenrod: '#B8860B', - // darkgray: '#A9A9A9', - // darkgreen: '#006400', - // darkgrey: '#A9A9A9', - // darkkhaki: '#BDB76B', - // darkmagenta: '#8B008B', - // darkolivegreen: '#556B2F', - // darkorange: '#FF8C00', - // darkorchid: '#9932CC', - // darkred: '#8B0000', - // darksalmon: '#E9967A', - // darkseagreen: '#8FBC8F', - // darkslateblue: '#483D8B', - // darkslategray: '#2F4F4F', - // darkslategrey: '#2F4F4F', - // darkturquoise: '#00CED1', - // darkviolet: '#9400D3', - // deeppink: '#FF1493', - // deepskyblue: '#00BFFF', - // dimgray: '#696969', - // dimgrey: '#696969', - // dodgerblue: '#1E90FF', - // firebrick: '#B22222', - // floralwhite: '#FFFAF0', - // forestgreen: '#228B22', - // gainsboro: '#DCDCDC', - // ghostwhite: '#F8F8FF', - // gold: '#FFD700', - // goldenrod: '#DAA520', - // grey: '#808080', - // greenyellow: '#ADFF2F', - // honeydew: '#F0FFF0', - // hotpink: '#FF69B4', - // indianred: '#CD5C5C', - // indigo: '#4B0082', - // ivory: '#FFFFF0', - // khaki: '#F0E68C', - // lavender: '#E6E6FA', - // lavenderblush: '#FFF0F5', - // lawngreen: '#7CFC00', - // lemonchiffon: '#FFFACD', - // lightblue: '#ADD8E6', - // lightcoral: '#F08080', - // lightcyan: '#E0FFFF', - // lightgoldenrodyellow: '#FAFAD2', - // lightgreen: '#90EE90', - // lightgrey: '#D3D3D3', - // lightpink: '#FFB6C1', - // lightsalmon: '#FFA07A', - // lightseagreen: '#20B2AA', - // lightskyblue: '#87CEFA', - // lightslategray: '#778899', - // lightslategrey: '#778899', - // lightsteelblue: '#B0C4DE', - // lightyellow: '#FFFFE0', - // limegreen: '#32CD32', - // linen: '#FAF0E6', - // magenta: '#FF00FF', - // mediumaquamarine: '#66CDAA', - // mediumblue: '#0000CD', - // mediumorchid: '#BA55D3', - // mediumpurple: '#9370DB', - // mediumseagreen: '#3CB371', - // mediumslateblue: '#7B68EE', - // mediumspringgreen: '#00FA9A', - // mediumturquoise: '#48D1CC', - // mediumvioletred: '#C71585', - // midnightblue: '#191970', - // mintcream: '#F5FFFA', - // mistyrose: '#FFE4E1', - // moccasin: '#FFE4B5', - // navajowhite: '#FFDEAD', - // oldlace: '#FDF5E6', - // olivedrab: '#6B8E23', - // orange: '#FFA500', - // orangered: '#FF4500', - // orchid: '#DA70D6', - // palegoldenrod: '#EEE8AA', - // palegreen: '#98FB98', - // paleturquoise: '#AFEEEE', - // palevioletred: '#DB7093', - // papayawhip: '#FFEFD5', - // peachpuff: '#FFDAB9', - // peru: '#CD853F', - // pink: '#FFC0CB', - // plum: '#DDA0DD', - // powderblue: '#B0E0E6', - // rosybrown: '#BC8F8F', - // royalblue: '#4169E1', - // saddlebrown: '#8B4513', - // salmon: '#FA8072', - // sandybrown: '#F4A460', - // seagreen: '#2E8B57', - // seashell: '#FFF5EE', - // sienna: '#A0522D', - // skyblue: '#87CEEB', - // slateblue: '#6A5ACD', - // slategray: '#708090', - // slategrey: '#708090', - // snow: '#FFFAFA', - // springgreen: '#00FF7F', - // steelblue: '#4682B4', - // tan: '#D2B48C', - // thistle: '#D8BFD8', - // tomato: '#FF6347', - // turquoise: '#40E0D0', - // violet: '#EE82EE', - // wheat: '#F5DEB3', - // whitesmoke: '#F5F5F5', - // yellowgreen: '#9ACD32' - // }; - - - function getRgbHslContent(styleString) { - var start = styleString.indexOf('(', 3); - var end = styleString.indexOf(')', start + 1); - var parts = styleString.substring(start + 1, end).split(','); - // add alpha if needed - if (parts.length != 4 || styleString.charAt(3) != 'a') { - parts[3] = 1; - } - return parts; - } - - function percent(s) { - return parseFloat(s) / 100; - } - - function clamp(v, min, max) { - return Math.min(max, Math.max(min, v)); - } - - function hslToRgb(parts) { - var r, g, b, h, s, l; - h = parseFloat(parts[0]) / 360 % 360; - if (h < 0) - h++; - s = clamp(percent(parts[1]), 0, 1); - l = clamp(percent(parts[2]), 0, 1); - if (s == 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1 / 3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1 / 3); - } - - return '#' + decToHex[Math.floor(r * 255)] + - decToHex[Math.floor(g * 255)] + - decToHex[Math.floor(b * 255)]; - } - - function hueToRgb(m1, m2, h) { - if (h < 0) - h++; - if (h > 1) - h--; - - if (6 * h < 1) - return m1 + (m2 - m1) * 6 * h; - else if (2 * h < 1) - return m2; - else if (3 * h < 2) - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - else - return m1; - } - - var processStyleCache = {}; - - function processStyle(styleString) { - if (styleString in processStyleCache) { - return processStyleCache[styleString]; - } - - var str, alpha = 1; - - styleString = String(styleString); - if (styleString.charAt(0) == '#') { - str = styleString; - } else if (/^rgb/.test(styleString)) { - var parts = getRgbHslContent(styleString); - var str = '#', n; - for (var i = 0; i < 3; i++) { - if (parts[i].indexOf('%') != -1) { - n = Math.floor(percent(parts[i]) * 255); - } else { - n = +parts[i]; - } - str += decToHex[clamp(n, 0, 255)]; - } - alpha = +parts[3]; - } else if (/^hsl/.test(styleString)) { - var parts = getRgbHslContent(styleString); - str = hslToRgb(parts); - alpha = parts[3]; - } else { - str = /*colorData[styleString] ||*/styleString; - } - return processStyleCache[styleString] = { color: str, alpha: alpha }; - } - - var DEFAULT_STYLE = { - style: 'normal', - variant: 'normal', - weight: 'normal', - size: 10, - family: 'sans-serif' - }; - - // Internal text style cache - // var fontStyleCache = {}; - - // function processFontStyle(styleString) { - // if (fontStyleCache[styleString]) { - // return fontStyleCache[styleString]; - // } - - // var el = document.createElement('div'); - // var style = el.style; - // try { - // style.font = styleString; - // } catch (ex) { - // // Ignore failures to set to invalid font. - // } - - // return fontStyleCache[styleString] = { - // style: style.fontStyle || DEFAULT_STYLE.style, - // variant: style.fontVariant || DEFAULT_STYLE.variant, - // weight: style.fontWeight || DEFAULT_STYLE.weight, - // size: style.fontSize || DEFAULT_STYLE.size, - // family: style.fontFamily || DEFAULT_STYLE.family - // }; - // } - - // function getComputedStyle(style, element) { - // var computedStyle = {}; - - // for (var p in style) { - // computedStyle[p] = style[p]; - // } - - // // Compute the size - // var canvasFontSize = parseFloat(element.currentStyle.fontSize), - // fontSize = parseFloat(style.size); - - // if (typeof style.size == 'number') { - // computedStyle.size = style.size; - // } else if (style.size.indexOf('px') != -1) { - // computedStyle.size = fontSize; - // } else if (style.size.indexOf('em') != -1) { - // computedStyle.size = canvasFontSize * fontSize; - // } else if(style.size.indexOf('%') != -1) { - // computedStyle.size = (canvasFontSize / 100) * fontSize; - // } else if (style.size.indexOf('pt') != -1) { - // computedStyle.size = fontSize / .75; - // } else { - // computedStyle.size = canvasFontSize; - // } - - // // Different scaling between normal text and VML text. This was found using - // // trial and error to get the same size as non VML text. - // computedStyle.size *= 0.981; - - // return computedStyle; - // } - - // function buildStyle(style) { - // return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + - // style.size + 'px ' + style.family; - // } - - var lineCapMap = { - 'butt': 'flat', - 'round': 'round' - }; - - function processLineCap(lineCap) { - return lineCapMap[lineCap] || 'square'; - } - - /** - * This class implements CanvasRenderingContext2D interface as described by - * the WHATWG. - * @param {HTMLElement} canvasElement The element that the 2D context should - * be associated with - */ - function CanvasRenderingContext2D_(canvasElement) { - this.m_ = createMatrixIdentity(); - - this.mStack_ = []; - this.aStack_ = []; - this.currentPath_ = []; - - // Canvas context properties - this.strokeStyle = '#000'; - this.fillStyle = '#000'; - - this.lineWidth = 1; - this.lineJoin = 'miter'; - this.lineCap = 'butt'; - this.miterLimit = Z * 1; - this.globalAlpha = 1; - //this.font = '10px sans-serif'; - //this.textAlign = 'left'; - //this.textBaseline = 'alphabetic'; - this.canvas = canvasElement; - - var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + - canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; - var el = canvasElement.ownerDocument.createElement('div'); - el.style.cssText = cssText; - canvasElement.appendChild(el); - - var overlayEl = el.cloneNode(false); - // Use a non transparent background. - overlayEl.style.backgroundColor = 'red'; - overlayEl.style.filter = 'alpha(opacity=0)'; - canvasElement.appendChild(overlayEl); - - this.element_ = el; - this.arcScaleX_ = 1; - this.arcScaleY_ = 1; - this.lineScale_ = 1; - } - - var contextPrototype = CanvasRenderingContext2D_.prototype; - contextPrototype.clearRect = function () { - if (this.textMeasureEl_) { - this.textMeasureEl_.removeNode(true); - this.textMeasureEl_ = null; - } - this.element_.innerHTML = ''; - }; - - contextPrototype.beginPath = function () { - // TODO: Branch current matrix so that save/restore has no effect - // as per safari docs. - this.currentPath_ = []; - }; - - contextPrototype.moveTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'moveTo', x: p.x, y: p.y }); - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.lineTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'lineTo', x: p.x, y: p.y }); - - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY) { - var p = getCoords(this, aX, aY); - var cp1 = getCoords(this, aCP1x, aCP1y); - var cp2 = getCoords(this, aCP2x, aCP2y); - bezierCurveTo(this, cp1, cp2, p); - }; - - // Helper function that takes the already fixed cordinates. - function bezierCurveTo(self, cp1, cp2, p) { - self.currentPath_.push({ - type: 'bezierCurveTo', - cp1x: cp1.x, - cp1y: cp1.y, - cp2x: cp2.x, - cp2y: cp2.y, - x: p.x, - y: p.y - }); - self.currentX_ = p.x; - self.currentY_ = p.y; - } - - contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { - // the following is lifted almost directly from - // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes - - var cp = getCoords(this, aCPx, aCPy); - var p = getCoords(this, aX, aY); - - var cp1 = { - x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), - y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) - }; - var cp2 = { - x: cp1.x + (p.x - this.currentX_) / 3.0, - y: cp1.y + (p.y - this.currentY_) / 3.0 - }; - - bezierCurveTo(this, cp1, cp2, p); - }; - - contextPrototype.arc = function (aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise) { - aRadius *= Z; - var arcType = aClockwise ? 'at' : 'wa'; - - var xStart = aX + mc(aStartAngle) * aRadius - Z2; - var yStart = aY + ms(aStartAngle) * aRadius - Z2; - - var xEnd = aX + mc(aEndAngle) * aRadius - Z2; - var yEnd = aY + ms(aEndAngle) * aRadius - Z2; - - // IE won't render arches drawn counter clockwise if xStart == xEnd. - if (xStart == xEnd && !aClockwise) { - xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something - // that can be represented in binary - } - - var p = getCoords(this, aX, aY); - var pStart = getCoords(this, xStart, yStart); - var pEnd = getCoords(this, xEnd, yEnd); - - this.currentPath_.push({ type: arcType, - x: p.x, - y: p.y, - radius: aRadius, - xStart: pStart.x, - yStart: pStart.y, - xEnd: pEnd.x, - yEnd: pEnd.y - }); - - }; - - // contextPrototype.rect = function(aX, aY, aWidth, aHeight) { - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // }; - - // contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.stroke(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.fill(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { - // var gradient = new CanvasGradient_('gradient'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // return gradient; - // }; - - // contextPrototype.createRadialGradient = function(aX0, aY0, aR0, - // aX1, aY1, aR1) { - // var gradient = new CanvasGradient_('gradientradial'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.r0_ = aR0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // gradient.r1_ = aR1; - // return gradient; - // }; - - // contextPrototype.drawImage = function(image, var_args) { - // var dx, dy, dw, dh, sx, sy, sw, sh; - - // // to find the original width we overide the width and height - // var oldRuntimeWidth = image.runtimeStyle.width; - // var oldRuntimeHeight = image.runtimeStyle.height; - // image.runtimeStyle.width = 'auto'; - // image.runtimeStyle.height = 'auto'; - - // // get the original size - // var w = image.width; - // var h = image.height; - - // // and remove overides - // image.runtimeStyle.width = oldRuntimeWidth; - // image.runtimeStyle.height = oldRuntimeHeight; - - // if (arguments.length == 3) { - // dx = arguments[1]; - // dy = arguments[2]; - // sx = sy = 0; - // sw = dw = w; - // sh = dh = h; - // } else if (arguments.length == 5) { - // dx = arguments[1]; - // dy = arguments[2]; - // dw = arguments[3]; - // dh = arguments[4]; - // sx = sy = 0; - // sw = w; - // sh = h; - // } else if (arguments.length == 9) { - // sx = arguments[1]; - // sy = arguments[2]; - // sw = arguments[3]; - // sh = arguments[4]; - // dx = arguments[5]; - // dy = arguments[6]; - // dw = arguments[7]; - // dh = arguments[8]; - // } else { - // throw Error('Invalid number of arguments'); - // } - - // var d = getCoords(this, dx, dy); - - // var w2 = sw / 2; - // var h2 = sh / 2; - - // var vmlStr = []; - - // var W = 10; - // var H = 10; - - // // For some reason that I've now forgotten, using divs didn't work - // vmlStr.push(' ' , - // '', - // ''); - - // this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); - // }; - - contextPrototype.stroke = function (aFill) { - var lineStr = []; - var lineOpen = false; - - var W = 10; - var H = 10; - - lineStr.push(''); - - if (!aFill) { - appendStroke(this, lineStr); - } else { - appendFill(this, lineStr, min, max); - } - - lineStr.push(''); - - this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - }; - - function appendStroke(ctx, lineStr) { - var a = processStyle(ctx.strokeStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - var lineWidth = ctx.lineScale_ * ctx.lineWidth; - - // VML cannot correctly render a line if the width is less than 1px. - // In that case, we dilute the color to make the line look thinner. - if (lineWidth < 1) { - opacity *= lineWidth; - } - - lineStr.push( - '' - ); - } - - function appendFill(ctx, lineStr, min, max) { - var fillStyle = ctx.fillStyle; - var arcScaleX = ctx.arcScaleX_; - var arcScaleY = ctx.arcScaleY_; - var width = max.x - min.x; - var height = max.y - min.y; - // if (fillStyle instanceof CanvasGradient_) { - // // TODO: Gradients transformed with the transformation matrix. - // var angle = 0; - // var focus = {x: 0, y: 0}; - - // // additional offset - // var shift = 0; - // // scale factor for offset - // var expansion = 1; - - // if (fillStyle.type_ == 'gradient') { - // var x0 = fillStyle.x0_ / arcScaleX; - // var y0 = fillStyle.y0_ / arcScaleY; - // var x1 = fillStyle.x1_ / arcScaleX; - // var y1 = fillStyle.y1_ / arcScaleY; - // var p0 = getCoords(ctx, x0, y0); - // var p1 = getCoords(ctx, x1, y1); - // var dx = p1.x - p0.x; - // var dy = p1.y - p0.y; - // angle = Math.atan2(dx, dy) * 180 / Math.PI; - - // // The angle should be a non-negative number. - // if (angle < 0) { - // angle += 360; - // } - - // // Very small angles produce an unexpected result because they are - // // converted to a scientific notation string. - // if (angle < 1e-6) { - // angle = 0; - // } - // } else { - // var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); - // focus = { - // x: (p0.x - min.x) / width, - // y: (p0.y - min.y) / height - // }; - - // width /= arcScaleX * Z; - // height /= arcScaleY * Z; - // var dimension = m.max(width, height); - // shift = 2 * fillStyle.r0_ / dimension; - // expansion = 2 * fillStyle.r1_ / dimension - shift; - // } - - // // We need to sort the color stops in ascending order by offset, - // // otherwise IE won't interpret it correctly. - // var stops = fillStyle.colors_; - // stops.sort(function(cs1, cs2) { - // return cs1.offset - cs2.offset; - // }); - - // var length = stops.length; - // var color1 = stops[0].color; - // var color2 = stops[length - 1].color; - // var opacity1 = stops[0].alpha * ctx.globalAlpha; - // var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; - - // var colors = []; - // for (var i = 0; i < length; i++) { - // var stop = stops[i]; - // colors.push(stop.offset * expansion + shift + ' ' + stop.color); - // } - - // // When colors attribute is used, the meanings of opacity and o:opacity2 - // // are reversed. - // lineStr.push(''); - // } else if (fillStyle instanceof CanvasPattern_) { - // if (width && height) { - // var deltaLeft = -min.x; - // var deltaTop = -min.y; - // lineStr.push(''); - // } - // } else { - var a = processStyle(ctx.fillStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - lineStr.push(''); - // } - } - - contextPrototype.fill = function () { - this.stroke(true); - }; - - contextPrototype.closePath = function () { - this.currentPath_.push({ type: 'close' }); - }; - - function getCoords(ctx, aX, aY) { - var m = ctx.m_; - return { - x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, - y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 - }; - }; - - contextPrototype.save = function () { - var o = {}; - copyState(this, o); - this.aStack_.push(o); - this.mStack_.push(this.m_); - this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); - }; - - contextPrototype.restore = function () { - if (this.aStack_.length) { - copyState(this.aStack_.pop(), this); - this.m_ = this.mStack_.pop(); - } - }; - - function matrixIsFinite(m) { - return isFinite(m[0][0]) && isFinite(m[0][1]) && - isFinite(m[1][0]) && isFinite(m[1][1]) && - isFinite(m[2][0]) && isFinite(m[2][1]); - } - - function setM(ctx, m, updateLineScale) { - if (!matrixIsFinite(m)) { - return; - } - ctx.m_ = m; - - if (updateLineScale) { - // Get the line scale. - // Determinant of this.m_ means how much the area is enlarged by the - // transformation. So its square root can be used as a scale factor - // for width. - var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; - ctx.lineScale_ = sqrt(abs(det)); - } - } - - contextPrototype.translate = function (aX, aY) { - var m1 = [ - [1, 0, 0], - [0, 1, 0], - [aX, aY, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), false); - }; - - // contextPrototype.rotate = function(aRot) { - // var c = mc(aRot); - // var s = ms(aRot); - - // var m1 = [ - // [c, s, 0], - // [-s, c, 0], - // [0, 0, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), false); - // }; - - contextPrototype.scale = function (aX, aY) { - this.arcScaleX_ *= aX; - this.arcScaleY_ *= aY; - var m1 = [ - [aX, 0, 0], - [0, aY, 0], - [0, 0, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), true); - }; - - // contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { - // var m1 = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), true); - // }; - - // contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { - // var m = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, m, true); - // }; - - /** - * The text drawing function. - * The maxWidth argument isn't taken in account, since no browser supports - * it yet. - */ - // contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { - // var m = this.m_, - // delta = 1000, - // left = 0, - // right = delta, - // offset = {x: 0, y: 0}, - // lineStr = []; - - // var fontStyle = getComputedStyle(processFontStyle(this.font), - // this.element_); - - // var fontStyleString = buildStyle(fontStyle); - - // var elementStyle = this.element_.currentStyle; - // var textAlign = this.textAlign.toLowerCase(); - // switch (textAlign) { - // case 'left': - // case 'center': - // case 'right': - // break; - // case 'end': - // textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; - // break; - // case 'start': - // textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; - // break; - // default: - // textAlign = 'left'; - // } - - // // 1.75 is an arbitrary number, as there is no info about the text baseline - // switch (this.textBaseline) { - // case 'hanging': - // case 'top': - // offset.y = fontStyle.size / 1.75; - // break; - // case 'middle': - // break; - // default: - // case null: - // case 'alphabetic': - // case 'ideographic': - // case 'bottom': - // offset.y = -fontStyle.size / 2.25; - // break; - // } - - // switch(textAlign) { - // case 'right': - // left = delta; - // right = 0.05; - // break; - // case 'center': - // left = right = delta / 2; - // break; - // } - - // var d = getCoords(this, x + offset.x, y + offset.y); - - // lineStr.push(''); - - // if (stroke) { - // appendStroke(this, lineStr); - // } else { - // // TODO: Fix the min and max params. - // appendFill(this, lineStr, {x: -left, y: 0}, - // {x: right, y: fontStyle.size}); - // } - - // var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + - // m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; - - // var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); - - // lineStr.push('', - // '', - // ''); - - // this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - // }; - - // contextPrototype.fillText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, false); - // }; - - // contextPrototype.strokeText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, true); - // }; - - // contextPrototype.measureText = function(text) { - // if (!this.textMeasureEl_) { - // var s = ''; - // this.element_.insertAdjacentHTML('beforeEnd', s); - // this.textMeasureEl_ = this.element_.lastChild; - // } - // var doc = this.element_.ownerDocument; - // this.textMeasureEl_.innerHTML = ''; - // this.textMeasureEl_.style.font = this.font; - // // Don't use innerHTML or innerText because they allow markup/whitespace. - // this.textMeasureEl_.appendChild(doc.createTextNode(text)); - // return {width: this.textMeasureEl_.offsetWidth}; - // }; - - /******** STUBS ********/ - // contextPrototype.clip = function() { - // // TODO: Implement - // }; - - // contextPrototype.arcTo = function() { - // // TODO: Implement - // }; - - // contextPrototype.createPattern = function(image, repetition) { - // return new CanvasPattern_(image, repetition); - // }; - - // // Gradient / Pattern Stubs - // function CanvasGradient_(aType) { - // this.type_ = aType; - // this.x0_ = 0; - // this.y0_ = 0; - // this.r0_ = 0; - // this.x1_ = 0; - // this.y1_ = 0; - // this.r1_ = 0; - // this.colors_ = []; - // } - - // CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { - // aColor = processStyle(aColor); - // this.colors_.push({offset: aOffset, - // color: aColor.color, - // alpha: aColor.alpha}); - // }; - - // function CanvasPattern_(image, repetition) { - // assertImageIsValid(image); - // switch (repetition) { - // case 'repeat': - // case null: - // case '': - // this.repetition_ = 'repeat'; - // break - // case 'repeat-x': - // case 'repeat-y': - // case 'no-repeat': - // this.repetition_ = repetition; - // break; - // default: - // throwException('SYNTAX_ERR'); - // } - - // this.src_ = image.src; - // this.width_ = image.width; - // this.height_ = image.height; - // } - - function throwException(s) { - throw new DOMException_(s); - } - - // function assertImageIsValid(img) { - // if (!img || img.nodeType != 1 || img.tagName != 'IMG') { - // throwException('TYPE_MISMATCH_ERR'); - // } - // if (img.readyState != 'complete') { - // throwException('INVALID_STATE_ERR'); - // } - // } - - function DOMException_(s) { - this.code = this[s]; - this.message = s + ': DOM Exception ' + this.code; - } - var p = DOMException_.prototype = new Error; - p.INDEX_SIZE_ERR = 1; - p.DOMSTRING_SIZE_ERR = 2; - p.HIERARCHY_REQUEST_ERR = 3; - p.WRONG_DOCUMENT_ERR = 4; - p.INVALID_CHARACTER_ERR = 5; - p.NO_DATA_ALLOWED_ERR = 6; - p.NO_MODIFICATION_ALLOWED_ERR = 7; - p.NOT_FOUND_ERR = 8; - p.NOT_SUPPORTED_ERR = 9; - p.INUSE_ATTRIBUTE_ERR = 10; - p.INVALID_STATE_ERR = 11; - p.SYNTAX_ERR = 12; - p.INVALID_MODIFICATION_ERR = 13; - p.NAMESPACE_ERR = 14; - p.INVALID_ACCESS_ERR = 15; - p.VALIDATION_ERR = 16; - p.TYPE_MISMATCH_ERR = 17; - - // set up externs - G_vmlCanvasManager = G_vmlCanvasManager_; - CanvasRenderingContext2D = CanvasRenderingContext2D_; - //CanvasGradient = CanvasGradient_; - //CanvasPattern = CanvasPattern_; - DOMException = DOMException_; - })(); - -} // if - -/*! JsRender v1.0pre: http://github.com/BorisMoore/jsrender */ -/* - * Optimized version of jQuery Templates, for rendering to string. - * Does not require jQuery, or HTML DOM - * Integrates with JsViews (http://github.com/BorisMoore/jsviews) - * Copyright 2012, Boris Moore - * Released under the MIT License. - */ -// informal pre beta commit counter: 3 - -this.jsviews || this.jQuery && jQuery.views || (function( window, undefined ) { - -//========================== Top-level vars ========================== - -var versionNumber = "v1.0pre", - - $, rTag, rTmplString, extend, - sub = {}, - FALSE = false, TRUE = true, - jQuery = window.jQuery, - - rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // nil object helper view viewProperty pathTokens leafToken string - - rParams = /(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - - rNewLine = /\r?\n/g, - rUnescapeQuotes = /\\(['"])/g, - rEscapeQuotes = /\\?(['"])/g, - rBuildHash = /\x08(~)?([^\x08]+)\x08/g, - - autoViewKey = 0, - autoTmplName = 0, - escapeMapForHtml = { - "&": "&", - "<": "<", - ">": ">" - }, - tmplAttr = "data-jsv-tmpl", - fnDeclStr = "var j=j||" + (jQuery ? "jQuery." : "js") + "views,", - htmlSpecialChar = /[\x00"&'<>]/g, - slice = Array.prototype.slice, - - render = {}, - - // jsviews object ($.views if jQuery is loaded) - jsv = { - jsviews: versionNumber, - sub: sub, // subscription, e.g. JsViews integration - debugMode: TRUE, - err: function( e ) { - return jsv.debugMode ? ("
          Error: " + (e.message || e) + ". ") : '""'; - }, - tmplFn: tmplFn, - render: render, - templates: templates, - tags: tags, - helpers: helpers, - converters: converters, - View: View, - convert: convert, - delimiters: setDelimiters, - tag: renderTag - }; - -//========================== Top-level functions ========================== - -//=================== -// jsviews.delimiters -//=================== - -function setDelimiters( openChars, closeChars ) { - // Set the tag opening and closing delimiters. Default is "{{" and "}}" - // openChar, closeChars: opening and closing strings, each with two characters - var firstOpenChar = "\\" + openChars.charAt( 0 ), // Escape the characters - since they could be regex special characters - secondOpenChar = "\\" + openChars.charAt( 1 ), - firstCloseChar = "\\" + closeChars.charAt( 0 ), - secondCloseChar = "\\" + closeChars.charAt( 1 ); - // Build regex with new delimiters - jsv.rTag = rTag // make rTag available to JsViews (or other components) for parsing binding expressions - = secondOpenChar - // tag (followed by / space or }) or colon or html or code - + "(?:(?:(\\w+(?=[\\/\\s" + firstCloseChar + "]))|(?:(\\w+)?(:)|(>)|(\\*)))" - // params - + "\\s*((?:[^" + firstCloseChar + "]|" + firstCloseChar + "(?!" + secondCloseChar + "))*?)" - // slash or closeBlock - + "(\\/)?|(?:\\/(\\w+)))" - // }} - + firstCloseChar; - - // Default rTag: tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/\s\}]))|(?:(\w+)?(:)|(>)|(\*)))\s*((?:[^}]|}(?!\}))*?)(\/)?|(?:\/(\w+)))}} - - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - rTag = new RegExp( firstOpenChar + rTag + secondCloseChar, "g" ); - rTmplString = new RegExp( "<.*>|" + openChars + ".*" + closeChars ); - return this; -} - -//================= -// View.hlp -//================= - -function getHelper( helper ) { - // Helper method called as view.hlp() from compiled template, for helper functions or template parameters ~foo - var view = this, - tmplHelpers = view.tmpl.helpers || {}; - helper = (view.ctx[ helper ] !== undefined ? view.ctx : tmplHelpers[ helper ] !== undefined ? tmplHelpers : helpers[ helper ] !== undefined ? helpers : {})[ helper ]; - return typeof helper !== "function" ? helper : function() { - return helper.apply(view, arguments); - }; -} - -//================= -// jsviews.convert -//================= - -function convert( converter, view, text ) { - var tmplConverters = view.tmpl.converters; - converter = tmplConverters && tmplConverters[ converter ] || converters[ converter ]; - return converter ? converter.call( view, text ) : text; -} - -//================= -// jsviews.tag -//================= - -function renderTag( tag, parentView, converter, content, tagObject ) { - // Called from within compiled template function, to render a nested tag - // Returns the rendered tag - tagObject.props = tagObject.props || {}; - var ret, - tmpl = tagObject.props.tmpl, - tmplTags = parentView.tmpl.tags, - nestedTemplates = parentView.tmpl.templates, - args = arguments, - tagFn = tmplTags && tmplTags[ tag ] || tags[ tag ]; - - if ( !tagFn ) { - return ""; - } - // Set the tmpl property to the content of the block tag, unless set as an override property on the tag - content = content && parentView.tmpl.tmpls[ content - 1 ]; - tmpl = tmpl || content || undefined; - tagObject.tmpl = - "" + tmpl === tmpl // if a string - ? nestedTemplates && nestedTemplates[ tmpl ] || templates[ tmpl ] || templates( tmpl ) - : tmpl; - - tagObject.isTag = TRUE; - tagObject.converter = converter; - tagObject.view = parentView; - tagObject.renderContent = renderContent; - if ( parentView.ctx ) { - extend( tagObject.ctx, parentView.ctx); - } - - ret = tagFn.apply( tagObject, args.length > 5 ? slice.call( args, 5 ) : [] ); - return ret || ( ret == undefined ? "" : ret.toString()); // (If ret is the value 0 or false, will render to string) -} - -//================= -// View constructor -//================= - -function View( context, path, parentView, data, template, index ) { - // Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded) - var views = parentView.views, -// TODO: add this, as part of smart re-linking on existing content ($.link method), or remove completely -// self = parentView.views[ index ]; -// if ( !self ) { ... } - self = { - tmpl: template, - path: path, - parent: parentView, - data: data, - ctx: context, - views: $.isArray( data ) ? [] : {}, - hlp: getHelper - }; - - if ( $.isArray( views )) { - views.splice( - self.index = index !== undefined - ? index - : views.length, 0, self - ); - } else { - views[ self.index = "_" + autoViewKey++ ] = self; - } - return self; -} - -//================= -// Registration -//================= - -function addToStore( self, store, name, item, process ) { - // Add item to named store such as templates, helpers, converters... - var key, onStore; - if ( name && typeof name === "object" && !name.nodeType ) { - // If name is a map, iterate over map and call store for key - for ( key in name ) { - store( key, name[ key ]); - } - return self; - } - if ( !name || item === undefined ) { - if ( process ) { - item = process( undefined, item || name ); - } - } else if ( "" + name === name ) { // name must be a string - if ( item === null ) { - // If item is null, delete this entry - delete store[name]; - } else if ( item = process ? process( name, item ) : item ) { - store[ name ] = item; - } - } - if ( onStore = sub.onStoreItem ) { - // e.g. JsViews integration - onStore( store, name, item, process ); - } - return item; -} - -function templates( name, tmpl ) { - // Register templates - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, templates, name, tmpl, compile ); -} - -function tags( name, tagFn ) { - // Register template tags - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, tags, name, tagFn ); -} - -function helpers( name, helperFn ) { - // Register helper functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.helpers( name, helperFn ) or $.view.helpers({ name: helperFn, ... }) to add additional helpers to the registered helpers collection. - // Getter: Use var helperFn = $.views.helpers( name ) or $.views.helpers[name] or $.views.helpers.name to return the function. - // Remove: Use $.view.helpers( name, null ) to remove a registered helper function from $.view.helpers. - // Within a template, access the helper using the syntax: {{... ~myHelper(...) ...}}. - return addToStore( this, helpers, name, helperFn ); -} - -function converters( name, converterFn ) { - // Register converter functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.converters( name, converterFn ) or $.view.converters({ name: converterFn, ... }) to add additional converters to the registered converters collection. - // Getter: Use var converterFn = $.views.converters( name ) or $.views.converters[name] or $.views.converters.name to return the converter function. - // Remove: Use $.view.converters( name, null ) to remove a registered converter from $.view.converters. - // Within a template, access the converter using the syntax: {{myConverter:...}}. - return addToStore( this, converters, name, converterFn ); -} - -//================= -// renderContent -//================= - -function renderContent( data, context, parentView, path, index ) { - // Render template against data as a tree of subviews (nested template), or as a string (top-level template). - // tagName parameter for internal use only. Used for rendering templates registered as tags (which may have associated presenter objects) - var i, l, dataItem, newView, itemWrap, itemsWrap, itemResult, parentContext, tmpl, layout, - props = {}, - swapContent = index === TRUE, - self = this, - result = ""; - - if ( self.isTag ) { - // This is a call from renderTag - tmpl = self.tmpl; - context = context || self.ctx; - parentView = parentView || self.view; - path = path || self.path; - index = index || self.index; - props = self.props; - } else { - tmpl = self.jquery && self[0] // This is a call $.fn.render - || self; // This is a call from tmpl.render - } - parentView = parentView || jsv.topView; - parentContext = parentView.ctx; - layout = tmpl.layout; - if ( data === parentView ) { - // Inherit the data from the parent view. - // This may be the contents of an {{if}} block - data = parentView.data; - layout = TRUE; - } - - // Set additional context on views created here, (as modified context inherited from the parent, and be inherited by child views) - // Note: If no jQuery, extend does not support chained copies - so limit extend() to two parameters - context = (context && context === parentContext) - ? parentContext - : (parentContext - // if parentContext, make copy - ? ((parentContext = extend( {}, parentContext ), context) - // If context, merge context with copied parentContext - ? extend( parentContext, context ) - : parentContext) - // if no parentContext, use context, or default to {} - : context || {}); - - if ( props.link === FALSE ) { - // Override inherited value of link by an explicit setting in props: link=false - // The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect. - context.link = FALSE; - } - if ( !tmpl.fn ) { - tmpl = templates[ tmpl ] || templates( tmpl ); - } - itemWrap = context.link && sub.onRenderItem; - itemsWrap = context.link && sub.onRenderItems; - - if ( tmpl ) { - if ( $.isArray( data ) && !layout ) { - // Create a view for the array, whose child views correspond to each data item. - // (Note: if index and parentView are passed in along with parent view, treat as - // insert -e.g. from view.addViews - so parentView is already the view item for array) - newView = swapContent ? parentView : (index !== undefined && parentView) || View( context, path, parentView, data, tmpl, index ); - - for ( i = 0, l = data.length; i < l; i++ ) { - // Create a view for each data item. - dataItem = data[ i ]; - itemResult = tmpl.fn( dataItem, View( context, path, newView, dataItem, tmpl, (index||0) + i ), jsv ); - result += itemWrap ? itemWrap( itemResult, props ) : itemResult; - } - } else { - // Create a view for singleton data object. - newView = swapContent ? parentView : View( context, path, parentView, data, tmpl, index ); - result += (data || layout) ? tmpl.fn( data, newView, jsv ) : ""; - } - parentView.topKey = newView.index; - return itemsWrap ? itemsWrap( result, path, newView.index, tmpl, props ) : result; - } - return ""; // No tmpl. Could throw... -} - -//=========================== -// Build and compile template -//=========================== - -// Generate a reusable function that will serve to render a template against data -// (Compile AST then build template function) - -function syntaxError() { - throw "Syntax error"; -} - -function tmplFn( markup, tmpl, bind ) { - // Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes - // Used for compiling templates, and also by JsViews to build functions for data link expressions - var newNode, node, i, l, code, hasTag, hasEncoder, getsValue, hasConverter, hasViewPath, tag, converter, params, hash, nestedTmpl, allowCode, - tmplOptions = tmpl ? { - allowCode: allowCode = tmpl.allowCode, - debug: tmpl.debug - } : {}, - nested = tmpl && tmpl.tmpls, - astTop = [], - loc = 0, - stack = [], - content = astTop, - current = [,,,astTop], - nestedIndex = 0; - - //==== nested functions ==== - function pushPreceedingContent( shift ) { - shift -= loc; - if ( shift ) { - content.push( markup.substr( loc, shift ).replace( rNewLine, "\\n" )); - } - } - - function parseTag( all, tagName, converter, colon, html, code, params, slash, closeBlock, index ) { - // tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(?:(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - // Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, contentMarkup ] - if ( html ) { - colon = ":"; - converter = "html"; - } - var hash = "", - passedCtx = "", - block = !slash && !colon; // Block tag if not self-closing and not {{:}} or {{>}} (special case) - - //==== nested helper function ==== - - tagName = tagName || colon; - pushPreceedingContent( index ); - loc = index + all.length; // location marker - parsed up to here - if ( code ) { - if ( allowCode ) { - content.push([ "*", params.replace( rUnescapeQuotes, "$1" ) ]); - } - } else if ( tagName ) { - if ( tagName === "else" ) { - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - content = current[ 3 ]; - block = TRUE; - } - params = (params - ? parseParams( params, bind ) - .replace( rBuildHash, function( all, isCtx, keyValue ) { - if ( isCtx ) { - passedCtx += keyValue + ","; - } else { - hash += keyValue + ","; - } - return ""; - }) - : ""); - hash = hash.slice( 0, -1 ); - params = params.slice( 0, -1 ); - newNode = [ - tagName, - converter || "", - params, - block && [], - "{" + (hash ? ("props:{" + hash + "},"): "") + "path:'" + params + "'" + (passedCtx ? ",ctx:{" + passedCtx.slice( 0, -1 ) + "}" : "") + "}" - ]; - if ( block ) { - stack.push( current ); - current = newNode; - current[ 5 ] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag - } - content.push( newNode ); - } else if ( closeBlock ) { - //if ( closeBlock !== current[ 0 ]) { - // throw "unmatched close tag: /" + closeBlock + ". Expected /" + current[ 0 ]; - //} - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - } - if ( !current ) { - throw "Expected block tag"; - } - content = current[ 3 ]; - } - //==== /end of nested functions ==== - - markup = markup.replace( rEscapeQuotes, "\\$1" ); - - // Build the AST (abstract syntax tree) under astTop - markup.replace( rTag, parseTag ); - - pushPreceedingContent( markup.length ); - - // Use the AST (astTop) to build the template function - l = astTop.length; - code = (l ? "" : '"";'); - - for ( i = 0; i < l; i++ ) { - // AST nodes: [ tagName, converter, params, content, hash, contentMarkup ] - node = astTop[ i ]; - if ( node[ 0 ] === "*" ) { - code = code.slice( 0, i ? -1 : -3 ) + ";" + node[ 1 ] + (i + 1 < l ? "ret+=" : ""); - } else if ( "" + node === node ) { // type string - code += '"' + node + '"+'; - } else { - tag = node[ 0 ]; - converter = node[ 1 ]; - params = node[ 2 ]; - content = node[ 3 ]; - hash = node[ 4 ]; - markup = node[ 5 ]; - if ( content ) { - // Create template object for nested template - nestedTmpl = TmplObject( markup, tmplOptions, tmpl, nestedIndex++ ); - // Compile to AST and then to compiled function - tmplFn( markup, nestedTmpl); - nested.push( nestedTmpl ); - } - hasViewPath = hasViewPath || hash.indexOf( "view" ) > -1; - code += (tag === ":" - ? (converter === "html" - ? (hasEncoder = TRUE, "e(" + params) - : converter - ? (hasConverter = TRUE, 'c("' + converter + '",view,' + params) - : (getsValue = TRUE, "((v=" + params + ')!=u?v:""') - ) - : (hasTag = TRUE, 't("' + tag + '",view,"' + (converter || "") + '",' - + (content ? nested.length : '""') // For block tags, pass in the key (nested.length) to the nested content template - + "," + hash + (params ? "," : "") + params)) - + ")+"; - } - } - code = new Function( "data, view, j, b, u", fnDeclStr - + (getsValue ? "v," : "") - + (hasTag ? "t=j.tag," : "") - + (hasConverter ? "c=j.convert," : "") - + (hasEncoder ? "e=j.converters.html," : "") - + "ret; try{\n\n" - + (tmplOptions.debug ? "debugger;" : "") - + (allowCode ? 'ret=' : 'return ') - + code.slice( 0, -1 ) + ";\n\n" - + (allowCode ? "return ret;" : "") - + "}catch(e){return j.err(e);}" - ); - - // Include only the var references that are needed in the code - if ( tmpl ) { - tmpl.fn = code; - tmpl.useVw = hasConverter || hasViewPath || hasTag; - } - return code; -} - -function parseParams( params, bind ) { - var named, - fnCall = {}, - parenDepth = 0, - quoted = FALSE, // boolean for string content in double quotes - aposed = FALSE; // or in single quotes - - function parseTokens( all, lftPrn0, lftPrn, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, prn2, space ) { - // rParams = /(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn path operator err eq path2 prn comma lftPrn3 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - operator = operator || ""; - lftPrn = lftPrn || lftPrn0 || lftPrn2; - path = path || path2; - prn = prn || prn2 || ""; - operator = operator || ""; - - function parsePath( all, object, helper, view, viewProperty, pathTokens, leafToken ) { - // rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // object helper view viewProperty pathTokens leafToken string - if ( object ) { - var ret = (helper - ? 'view.hlp("' + helper + '")' - : view - ? "view" - : "data") - + (leafToken - ? (viewProperty - ? "." + viewProperty - : helper - ? "" - : (view ? "" : "." + object) - ) + (pathTokens || "") - : (leafToken = helper ? "" : view ? viewProperty || "" : object, "")); - - if ( bind && prn !== "(" ) { - ret = "b(" + ret + ',"' + leafToken + '")'; - } - return ret + (leafToken ? "." + leafToken : ""); - } - return all; - } - - if ( err ) { - syntaxError(); - } else { - return (aposed - // within single-quoted string - ? (aposed = !apos, (aposed ? all : '"')) - : quoted - // within double-quoted string - ? (quoted = !quot, (quoted ? all : '"')) - : - ( - (lftPrn - ? (parenDepth++, lftPrn) - : "") - + (space - ? (parenDepth - ? "" - : named - ? (named = FALSE, "\b") - : "," - ) - : eq - // named param - ? (parenDepth && syntaxError(), named = TRUE, '\b' + path + ':') - : path - // path - ? (path.replace( rPath, parsePath ) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : operator) - ) - : operator - ? all - : rtPrn - // function - ? ((fnCall[ parenDepth-- ] = FALSE, rtPrn) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : "") - ) - : comma - ? (fnCall[ parenDepth ] || syntaxError(), ",") // We don't allow top-level literal arrays or objects - : lftPrn0 - ? "" - : (aposed = apos, quoted = quot, '"') - )) - ); - } - } - params = (params + " " ).replace( rParams, parseTokens ); - return params; -} - -function compile( name, tmpl, parent, options ) { - // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object - // options is the set of template properties, c - var tmplOrMarkup, elem, key, nested, nestedItem; - - //==== nested functions ==== - function tmplOrMarkupFromStr( value ) { - // If value is of type string - treat as selector, or name of compiled template - // Return the template object, if already compiled, or the markup string - - if ( ("" + value === value) || value.nodeType > 0 ) { - // If selector is valid and returns at least one element, get first element - elem = value.nodeType > 0 ? value : !rTmplString.test( value ) && jQuery && jQuery( value )[0]; - if ( elem && elem.type ) { - // It is a script element - // Create a name for data linking if none provided - value = templates[ elem.getAttribute( tmplAttr )]; - if ( !value ) { - // Not already compiled and cached, so compile and cache the name - name = name || "_" + autoTmplName++; - elem.setAttribute( tmplAttr, name ); - value = compile( name, elem.innerHTML, parent, options ); // Use tmpl as options - templates[ name ] = value; - } - } - return value; - } - // If value is not a string or dom element, return undefined - } - - //==== Compile the template ==== - tmplOrMarkup = tmplOrMarkupFromStr( tmpl ); - - // If tmpl is a template object, use it for options - options = options || (tmpl.markup ? tmpl : {}); - options.name = name; - nested = options.templates; - - // If tmpl is not a markup string or a selector string, then it must be a template object - // In that case, get it from the markup property of the object - if ( !tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr( tmpl.markup ))) { - if ( tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode )) { - // if the string references a compiled template object, but the debug or allowCode props are different, need to recompile - tmplOrMarkup = tmplOrMarkup.markup; - } - } - if ( tmplOrMarkup !== undefined ) { - if ( name && !parent ) { - render[ name ] = function() { - return tmpl.render.apply( tmpl, arguments ); - }; - } - if ( tmplOrMarkup.fn || tmpl.fn ) { - // tmpl is already compiled, so use it, or if different name is provided, clone it - if ( tmplOrMarkup.fn ) { - if ( name && name !== tmplOrMarkup.name ) { - tmpl = extend( extend( {}, tmplOrMarkup ), options); - } else { - tmpl = tmplOrMarkup; - } - } - } else { - // tmplOrMarkup is a markup string, not a compiled template - // Create template object - tmpl = TmplObject( tmplOrMarkup, options, parent, 0 ); - // Compile to AST and then to compiled function - tmplFn( tmplOrMarkup, tmpl ); - } - for ( key in nested ) { - // compile nested template declarations - nestedItem = nested[ key ]; - if ( nestedItem.name !== key ) { - nested[ key ] = compile( key, nestedItem, tmpl ); - } - } - return tmpl; - } -} -//==== /end of function compile ==== - -function TmplObject( markup, options, parent, index ) { - // Template object constructor - - // nested helper function - function extendStore( storeName ) { - if ( parent[ storeName ]) { - // Include parent items except if overridden by item of same name in options - tmpl[ storeName ] = extend( extend( {}, parent[ storeName ] ), options[ storeName ] ); - } - } - - options = options || {}; - var tmpl = { - markup: markup, - tmpls: [], - links: [], - render: renderContent - }; - if ( parent ) { - if ( parent.templates ) { - tmpl.templates = extend( extend( {}, parent.templates ), options.templates ); - } - tmpl.parent = parent; - tmpl.name = parent.name + "[" + index + "]"; - tmpl.index = index; - } - - extend( tmpl, options ); - if ( parent ) { - extendStore( "templates" ); - extendStore( "tags" ); - extendStore( "helpers" ); - extendStore( "converters" ); - } - return tmpl; -} - -//========================== Initialize ========================== - -if ( jQuery ) { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is loaded, so make $ the jQuery object - $ = jQuery; - $.templates = templates; - $.render = render; - $.views = jsv; - $.fn.render = renderContent; - -} else { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is not loaded. - - $ = window.jsviews = jsv; - $.extend = function( target, source ) { - var name; - target = target || {}; - for ( name in source ) { - target[ name ] = source[ name ]; - } - return target; - }; - - $.isArray = Array && Array.isArray || function( obj ) { - return Object.prototype.toString.call( obj ) === "[object Array]"; - }; -} - -extend = $.extend; - -jsv.topView = { views: {}, tmpl: {}, hlp: getHelper, ctx: jsv.helpers }; - -function replacerForHtml( ch ) { - // Original code from Mike Samuel - return escapeMapForHtml[ ch ] - // Intentional assignment that caches the result of encoding ch. - || (escapeMapForHtml[ ch ] = "&#" + ch.charCodeAt( 0 ) + ";"); -} - -//========================== Register tags ========================== - -tags({ - "if": function() { - var ifTag = this, - view = ifTag.view; - - view.onElse = function( tagObject, args ) { - var i = 0, - l = args.length; - - while ( l && !args[ i++ ]) { - // Only render content if args.length === 0 (i.e. this is an else with no condition) or if a condition argument is truey - if ( i === l ) { - return ""; - } - } - view.onElse = undefined; // If condition satisfied, so won't run 'else'. - tagObject.path = ""; - return tagObject.renderContent( view ); - // Test is satisfied, so render content, while remaining in current data context - // By passing the view, we inherit data context from the parent view, and the content is treated as a layout template - // (so if the data is an array, it will not iterate over the data - }; - return view.onElse( this, arguments ); - }, - "else": function() { - var view = this.view; - return view.onElse ? view.onElse( this, arguments ) : ""; - }, - "for": function() { - var i, - self = this, - result = "", - args = arguments, - l = args.length; - if ( self.props.layout ) { - self.tmpl.layout = TRUE; - } - for ( i = 0; i < l; i++ ) { - result += self.renderContent( args[ i ]); - } - return result; - }, - "=": function( value ) { - return value; - }, - "*": function( value ) { - return value; - } -}); - -//========================== Register global helpers ========================== - -// helpers({ // Global helper functions -// // TODO add any useful built-in helper functions -// }); - -//========================== Register converters ========================== - -converters({ - html: function( text ) { - // HTML encoding helper: Replace < > & and ' and " by corresponding entities. - // inspired by Mike Samuel - return text != undefined ? String( text ).replace( htmlSpecialChar, replacerForHtml ) : ""; - } -}); - -//========================== Define default delimiters ========================== -setDelimiters( "{{", "}}" ); - -})( this ); - -/*! - * jQuery Mousewheel 3.1.13 - * - * Copyright jQuery Foundation and other contributors - * Released under the MIT license - * http://jquery.org/license - */ - -(function (factory) { - if ( typeof define === 'function' && define.amd ) { - // AMD. Register as an anonymous module. - define(['jquery'], factory); - } else if (typeof exports === 'object') { - // Node/CommonJS style for Browserify - module.exports = factory; - } else { - // Browser globals - factory(jQuery); - } -}(function ($) { - - var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], - toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? - ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], - slice = Array.prototype.slice, - nullLowestDeltaTimeout, lowestDelta; - - if ( $.event.fixHooks ) { - for ( var i = toFix.length; i; ) { - $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; - } - } - - var special = $.event.special.mousewheel = { - version: '3.1.12', - - setup: function() { - if ( this.addEventListener ) { - for ( var i = toBind.length; i; ) { - this.addEventListener( toBind[--i], handler, false ); - } - } else { - this.onmousewheel = handler; - } - // Store the line height and page height for this particular element - $.data(this, 'mousewheel-line-height', special.getLineHeight(this)); - $.data(this, 'mousewheel-page-height', special.getPageHeight(this)); - }, - - teardown: function() { - if ( this.removeEventListener ) { - for ( var i = toBind.length; i; ) { - this.removeEventListener( toBind[--i], handler, false ); - } - } else { - this.onmousewheel = null; - } - // Clean up the data we added to the element - $.removeData(this, 'mousewheel-line-height'); - $.removeData(this, 'mousewheel-page-height'); - }, - - getLineHeight: function(elem) { - var $elem = $(elem), - $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent'](); - if (!$parent.length) { - $parent = $('body'); - } - return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16; - }, - - getPageHeight: function(elem) { - return $(elem).height(); - }, - - settings: { - adjustOldDeltas: true, // see shouldAdjustOldDeltas() below - normalizeOffset: true // calls getBoundingClientRect for each event - } - }; - - $.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); - }, - - unmousewheel: function(fn) { - return this.unbind('mousewheel', fn); - } - }); - - - function handler(event) { - var orgEvent = event || window.event, - args = slice.call(arguments, 1), - delta = 0, - deltaX = 0, - deltaY = 0, - absDelta = 0, - offsetX = 0, - offsetY = 0; - event = $.event.fix(orgEvent); - event.type = 'mousewheel'; - - // Old school scrollwheel delta - if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } - if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } - if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } - if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } - - // Firefox < 17 horizontal scrolling related to DOMMouseScroll event - if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { - deltaX = deltaY * -1; - deltaY = 0; - } - - // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy - delta = deltaY === 0 ? deltaX : deltaY; - - // New school wheel delta (wheel event) - if ( 'deltaY' in orgEvent ) { - deltaY = orgEvent.deltaY * -1; - delta = deltaY; - } - if ( 'deltaX' in orgEvent ) { - deltaX = orgEvent.deltaX; - if ( deltaY === 0 ) { delta = deltaX * -1; } - } - - // No change actually happened, no reason to go any further - if ( deltaY === 0 && deltaX === 0 ) { return; } - - // Need to convert lines and pages to pixels if we aren't already in pixels - // There are three delta modes: - // * deltaMode 0 is by pixels, nothing to do - // * deltaMode 1 is by lines - // * deltaMode 2 is by pages - if ( orgEvent.deltaMode === 1 ) { - var lineHeight = $.data(this, 'mousewheel-line-height'); - delta *= lineHeight; - deltaY *= lineHeight; - deltaX *= lineHeight; - } else if ( orgEvent.deltaMode === 2 ) { - var pageHeight = $.data(this, 'mousewheel-page-height'); - delta *= pageHeight; - deltaY *= pageHeight; - deltaX *= pageHeight; - } - - // Store lowest absolute delta to normalize the delta values - absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) ); - - if ( !lowestDelta || absDelta < lowestDelta ) { - lowestDelta = absDelta; - - // Adjust older deltas if necessary - if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { - lowestDelta /= 40; - } - } - - // Adjust older deltas if necessary - if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { - // Divide all the things by 40! - delta /= 40; - deltaX /= 40; - deltaY /= 40; - } - - // Get a whole, normalized value for the deltas - delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); - deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); - deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); - - // Normalise offsetX and offsetY properties - if ( special.settings.normalizeOffset && this.getBoundingClientRect ) { - var boundingRect = this.getBoundingClientRect(); - offsetX = event.clientX - boundingRect.left; - offsetY = event.clientY - boundingRect.top; - } - - // Add information to the event object - event.deltaX = deltaX; - event.deltaY = deltaY; - event.deltaFactor = lowestDelta; - event.offsetX = offsetX; - event.offsetY = offsetY; - // Go ahead and set deltaMode to 0 since we converted to pixels - // Although this is a little odd since we overwrite the deltaX/Y - // properties with normalized deltas. - event.deltaMode = 0; - - // Add event and delta to the front of the arguments - args.unshift(event, delta, deltaX, deltaY); - - // Clearout lowestDelta after sometime to better - // handle multiple device types that give different - // a different lowestDelta - // Ex: trackpad = 3 and mouse wheel = 120 - if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } - nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); - - return ($.event.dispatch || $.event.handle).apply(this, args); - } - - function nullLowestDelta() { - lowestDelta = null; - } - - function shouldAdjustOldDeltas(orgEvent, absDelta) { - // If this is an older event and the delta is divisable by 120, - // then we are assuming that the browser is treating this as an - // older mouse wheel event and that we should divide the deltas - // by 40 to try and get a more usable deltaFactor. - // Side note, this actually impacts the reported scroll distance - // in older browsers and can cause scrolling to be slower than native. - // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. - return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; - } - -})); - -/*! - * jQuery UI Widget 1.8.18 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ - -if ( ! $.widget ) { - -(function( $, undefined ) { - -// jQuery 1.4+ -if ( $.cleanData ) { - var _cleanData = $.cleanData; - $.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); - }; -} else { - var _remove = $.fn.remove; - $.fn.remove = function( selector, keepData ) { - return this.each(function() { - if ( !keepData ) { - if ( !selector || $.filter( selector, [ this ] ).length ) { - $( "*", this ).add( [ this ] ).each(function() { - try { - $( this ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - }); - } - } - return _remove.call( $(this), selector, keepData ); - }); - }; -} - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from -// $.each( basePrototype, function( key, val ) { -// if ( $.isPlainObject(val) ) { -// basePrototype[ key ] = $.extend( {}, val ); -// } -// }); - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = Array.prototype.slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - // prevent calls to internal methods - if ( isMethodCall && options.charAt( 0 ) === "_" ) { - return returnValue; - } - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ), - methodValue = instance && $.isFunction( instance[options] ) ? - instance[ options ].apply( instance, args ) : - instance; - // TODO: add this back in 1.9 and use $.error() (see #5972) -// if ( !instance ) { -// throw "cannot call methods on " + name + " prior to initialization; " + -// "attempted to call method '" + options + "'"; -// } -// if ( !$.isFunction( instance[options] ) ) { -// throw "no such method '" + options + "' for " + name + " widget instance"; -// } -// var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, name, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - // $.widget.bridge stores the plugin instance, but we do it anyway - // so that it's stored even before the _create function runs - $.data( element, this.widgetName, this ); - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - var self = this; - this.element.bind( "remove." + this.widgetName, function() { - self.destroy(); - }); - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: function() {}, - _init: function() {}, - - destroy: function() { - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - }, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - [ value ? "addClass" : "removeClass"]( - this.widgetBaseClass + "-disabled" + " " + - "ui-state-disabled" ) - .attr( "aria-disabled", value ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - - return !( $.isFunction(callback) && - callback.call( this.element[0], event, data ) === false || - event.isDefaultPrevented() ); - } -}; - -})( jQuery ); - -}; - - -(function ($, window, undefined) { - window.toStaticHTML = window.toStaticHTML || function ( x ) { return x; }; - - var pos_oo = Number.POSITIVE_INFINITY, - neg_oo = Number.NEGATIVE_INFINITY; - - $.geo = { - // - // utility functions - // - - _allCoordinates: function (geom) { - // return array of all positions in all geometries of geom - // not in JTS - var geometries = this._flatten(geom), - curGeom = 0, - result = []; - - for (; curGeom < geometries.length; curGeom++) { - var coordinates = geometries[curGeom].coordinates, - isArray = coordinates && $.isArray(coordinates[0]), - isDblArray = isArray && $.isArray(coordinates[0][0]), - isTriArray = isDblArray && $.isArray(coordinates[0][0][0]), - i, j, k; - - if (!isTriArray) { - if (!isDblArray) { - if (!isArray) { - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - for (k = 0; k < coordinates[i][j].length; k++) { - result.push(coordinates[i][j][k]); - } - } - } - } - return result; - }, - - _isGeodetic: function( coords ) { - // returns true if the first coordinate it can find is geodetic - - while ( $.isArray( coords ) ) { - if ( coords.length > 1 && ! $.isArray( coords[ 0 ] ) ) { - return ( coords[ 0 ] >= -180.001 && coords[ 0 ] <= 180.001 && coords[ 1 ] >= -90.001 && coords[ 1 ] <= 90.001 ); - } else { - coords = coords[ 0 ]; - } - } - - return false; - }, - - // - // bbox functions - // - - center: function (bbox, _ignoreGeo /* Internal Use Only */) { - // Envelope.centre in JTS - // bbox only, use centroid for geom - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return wasGeodetic ? $.geo.proj.toGeodetic(center) : center; - }, - - expandBy: function (bbox, dx, dy, _ignoreGeo /* Internal Use Only */) { - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - bbox = [bbox[0] - dx, bbox[1] - dy, bbox[2] + dx, bbox[3] + dy]; - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - height: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[3] - bbox[1]; - }, - - _in: function(bbox1, bbox2) { - return bbox1[0] <= bbox2[0] && - bbox1[1] <= bbox2[1] && - bbox1[2] >= bbox2[2] && - bbox1[3] >= bbox2[3]; - }, - - _bboxDisjoint: function( bbox1, bbox2 ) { - return bbox2[ 0 ] > bbox1[ 2 ] || - bbox2[ 2 ] < bbox1[ 0 ] || - bbox2[ 1 ] > bbox1[ 3 ] || - bbox2[ 3 ] < bbox1[ 1 ]; - }, - - include: function( bbox, value, _ignoreGeo /* Internal Use Only */ ) { - // similar to Envelope.expandToInclude in JTS - if ( !value || !$.isArray( value ) ) { - return bbox; - } - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox || value ) ) { - wasGeodetic = true; - } - - if ( !bbox ) { - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - } else if ( wasGeodetic ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - - if ( value.length === 2 ) { - value = [ value[ 0 ], value[ 1 ], value[ 0 ], value[ 1 ] ]; - } - - if ( $.geo.proj ) { - value = $.geo.proj.fromGeodetic( value ); - } - - bbox[0] = Math.min( value[ 0 ], bbox[ 0 ] ); - bbox[1] = Math.min( value[ 1 ], bbox[ 1 ] ); - bbox[2] = Math.max( value[ 2 ], bbox[ 2 ] ); - bbox[3] = Math.max( value[ 3 ], bbox[ 3 ] ); - - return wasGeodetic ? $.geo.proj.toGeodetic( bbox ) : bbox; - }, - - polygonize: function( bbox, _ignoreGeo /* Internal Use Only */ ) { - // adaptation of Polygonizer class in JTS for use with bboxes - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var polygon = { - type: "Polygon", - coordinates: [ [ - [ bbox[ 0 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 1 ] ] - ] ] - }; - - if ( wasGeodetic ) { - polygon.coordinates = $.geo.proj.toGeodetic( polygon.coordinates ); - } - - return polygon; - }, - - reaspect: function (bbox, ratio, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var width = this.width(bbox, true), - height = this.height(bbox, true), - center = this.center(bbox, true), - dx, dy; - - if (width !== 0 && height !== 0 && ratio > 0) { - if (width / height > ratio) { - dx = width / 2; - dy = dx / ratio; - } else { - dy = height / 2; - dx = dy * ratio; - } - - bbox = [center[0] - dx, center[1] - dy, center[0] + dx, center[1] + dy]; - } - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - recenter: function( bbox, center, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj ) { - if ( this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - if ( this._isGeodetic( center ) ) { - center = $.geo.proj.fromGeodetic(center); - } - } - - var halfWidth = ( bbox[ 2 ] - bbox[ 0 ] ) / 2, - halfHeight = ( bbox[ 3 ] - bbox[ 1 ] ) / 2; - - bbox = [ - center[ 0 ] - halfWidth, - center[ 1 ] - halfHeight, - center[ 0 ] + halfWidth, - center[ 1 ] + halfHeight - ]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - scaleBy: function ( bbox, scale, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var c = this.center(bbox, true), - dx = (bbox[2] - bbox[0]) * scale / 2, - dy = (bbox[3] - bbox[1]) * scale / 2; - - bbox = [c[0] - dx, c[1] - dy, c[0] + dx, c[1] + dy]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - width: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[2] - bbox[0]; - }, - - // - // geometry functions - // - - // bbox (Geometry.getEnvelope in JTS) - - bbox: function ( geom, _ignoreGeo /* Internal Use Only */ ) { - var result, wasGeodetic = false; - if ( !geom ) { - return undefined; - } else if ( geom.bbox ) { - result = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.bbox ) ) ? $.geo.proj.fromGeodetic( geom.bbox ) : geom.bbox; - } else { - result = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var coordinates = this._allCoordinates( geom ), - curCoord = 0; - - if ( coordinates.length === 0 ) { - return undefined; - } - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coordinates ) ) { - wasGeodetic = true; - coordinates = $.geo.proj.fromGeodetic( coordinates ); - } - - for ( ; curCoord < coordinates.length; curCoord++ ) { - result[0] = Math.min(coordinates[curCoord][0], result[0]); - result[1] = Math.min(coordinates[curCoord][1], result[1]); - result[2] = Math.max(coordinates[curCoord][0], result[2]); - result[3] = Math.max(coordinates[curCoord][1], result[3]); - } - } - - return wasGeodetic ? $.geo.proj.toGeodetic(result) : result; - }, - - // centroid - - centroid: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var c; //< temp storage for any coordinate during centroid op - - switch (geom.type) { - case "Point": - return $.extend({}, geom); - - case "LineString": - case "Polygon": - var a = 0, - coords = $.merge( [ ], geom.type === "Polygon" ? geom.coordinates[0] : geom.coordinates ), - i = 1, j, n, - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - c = [ 0, 0 ]; - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coords ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic(coords); - } - - //if (coords[0][0] != coords[coords.length - 1][0] || coords[0][1] != coords[coords.length - 1][1]) { - // coords.push(coords[0]); - //} - - for (; i <= coords.length; i++) { - j = i % coords.length; - - bbox[0] = Math.min(coords[j][0], bbox[0]); - bbox[1] = Math.min(coords[j][1], bbox[1]); - bbox[2] = Math.max(coords[j][0], bbox[2]); - bbox[3] = Math.max(coords[j][1], bbox[3]); - - n = (coords[i - 1][0] * coords[j][1]) - (coords[j][0] * coords[i - 1][1]); - a += n; - c[0] += (coords[i - 1][0] + coords[j][0]) * n; - c[1] += (coords[i - 1][1] + coords[j][1]) * n; - } - - if (a === 0) { - if (coords.length > 0) { - c[0] = Math.min( Math.max( coords[0][0], bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( coords[0][1], bbox[ 1 ] ), bbox[ 3 ] ); - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } else { - return undefined; - } - } - - a *= 3; - //c[0] /= a; - //c[1] /= a; - - c[0] = Math.min( Math.max( c[0] / a, bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( c[1] / a, bbox[ 1 ] ), bbox[ 3 ] ); - - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - - case "MultiPoint": - // should return center of mass for point cluster but just return first point for now - if ( geom.coordinates.length > 0 ) { - c = geom.coordinates[ 0 ]; - return { - type: "Point", - coordinates: [ c[ 0 ], c[ 1 ] ] - }; - } - break; - - case "MultiLineString": - case "MultiPolygon": - if ( geom.coordinates.length > 0 ) { - return this.centroid( { - type: geom.type.substr( 5 ), - coordinates: geom.coordinates[ 0 ] - }, _ignoreGeo ); - } - break; - - } - return undefined; - }, - - // contains - - contains: function (geom1, geom2) { - if (geom1.type !== "Polygon") { - return false; - } - - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1.coordinates, geom2.coordinates); - - case "LineString": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates); - - case "Polygon": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates[0]); - - default: - return false; - } - }, - - _containsPolygonPoint: function (polygonCoordinates, pointCoordinate) { - if (polygonCoordinates.length === 0 || polygonCoordinates[0].length < 4) { - return false; - } - - var rayCross = 0, - a = polygonCoordinates[0][0], - i = 1, - b, - x; - - for (; i < polygonCoordinates[0].length; i++) { - b = polygonCoordinates[0][i]; - - if ((a[1] <= pointCoordinate[1] && pointCoordinate[1] < b[1]) || (b[1] <= pointCoordinate[1] && pointCoordinate[1] < a[1]) && (pointCoordinate[0] < a[0] || pointCoordinate[0] < b[0])) { - x = a[0] + (b[0] - a[0]) * (pointCoordinate[1] - a[1]) / (b[1] - a[1]); - - if (x > pointCoordinate[0]) { - rayCross++; - } - } - - a = b; - } - - return rayCross % 2 === 1; - }, - - _containsPolygonLineString: function (polygonCoordinates, lineStringCoordinates) { - for (var i = 0; i < lineStringCoordinates.length; i++) { - if (!this._containsPolygonPoint(polygonCoordinates, lineStringCoordinates[i])) { - return false; - } - } - return true; - }, - - // distance - - distance: function ( geom1, geom2, _ignoreGeo /* Internal Use Only */ ) { - var geom1CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom1.coordinates ) ) ? $.geo.proj.fromGeodetic(geom1.coordinates) : geom1.coordinates, - geom2CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom2.coordinates ) ) ? $.geo.proj.fromGeodetic(geom2.coordinates) : geom2.coordinates; - - switch (geom1.type) { - case "Point": - switch (geom2.type) { - case "Point": - return this._distancePointPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "LineString": - return this._distanceLineStringPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "Polygon": - return this._containsPolygonPoint(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "LineString": - switch (geom2.type) { - case "Point": - return this._distanceLineStringPoint(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "LineString": - return this._distanceLineStringLineString(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "Polygon": - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "LineString": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected[0]) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected[0]); - default: - return undefined; - } - break; - } - }, - - _distancePointPoint: function (coordinate1, coordinate2) { - var dx = coordinate2[0] - coordinate1[0], - dy = coordinate2[1] - coordinate1[1]; - return Math.sqrt((dx * dx) + (dy * dy)); - }, - - _distanceLineStringPoint: function (lineStringCoordinates, pointCoordinate) { - var minDist = pos_oo; - - if (lineStringCoordinates.length > 0) { - var a = lineStringCoordinates[0], - - apx = pointCoordinate[0] - a[0], - apy = pointCoordinate[1] - a[1]; - - if (lineStringCoordinates.length === 1) { - return Math.sqrt(apx * apx + apy * apy); - } else { - for (var i = 1; i < lineStringCoordinates.length; i++) { - var b = lineStringCoordinates[i], - - abx = b[0] - a[0], - aby = b[1] - a[1], - bpx = pointCoordinate[0] - b[0], - bpy = pointCoordinate[1] - b[1], - - d = this._distanceSegmentPoint(abx, aby, apx, apy, bpx, bpy); - - if (d === 0) { - return 0; - } - - if (d < minDist) { - minDist = d; - } - - a = b; - apx = bpx; - apy = bpy; - } - } - } - - return Math.sqrt(minDist); - }, - - _distanceSegmentPoint: function (abx, aby, apx, apy, bpx, bpy) { - var dot1 = abx * apx + aby * apy; - - if (dot1 <= 0) { - return apx * apx + apy * apy; - } - - var dot2 = abx * abx + aby * aby; - - if (dot1 >= dot2) { - return bpx * bpx + bpy * bpy; - } - - return apx * apx + apy * apy - dot1 * dot1 / dot2; - }, - - _distanceLineStringLineString: function (lineStringCoordinates1, lineStringCoordinates2) { - var minDist = pos_oo; - for (var i = 0; i < lineStringCoordinates2.length; i++) { - minDist = Math.min(minDist, this._distanceLineStringPoint(lineStringCoordinates1, lineStringCoordinates2[i])); - } - return minDist; - }, - - // buffer - - _buffer: function( geom, distance, _ignoreGeo /* Internal Use Only */ ) { - var wasGeodetic = false, - coords = geom.coordinates; - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.coordinates ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic( geom.coordinates ); - } - - if ( geom.type === "Point" ) { - var resultCoords = [], - slices = 180, - i = 0, - a; - - for ( ; i <= slices; i++ ) { - a = ( i * 360 / slices ) * ( Math.PI / 180 ); - resultCoords.push( [ - coords[ 0 ] + Math.cos( a ) * distance, - coords[ 1 ] + Math.sin( a ) * distance - ] ); - } - - return { - type: "Polygon", - coordinates: [ ( wasGeodetic ? $.geo.proj.toGeodetic( resultCoords ) : resultCoords ) ] - }; - } else { - return undefined; - } - }, - - - // - // feature - // - - _basic: function( geom ) { - // return an array of all basic geometries - // e.g., MultiPolygons become multiple Polygons - // coordinate arrays are kept as references for speed & should not be altered - // not in JTS - var geometries = [ ]; - var multiType; - var i = 0; - var j; - - var flat = this._flatten( geom ); - - for ( ; i < flat.length; i++ ) { - if ( flat[ i ].type.substring( 0, 5 ) === "Multi" ) { - multiType = flat[ i ].type.substring( 5 ); - - for ( j = 0; j < flat[ i ].coordinates.length; j++ ) { - geometries.push( { - type: multiType, - coordinates: flat[ i ].coordinates[ j ] - } ); - } - } else { - geometries.push( flat[ i ] ); - } - } - - return geometries; - }, - - _flatten: function (geom) { - // return an array of only geometries - // will extract geometries from Feature, FeatureCollection, & GeometryCollection - // not in JTS - var geometries = [], - curGeom = 0; - switch (geom.type) { - case "Feature": - $.merge(geometries, this._flatten(geom.geometry)); - break; - - case "FeatureCollection": - for (; curGeom < geom.features.length; curGeom++) { - $.merge(geometries, this._flatten(geom.features[curGeom].geometry)); - } - break; - - case "GeometryCollection": - for (; curGeom < geom.geometries.length; curGeom++) { - $.merge(geometries, this._flatten(geom.geometries[curGeom])); - } - break; - - default: - geometries[0] = geom; - break; - } - return geometries; - }, - - length: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - lineStringCoordinates, - i = 1, dx, dy; - - switch ( geom.type ) { - case "Point": - return 0; - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][0] - lineStringCoordinates[ i - 1 ][0]; - dy = lineStringCoordinates[ i ][1] - lineStringCoordinates[ i - 1 ][1]; - sum += Math.sqrt((dx * dx) + (dy * dy)); - } - - return sum; - } - - // return undefined; - }, - - area: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - polygonCoordinates, - i = 1, j; - - switch ( geom.type ) { - case "Point": - case "LineString": - return 0; - - case "Polygon": - polygonCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( polygonCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( polygonCoordinates ) ) { - polygonCoordinates = $.geo.proj.fromGeodetic( polygonCoordinates ); - } - - for ( ; i <= polygonCoordinates.length; i++) { - j = i % polygonCoordinates.length; - sum += ( polygonCoordinates[ i - 1 ][ 0 ] - polygonCoordinates[ j ][ 0 ] ) * ( polygonCoordinates[ i - 1 ][ 1 ] + polygonCoordinates[ j ][ 1 ] ) / 2; - } - - return Math.abs( sum ); - } - }, - - pointAlong: function( geom, percentage, _ignoreGeo /* Internal Use Only */ ) { - var totalLength = 0, - previousPercentageSum = 0, - percentageSum = 0, - remainderPercentageSum, - len, - lineStringCoordinates, - segmentLengths = [], - i = 1, dx, dy, - c, c0, c1, - wasGeodetic = false; - - switch ( geom.type ) { - case "Point": - return $.extend( { }, geom ); - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( percentage === 0 ) { - return { - type: "Point", - coordinates: [ lineStringCoordinates[ 0 ][ 0 ], lineStringCoordinates[ 0 ][ 1 ] ] - }; - } else if ( percentage === 1 ) { - i = lineStringCoordinates.length - 1; - return { - type: "Point", - coordinates: [ lineStringCoordinates[ i ][ 0 ], lineStringCoordinates[ i ][ 1 ] ] - }; - } else { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - wasGeodetic = true; - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][ 0 ] - lineStringCoordinates[ i - 1 ][ 0 ]; - dy = lineStringCoordinates[ i ][ 1 ] - lineStringCoordinates[ i - 1 ][ 1 ]; - len = Math.sqrt((dx * dx) + (dy * dy)); - segmentLengths.push( len ); - totalLength += len; - } - - for ( i = 0; i < segmentLengths.length && percentageSum < percentage; i++ ) { - previousPercentageSum = percentageSum; - percentageSum += ( segmentLengths[ i ] / totalLength ); - } - - remainderPercentageSum = percentage - previousPercentageSum; - - c0 = lineStringCoordinates[ i - 1 ]; - c1 = lineStringCoordinates[ i ]; - - c = [ - c0[ 0 ] + ( remainderPercentageSum * ( c1[ 0 ] - c0[ 0 ] ) ), - c0[ 1 ] + ( remainderPercentageSum * ( c1[ 1 ] - c0[ 1 ] ) ) - ]; - - return { - type: "Point", - coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c - }; - } - } - }, - - // - // WKT functions - // - - WKT: (function () { - function pointToString(value) { - return "POINT " + pointToUntaggedString(value.coordinates); - } - - function pointToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - return "(" + coordinates.join(" ") + ")"; - } - } - - function lineStringToString(value) { - return "LINESTRING " + lineStringToUntaggedString(value.coordinates); - } - - function lineStringToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var points = []; - - for (var i = 0; i < coordinates.length; i++) { - points.push(coordinates[i].join(" ")); - } - - return "(" + points + ")"; - } - } - - function polygonToString(value) { - return "POLYGON " + polygonToUntaggedString(value.coordinates); - } - - function polygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMTPY"; - } else { - var lineStrings = []; - - for (var i = 0; i < coordinates.length; i++) { - lineStrings.push(lineStringToUntaggedString(coordinates[i])); - } - - return "(" + lineStrings + ")"; - } - } - - function multiPointToString(value) { - return "MULTIPOINT " + lineStringToUntaggedString(value.coordinates); - } - - function multiLineStringToString(value) { - return "MULTILINSTRING " + polygonToUntaggedString(value.coordinates); - } - - function multiPolygonToString(value) { - return "MULTIPOLYGON " + multiPolygonToUntaggedString(value.coordinates); - } - - function multiPolygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var polygons = []; - for (var i = 0; i < coordinates.length; i++) { - polygons.push(polygonToUntaggedString(coordinates[i])); - } - return "(" + polygons + ")"; - } - } - - function geometryCollectionToString(value) { - return "GEOMETRYCOLLECTION " + geometryCollectionToUntaggedString(value.geometries); - } - - function geometryCollectionToUntaggedString(geometries) { - if (!(geometries && geometries.length)) { - return "EMPTY"; - } else { - var geometryText = []; - for (var i = 0; i < geometries.length; i++) { - geometryText.push(stringify(geometries[i])); - } - return "(" + geometries + ")"; - } - } - - function stringify(value) { - if (!(value && value.type)) { - return ""; - } else { - switch (value.type) { - case "Point": - return pointToString(value); - - case "LineString": - return lineStringToString(value); - - case "Polygon": - return polygonToString(value); - - case "MultiPoint": - return multiPointToString(value); - - case "MultiLineString": - return multiLineStringToString(value); - - case "MultiPolygon": - return multiPolygonToString(value); - - case "GeometryCollection": - return geometryCollectionToString(value); - - default: - return ""; - } - } - } - - function pointParseUntagged(wkt) { - var pointString = wkt.match( /\(\s*([\d\.\-]+)\s+([\d\.\-]+)\s*\)/ ); - return pointString && pointString.length > 2 ? { - type: "Point", - coordinates: [ - parseFloat(pointString[1]), - parseFloat(pointString[2]) - ] - } : null; - } - - function lineStringParseUntagged(wkt) { - var lineString = wkt.match( /\s*\((.*)\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( lineString && lineString.length > 1 ) { - pointStrings = lineString[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "LineString", - coordinates: coords - }; - } else { - return null; - } - } - - function polygonParseUntagged(wkt) { - var polygon = wkt.match( /\s*\(\s*\((.*)\)\s*\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( polygon && polygon.length > 1 ) { - pointStrings = polygon[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "Polygon", - coordinates: [ coords ] - }; - } else { - return null; - } - } - - function multiPointParseUntagged(wkt) { - var multiSomething; - - if ( wkt.indexOf( "((" ) === -1 ) { - multiSomething = lineStringParseUntagged( wkt ); - } else { - multiSomething = multiLineStringParseUntagged( wkt ); - multiSomething.coordinates = $.geo._allCoordinates( multiSomething ); - } - - multiSomething.type = "MultiPoint"; - - return multiSomething; - } - - function multiLineStringParseUntagged(wkt) { - var lineStringsWkt = wkt.substr( 2, wkt.length - 4 ), - lineString, - lineStrings = lineStringsWkt.split( /\),\s*\(/ ), - i = 0, - multiLineString = { - type: "MultiLineString", - coordinates: [ ] - }; - - for ( ; i < lineStrings.length; i++ ) { - lineString = lineStringParseUntagged( "(" + lineStrings[ i ] + ")" ); - if ( lineString ) { - multiLineString.coordinates.push( lineString.coordinates ); - } - } - - return multiLineString; - } - - function multiPolygonParseUntagged(wkt) { - var polygonsWkt = wkt.substr( 1, wkt.length - 2 ), - polygon, - polygons = polygonsWkt.split( /\),\s*\(/ ), - i = 0, - multiPolygon = { - type: "MultiPolygon", - coordinates: [ ] - }; - - for ( ; i < polygons.length; i++ ) { - polygon = polygonParseUntagged( "(" + polygons[ i ] + ")" ); - if ( polygon ) { - multiPolygon.coordinates.push( polygon.coordinates ); - } - } - - return multiPolygon; - } - - function geometryCollectionParseUntagged( wkt ) { - var geometriesWkt = wkt.substr( 1, wkt.length - 2 ), - geometries = geometriesWkt.match( /\),[a-zA-Z]/g ), - geometryCollection = { - type: "GeometryCollection", - geometries: [ ] - }, - curGeom, - i = 0, curStart = 0, curLen; - - if ( geometries && geometries.length > 0 ) { - for ( ; i < geometries.length; i++ ) { - curLen = geometriesWkt.indexOf( geometries[ i ], curStart ) - curStart + 1; - curGeom = parse( geometriesWkt.substr( curStart, curLen ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - curStart += curLen + 1; - } - - // one more - curGeom = parse( geometriesWkt.substr( curStart ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - - return geometryCollection; - } else { - return null; - } - } - - function parse(wkt) { - wkt = $.trim(wkt); - - var typeIndex = wkt.indexOf( "(" ), - untagged = wkt.substr( typeIndex ); - - switch ($.trim(wkt.substr(0, typeIndex)).toUpperCase()) { - case "POINT": - return pointParseUntagged( untagged ); - - case "LINESTRING": - return lineStringParseUntagged( untagged ); - - case "POLYGON": - return polygonParseUntagged( untagged ); - - case "MULTIPOINT": - return multiPointParseUntagged( untagged ); - - case "MULTILINESTRING": - return multiLineStringParseUntagged( untagged ); - - case "MULTIPOLYGON": - return multiPolygonParseUntagged( untagged ); - - case "GEOMETRYCOLLECTION": - return geometryCollectionParseUntagged( untagged ); - - default: - return null; - } - } - - return { - stringify: stringify, - - parse: parse - }; - }()), - - // - // projection functions - // - - proj: (function () { - var halfPi = 1.5707963267948966192, - quarterPi = 0.7853981633974483096, - radiansPerDegree = 0.0174532925199432958, - degreesPerRadian = 57.295779513082320877, - semiMajorAxis = 6378137; - - return { - fromGeodeticPos: function (coordinate) { - return [ - semiMajorAxis * coordinate[ 0 ] * radiansPerDegree, - semiMajorAxis * Math.log(Math.tan(quarterPi + coordinate[ 1 ] * radiansPerDegree / 2)) - ]; - }, - - fromGeodetic: function ( coordinates ) { - if ( ! $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - fromGeodeticPos = this.fromGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length === 4) { - // bbox - var min = fromGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = fromGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = fromGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - }, - - toGeodeticPos: function (coordinate) { - return [ - (coordinate[ 0 ] / semiMajorAxis) * degreesPerRadian, - (halfPi - 2 * Math.atan(1 / Math.exp(coordinate[ 1 ] / semiMajorAxis))) * degreesPerRadian - ]; - }, - - toGeodetic: function (coordinates) { - if ( $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - toGeodeticPos = this.toGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length === 4) { - // bbox - var min = toGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = toGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = toGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - } - }; - }()), - - // - // service types (defined in other files) - // - - _serviceTypes: {} - }; -}(jQuery, this)); - -(function ($, window, undefined) { - var _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ); - - $.widget("geo.geographics", { - _$elem: undefined, - _options: {}, - _trueCanvas: true, - _trueDoubleBuffer: true, - - _width: 0, - _height: 0, - - _$canvas: undefined, - _context: undefined, - - _$canvasSceneFront: undefined, //< if _trueCanvas, where canvas images get written (front buffer) - _$canvasSceneBack: undefined, //< if _trueCanvas, where canvas images get written (back buffer) - _timeoutEnd: null, - _requireFlip: false, - - _blitcanvas: undefined, - _blitcontext: undefined, - - _$labelsContainerFront: undefined, - _$labelsContainerBack: undefined, - _labelsHtml: "", - - options: { - style: { - borderRadius: "8px", - color: "#7f0000", - //fill: undefined, - fillOpacity: 0.2, - height: "8px", - opacity: 1, - //stroke: undefined, - strokeOpacity: 1, - strokeWidth: "2px", - visibility: "visible", - width: "8px" - }, - - doubleBuffer: true - }, - - _create: function () { - this._$elem = this.element; - this._options = this.options; - - this._$elem.css( { - webkitTransform: "translateZ(0)", - display: "inline-block", - overflow: "hidden", - textAlign: "left" - } ); - - if (this._$elem.css("position") === "static") { - this._$elem.css("position", "relative"); - } - - this._$elem.addClass( "geo-graphics" ); - - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - var posCss = 'position:absolute;left:0;top:0;margin:0;padding:0;', - sizeCss = 'width:' + this._width + 'px;height:' + this._height + 'px;', - sizeAttr = 'width="' + this._width + '" height="' + this._height + '"'; - - this._blitcanvas = document.createElement( "canvas" ); - - if ( this._blitcanvas.getContext ) { - this._$canvas = $( window.toStaticHTML( '' ) ); - - // test _trueDoubleBuffer - this._blitcanvas.width = 1; - this._blitcanvas.height = 1; - this._trueDoubleBuffer = this._blitcanvas.toDataURL().length > 6; - - if ( !(this._options.doubleBuffer && this._trueDoubleBuffer) ) { - this._$elem.append( this._$canvas ); - } - - this._context = this._$canvas[0].getContext("2d"); - - this._blitcanvas.width = this._width; - this._blitcanvas.height = this._height; - this._blitcontext = this._blitcanvas.getContext("2d"); - - // create our front & back buffers - // though, at any time either one can be in front - this._$canvasSceneFront = $( window.toStaticHTML( '' ) ); //.load($.proxy(this._canvasSceneLoad, this)); - this._$canvasSceneBack = $( window.toStaticHTML( '' ) ); //.load($.proxy(this._canvasSceneLoad, this)); - - } else if (_ieVersion <= 8) { - this._trueCanvas = false; - this._$elem.append( '
          '); - this._$canvas = this._$elem.children(':last'); - - G_vmlCanvasManager.initElement(this._$canvas[0]); - this._context = this._$canvas[0].getContext("2d"); - this._$canvas.children().css({ backgroundColor: "transparent", width: this._width, height: this._height }); - } - - // create our front & back label containers - this._$labelsContainerFront = $( window.toStaticHTML( '
          ' ) ); - this._$labelsContainerBack = $( window.toStaticHTML( '
          ' ) ); - }, - - _setOption: function (key, value) { - if (key === "style") { - value = $.extend({}, this._options.style, value); - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - destroy: function () { - $.Widget.prototype.destroy.apply(this, arguments); - this._$elem.html(""); - this._$elem.removeClass( "geo-graphics" ); - }, - - clear: function () { - this._context.clearRect(0, 0, this._width, this._height); - this._labelsHtml = ""; - this._end( ); - }, - - drawArc: function (coordinates, startAngle, sweepAngle, style) { - style = this._getGraphicStyle(style); - - if (style.visibility !== "hidden" && style.opacity > 0 && style.widthValue > 0 && style.heightValue > 0) { - var r = Math.min(style.widthValue, style.heightValue) / 2; - - startAngle = (startAngle * Math.PI / 180); - sweepAngle = (sweepAngle * Math.PI / 180); - - this._context.save(); - this._context.translate(coordinates[0], coordinates[1]); - if (style.widthValue > style.heightValue) { - this._context.scale(style.widthValue / style.heightValue, 1); - } else { - this._context.scale(1, style.heightValue / style.widthValue); - } - - this._context.beginPath(); - this._context.arc(0, 0, r, startAngle, sweepAngle, false); - - if (this._trueCanvas) { - this._context.restore(); - } - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - if (!this._trueCanvas) { - this._context.restore(); - } - } - - this._end( ); - }, - - drawPoint: function (coordinates, style) { - style = this._getGraphicStyle(style); - if (style.widthValue === style.heightValue && style.heightValue === style.borderRadiusValue) { - this.drawArc(coordinates, 0, 360, style); - } else if (style.visibility !== "hidden" && style.opacity > 0) { - style.borderRadiusValue = Math.min(Math.min(style.widthValue, style.heightValue) / 2, style.borderRadiusValue); - coordinates[0] -= style.widthValue / 2; - coordinates[1] -= style.heightValue / 2; - this._context.beginPath(); - this._context.moveTo(coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.lineTo(coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1]); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1], coordinates[0] + style.widthValue, coordinates[1] + style.borderRadiusValue); - this._context.lineTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue, coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.lineTo(coordinates[0] + style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1] + style.heightValue, coordinates[0], coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.lineTo(coordinates[0], coordinates[1] + style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1], coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.closePath(); - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - - this._context.stroke(); - } - - this._end( ); - } - }, - - drawLineString: function (coordinates, style) { - this._drawLines([coordinates], false, style); - }, - - drawPolygon: function (coordinates, style) { - if ( !this._trueCanvas || coordinates.length === 1 ) { - // either we don't have fancy rendering or there's no need for it (no holes) - this._drawLines( coordinates, true, style ); - } else { - if ( !coordinates || !coordinates.length || coordinates[ 0 ].length < 3 ) { - // this is not a Polygon or it doesn't have a proper outer ring - return; - } - - style = this._getGraphicStyle(style); - this._blitcontext.globalCompositeOperation = "copy"; - - var pixelBbox, i, j; - - if ( style.visibility !== "hidden" && style.opacity > 0 ) { - this._blitcontext.clearRect(0, 0, this._width, this._height); - - if ( style.doFill ) { - if ( coordinates.length > 1 ) { - // stencil inner rings - this._blitcontext.globalCompositeOperation = "source-out"; - this._blitcontext.globalAlpha = 1; - - this._blitcontext.beginPath(); - - for ( i = 1; i < coordinates.length; i++ ) { - // start drawing inner rings, i - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - - for ( j = 0; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - } - - this._blitcontext.closePath(); - - this._blitcontext.fill( ); - } - } - - // path outer ring - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ 0 ][ 0 ][ 0 ], coordinates[ 0 ][ 0 ][ 1 ] ); - - pixelBbox = [ coordinates[ 0 ][ 0 ][ 0 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 0 ] + style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] + style.strokeWidthValue ]; - - for ( i = 1; i < coordinates[ 0 ].length - 1; i++ ) { - this._blitcontext.lineTo( coordinates[ 0 ][ i ][ 0 ], coordinates[ 0 ][ i ][ 1 ] ); - - pixelBbox[ 0 ] = Math.min( coordinates[ 0 ][ i ][ 0 ] - style.strokeWidthValue, pixelBbox[ 0 ] ); - pixelBbox[ 1 ] = Math.min( coordinates[ 0 ][ i ][ 1 ] - style.strokeWidthValue, pixelBbox[ 1 ] ); - pixelBbox[ 2 ] = Math.max( coordinates[ 0 ][ i ][ 0 ] + style.strokeWidthValue, pixelBbox[ 2 ] ); - pixelBbox[ 3 ] = Math.max( coordinates[ 0 ][ i ][ 1 ] + style.strokeWidthValue, pixelBbox[ 3 ] ); - } - - this._blitcontext.closePath(); - - if ( style.doFill ) { - // fill outer ring - this._blitcontext.fillStyle = style.fill; - this._blitcontext.globalAlpha = style.opacity * style.fillOpacity; - this._blitcontext.fill( ); - } - - this._blitcontext.globalCompositeOperation = "source-over"; - if ( style.doStroke ) { - // stroke outer ring - this._blitcontext.lineCap = this._blitcontext.lineJoin = "round"; - this._blitcontext.lineWidth = style.strokeWidthValue; - this._blitcontext.strokeStyle = style.stroke; - - this._blitcontext.globalAlpha = style.opacity * style.strokeOpacity; - this._blitcontext.stroke( ); - - if ( coordinates.length > 1 ) { - // stroke inner rings - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.stroke( ); - } - } - } - - // blit - pixelBbox[ 0 ] = Math.min( Math.max( pixelBbox[ 0 ], 0), this._width ); - pixelBbox[ 1 ] = Math.min( Math.max( pixelBbox[ 1 ], 0), this._height ); - pixelBbox[ 2 ] = Math.min( Math.max( pixelBbox[ 2 ], 0), this._width ); - pixelBbox[ 3 ] = Math.min( Math.max( pixelBbox[ 3 ], 0), this._height ); - - if ( pixelBbox[ 0 ] !== pixelBbox[ 2 ] && pixelBbox[ 1 ] !== pixelBbox[ 3 ] ) { - this._context.drawImage(this._blitcanvas, pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ], pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ] ); - - this._end( ); - } - } - } - }, - - drawBbox: function (bbox, style) { - this._drawLines([[ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ]], true, style); - }, - - drawLabel: function( coordinates, label ) { - this._labelsHtml += '
          ' + label + '
          '; - }, - - resize: function( dx, dy ) { - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - if ( this._trueCanvas ) { - this._$canvas[0].width = this._width; - this._$canvas[0].height = this._height; - - this._$canvasSceneFront.css( { - left: dx, - top: dy - } ); - - this._$canvasSceneBack.css( { - width: this._width, - height: this._height - } ); - } else { - this._$canvas.css( { - width: this._width, - height: this._height - } ); - } - - var labelPositionFront = this._$labelsContainerFront.position(); - - this._$labelsContainerFront.css( { - left: labelPositionFront.left + dx, - top: labelPositionFront.top + dy, - width: this._width, - height: this._height - } ); - - this._$labelsContainerBack.css( { - width: this._width, - height: this._height - } ); - }, - - interactiveTransform: function( origin, scale ) { - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - if ( this._trueCanvas ) { - if ( this._options.doubleBuffer && this._trueDoubleBuffer ) { - - var geographics = this; - - if ( this._requireFlip ) { - geographics._requireFlip = false; - - var oldCanvasScene = geographics._$canvasSceneFront; - - geographics._$canvasSceneFront = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ).prependTo( geographics._$elem ); - - geographics._$canvasSceneBack = oldCanvasScene.prop( "src", "" ).detach(); - } - - // transform a finished scene, can assume no drawing during these calls - this._$canvasSceneFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - - // transform labels - this._$labelsContainerFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - }, - - _canvasSceneLoad: function() { - var geographics = this; - if ( geographics._requireFlip ) { - geographics._requireFlip = false; - var oldCanvasScene = geographics._$canvasSceneFront; - - geographics._$canvasSceneFront = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prependTo( geographics._$elem ); - - geographics._$canvasSceneBack = oldCanvasScene.prop( "src", "" ).detach(); - } - }, - - _endCallback: function() { - var geographics = this; - - if ( !geographics._timeoutEnd ) { - // something has canceled the draw - return; - } - - if ( geographics._trueCanvas && geographics._options.doubleBuffer && geographics._trueDoubleBuffer ) { - geographics._$canvasSceneBack.prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ); - this._canvasSceneLoad( ); - } - - - geographics._$labelsContainerBack.html( window.toStaticHTML( geographics._labelsHtml ) ).find("a").css({ - position: "relative", - zIndex: 1, - display: "inline-block", - webkitTransform: "translateZ(0)" - }); - - var oldLabelsContainer = geographics._$labelsContainerFront; - - geographics._$labelsContainerFront = geographics._$labelsContainerBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).appendTo( geographics._$elem ); - - geographics._$labelsContainerBack = oldLabelsContainer.detach(); - - geographics._timeoutEnd = null; - }, - - _end: function( ) { - // end/finalize a scene - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - this._requireFlip = true; - - this._timeoutEnd = setTimeout( $.proxy(this._endCallback, this), 20 ); - }, - - _getGraphicStyle: function (style) { - function safeParse(value) { - value = parseInt(value, 10); - return (+value + '') === value ? +value : value; - } - - style = $.extend({}, this._options.style, style); - style.borderRadiusValue = safeParse(style.borderRadius); - style.fill = style.fill || style.color; - style.doFill = style.fill && style.fillOpacity > 0; - style.stroke = style.stroke || style.color; - style.strokeWidthValue = safeParse(style.strokeWidth); - style.doStroke = style.stroke && style.strokeOpacity > 0 && style.strokeWidthValue > 0; - style.widthValue = safeParse(style.width); - style.heightValue = safeParse(style.height); - return style; - }, - - _drawLines: function (coordinates, close, style) { - if (!coordinates || !coordinates.length || coordinates[0].length < 2) { - return; - } - - var i, j; - style = this._getGraphicStyle(style); - - if (style.visibility !== "hidden" && style.opacity > 0) { - this._context.beginPath(); - - for (i = 0; i < coordinates.length; i++) { - this._context.moveTo(coordinates[i][0][0], coordinates[i][0][1]); - for (j = 1; j < coordinates[i].length; j++) { - this._context.lineTo(coordinates[i][j][0], coordinates[i][j][1]); - } - } - - if (close) { - this._context.closePath(); - } - - if (close && style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineCap = this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - this._end( ); - } - } - }); -}(jQuery, window)); - - -(function ($, window, undefined) { - var _widgetIdSeed = 0, - _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ), - - _defaultOptions = { - bbox: [-180, -85, 180, 85], - bboxMax: [-180, -85, 180, 85], - center: [0, 0], - cursors: { - "static": "default", - pan: "url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move", - click: "crosshair", - zoom: "crosshair", - dragBox: "crosshair", - dragCircle: "crosshair", - drawPoint: "crosshair", - drawLineString: "crosshair", - drawPolygon: "crosshair", - measureLength: "crosshair", - measureArea: "crosshair" - }, - measureLabels: { - length: "{{:length.toFixed( 2 )}} m", - area: "{{:area.toFixed( 2 )}} sq m" - }, - drawStyle: {}, - shapeStyle: {}, - mode: "pan", - pannable: true, - scroll: "default", - shift: "default", - services: [ - { - "class": "osm", - type: "tiled", - src: function (view) { - return "//otile" + ((view.index % 4) + 1) + ((location.protocol === 'https:') ? "-s" : "") + ".mqcdn.com/tiles/1.0.0/osm/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; - }, - attr: 'Tiles Courtesy of MapQuest ' - } - ], - tilingScheme: { - tileWidth: 256, - tileHeight: 256, - levels: 18, - basePixelSize: 156543.03392799936, - origin: [-20037508.342787, 20037508.342787] - }, - axisLayout: "map", - zoom: 0, - zoomMin: 0, - zoomMax: Number.POSITIVE_INFINITY, - zoomFactor: 2, //< determines what a zoom level means - pixelSize: 0 - }; - - $.widget("geo.geomap", { - // private widget members - _$elem: undefined, //< map div for maps, service div for services - _map: undefined, //< only defined in services - _created: false, - _createdGraphics: false, - _widgetId: 0, - _tmplLengthId: "", - _tmplAreaId: "", - - _contentBounds: {}, - - _$resizeContainer: undefined, //< all elements that should match _contentBounds' size - - _$eventTarget: undefined, - _$contentFrame: undefined, - _$existingChildren: undefined, - _$attrList: undefined, - _$servicesContainer: undefined, - _$shapesContainers: undefined, //< all shapesContainer divs (map only) - - _$panContainer: undefined, //< all non-service elements that move while panning - _$shapesContainer: undefined, //< just "our" shapesContainer div (map & service) - _$drawContainer: undefined, - _$measureContainer: undefined, - _$measureLabel: undefined, - - _dpi: 96, - - _currentServices: [], //< internal copy - - _center: undefined, - _pixelSize: undefined, - _centerMax: undefined, - _pixelSizeMax: undefined, - _pixelSizeMin: undefined, - - _userGeodetic: true, - - _centerInteractive: undefined, - _pixelSizeInteractive: undefined, - _timeoutInteractive: null, - _triggerInteractive: false, - - _timeoutRefreshShapes: null, - - _loadCount: 0, - - _wheelLevel: 0, - - _fullZoomFactor: 2, //< interactiveScale factor needed to zoom a whole level - _partialZoomFactor: 1.18920711500273, //< interactiveScale factor needed to zoom a fraction of a level (the fourth root of 2) - - _mouseDown: undefined, - _inOp: undefined, - _toolPan: undefined, - _shiftDown: undefined, - _anchor: undefined, - _current: undefined, - _downDate: undefined, - _moveDate: undefined, - _clickDate: undefined, - _lastMove: undefined, - _lastDrag: undefined, - - _windowHandler: null, - _resizeTimeout: null, - - _panning: undefined, - _velocity: undefined, - _friction: undefined, - - _pointerEvents: undefined, - _supportTouch: undefined, - _softDblClick: undefined, - _isTap: undefined, - _isDbltap: undefined, - - _isMultiTouch: undefined, - _multiTouchAnchor: [], //< TouchList - _multiTouchAnchorBbox: undefined, //< bbox - _multiTouchCurrentBbox: undefined, //< bbox - - _drawTimeout: null, //< used in drawPoint mode so we don't send two shape events on dbltap - _drawPixels: [], //< an array of coordinate arrays for drawing lines & polygons, in pixel coordinates - _drawCoords: [], - - _graphicShapes: [], //< an array of objects containing style object refs & GeoJSON object refs - - _initOptions: {}, - - _options: {}, - - options: $.extend({}, _defaultOptions), - - _createWidget: function (options, element) { - this._$elem = $(element); - - if (this._$elem.is(".geo-service")) { - this._graphicShapes = []; - $.Widget.prototype._createWidget.apply(this, arguments); - return; - } - - this._widgetId = _widgetIdSeed++; - this._serviceIdSeed = 0; - this._tmplLengthId = "geoMeasureLength" + this._widgetId; - this._tmplAreaId = "geoMeasureArea" + this._widgetId; - - this._$elem.addClass("geo-map").css( { - webkitTransform: "translateZ(0)", - touchAction: 'none' - } ); - - - this._initOptions = options || {}; - - this._forcePosition(this._$elem); - - this._$elem.css("text-align", "left"); - - var size = this._findMapSize(); - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._createChildren(); - - this._center = [ 0, 0 ]; - this._centerMax = [ 0, 0 ]; - this._centerInteractive = [ 0, 0 ]; - - this.options["pixelSize"] = this._pixelSize = this._pixelSizeMax = 156543.03392799936; - this._pixelSizeMin = this._pixelSizeMax / Math.pow( 2, 17 ); - - this._mouseDown = - this._inOp = - this._toolPan = - this._shiftDown = - this._panning = - this._isTap = - this._isDbltap = false; - - this._anchor = [ 0, 0 ]; /* mouse down */ - this._current = [ 0, 0 ]; /* mouse move no matter what */ - this._lastMove = [ 0, 0 ]; - this._lastDrag = [ 0, 0 ]; - this._velocity = [ 0, 0 ]; - - this._friction = [0.8, 0.8]; - - this._downDate = - this._moveDate = - this._clickDate = 0; - - this._drawPixels = []; - this._drawCoords = []; - this._graphicShapes = []; - - - $.Widget.prototype._createWidget.apply(this, arguments); - }, - - _create: function () { - this._options = this.options; - - if (this._$elem.is(".geo-service")) { - this._map = this._$elem.data( "geoMap" ); - this._$elem.data( "geoService", this ); - return; - } - - this._map = this; - - this._pointerEvents = window.PointerEvent; - this._supportTouch = ("ontouchend" in document); - this._softDblClick = this._supportTouch || _ieVersion === 7; - - var geomap = this, - touchStartEvent = this._pointerEvents ? 'pointerdown' : ( this._supportTouch ? "touchstart mousedown" : "mousedown" ), - touchStopEvent = this._pointerEvents ? 'pointerup pointercancel' : ( this._supportTouch ? "touchend touchcancel mouseup" : "mouseup" ), - touchMoveEvent = this._pointerEvents ? 'pointermove' : ( this._supportTouch ? "touchmove mousemove" : "mousemove" ); - - $(document).keydown($.proxy(this._document_keydown, this)); - - this._$eventTarget.dblclick($.proxy(this._eventTarget_dblclick, this)); - - this._$eventTarget.bind(touchStartEvent, $.proxy(this._eventTarget_touchstart, this)); - - var dragTarget = (this._$eventTarget[0].setCapture) ? this._$eventTarget : $(document); - dragTarget.bind(touchMoveEvent, $.proxy(this._dragTarget_touchmove, this)); - dragTarget.bind(touchStopEvent, $.proxy(this._dragTarget_touchstop, this)); - - this._$eventTarget.mousewheel($.proxy(this._eventTarget_mousewheel, this)); - - this._windowHandler = function () { - if (geomap._resizeTimeout) { - clearTimeout(geomap._resizeTimeout); - } - geomap._resizeTimeout = setTimeout(function () { - if (geomap._created) { - geomap._$elem.geomap( "resize", true ); - } - }, 500); - }; - - $(window).resize(this._windowHandler); - - this._$drawContainer.geographics({ style: this._initOptions.drawStyle || {}, doubleBuffer: false }); - this._options["drawStyle"] = this._$drawContainer.geographics("option", "style"); - - this._$shapesContainer.geographics( { style: this._initOptions.shapeStyle || { } } ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - - if (this._initOptions) { - // always init tilingScheme right away, even if it's null - if ( this._initOptions.tilingScheme !== undefined ) { - this._setOption("tilingScheme", this._initOptions.tilingScheme || null, false); - } - - if ( this._initOptions.services ) { - // jQuery UI Widget Factory merges user services with our default, we want to clobber the default - this._options[ "services" ] = $.merge( [ ], this._initOptions.services ); - } - if (this._initOptions.bboxMax) { - this._setOption("bboxMax", this._initOptions.bboxMax, false); - this._setOption("bbox", this._initOptions.bboxMax, false); - } - if (this._initOptions.zoomMin !== undefined) { - this._setOption("zoomMin", this._initOptions.zoomMin, false); - } - if (this._initOptions.zoomMax !== undefined) { - this._setOption("zoomMax", this._initOptions.zoomMax, false); - } - if (this._initOptions.zoomFactor !== undefined) { - this._setOption("zoomFactor", this._initOptions.zoomFactor, false); - this._fullZoomFactor = this._initOptions.zoomFactor; - this._partialZoomFactor = Math.pow(4, 1 / this._fullZoomFactor); // 4th root of full - } - if (this._initOptions.bbox) { - this._setOption("bbox", this._initOptions.bbox, false); - } - if (this._initOptions.center) { - this._setOption("center", this._initOptions.center, false); - } - if (this._initOptions.zoom !== undefined) { - this._setOption("zoom", this._initOptions.zoom, false); - } - } - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._createServices(); - this._refresh(); - - this._created = true; - }, - - _setOption: function (key, value, refresh) { - if ( key === "pixelSize" ) { - return; - } - - refresh = (refresh === undefined || refresh); - - if ( this._$elem.is( ".geo-map" ) ) { - this._panFinalize(); - } - - var center, pixelSize, bbox, zoom; - - switch (key) { - case "bbox": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2]; - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height); - - // clamp to zoom - zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( center, pixelSize ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( center, pixelSize, false, refresh ); - } - - value = this._getBbox( center, pixelSize ); - break; - - case "bboxMax": - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - break; - - case "center": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( value, this._pixelSizeInteractive ); - this._interactiveTransform( ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( value, this._pixelSize, false, refresh ); - } - break; - - case "measureLabels": - value = $.extend( this._options[ "measureLabels" ], value ); - - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - break; - - case "drawStyle": - if (this._$drawContainer) { - this._$drawContainer.geographics("option", "style", value); - value = this._$drawContainer.geographics("option", "style"); - } - break; - - case "shapeStyle": - if ( this._$elem.is( ".geo-service" ) && !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("option", "style", value); - value = this._$shapesContainer.geographics("option", "style"); - } - break; - - case "mode": - this._resetDrawing( ); - this._$eventTarget.css("cursor", this._options["cursors"][value]); - break; - - case "zoom": - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj; - if ( this._created ) { - this._setZoom(value, false, refresh); - } else { - value = Math.max( value, 0 ); - this._setCenterAndSize( this._center, this._getPixelSize( value ), false, refresh ); - } - break; - } - - $.Widget.prototype._setOption.apply(this, arguments); - - switch ( key ) { - case "bbox": - case "center": - if ( this._userGeodetic ) { - this._options[ "bbox" ] = $.geo.proj.toGeodetic( this._options[ "bbox" ] ); - this._options[ "center" ] = $.geo.proj.toGeodetic( this._center ); - } - break; - - case "tilingScheme": - if ( value !== null ) { - this._pixelSizeMax = this._getPixelSize( 0 ); - this._pixelSizeMin = this._getPixelSize( value.pixelSizes ? value.pixelSizes.length - 1 : value.levels - 1 ); - this._centerMax = [ - value.origin[ 0 ] + this._pixelSizeMax * value.tileWidth / 2, - value.origin[ 1 ] + this._pixelSizeMax * value.tileHeight / 2 - ]; - } - break; - - case "bboxMax": - if ( this._userGeodetic ) { - bbox = $.geo.proj.fromGeodetic( value ); - } else { - bbox = value; - } - - this._centerMax = $.geo.center( bbox ); - this._pixelSizeMax = Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - break; - - case "services": - this._createServices(); - if (refresh) { - this._refresh(); - this._refreshAllShapes(); - } - break; - - case "shapeStyle": - if ( refresh && this._createdGraphics ) { - this._$shapesContainer.geographics("clear"); - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - break; - } - }, - - destroy: function () { - if ( this._$elem.is(".geo-service") ) { - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - } - } else { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - - this._created = false; - - $(window).unbind("resize", this._windowHandler); - - for ( var i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - - this._$drawContainer.geographics("destroy"); - this._$drawContainer = undefined; - - this._$existingChildren.detach(); - this._$elem.html(""); - this._$elem.append(this._$existingChildren); - this._$elem.removeClass("geo-map"); - } - - $.Widget.prototype.destroy.apply(this, arguments); - }, - - toMap: function (p) { - p = this._toMap(p); - return this._userGeodetic ? $.geo.proj.toGeodetic(p) : p; - }, - - toPixel: function ( p, _center /* Internal Use Only */, _pixelSize /* Internal Use Only */ ) { - return this._toPixel( $.geo.proj ? $.geo.proj.fromGeodetic( p ) : p, _center, _pixelSize ); - }, - - opacity: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "opacity", value, this._$elem ); - } else { - if ( value >= 0 || value <= 1 ) { - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - service.style.opacity = value; - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - $.geo[ "_serviceTypes" ][ service.type ].opacity( this, service ); - } - } - } - } - }, - - toggle: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "toggle", value, this._$elem ); - } else { - - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - if ( value === undefined ) { - // toggle visibility - value = ( service.style.visibility !== "visible" ); - } - - service.style.visibility = ( value ? "visible" : "hidden" ); - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - service.serviceContainer.toggle( value ); - - if ( value ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service ); - } - } - } - } - }, - - zoom: function (numberOfLevels) { - if (numberOfLevels !== null) { - this._setZoom(this._options["zoom"] + numberOfLevels, false, true); - } - }, - - refresh: function ( force, _serviceContainer ) { - if ( !this._panning ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "refresh", force, this._$elem ); - } else { - this._refresh( force, _serviceContainer ); - this._refreshAllShapes( _serviceContainer ); - } - } - }, - - resize: function ( _trigger /* Internal Use Only */ ) { - var size = this._findMapSize(), - dx = size["width"]/2 - this._contentBounds.width/2, - dy = size["height"]/2 - this._contentBounds.height/2, - i; - - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._$resizeContainer.css( { - width: size["width"], - height: size["height"] - } ); - - for (i = 0; i < this._currentServices.length; i++) { - $.geo["_serviceTypes"][this._currentServices[i].type].resize(this, this._currentServices[i], dx, dy); - } - - this._$elem.find( ".geo-graphics" ).css( { - width: size["width"], - height: size["height"] - }).geographics( "resize", dx, dy ); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._setCenterAndSize(this._center, this._pixelSize, _trigger, true); - }, - - append: function ( shape /* , style, label, refresh */ ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - if ( !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - var shapes, arg, i, realStyle, realLabel, realRefresh; - - if ( $.isArray( shape ) ) { - shapes = shape; - } else if ( shape.type === "FeatureCollection" ) { - shapes = shape.features; - } else { - shapes = [ shape ]; - } - - for ( i = 1; i < arguments.length; i++ ) { - arg = arguments[ i ]; - - if ( arg !== null ) { - if ( typeof arg === "object" ) { - realStyle = arg; - } else if ( typeof arg === "number" || typeof arg === "string" ) { - realLabel = arg; - } else if ( typeof arg === "boolean" ) { - realRefresh = arg; - } - } - } - - for ( i = 0; i < shapes.length; i++ ) { - if ( !$.data( shapes[ i ], "geoBbox" ) ) { - var bbox = $.geo.bbox( shapes[ i ] ); - if ( $.geo.proj && $.geo._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - $.data( shapes[ i ], "geoBbox", bbox ); - } - - this._graphicShapes.push( { - shape: shapes[ i ], - style: realStyle, - label: realLabel - } ); - } - - if ( realRefresh === undefined || realRefresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - empty: function ( refresh ) { - this._graphicShapes = []; - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - }, - - find: function ( selector, pixelTolerance ) { - if ( this._timeoutInteractive ) { - return []; - } - - var isPoint = $.isPlainObject( selector ), - //searchPixel = isPoint ? this._map.toPixel( selector.coordinates ) : undefined, - mapTol = this._map._pixelSize * pixelTolerance, - result = [], - graphicShape, - geometries, - curGeom, - i; - - if ( this._$elem.is( ".geo-map" ) ) { - $( this._$elem.find( ".geo-service" ).get().reverse() ).each( function( ) { - result = $.merge( result, $( this ).geomap( "find", selector, pixelTolerance ) ); - } ); - } - - for ( i = this._graphicShapes.length - 1; i >= 0; i-- ) { - graphicShape = this._graphicShapes[ i ]; - - if ( isPoint ) { - if ( graphicShape.shape.type === "Point" ) { - if ( $.geo.distance( graphicShape.shape, selector ) <= mapTol ) { - result.push( graphicShape.shape ); - } - } else { - var bbox = $.data( graphicShape.shape, "geoBbox" ), - bboxPolygon = { - type: "Polygon", - coordinates: [ [ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ] ] - }, - projectedPoint = { - type: "Point", - coordinates: $.geo.proj && $.geo._isGeodetic( selector.coordinates ) ? $.geo.proj.fromGeodetic( selector.coordinates ) : selector.coordinates - }; - - if ( $.geo.distance( bboxPolygon, projectedPoint, true ) <= mapTol ) { - geometries = $.geo._basic( graphicShape.shape ); - for ( curGeom = 0; curGeom < geometries.length; curGeom++ ) { - if ( $.geo.distance( geometries[ curGeom ], selector ) <= mapTol ) { - result.push( graphicShape.shape ); - break; - } - } - } - } - } else { - result.push( graphicShape.shape ); - } - } - - return result; - }, - - remove: function ( shape, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - var shapes = $.isArray( shape ) ? shape : [ shape ], - rest; - - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - if ( $.inArray( this._graphicShapes[ i ].shape, shapes ) >= 0 ) { - rest = this._graphicShapes.slice( i + 1 ); - this._graphicShapes.length = i; - this._graphicShapes.push.apply( this._graphicShapes, rest ); - i--; - } - } - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - _getBbox: function (center, pixelSize) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - // calculate the internal bbox - var halfWidth = this._contentBounds[ "width" ] / 2 * pixelSize, - halfHeight = this._contentBounds[ "height" ] / 2 * pixelSize; - return [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - }, - - _setBbox: function (value /* , trigger, refresh */ ) { - var center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2], - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height), - zoom = this._getZoom( center, pixelSize ); - - // clamp to zoom - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._setInteractiveCenterAndSize( center, pixelSize ); - this._interactiveTransform( ); - }, - - _getBboxMax: function () { - // calculate the internal bboxMax - var halfWidth = this._contentBounds["width"] / 2 * this._pixelSizeMax, - halfHeight = this._contentBounds["height"] / 2 * this._pixelSizeMax; - return [this._centerMax[0] - halfWidth, this._centerMax[1] - halfHeight, this._centerMax[0] + halfWidth, this._centerMax[1] + halfHeight]; - }, - - _getCenter: function () { - return this._center; - }, - - _getContentBounds: function () { - return this._contentBounds; - }, - - _getServicesContainer: function () { - return this._$servicesContainer; - }, - - _getZoom: function ( center, pixelSize ) { - // calculate the internal zoom level, vs. public zoom property - // this does not take zoomMin or zoomMax into account - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var tilingScheme = this._options["tilingScheme"]; - if ( tilingScheme ) { - if ( tilingScheme.pixelSizes ) { - var roundedPixelSize = Math.floor(pixelSize * 1000), - levels = tilingScheme.pixelSizes.length, - i = levels - 1; - - for ( ; i >= 0; i-- ) { - if ( Math.floor( tilingScheme.pixelSizes[ i ] * 1000 ) >= roundedPixelSize ) { - return i; - } - } - - return 0; - } else { - return Math.round( Math.log( tilingScheme.basePixelSize / pixelSize) / Math.log( 2 ) ); - } - } else { - var ratio = this._contentBounds["width"] / this._contentBounds["height"], - bbox = $.geo.reaspect( this._getBbox( center, pixelSize ), ratio, true ), - bboxMax = $.geo.reaspect(this._getBboxMax(), ratio, true); - - return Math.round( Math.log($.geo.width(bboxMax, true) / $.geo.width(bbox, true)) / Math.log(this._fullZoomFactor) ); - } - }, - - _setZoom: function ( value, trigger /* , refresh */ ) { - // set the map widget's zoom, taking zoomMin and zoomMax into account - this._clearInteractiveTimeout( ); - - value = Math.min( Math.max( value, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ); - - this._setInteractiveCenterAndSize( this._centerInteractive, this._getPixelSize( value ) ); - this._interactiveTransform( ); - this._setInteractiveTimeout( trigger ); - }, - - _createChildren: function () { - this._$existingChildren = this._$elem.children(); - - this._forcePosition(this._$existingChildren); - - this._$existingChildren.detach().css( { - mozUserSelect: "none" - } ); - - - var contentSizeCss = "width:" + this._contentBounds["width"] + "px; height:" + this._contentBounds["height"] + "px; margin:0; padding:0;", - contentPosCss = "position:absolute; left:0; top:0;"; - - this._$elem.prepend( window.toStaticHTML( '
          ' ) ); - this._$eventTarget = this._$contentFrame = this._$elem.children(':first'); - - this._$contentFrame.append('
          '); - this._$servicesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append( '
            ' ); - this._$attrList = this._$contentFrame.children( ":last" ); - - this._$contentFrame.append('
            '); - this._$drawContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
            '); - this._$measureContainer = this._$contentFrame.children(':last'); - this._$measureLabel = this._$measureContainer.children(); - - this._$contentFrame.append('
            '); - this._$shapesContainer = this._$contentFrame.children(':last'); - - this._$panContainer = $( [ this._$shapesContainer[ 0 ], this._$drawContainer[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$resizeContainer = $( [ this._$contentFrame[ 0 ], this._$servicesContainer[ 0 ], this._$eventTarget[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$contentFrame.append(this._$existingChildren); - - if ( ! $("#geo-measure-style").length ) { - $("head").prepend( window.toStaticHTML( '' ) ); - } - }, - - _createServices: function () { - var service, i; - - for ( i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap( "destroy" ); - $.geo[ "_serviceTypes" ][ this._currentServices[ i ].type ].destroy( this, this._$servicesContainer, this._currentServices[ i ] ); - } - - this._currentServices = [ ]; - this._$servicesContainer.html( "" ); - this._$attrList.html( "" ); - - for ( i = 0; i < this._options[ "services" ].length; i++ ) { - service = this._currentServices[ i ] = $.extend( { }, this._options[ "services" ][ i ] ); - - // keep a reference to the original - service.serviceObject = this._options[ "services" ][ i ]; - - // default the service style property on our copy - service.style = $.extend( { - visibility: "visible", - opacity: 1 - }, service.style ); - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = 'class="geo-service ' + ( service["class"] ? service["class"] : '' ) + '"', - scHtml = '
            ', - serviceContainer; - - this._$servicesContainer.append( window.toStaticHTML( scHtml ) ); - serviceContainer = this._$servicesContainer.children( ":last" ); - service.serviceContainer = serviceContainer; - - $.geo[ "_serviceTypes" ][ service.type ].create( this, serviceContainer, service, i ); - - serviceContainer.data( "geoMap", this ).geomap(); - - if ( service.attr ) { - this._$attrList.append( '
          • ' + service.attr + '
          • ' ); - } - } - - // start with our map-level shapesContainer - this._$shapesContainers = this._$shapesContainer; - - this._$attrList.find( "a" ).css( { - position: "relative", - zIndex: 1, - display: "inline-block", - webkitTransform: "translateZ(0)" - } ); - }, - - _createServiceGraphics: function( ) { - // only called in the context of a service-level geomap - var $contentFrame = this._$elem.closest( ".geo-content-frame" ); - this._$elem.append('
            '); - this._$shapesContainer = this._$elem.children(':last'); - - this._map._$shapesContainers = this._map._$shapesContainers.add( this._$shapesContainer ); - - this._$shapesContainer.geographics( ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - }, - - _refreshDrawing: function ( ) { - this._$drawContainer.geographics("clear"); - - if ( this._drawPixels.length > 0 ) { - var mode = this._options[ "mode" ], - pixels = this._drawPixels, - coords = this._drawCoords, - label, - labelShape, - labelPixel, - widthOver, - heightOver; - - switch ( mode ) { - case "measureLength": - mode = "drawLineString"; - labelShape = { - type: "LineString", - coordinates: coords - }; - label = $.render[ this._tmplLengthId ]( { length: $.geo.length( labelShape, true ) } ); - labelPixel = $.merge( [], pixels[ pixels.length - 1 ] ); - break; - - case "measureArea": - mode = "drawPolygon"; - - labelShape = { - type: "Polygon", - coordinates: [ $.merge( [ ], coords ) ] - }; - labelShape.coordinates[ 0 ].push( coords[ 0 ] ); - - label = $.render[ this._tmplAreaId ]( { area: $.geo.area( labelShape, true ) } ); - labelPixel = this._toPixel( $.geo.centroid( labelShape ).coordinates ); - pixels = [ pixels ]; - break; - - case "drawPolygon": - pixels = [ pixels ]; - break; - } - - this._$drawContainer.geographics( mode, pixels ); - - if ( label ) { - this._$measureLabel.html( label ); - - widthOver = this._contentBounds.width - ( this._$measureLabel.outerWidth( true ) + labelPixel[ 0 ] ); - heightOver = this._contentBounds.height - ( this._$measureLabel.outerHeight( true ) + labelPixel[ 1 ] ); - - if ( widthOver < 0 ) { - labelPixel[ 0 ] += widthOver; - } - - if ( heightOver < 0 ) { - labelPixel[ 1 ] += heightOver; - } - - this._$measureLabel.css( { - left: Math.max( labelPixel[ 0 ], 0 ), - top: Math.max( labelPixel[ 1 ], 0 ) - } ).show(); - } - } - }, - - _resetDrawing: function () { - this._drawPixels = []; - this._drawCoords = []; - this._$drawContainer.geographics("clear"); - this._$measureLabel.hide(); - }, - - _refreshAllShapes: function ( _serviceContainer ) { - this._timeoutRefreshShapes = null; - - var service, - geoService, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - geoService = service.serviceContainer.data( "geoService" ); - - if ( geoService._createdGraphics ) { - geoService._$shapesContainer.geographics( "clear" ); - if ( geoService._graphicShapes.length > 0 ) { - geoService._refreshShapes( geoService._$shapesContainer, geoService._graphicShapes, geoService._graphicShapes, geoService._graphicShapes ); - } - } - } - } - - if ( this._createdGraphics && !_serviceContainer ) { - this._$shapesContainer.geographics( "clear" ); - if ( this._graphicShapes.length > 0 ) { - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - } - }, - - - _refreshShapes: function (geographics, shapes, styles, labels, center, pixelSize) { - var i, mgi, - shape, - shapeBbox, - style, - label, - hasLabel, - labelPixel, - centroid, - bbox = this._map._getBbox(center, pixelSize); - - for (i = 0; i < shapes.length; i++) { - shape = shapes[i].shape || shapes[i]; - shape = shape.geometry || shape; - shapeBbox = $.data(shape, "geoBbox"); - - if ( shapeBbox && $.geo._bboxDisjoint( bbox, shapeBbox ) ) { - continue; - } - - style = $.isArray(styles) ? styles[i].style : styles; - label = $.isArray(labels) ? labels[i].label : labels; - hasLabel = ( label !== undefined ); - labelPixel = undefined; - centroid = $.geo.centroid( shape ); - - switch (shape.type) { - case "Point": - labelPixel = this._map.toPixel( shape.coordinates, center, pixelSize ); - this._$shapesContainer.geographics("drawPoint", labelPixel, style); - break; - case "LineString": - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.pointAlong( shape, 0.5 ).coordinates, center, pixelSize ); - } - break; - case "Polygon": - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiPoint": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPoint", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiLineString": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiPolygon": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - - case "GeometryCollection": - this._refreshShapes(geographics, shape.geometries, style, label, center, pixelSize); - break; - } - - if ( hasLabel && labelPixel ) { - this._$shapesContainer.geographics( "drawLabel", labelPixel, label ); - } - } - }, - - _findMapSize: function () { - // really, really attempt to find a size for this thing - // even if it's hidden (look at parents) - var size = { width: 0, height: 0 }, - sizeContainer = this._$elem; - - while (sizeContainer.size() && !(size["width"] > 0 && size["height"] > 0)) { - size = { width: sizeContainer.width(), height: sizeContainer.height() }; - if (size["width"] <= 0 || size["height"] <= 0) { - size = { width: parseInt(sizeContainer.css("width"), 10), height: parseInt(sizeContainer.css("height"), 10) }; - } - sizeContainer = sizeContainer.parent(); - } - return size; - }, - - _forcePosition: function (elem) { - var cssPosition = elem.css("position"); - if (cssPosition !== "relative" && cssPosition !== "absolute" && cssPosition !== "fixed") { - elem.css("position", "relative"); - } - }, - - _getPixelSize: function ( zoom ) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme !== null) { - if (zoom === 0) { - return tilingScheme.pixelSizes ? tilingScheme.pixelSizes[0] : tilingScheme.basePixelSize; - } - - zoom = Math.round(zoom); - zoom = Math.max(zoom, 0); - var levels = tilingScheme.pixelSizes ? tilingScheme.pixelSizes.length : tilingScheme.levels; - zoom = Math.min(zoom, levels - 1); - - if ( tilingScheme.pixelSizes ) { - return tilingScheme.pixelSizes[zoom]; - } else { - return tilingScheme.basePixelSize / Math.pow(2, zoom); - } - } else { - var bbox = $.geo.scaleBy( this._getBboxMax(), 1 / Math.pow( this._fullZoomFactor, zoom ), true ); - return Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - } - }, - - _getZoomCenterAndSize: function ( anchor, zoomDelta, full ) { - var zoomFactor = ( full ? this._fullZoomFactor : this._partialZoomFactor ), - scale = Math.pow( zoomFactor, -zoomDelta ), - pixelSize = this._pixelSizeInteractive * scale; - - if ( this._options[ "tilingScheme" ] ) { - // clamp to min/max pixelSize - pixelSize = Math.min( Math.max( pixelSize, this._pixelSizeMin ), this._pixelSizeMax ); - } - - var zoom = this._getZoom(this._centerInteractive, pixelSize); - - // clamp to zoom - if ( full && this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoomDelta < 0 && zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._pixelSizeInteractive; - } else if ( zoomDelta > 0 && zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._pixelSizeInteractive; - } - } - - var ratio = pixelSize / this._pixelSizeInteractive, - anchorMapCoord = this._toMap( anchor, this._centerInteractive, this._pixelSizeInteractive ), - centerDelta = [(this._centerInteractive[0] - anchorMapCoord[0]) * ratio, (this._centerInteractive[1] - anchorMapCoord[1]) * ratio], - scaleCenter = [anchorMapCoord[0] + centerDelta[0], anchorMapCoord[1] + centerDelta[1]]; - - return { pixelSize: pixelSize, center: scaleCenter }; - }, - - _panFinalize: function () { - if (this._panning) { - this._velocity = [0, 0]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._inOp = false; - this._anchor = this._current; - this._mouseDown = this._toolPan = this._panning = false; - } - }, - - _panMove: function () { - if ( ! this._options[ "pannable" ] ) { - return; - } - - var dx = this._current[0] - this._lastDrag[0], - dy = this._current[1] - this._lastDrag[1]; - - if (this._toolPan || dx > 3 || dx < -3 || dy > 3 || dy < -3) { - if (!this._toolPan) { - this._toolPan = true; - this._$eventTarget.css("cursor", this._options["cursors"]["pan"]); - } - - if (this._mouseDown) { - this._velocity = [dx, dy]; - } - - if (dx !== 0 || dy !== 0) { - this._panning = true; - this._lastDrag = this._current; - - this._centerInteractive[ 0 ] -= ( dx * this._pixelSizeInteractive ); - this._centerInteractive[ 1 ] += ( ( this._options[ "axisLayout" ] === "image" ? -1 : 1 ) * dy * this._pixelSizeInteractive ); - this._setInteractiveCenterAndSize( this._centerInteractive, this._pixelSizeInteractive ); - this._interactiveTransform( ); - } - } - }, - - _clearInteractiveTimeout: function() { - if ( this._timeoutRefreshShapes ) { - clearTimeout( this._timeoutRefreshShapes ); - this._timeoutRefreshShapes = null; - } - - if ( this._timeoutInteractive ) { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - return true; - } else { - this._centerInteractive[ 0 ] = this._center[ 0 ]; - this._centerInteractive[ 1 ] = this._center[ 1 ]; - this._pixelSizeInteractive = this._pixelSize; - return false; - } - }, - - _interactiveTransform: function( ) { - var service, - - scalePixelSize = this._pixelSize, - scaleRatio = scalePixelSize / this._pixelSizeInteractive; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = this._toMap( [ 0, 0 ] ), - newPixelPoint = this._toPixel( oldMapOrigin, this._centerInteractive, this._pixelSizeInteractive ); - - - this._$shapesContainers.geographics("interactiveTransform", newPixelPoint, scaleRatio); - } - - for ( var i = 0; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo[ "_serviceTypes" ][ service.type ].interactiveTransform( this, service, this._centerInteractive, this._pixelSizeInteractive ); - } - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel( this._drawCoords, this._centerInteractive, this._pixelSizeInteractive ); - this._refreshDrawing(); - } - }, - - _interactiveTimeout: function( ) { - if ( this._isMultiTouch ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - } else if ( this._created && this._timeoutInteractive ) { - this._setCenterAndSize( this._centerInteractive, this._pixelSizeInteractive, this._triggerInteractive, true ); - this._timeoutInteractive = null; - this._triggerInteractive = false; - - this._timeoutRefreshShapes = setTimeout( $.proxy( this._refreshAllShapes, this ), 128 ); - } - }, - - _setInteractiveTimeout: function( trigger ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - this._triggerInteractive |= trigger; - }, - - _refresh: function ( force, _serviceContainer ) { - var service, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service, force ); - } - } - }, - - _setInteractiveCenterAndSize: function ( center, pixelSize ) { - // set the temporary (interactive) center & size - // also, update the public-facing options - // this does not take zoomMin or zoomMax into account - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - this._pixelSizeInteractive = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox( center, pixelSize ) ); - this._options["center"] = $.geo.proj.toGeodetic( center ); - } else { - this._options["bbox"] = this._getBbox( center, pixelSize ); - this._options["center"][ 0 ] = center[ 0 ]; - this._options["center"][ 1 ] = center[ 1 ]; - } - - this._options["pixelSize"] = pixelSize; - this._options["zoom"] = this._getZoom( center, pixelSize ); - }, - - _setCenterAndSize: function (center, pixelSize, trigger, refresh) { - if ( ! $.isArray( center ) || center.length !== 2 || typeof center[ 0 ] !== "number" || typeof center[ 1 ] !== "number" ) { - return; - } - - // the final call during any extent change - // only called by timeoutInteractive & resize - // clamp to zoom - var zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - - if ( this._created ) { - // one last interactiveTransform to put pinched map into place - this._interactiveTransform( ); - } - - this._options["pixelSize"] = this._pixelSize = pixelSize; - - this._center[ 0 ] = center[ 0 ]; - this._center[ 1 ] = center[ 1 ]; - - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox() ); - this._options["center"] = $.geo.proj.toGeodetic( this._center ); - } else { - this._options["bbox"] = this._getBbox(); - this._options["center"] = $.merge( [ ], center ); - } - - this._options["zoom"] = zoom; - - if (trigger) { - this._trigger("bboxchange", window.event, { bbox: $.merge( [ ], this._options["bbox"] ) }); - } - - if (refresh) { - this._refresh(); - this._refreshAllShapes( ); - this._refreshDrawing(); - } - }, - - _requestQueued: function ( ) { - if ( this._loadCount === 0 ) { - this._trigger( "loadstart", window.event ); - } - this._loadCount++; - }, - - _requestComplete: function ( ) { - this._loadCount--; - if ( this._loadCount <= 0 ) { - this._loadCount = 0; - this._trigger( "loadend", window.event ); - } - }, - - _toMap: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - xRatio = $.geo.width(bbox, true) / width, - yRatio = $.geo.height(bbox, true) / height, - yOffset, - image = this._options[ "axisLayout" ] === "image", - result = [], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - yOffset = (p[ i ][ j ][ k ][1] * yRatio); - result[ i ][ j ][ k ] = [ - bbox[ 0 ] + ( p[ i ][ j ][ k ][ 0 ] * xRatio ), - image ? bbox[ 1 ] + yOffset : bbox[ 3 ] - yOffset - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _toPixel: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - bboxWidth = $.geo.width(bbox, true), - bboxHeight = $.geo.height(bbox, true), - image = this._options[ "axisLayout" ] === "image", - xRatio = width / bboxWidth, - yRatio = height / bboxHeight, - result = [ ], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = [ - Math.round( ( p[ i ][ j ][ k ][ 0 ] - bbox[ 0 ] ) * xRatio ), - Math.round( ( image ? p[ i ][ j ][ k ][ 1 ] - bbox[ 1 ] : bbox[ 3 ] - p[ i ][ j ][ k ][ 1 ] ) * yRatio ) - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _document_keydown: function (e) { - var len = this._drawCoords.length; - if (len > 0 && e.which === 27) { - if (len <= 2) { - this._resetDrawing(); - this._inOp = false; - } else { - this._drawCoords[len - 2] = $.merge( [], this._drawCoords[ len - 1 ] ); - this._drawPixels[len - 2] = $.merge( [], this._drawPixels[ len - 1 ] ); - - this._drawCoords.length--; - this._drawPixels.length--; - - this._refreshDrawing(); - } - } - }, - - _eventTarget_dblclick_zoom: function(e) { - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - this._trigger("dblclick", e, { type: "Point", coordinates: this._toMap(this._current, this._centerInteractive, this._pixelSizeInteractive ) }); - - if (!e.isDefaultPrevented()) { - var centerAndSize = this._getZoomCenterAndSize(this._current, 1, true ); - - this._setInteractiveCenterAndSize( centerAndSize.center, centerAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - }, - - _eventTarget_dblclick: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - switch (this._options["mode"]) { - case "drawLineString": - case "measureLength": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] === this._drawCoords[1][0] && - this._drawCoords[0][1] === this._drawCoords[1][1] ) ) { - this._drawCoords.length--; - this._trigger( "shape", e, { - type: "LineString", - coordinates: this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords - } ); - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "drawPolygon": - case "measureArea": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] === this._drawCoords[1][0] && - this._drawCoords[0][1] === this._drawCoords[1][1] ) ) { - var endIndex = this._drawCoords.length - 1; - if (endIndex > 2) { - this._drawCoords[endIndex] = $.merge( [], this._drawCoords[0] ); - this._trigger( "shape", e, { - type: "Polygon", - coordinates: [ this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords ] - } ); - } - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - default: - this._eventTarget_dblclick_zoom(e); - break; - } - - this._inOp = false; - }, - - _eventTarget_touchstart: function (e) { - if ( typeof( document.elementFromPoint ) !== "undefined" ) { - var elFromPt = document.elementFromPoint( e.pageX, e.pageY ); - if ( elFromPt && elFromPt.nodeName === "A" ) { - return; - } - } - - var mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ); - - if ( mode === "static" ) { - return; - } - - if ( !this._pointerEvents && !this._supportTouch && e.which !== 1 ) { - return; - } - - if ( this._pointerEvents ) { - console.log( 'PointerEvent touchstart' ); - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var offset = $(e.currentTarget).offset(), - touches = e.originalEvent.changedTouches; - - if ( this._pointerEvents ) { - e.currentTarget.setPointerCapture( e.originalEvent.pointerId ); - - - - - - - - - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 && e.originalEvent.pointerId !== this._multiTouchAnchor[ 0 ].pointerId ) { - // switch to multitouch - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( e.originalEvent ); - - - - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._anchor = $.geo.center( this._multiTouchCurrentBbox, true ); - this._current = $.merge( [], this._anchor ); - - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - } else { - this._multiTouchAnchor.push( e.originalEvent ); - - this._multiTouchCurrentBbox = [ - this._multiTouchAnchor[0].pageX - offset.left, - this._multiTouchAnchor[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ this._multiTouchAnchor[0].pageX - offset.left, this._multiTouchAnchor[0].pageY - offset.top ]; - } - } else if ( this._supportTouch && touches ) { - this._multiTouchAnchor = $.merge( [ ], touches ); - - this._isMultiTouch = this._multiTouchAnchor.length > 1; - - if ( this._isMultiTouch ) { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - touches[1].pageX - offset.left, - touches[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ touches[0].pageX - offset.left, touches[0].pageY - offset.top ]; - } - } else { - this._current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - var downDate = $.now(); - if (downDate - this._downDate < 750) { - if (this._isTap) { - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance > 8) { - this._isTap = false; - } else { - this._current = $.merge( [ ], this._anchor ); - } - } - - if (this._isDbltap) { - this._isDbltap = false; - } else { - this._isDbltap = this._isTap; - } - } else { - this._isDbltap = false; - } - this._isTap = true; - this._downDate = downDate; - } - - this._mouseDown = true; - this._anchor = $.merge( [ ], this._current ); - - if (!this._inOp && e.shiftKey && shift !== "off") { - this._shiftDown = true; - this._$eventTarget.css( "cursor", this._options[ "cursors" ][ shift === "default" ? defaultShift : shift ] ); - } else if ( !this._isMultiTouch && ( this._options[ "pannable" ] || mode === "dragBox" || mode === "dragCircle" ) ) { - this._inOp = true; - - if ( mode !== "zoom" && mode !== "dragBox" && mode !== "dragCircle" ) { - this._lastDrag = this._current; - - if (e.currentTarget.setCapture) { - e.currentTarget.setCapture(); - } - } - } - - e.preventDefault(); - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - }, - - _dragTarget_touchmove: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - var doInteractiveTimeout = false; - if ( this._mouseDown ) { - doInteractiveTimeout = this._clearInteractiveTimeout( ); - } - - var offset = this._$eventTarget.offset(), - drawCoordsLen = this._drawCoords.length, - touches = e.originalEvent.changedTouches, - current, - anchorDistance, - currentDistance, - wheelLevel, - delta, - pinchCenterAndSize, - i; - - if ( this._pointerEvents ) { - - if ( this._isMultiTouch ) { - - if ( e.originalEvent.pointerId === this._multiTouchAnchor[ 0 ].pointerId ) { - this._multiTouchCurrentBbox[ 0 ] = e.originalEvent.pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = e.originalEvent.pageY - offset.top; - } else if ( e.originalEvent.pointerId === this._multiTouchAnchor[ 1 ].pointerId ) { - this._multiTouchCurrentBbox[ 2 ] = e.originalEvent.pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = e.originalEvent.pageY - offset.top; - } - - anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ); - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchAnchor[ 0 ] = e.originalEvent; - - this._multiTouchCurrentBbox = [ - this._multiTouchAnchor[0].pageX - offset.left, - this._multiTouchAnchor[0].pageY - offset.top, - NaN, - NaN - ]; - - current = [e.originalEvent.pageX - offset.left, e.originalEvent.pageY - offset.top]; - } - } else if ( this._supportTouch && touches ) { - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 && touches[ 0 ].identifier !== this._multiTouchAnchor[ 0 ].identifier ) { - // switch to multitouch - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( touches[ 0 ] ); - - - - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._anchor = this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - if ( this._isMultiTouch ) { - - for ( i = 0; i < touches.length; i++ ) { - if ( touches[ i ].identifier === this._multiTouchAnchor[ 0 ].identifier ) { - this._multiTouchCurrentBbox[ 0 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = touches[ i ].pageY - offset.top; - } else if ( touches[ i ].identifier === this._multiTouchAnchor[ 1 ].identifier ) { - this._multiTouchCurrentBbox[ 2 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = touches[ i ].pageY - offset.top; - } - } - - anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ); - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (current[0] === this._lastMove[0] && current[1] === this._lastMove[1]) { - if ( this._inOp ) { - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } else { - // fixes: [bug] highlight pop - return false; - } - } - - if ( _ieVersion === 7 ) { - this._isDbltap = this._isTap = false; - } - - if (this._mouseDown) { - this._current = current; - this._moveDate = $.now(); - } - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - var mode = this._options["mode"], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - dx, dy, circleSize; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - switch (mode) { - case "zoom": - case "dragBox": - if ( this._mouseDown ) { - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawBbox", [ - this._anchor[ 0 ], - this._anchor[ 1 ], - current[ 0 ], - current[ 1 ] - ] ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "dragCircle": - if ( this._mouseDown ) { - dx = current[ 0 ] - this._anchor[ 0 ]; - dy = current[ 1 ] - this._anchor[ 1 ]; - circleSize = Math.sqrt( ( dx * dx) + ( dy * dy ) ) * 2; - //circleSize = Math.max( Math.abs( current[ 0 ] - this._anchor[ 0 ] ), Math.abs( current[ 1 ] - this._anchor[ 1 ] ) ) * 2; - - // not part of _refreshDrawing - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawArc", this._anchor, 0, 360, { - width: circleSize, - height: circleSize - } ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - if (drawCoordsLen > 0) { - this._drawCoords[drawCoordsLen - 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[drawCoordsLen - 1] = current; - - this._refreshDrawing(); - } - - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - default: - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - } - - this._lastMove = current; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchstop: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if ( this._pointerEvents ) { - console.log( 'PointerEvent touchstop' ); - } - - if ( !this._mouseDown ) { - if ( _ieVersion === 7 ) { - // ie7 doesn't appear to trigger dblclick on this._$eventTarget, - // we fake regular click here to cause soft dblclick - this._eventTarget_touchstart(e); - } else { - // Chrome & Firefox trigger a rogue mouseup event when doing a dblclick maximize in Windows(/Linux?) - // ignore it - return; - } - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var mouseWasDown = this._mouseDown, - wasToolPan = this._toolPan, - offset = this._$eventTarget.offset(), - mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - current, i, clickDate, - dx, dy, - coordBuffer, - triggerShape; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - if ( this._pointerEvents ) { - current = [e.pageX - offset.left, e.pageY - offset.top]; - - for ( i = 0; i < this._multiTouchAnchor.length; i++ ) { - e.currentTarget.releasePointerCapture( this._multiTouchAnchor[ i ].pointerId ); - } - - this._multiTouchAnchor = []; - this._inOp = false; - } else if (this._supportTouch && e.originalEvent.changedTouches) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - this._multiTouchAnchor = []; - this._inOp = false; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - if (this._isTap) { - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - if (Math.sqrt((dx * dx) + (dy * dy)) <= 8) { - current = $.merge( [ ], this._anchor ); - } - } - } - - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._shiftDown = this._mouseDown = this._toolPan = false; - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isMultiTouch = false; - - this._wheelLevel = 0; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return; - } - - if (document.releaseCapture) { - document.releaseCapture(); - } - - if (mouseWasDown) { - clickDate = $.now(); - this._current = current; - - switch ( mode ) { - case "zoom": - case "dragBox": - if ( dx !== 0 || dy !== 0 ) { - var minSize = this._pixelSize * 6, - bboxCoords = this._toMap( [ this._anchor, current ] ), - bbox = [ - Math.min( bboxCoords[0][0], bboxCoords[1][0] ), - Math.min( bboxCoords[0][1], bboxCoords[1][1] ), - Math.max( bboxCoords[0][0], bboxCoords[1][0] ), - Math.max( bboxCoords[0][1], bboxCoords[1][1] ) - ]; - - if ( mode === "zoom" ) { - if ( ( bbox[2] - bbox[0] ) < minSize && ( bbox[3] - bbox[1] ) < minSize ) { - bbox = $.geo.scaleBy( this._getBbox( $.geo.center( bbox, true ) ), 0.5, true ); - } - - this._setBbox(bbox, true, true); - doInteractiveTimeout = true; - } else { - triggerShape = $.geo.polygonize( bbox, true ); - triggerShape.bbox = bbox; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - this._trigger( "shape", e, triggerShape ); - } - } else { - if ( mode === "dragBox" ) { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - } - - this._resetDrawing(); - break; - - case "dragCircle": - if ( dx !== 0 || dy !== 0 ) { - var image = this._options[ "axisLayout" ] === "image", - d = Math.sqrt( ( dx * dx) + ( dy * dy ) ), - n = 180, - a; - - this._drawPixels.length = n + 1; - - for ( i = 0; i < n; i++ ) { - a = ( i * 360 / n ) * ( Math.PI / 180 ); - this._drawPixels[ i ] = [ - this._anchor[ 0 ] + Math.cos( a ) * d, - this._anchor[ 1 ] + Math.sin( a ) * d - ]; - } - - this._drawPixels[ n ] = [ - this._drawPixels[ 0 ][ 0 ], - this._drawPixels[ 0 ][ 1 ] - ]; - - // using coordBuffer for bbox coords - coordBuffer = this._toMap( [ - [ this._anchor[ 0 ] - d, this._anchor[ 1 ] + ( image ? -d : d ) ], - [ this._anchor[ 0 ] + d, this._anchor[ 1 ] + ( image ? d : -d ) ] - ] ); - - triggerShape = { - type: "Polygon", - coordinates: [ this._toMap( this._drawPixels ) ], - bbox: [ coordBuffer[ 0 ][ 0 ], coordBuffer[ 0 ][ 1 ], coordBuffer[ 1 ][ 0 ], coordBuffer[ 1 ][ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - - this._resetDrawing(); - } else { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - break; - - case "drawPoint": - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - var geomap = this; - this._drawTimeout = setTimeout(function () { - if (geomap._drawTimeout) { - geomap._trigger("shape", e, { type: "Point", coordinates: geomap.toMap(current) }); - geomap._inOp = false; - geomap._drawTimeout = null; - } - }, 250); - } - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (wasToolPan) { - this._panFinalize(); - } else { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - - if (!e.isDefaultPrevented()) { - i = (this._drawCoords.length === 0 ? 0 : this._drawCoords.length - 1); - - this._drawCoords[i] = this._toMap(current); - this._drawPixels[i] = current; - - if (i < 2 || !(this._drawCoords[i][0] === this._drawCoords[i-1][0] && - this._drawCoords[i][1] === this._drawCoords[i-1][1])) { - this._drawCoords[i + 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[i + 1] = current; - } - - this._refreshDrawing(); - } - } - break; - - default: - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - this._inOp = false; - } - } - break; - } - - this._clickDate = clickDate; - - if (this._softDblClick && this._isDbltap) { - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - this._$eventTarget.trigger("dblclick", e); - return false; - } - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _eventTarget_mousewheel: function ( e ) { - if ( this._options[ "mode" ] === "static" || this._options[ "scroll" ] === "off" ) { - return; - } - - e.preventDefault(); - - if ( this._mouseDown ) { - return false; - } - - if (e.deltaY !== 0) { - this._clearInteractiveTimeout( ); - - var delta = e.deltaY > 0 ? 1 : -1; - - var offset = $(e.currentTarget).offset(); - this._anchor = [e.pageX - offset.left, e.pageY - offset.top]; - - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, this._options[ "tilingScheme" ] !== null ); - - this._setInteractiveCenterAndSize( wheelCenterAndSize.center, wheelCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - this._setInteractiveTimeout( true ); - } - - return false; - } - } - ); -}(jQuery, window)); - - -(function ($, window, undefined) { - $.geo._serviceTypes.tiled = (function () { - var rTmplString = new RegExp( "<.*>|{{.*}}" ); - - return { - _serviceId: 0, - _tmplGeoSrcId: "", - - - create: function (map, serviceContainer, service /* , index */) { - this._serviceId = map._serviceIdSeed++; - this._tmplGeoSrcId = "geoSrc" + this._serviceId; - - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0, - reloadTiles: false - }; - - var scHtml = '
            '; - - serviceContainer.append( window.toStaticHTML( scHtml ) ); - - serviceState.serviceContainer = serviceContainer.children( ":last" ); - - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - //console.log( "tiled.interactiveTransform( " + center.join( ", " ) + ", " + pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ), - tilingScheme = map.options[ "tilingScheme" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data("pixelSize"), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapCoord = $scaleContainer.data("scaleOrigin"), - newPixelPoint = map._toPixel(oldMapCoord, center, pixelSize); - - $scaleContainer.css( { - left: Math.round(newPixelPoint[0]) + "px", - top: Math.round(newPixelPoint[1]) + "px", - width: tilingScheme.tileWidth * scaleRatio, - height: tilingScheme.tileHeight * scaleRatio - } ); - - /* - if ( $("body")[0].filters !== undefined ) { - $scaleContainer.children().each( function ( i ) { - $( this ).css( "filter", "progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11=" + scaleRatio + ",M22=" + scaleRatio + ",sizingmethod='auto expand')" ); - } ); - } - */ - } - }); - } - }, - - refresh: function (map, service, force) { - //console.log( "tiled.refresh( " + map._center.join( ", " ) + ", " + map._pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ); - - this._cancelUnloaded(map, service); - - if ( serviceState && force ) { - // if hidden atm, we want to make sure we reload this service after it becomes visible - serviceState.reloadTiles = true; - } - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - $serviceContainer = serviceState.serviceContainer, - - image = map.options[ "axisLayout" ] === "image", - ySign = image ? +1 : -1, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - - tileX = Math.floor((bbox[0] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.max( Math.floor( ( image ? bbox[1] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 3 ] ) / (pixelSize * tileHeight) ), 0 ), - tileX2 = Math.ceil((bbox[2] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil( ( image ? bbox[3] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 1 ] ) / (pixelSize * tileHeight) ), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] + ySign * bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMinOrMaxY = tilingScheme.origin[1] + ySign * (fullYAtScale * tileHeight) * pixelSize, - - serviceLeft = Math.round((fullXMinX - bbox[0]) / pixelSize), - serviceTop = Math.round( ( image ? fullYMinOrMaxY - bbox[1] : bbox[3] - fullYMinOrMaxY ) / pixelSize), - - scaleContainers = $serviceContainer.children().show(), - scaleContainer = scaleContainers.filter("[data-pixel-size='" + pixelSize + "']").appendTo($serviceContainer), - - opacity = service.style.opacity, - - x, y, - - loadImageDeferredDone = function( url ) { - // when a Deferred call is done, add the image to the map - // a reference to the correct img element is on the Deferred object itself - serviceObj._loadImage( this.img, url, pixelSize, map, serviceState, opacity ); - }, - - loadImageDeferredFail = function( ) { - delete this.img; - serviceState.loadCount--; - map._requestComplete(); - }; - - if (serviceState.reloadTiles) { - scaleContainers.find("img").attr("data-dirty", "true"); - } - - if (!scaleContainer.size()) { - $serviceContainer.append( window.toStaticHTML( "
            " ) ); - scaleContainer = $serviceContainer.children(":last").data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - } else { - scaleContainer.css({ - left: (serviceLeft % tileWidth) + "px", - top: (serviceTop % tileHeight) + "px" - }).data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - - scaleContainer.children().each( function () { - var $img = $(this), - tile = $img.attr("data-tile").split(","); - - $img.css({ - left: Math.round(((parseInt(tile[0], 10) - fullXAtScale) * 100) + (serviceLeft - (serviceLeft % tileWidth)) / tileWidth * 100) + "%", - top: Math.round(((parseInt(tile[1], 10) - fullYAtScale) * 100) + (serviceTop - (serviceTop % tileHeight)) / tileHeight * 100) + "%" - }); - - if (opacity < 1) { - $img.fadeTo(0, opacity); - } - } ); - } - - for (x = tileX; x < tileX2; x++) { - for (y = tileY; y < tileY2; y++) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ($img.size() === 0 || serviceState.reloadTiles) { - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] + ySign * (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] + ySign * ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - urlArgs = { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }, - isFunc = $.isFunction( service[ 'src' ] ), - imageUrl; - - if ( isFunc ) { - imageUrl = service[ 'src' ]( urlArgs ); - } else { - if ( rTmplString.test( service[ 'src' ] ) ) { - $.templates( this._tmplGeoSrcId, service[ 'src' ] ); - imageUrl = $.render[ this._tmplGeoSrcId ]( urlArgs ); - } else { - imageUrl = service[ 'src' ]; - } - } - - serviceState.loadCount++; - map._requestQueued(); - - if (serviceState.reloadTiles && $img.size() > 0) { - $img.attr("src", imageUrl); - } else { - var imgMarkup = ""; - - scaleContainer.append( window.toStaticHTML( imgMarkup ) ); - $img = scaleContainer.children(":last"); - } - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl && $.isFunction( imageUrl.promise ) ) { - // assume Deferred - $.extend( imageUrl.promise( ), { img: $img } ); - imageUrl.done( loadImageDeferredDone ).fail( loadImageDeferredFail ); - } else { - $img.remove( ); - } - } - } - } - - scaleContainers.find("[data-dirty]").remove(); - serviceState.reloadTiles = false; - } - }, - - resize: function ( /* map, service, dx, dy */ ) { - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.css( "display", service.style.visibility === "visible" ? "block" : "none" ); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if (serviceState && serviceState.loadCount > 0) { - /* - * #193 - disabled until we can do this without canceling all AJAX requests - * - if ( window.stop !== undefined ) { - window.stop(); - } else if( document.execCommand !== undefined ) { - document.execCommand("Stop", false); - } - */ - - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery, window)); - -(function ($, window, undefined) { - $.geo._serviceTypes.shingled = (function () { - var rTmplString = new RegExp( "<.*>|{{.*}}" ); - - return { - _serviceId: 0, - _tmplGeoSrcId: "", - - create: function ( map, serviceContainer, service /* , index */ ) { - this._serviceId = map._serviceIdSeed++; - this._tmplGeoSrcId = "geoSrc" + this._serviceId; - - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0 - }; - - var scHtml = '
            '; - - serviceContainer.append( window.toStaticHTML( scHtml ) ); - - serviceState.serviceContainer = serviceContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - var serviceState = $.data( service, "geoServiceState" ), - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds[ "width" ], - mapHeight = contentBounds[ "height" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data( "pixelSize" ), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin, center, pixelSize ); - - $scaleContainer.css( { - left: Math.round( newPixelPoint[ 0 ] ), - top: Math.round( newPixelPoint[ 1 ] ), - width: mapWidth * scaleRatio, - height: mapHeight * scaleRatio - } ); - } - }); - } - }, - - refresh: function (map, service, force) { - var serviceState = $.data(service, "geoServiceState"); - - this._cancelUnloaded(map, service); - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainer = serviceContainer.children('[data-pixel-size="' + pixelSize + '"]'), - - opacity = service.style.opacity, - - $img; - - if (opacity < 1 || force || service.shinglesMax === 1) { - serviceContainer.find("img").attr("data-keep-alive", "0"); - } else if ( service.shinglesMax > 1 ) { - serviceContainer.find("img").slice( 0, -( service.shinglesMax - 1 ) ).attr("data-keep-alive", "0"); - } - - if ( !scaleContainer.size() ) { - serviceContainer.append( window.toStaticHTML( '
            ' ) ); - scaleContainer = serviceContainer.children(":last"); - } - - var urlArgs = { - bbox: bbox, - width: mapWidth, - height: mapHeight, - zoom: map._getZoom(), - tile: null, - index: 0 - }, - isFunc = $.isFunction( service[ 'src' ] ), - imageUrl, - imagePos = scaleContainer.position( ); - - imagePos.left = - ( imagePos.left ); - imagePos.top = - ( imagePos.top ); - - if ( isFunc ) { - imageUrl = service[ 'src' ]( urlArgs ); - } else { - if ( rTmplString.test( service[ 'src' ] ) ) { - $.templates( this._tmplGeoSrcId, service[ 'src' ] ); - imageUrl = $.render[ this._tmplGeoSrcId ]( urlArgs ); - } else { - imageUrl = service[ 'src' ]; - } - } - - serviceState.loadCount++; - map._requestQueued(); - - scaleContainer.append( window.toStaticHTML( '' ) ); - $img = scaleContainer.children(":last").data("center", map._center); - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl ) { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, map, serviceState, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - map._requestComplete(); - } ); - } - - } - }, - - resize: function ( map, service /* , dx, dy */ ) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState && service && service.style.visibility === "visible" ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainers = serviceContainer.children(); - - scaleContainers.attr("data-pixel-size", "0"); - - scaleContainers.each( function ( ) { - var $scaleContainer = $(this), - position = $scaleContainer.position( ); - - $scaleContainer.css( { - left: position.left + ( mapWidth - $scaleContainer.width( ) ) / 2, - top: position.top + ( mapHeight - $scaleContainer.height( ) ) / 2 - } ); - - } ); - } - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.css("display", service.style.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - // #newpanzoom - serviceContainer.children(':not([data-pixel-size="' + pixelSize + '"])').remove(); - - serviceContainer.find( "img[data-keep-alive]" ).remove( ); - - serviceState.loadCount = 0; - } - }).error(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery, window)); diff --git a/dist/jquery.geo-1.0.0-b3.2.min.js b/dist/jquery.geo-1.0.0-b3.2.min.js deleted file mode 100644 index 021f256..0000000 --- a/dist/jquery.geo-1.0.0-b3.2.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! jQuery Geo - v1.0.0-b3.2 - 2016-01-16 -* http://jquerygeo.com -* Copyright (c) 2016 Ryan Morrison-Westphal; Licensed MIT */ -document.createElement("canvas").getContext||!function(){function a(){return this.context_||(this.context_=new q(this))}function b(a,b){var c=G.call(arguments,2);return function(){return a.apply(b,c.concat(G.call(arguments)))}}function c(a,b,c){a.namespaces[b]||a.namespaces.add(b,c,"#default#VML")}function d(a){if(c(a,"g_vml_","urn:schemas-microsoft-com:vml"),c(a,"g_o_","urn:schemas-microsoft-com:office:office"),!a.styleSheets.ex_canvas_){var b=a.createStyleSheet();b.owningElement.id="ex_canvas_",b.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function e(a){var b=a.srcElement;switch(a.propertyName){case"width":b.getContext().clearRect(),b.style.width=b.attributes.width.nodeValue+"px",b.firstChild.style.width=b.clientWidth+"px";break;case"height":b.getContext().clearRect(),b.style.height=b.attributes.height.nodeValue+"px",b.firstChild.style.height=b.clientHeight+"px"}}function f(a){var b=a.srcElement;b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px",b.firstChild.style.height=b.clientHeight+"px")}function g(){return[[1,0,0],[0,1,0],[0,0,1]]}function h(a,b){for(var c=g(),d=0;3>d;d++)for(var e=0;3>e;e++){for(var f=0,h=0;3>h;h++)f+=a[d][h]*b[h][e];c[d][e]=f}return c}function i(a,b){b.fillStyle=a.fillStyle,b.lineCap=a.lineCap,b.lineJoin=a.lineJoin,b.lineWidth=a.lineWidth,b.miterLimit=a.miterLimit,b.shadowBlur=a.shadowBlur,b.shadowColor=a.shadowColor,b.shadowOffsetX=a.shadowOffsetX,b.shadowOffsetY=a.shadowOffsetY,b.strokeStyle=a.strokeStyle,b.globalAlpha=a.globalAlpha,b.font=a.font,b.textAlign=a.textAlign,b.textBaseline=a.textBaseline,b.arcScaleX_=a.arcScaleX_,b.arcScaleY_=a.arcScaleY_,b.lineScale_=a.lineScale_}function j(a){var b=a.indexOf("(",3),c=a.indexOf(")",b+1),d=a.substring(b+1,c).split(",");return(4!=d.length||"a"!=a.charAt(3))&&(d[3]=1),d}function k(a){return parseFloat(a)/100}function l(a,b,c){return Math.min(c,Math.max(b,a))}function m(a){var b,c,d,e,f,g;if(e=parseFloat(a[0])/360%360,0>e&&e++,f=l(k(a[1]),0,1),g=l(k(a[2]),0,1),0==f)b=c=d=g;else{var h=.5>g?g*(1+f):g+f-g*f,i=2*g-h;b=n(i,h,e+1/3),c=n(i,h,e),d=n(i,h,e-1/3)}return"#"+I[Math.floor(255*b)]+I[Math.floor(255*c)]+I[Math.floor(255*d)]}function n(a,b,c){return 0>c&&c++,c>1&&c--,1>6*c?a+6*(b-a)*c:1>2*c?b:2>3*c?a+(b-a)*(2/3-c)*6:a}function o(a){if(a in L)return L[a];var b,c=1;if(a=String(a),"#"==a.charAt(0))b=a;else if(/^rgb/.test(a)){for(var d,e=j(a),b="#",f=0;3>f;f++)d=-1!=e[f].indexOf("%")?Math.floor(255*k(e[f])):+e[f],b+=I[l(d,0,255)];c=+e[3]}else if(/^hsl/.test(a)){var e=j(a);b=m(e),c=e[3]}else b=a;return L[a]={color:b,alpha:c}}function p(a){return M[a]||"square"}function q(a){this.m_=g(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.strokeStyle="#000",this.fillStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=1*E,this.globalAlpha=1,this.canvas=a;var b="width:"+a.clientWidth+"px;height:"+a.clientHeight+"px;overflow:hidden;position:absolute",c=a.ownerDocument.createElement("div");c.style.cssText=b,a.appendChild(c);var d=c.cloneNode(!1);d.style.backgroundColor="red",d.style.filter="alpha(opacity=0)",a.appendChild(d),this.element_=c,this.arcScaleX_=1,this.arcScaleY_=1,this.lineScale_=1}function r(a,b,c,d){a.currentPath_.push({type:"bezierCurveTo",cp1x:b.x,cp1y:b.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y}),a.currentX_=d.x,a.currentY_=d.y}function s(a,b){var c=o(a.strokeStyle),d=c.color,e=c.alpha*a.globalAlpha,f=a.lineScale_*a.lineWidth;1>f&&(e*=f),b.push("')}function t(a,b,c,d){var e=(a.fillStyle,a.arcScaleX_,a.arcScaleY_,d.x-c.x,d.y-c.y,o(a.fillStyle)),f=e.color,g=e.alpha*a.globalAlpha;b.push('')}function u(a,b,c){var d=a.m_;return{x:E*(b*d[0][0]+c*d[1][0]+d[2][0])-F,y:E*(b*d[0][1]+c*d[1][1]+d[2][1])-F}}function v(a){return isFinite(a[0][0])&&isFinite(a[0][1])&&isFinite(a[1][0])&&isFinite(a[1][1])&&isFinite(a[2][0])&&isFinite(a[2][1])}function w(a,b,c){if(v(b)&&(a.m_=b,c)){var d=b[0][0]*b[1][1]-b[0][1]*b[1][0];a.lineScale_=D(C(d))}}function x(a){this.code=this[a],this.message=a+": DOM Exception "+this.code}var y=Math,z=y.round,A=y.sin,B=y.cos,C=y.abs,D=y.sqrt,E=10,F=E/2,G=(+navigator.userAgent.match(/MSIE ([\d.]+)?/)[1],Array.prototype.slice);d(document);var H={init:function(a){var c=a||document;c.createElement("canvas"),c.attachEvent("onreadystatechange",b(this.init_,this,c))},init_:function(a){for(var b=a.getElementsByTagName("canvas"),c=0;cJ;J++)for(var K=0;16>K;K++)I[16*J+K]=J.toString(16)+K.toString(16);var L={},M={butt:"flat",round:"round"},N=q.prototype;N.clearRect=function(){this.textMeasureEl_&&(this.textMeasureEl_.removeNode(!0),this.textMeasureEl_=null),this.element_.innerHTML=""},N.beginPath=function(){this.currentPath_=[]},N.moveTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"moveTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.lineTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"lineTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.bezierCurveTo=function(a,b,c,d,e,f){var g=u(this,e,f),h=u(this,a,b),i=u(this,c,d);r(this,h,i,g)},N.quadraticCurveTo=function(a,b,c,d){var e=u(this,a,b),f=u(this,c,d),g={x:this.currentX_+2/3*(e.x-this.currentX_),y:this.currentY_+2/3*(e.y-this.currentY_)},h={x:g.x+(f.x-this.currentX_)/3,y:g.y+(f.y-this.currentY_)/3};r(this,g,h,f)},N.arc=function(a,b,c,d,e,f){c*=E;var g=f?"at":"wa",h=a+B(d)*c-F,i=b+A(d)*c-F,j=a+B(e)*c-F,k=b+A(e)*c-F;h!=j||f||(h+=.125);var l=u(this,a,b),m=u(this,h,i),n=u(this,j,k);this.currentPath_.push({type:g,x:l.x,y:l.y,radius:c,xStart:m.x,yStart:m.y,xEnd:n.x,yEnd:n.y})},N.stroke=function(a){var b=[],c=10,d=10;b.push("f.x)&&(f.x=i.x),(null==e.y||i.yf.y)&&(f.y=i.y))}b.push(' ">'),a?t(this,b,e,f):s(this,b),b.push(""),this.element_.insertAdjacentHTML("beforeEnd",b.join(""))},N.fill=function(){this.stroke(!0)},N.closePath=function(){this.currentPath_.push({type:"close"})},N.save=function(){var a={};i(this,a),this.aStack_.push(a),this.mStack_.push(this.m_),this.m_=h(g(),this.m_)},N.restore=function(){this.aStack_.length&&(i(this.aStack_.pop(),this),this.m_=this.mStack_.pop())},N.translate=function(a,b){var c=[[1,0,0],[0,1,0],[a,b,1]];w(this,h(c,this.m_),!1)},N.scale=function(a,b){this.arcScaleX_*=a,this.arcScaleY_*=b;var c=[[a,0,0],[0,b,0],[0,0,1]];w(this,h(c,this.m_),!0)};var O=x.prototype=new Error;O.INDEX_SIZE_ERR=1,O.DOMSTRING_SIZE_ERR=2,O.HIERARCHY_REQUEST_ERR=3,O.WRONG_DOCUMENT_ERR=4,O.INVALID_CHARACTER_ERR=5,O.NO_DATA_ALLOWED_ERR=6,O.NO_MODIFICATION_ALLOWED_ERR=7,O.NOT_FOUND_ERR=8,O.NOT_SUPPORTED_ERR=9,O.INUSE_ATTRIBUTE_ERR=10,O.INVALID_STATE_ERR=11,O.SYNTAX_ERR=12,O.INVALID_MODIFICATION_ERR=13,O.NAMESPACE_ERR=14,O.INVALID_ACCESS_ERR=15,O.VALIDATION_ERR=16,O.TYPE_MISMATCH_ERR=17,G_vmlCanvasManager=H,CanvasRenderingContext2D=q,DOMException=x}(),this.jsviews||this.jQuery&&jQuery.views||function(a,b){function c(a,b){var c="\\"+a.charAt(0),d="\\"+a.charAt(1),e="\\"+b.charAt(0),f="\\"+b.charAt(1);return Q.rTag=u=d+"(?:(?:(\\w+(?=[\\/\\s"+e+"]))|(?:(\\w+)?(:)|(>)|(\\*)))\\s*((?:[^"+e+"]|"+e+"(?!"+f+"))*?)(\\/)?|(?:\\/(\\w+)))"+e,u=new RegExp(c+u+f,"g"),v=new RegExp("<.*>|"+a+".*"+b),this}function d(a){var c=this,d=c.tmpl.helpers||{};return a=(c.ctx[a]!==b?c.ctx:d[a]!==b?d:k[a]!==b?k:{})[a],"function"!=typeof a?a:function(){return a.apply(c,arguments)}}function e(a,b,c){var d=b.tmpl.converters;return a=d&&d[a]||l[a],a?a.call(b,c):c}function f(a,c,d,e,f){f.props=f.props||{};var g,h=f.props.tmpl,k=c.tmpl.tags,l=c.tmpl.templates,n=arguments,o=k&&k[a]||j[a];return o?(e=e&&c.tmpl.tmpls[e-1],h=h||e||b,f.tmpl=""+h===h?l&&l[h]||i[h]||i(h):h,f.isTag=A,f.converter=d,f.view=c,f.renderContent=m,c.ctx&&w(f.ctx,c.ctx),g=o.apply(f,n.length>5?O.call(n,5):[]),g||(g==b?"":g.toString())):""}function g(a,c,e,f,g,h){var i=e.views,j={tmpl:g,path:c,parent:e,data:f,ctx:a,views:t.isArray(f)?[]:{},hlp:d};return t.isArray(i)?i.splice(j.index=h!==b?h:i.length,0,j):i[j.index="_"+I++]=j,j}function h(a,c,d,e,f){var g,h;if(d&&"object"==typeof d&&!d.nodeType){for(g in d)c(g,d[g]);return a}return d&&e!==b?""+d===d&&(null===e?delete c[d]:(e=f?f(d,e):e)&&(c[d]=e)):f&&(e=f(b,e||d)),(h=y.onStoreItem)&&h(c,d,e,f),e}function i(a,b){return h(this,i,a,b,q)}function j(a,b){return h(this,j,a,b)}function k(a,b){return h(this,k,a,b)}function l(a,b){return h(this,l,a,b)}function m(a,c,d,e,f){var h,j,k,l,m,n,o,p,q,r,s={},u=f===A,v=this,x="";if(v.isTag?(q=v.tmpl,c=c||v.ctx,d=d||v.view,e=e||v.path,f=f||v.index,s=v.props):q=v.jquery&&v[0]||v,d=d||Q.topView,p=d.ctx,r=q.layout,a===d&&(a=d.data,r=A),c=c&&c===p?p:p?(p=w({},p),c?w(p,c):p):c||{},s.link===z&&(c.link=z),q.fn||(q=i[q]||i(q)),m=c.link&&y.onRenderItem,n=c.link&&y.onRenderItems,q){if(t.isArray(a)&&!r)for(l=u?d:f!==b&&d||g(c,e,d,a,q,f),h=0,j=a.length;j>h;h++)k=a[h],o=q.fn(k,g(c,e,l,k,q,(f||0)+h),Q),x+=m?m(o,s):o;else l=u?d:g(c,e,d,a,q,f),x+=a||r?q.fn(a,l,Q):"";return d.topKey=l.index,n?n(x,e,l.index,q,s):x}return""}function n(){throw"Syntax error"}function o(a,b,c){function d(b){b-=D,b&&J.push(a.substr(D,b).replace(E,"\\n"))}function e(b,e,g,h,i,j,k,l,m,n){i&&(h=":",g="html");var o="",q="",r=!l&&!h;if(e=e||h,d(n),D=n+b.length,j?y&&J.push(["*",k.replace(F,"$1")]):e?("else"===e&&(K[5]=a.substring(K[5],n),K=I.pop(),J=K[3],r=A),k=k?p(k,c).replace(H,function(a,b,c){return b?q+=c+",":o+=c+",",""}):"",o=o.slice(0,-1),k=k.slice(0,-1),f=[e,g||"",k,r&&[],"{"+(o?"props:{"+o+"},":"")+"path:'"+k+"'"+(q?",ctx:{"+q.slice(0,-1)+"}":"")+"}"],r&&(I.push(K),K=f,K[5]=D),J.push(f)):m&&(K[5]=a.substring(K[5],n),K=I.pop()),!K)throw"Expected block tag";J=K[3]}var f,g,h,i,j,k,l,m,n,q,s,t,v,w,x,y,z=b?{allowCode:y=b.allowCode,debug:b.debug}:{},B=b&&b.tmpls,C=[],D=0,I=[],J=C,K=[,,,C],L=0;for(a=a.replace(G,"\\$1"),a.replace(u,e),d(a.length),i=C.length,j=i?"":'"";',h=0;i>h;h++)g=C[h],"*"===g[0]?j=j.slice(0,h?-1:-3)+";"+g[1]+(i>h+1?"ret+=":""):""+g===g?j+='"'+g+'"+':(s=g[0],t=g[1],v=g[2],J=g[3],w=g[4],a=g[5],J&&(x=r(a,z,b,L++),o(a,x),B.push(x)),q=q||w.indexOf("view")>-1,j+=(":"===s?"html"===t?(l=A,"e("+v):t?(n=A,'c("'+t+'",view,'+v):(m=A,"((v="+v+')!=u?v:""'):(k=A,'t("'+s+'",view,"'+(t||"")+'",'+(J?B.length:'""')+","+w+(v?",":"")+v))+")+");return j=new Function("data, view, j, b, u",M+(m?"v,":"")+(k?"t=j.tag,":"")+(n?"c=j.convert,":"")+(l?"e=j.converters.html,":"")+"ret; try{\n\n"+(z.debug?"debugger;":"")+(y?"ret=":"return ")+j.slice(0,-1)+";\n\n"+(y?"return ret;":"")+"}catch(e){return j.err(e);}"),b&&(b.fn=j,b.useVw=n||q||k),j}function p(a,b){function c(a,c,i,j,k,l,m,o,p,q,r,s,t,u,v,w){function x(a,c,d,e,f,g,h){if(c){var i=(d?'view.hlp("'+d+'")':e?"view":"data")+(h?(f?"."+f:d?"":e?"":"."+c)+(g||""):(h=d?"":e?f||"":c,""));return b&&"("!==p&&(i="b("+i+',"'+h+'")'),i+(h?"."+h:"")}return a}return k=k||"",i=i||c||r,j=j||o,p=p||v||"",k=k||"",l?void n():h?(h=!s,h?a:'"'):g?(g=!t,g?a:'"'):(i?(f++,i):"")+(w?f?"":d?(d=z,"\b"):",":m?(f&&n(),d=A,"\b"+j+":"):j?j.replace(C,x)+(p?(e[++f]=A,p):k):k?a:u?(e[f--]=z,u+(p?(e[++f]=A,p):"")):q?(e[f]||n(),","):c?"":(h=s,g=t,'"'))}var d,e={},f=0,g=z,h=z;return a=(a+" ").replace(D,c)}function q(a,c,d,e){function f(b){return""+b===b||b.nodeType>0?(h=b.nodeType>0?b:!v.test(b)&&B&&B(b)[0],h&&h.type&&(b=i[h.getAttribute(L)],b||(a=a||"_"+J++,h.setAttribute(L,a),b=q(a,h.innerHTML,d,e),i[a]=b)),b):void 0}var g,h,j,k,l;if(g=f(c),e=e||(c.markup?c:{}),e.name=a,k=e.templates,!g&&c.markup&&(g=f(c.markup))&&(!g.fn||g.debug===c.debug&&g.allowCode===c.allowCode||(g=g.markup)),g!==b){a&&!d&&(P[a]=function(){return c.render.apply(c,arguments)}),g.fn||c.fn?g.fn&&(c=a&&a!==g.name?w(w({},g),e):g):(c=r(g,e,d,0),o(g,c));for(j in k)l=k[j],l.name!==j&&(k[j]=q(j,l,c));return c}}function r(a,b,c,d){function e(a){c[a]&&(f[a]=w(w({},c[a]),b[a]))}b=b||{};var f={markup:a,tmpls:[],links:[],render:m};return c&&(c.templates&&(f.templates=w(w({},c.templates),b.templates)),f.parent=c,f.name=c.name+"["+d+"]",f.index=d),w(f,b),c&&(e("templates"),e("tags"),e("helpers"),e("converters")),f}function s(a){return K[a]||(K[a]="&#"+a.charCodeAt(0)+";")}var t,u,v,w,x="v1.0pre",y={},z=!1,A=!0,B=a.jQuery,C=/^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g,D=/(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,E=/\r?\n/g,F=/\\(['"])/g,G=/\\?(['"])/g,H=/\x08(~)?([^\x08]+)\x08/g,I=0,J=0,K={"&":"&","<":"<",">":">"},L="data-jsv-tmpl",M="var j=j||"+(B?"jQuery.":"js")+"views,",N=/[\x00"&'<>]/g,O=Array.prototype.slice,P={},Q={jsviews:x,sub:y,debugMode:A,err:function(a){return Q.debugMode?"
            Error: "+(a.message||a)+". ":'""'},tmplFn:o,render:P,templates:i,tags:j,helpers:k,converters:l,View:g,convert:e,delimiters:c,tag:f};B?(t=B,t.templates=i,t.render=P,t.views=Q,t.fn.render=m):(t=a.jsviews=Q,t.extend=function(a,b){var c;a=a||{};for(c in b)a[c]=b[c];return a},t.isArray=Array&&Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)}),w=t.extend,Q.topView={views:{},tmpl:{},hlp:d,ctx:Q.helpers},j({"if":function(){var a=this,c=a.view;return c.onElse=function(a,d){for(var e=0,f=d.length;f&&!d[e++];)if(e===f)return"";return c.onElse=b,a.path="",a.renderContent(c)},c.onElse(this,arguments)},"else":function(){var a=this.view;return a.onElse?a.onElse(this,arguments):""},"for":function(){var a,b=this,c="",d=arguments,e=d.length;for(b.props.layout&&(b.tmpl.layout=A),a=0;e>a;a++)c+=b.renderContent(d[a]);return c},"=":function(a){return a},"*":function(a){return a}}),l({html:function(a){return a!=b?String(a).replace(N,s):""}}),c("{{","}}")}(this),function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})}),$.widget||!function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d,e=0;null!=(d=b[e]);e++)try{a(d).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){return c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}}),d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e,f=b.split(".")[0];b=b.split(".")[1],e=f+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][e]=function(c){return!!a.data(c,b)},a[f]=a[f]||{},a[f][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[f][b].prototype=a.extend(!0,g,{namespace:f,widgetName:b,widgetEventPrefix:a[f][b].prototype.widgetEventPrefix||b,widgetBaseClass:e},d),a.widget.bridge(b,a[f][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f="string"==typeof e,g=Array.prototype.slice.call(arguments,1),h=this;return e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e,f&&"_"===e.charAt(0)?h:(this.each(f?function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;return f!==d&&f!==b?(h=f,!1):void 0}:function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))}),h)}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(0===arguments.length)return a.extend({},this.options);if("string"==typeof c){if(d===b)return this.options[c];e={},e[c]=d}return this._setOptions(e),this},_setOptions:function(b){var c=this;return a.each(b,function(a,b){c._setOption(a,b)}),this},_setOption:function(a,b){return this.options[a]=b,"disabled"===a&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",b),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];if(d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}}(jQuery),function(a,b,c){b.toStaticHTML=b.toStaticHTML||function(a){return a};var d=Number.POSITIVE_INFINITY,e=Number.NEGATIVE_INFINITY;a.geo={_allCoordinates:function(b){for(var c=this._flatten(b),d=0,e=[];d1&&!a.isArray(b[0]))return b[0]>=-180.001&&b[0]<=180.001&&b[1]>=-90.001&&b[1]<=90.001;b=b[0]}return!1},center:function(b,c){var d=!1;!c&&a.geo.proj&&this._isGeodetic(b)&&(d=!0,b=a.geo.proj.fromGeodetic(b));var e=[(b[0]+b[2])/2,(b[1]+b[3])/2];return d?a.geo.proj.toGeodetic(e):e},expandBy:function(b,c,d,e){var f=!1;return!e&&a.geo.proj&&this._isGeodetic(b)&&(f=!0,b=a.geo.proj.fromGeodetic(b)),b=[b[0]-c,b[1]-d,b[2]+c,b[3]+d],f?a.geo.proj.toGeodetic(b):b},height:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[3]-b[1]},_in:function(a,b){return a[0]<=b[0]&&a[1]<=b[1]&&a[2]>=b[2]&&a[3]>=b[3]},_bboxDisjoint:function(a,b){return b[0]>a[2]||b[2]a[3]||b[3]0&&(h/i>c?(f=h/2,g=f/c):(g=i/2,f=g*c),b=[j[0]-f,j[1]-g,j[0]+f,j[1]+g]),e?a.geo.proj.toGeodetic(b):b},recenter:function(b,c,d){var e=!1;!d&&a.geo.proj&&(this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b)),this._isGeodetic(c)&&(c=a.geo.proj.fromGeodetic(c)));var f=(b[2]-b[0])/2,g=(b[3]-b[1])/2;return b=[c[0]-f,c[1]-g,c[0]+f,c[1]+g],e?a.geo.proj.toGeodetic(b):b},scaleBy:function(b,c,d){var e=!1;!d&&a.geo.proj&&this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b));var f=this.center(b,!0),g=(b[2]-b[0])*c/2,h=(b[3]-b[1])*c/2;return b=[f[0]-g,f[1]-h,f[0]+g,f[1]+h],e?a.geo.proj.toGeodetic(b):b},width:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[2]-b[0]},bbox:function(b,f){var g,h=!1;if(!b)return c;if(b.bbox)g=!f&&a.geo.proj&&this._isGeodetic(b.bbox)?a.geo.proj.fromGeodetic(b.bbox):b.bbox;else{g=[d,d,e,e];var i=this._allCoordinates(b),j=0;if(0===i.length)return c;for(!f&&a.geo.proj&&this._isGeodetic(i)&&(h=!0,i=a.geo.proj.fromGeodetic(i));j0?(g[0]=Math.min(Math.max(k[0][0],m[0]),m[2]),g[1]=Math.min(Math.max(k[0][1],m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g}):c:(j*=3,g[0]=Math.min(Math.max(g[0]/j,m[0]),m[2]),g[1]=Math.min(Math.max(g[1]/j,m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g});case"MultiPoint":if(b.coordinates.length>0)return g=b.coordinates[0],{type:"Point",coordinates:[g[0],g[1]]};break;case"MultiLineString":case"MultiPolygon":if(b.coordinates.length>0)return this.centroid({type:b.type.substr(5),coordinates:b.coordinates[0]},f)}return c},contains:function(a,b){if("Polygon"!==a.type)return!1;switch(b.type){case"Point":return this._containsPolygonPoint(a.coordinates,b.coordinates);case"LineString":return this._containsPolygonLineString(a.coordinates,b.coordinates);case"Polygon":return this._containsPolygonLineString(a.coordinates,b.coordinates[0]);default:return!1}},_containsPolygonPoint:function(a,b){if(0===a.length||a[0].length<4)return!1;for(var c,d,e=0,f=a[0][0],g=1;gb[0]&&e++),f=c;return e%2===1},_containsPolygonLineString:function(a,b){for(var c=0;c0){var e=a[0],f=b[0]-e[0],g=b[1]-e[1];if(1===a.length)return Math.sqrt(f*f+g*g);for(var h=1;hn&&(c=n),e=i,f=l,g=m}}return Math.sqrt(c)},_distanceSegmentPoint:function(a,b,c,d,e,f){var g=a*c+b*d;if(0>=g)return c*c+d*d;var h=a*a+b*b;return g>=h?e*e+f*f:c*c+d*d-g*g/h},_distanceLineStringLineString:function(a,b){for(var c=d,e=0;e=k;k++)h=360*k/j*(Math.PI/180),i.push([g[0]+Math.cos(h)*d,g[1]+Math.sin(h)*d]);return{type:"Polygon",coordinates:[f?a.geo.proj.toGeodetic(i):i]}}return c},_basic:function(a){for(var b,c,d=[],e=0,f=this._flatten(a);eo;q++)n=o,o+=p[q]/m;return e=c-n,k=g[q-1],l=g[q],j=[k[0]+e*(l[0]-k[0]),k[1]+e*(l[1]-k[1])],{type:"Point",coordinates:r?a.geo.proj.toGeodetic(j):j}}},WKT:function(){function b(a){return"POINT "+c(a.coordinates)}function c(a){return a&&a.length?"("+a.join(" ")+")":"EMPTY"}function d(a){return"LINESTRING "+e(a.coordinates)}function e(a){if(a&&a.length){for(var b=[],c=0;c2?{type:"Point",coordinates:[parseFloat(b[1]),parseFloat(b[2])]}:null}function p(a){var b,c,d=a.match(/\s*\((.*)\)/),e=[],f=0;if(d&&d.length>1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f0){for(;g
            ";while(c[0]);return a>6?a:!a}();a.widget("geo.geographics",{_$elem:c,_options:{},_trueCanvas:!0,_trueDoubleBuffer:!0,_width:0,_height:0,_$canvas:c,_context:c,_$canvasSceneFront:c,_$canvasSceneBack:c,_timeoutEnd:null,_requireFlip:!1,_blitcanvas:c,_blitcontext:c,_$labelsContainerFront:c,_$labelsContainerBack:c,_labelsHtml:"",options:{style:{borderRadius:"8px",color:"#7f0000",fillOpacity:.2,height:"8px",opacity:1,strokeOpacity:1,strokeWidth:"2px",visibility:"visible",width:"8px"},doubleBuffer:!0},_create:function(){this._$elem=this.element,this._options=this.options,this._$elem.css({webkitTransform:"translateZ(0)",display:"inline-block",overflow:"hidden",textAlign:"left"}),"static"===this._$elem.css("position")&&this._$elem.css("position","relative"),this._$elem.addClass("geo-graphics"),this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10));var c="position:absolute;left:0;top:0;margin:0;padding:0;",e="width:"+this._width+"px;height:"+this._height+"px;",f='width="'+this._width+'" height="'+this._height+'"';this._blitcanvas=document.createElement("canvas"),this._blitcanvas.getContext?(this._$canvas=a(b.toStaticHTML("')),this._blitcanvas.width=1,this._blitcanvas.height=1,this._trueDoubleBuffer=this._blitcanvas.toDataURL().length>6,this._options.doubleBuffer&&this._trueDoubleBuffer||this._$elem.append(this._$canvas),this._context=this._$canvas[0].getContext("2d"),this._blitcanvas.width=this._width,this._blitcanvas.height=this._height,this._blitcontext=this._blitcanvas.getContext("2d"),this._$canvasSceneFront=a(b.toStaticHTML('')),this._$canvasSceneBack=a(b.toStaticHTML(''))):8>=d&&(this._trueCanvas=!1,this._$elem.append("
            '),this._$canvas=this._$elem.children(":last"),G_vmlCanvasManager.initElement(this._$canvas[0]),this._context=this._$canvas[0].getContext("2d"),this._$canvas.children().css({backgroundColor:"transparent",width:this._width,height:this._height})),this._$labelsContainerFront=a(b.toStaticHTML('
            ')),this._$labelsContainerBack=a(b.toStaticHTML('
            '))},_setOption:function(b,c){"style"===b&&(c=a.extend({},this._options.style,c)),a.Widget.prototype._setOption.apply(this,arguments)},destroy:function(){a.Widget.prototype.destroy.apply(this,arguments),this._$elem.html(""),this._$elem.removeClass("geo-graphics")},clear:function(){this._context.clearRect(0,0,this._width,this._height),this._labelsHtml="",this._end()},drawArc:function(a,b,c,d){if(d=this._getGraphicStyle(d),"hidden"!==d.visibility&&d.opacity>0&&d.widthValue>0&&d.heightValue>0){var e=Math.min(d.widthValue,d.heightValue)/2;b=b*Math.PI/180,c=c*Math.PI/180,this._context.save(),this._context.translate(a[0],a[1]),d.widthValue>d.heightValue?this._context.scale(d.widthValue/d.heightValue,1):this._context.scale(1,d.heightValue/d.widthValue),this._context.beginPath(),this._context.arc(0,0,e,b,c,!1),this._trueCanvas&&this._context.restore(),d.doFill&&(this._context.fillStyle=d.fill,this._context.globalAlpha=d.opacity*d.fillOpacity,this._context.fill()),d.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=d.strokeWidthValue,this._context.strokeStyle=d.stroke,this._context.globalAlpha=d.opacity*d.strokeOpacity,this._context.stroke()),this._trueCanvas||this._context.restore()}this._end()},drawPoint:function(a,b){b=this._getGraphicStyle(b),b.widthValue===b.heightValue&&b.heightValue===b.borderRadiusValue?this.drawArc(a,0,360,b):"hidden"!==b.visibility&&b.opacity>0&&(b.borderRadiusValue=Math.min(Math.min(b.widthValue,b.heightValue)/2,b.borderRadiusValue),a[0]-=b.widthValue/2,a[1]-=b.heightValue/2,this._context.beginPath(),this._context.moveTo(a[0]+b.borderRadiusValue,a[1]),this._context.lineTo(a[0]+b.widthValue-b.borderRadiusValue,a[1]),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1],a[0]+b.widthValue,a[1]+b.borderRadiusValue),this._context.lineTo(a[0]+b.widthValue,a[1]+b.heightValue-b.borderRadiusValue),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1]+b.heightValue,a[0]+b.widthValue-b.borderRadiusValue,a[1]+b.heightValue),this._context.lineTo(a[0]+b.borderRadiusValue,a[1]+b.heightValue),this._context.quadraticCurveTo(a[0],a[1]+b.heightValue,a[0],a[1]+b.heightValue-b.borderRadiusValue),this._context.lineTo(a[0],a[1]+b.borderRadiusValue),this._context.quadraticCurveTo(a[0],a[1],a[0]+b.borderRadiusValue,a[1]),this._context.closePath(),b.doFill&&(this._context.fillStyle=b.fill,this._context.globalAlpha=b.opacity*b.fillOpacity,this._context.fill()),b.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=b.strokeWidthValue,this._context.strokeStyle=b.stroke,this._context.globalAlpha=b.opacity*b.strokeOpacity,this._context.stroke()),this._end())},drawLineString:function(a,b){this._drawLines([a],!1,b)},drawPolygon:function(a,b){if(this._trueCanvas&&1!==a.length){if(!a||!a.length||a[0].length<3)return;b=this._getGraphicStyle(b),this._blitcontext.globalCompositeOperation="copy";var c,d,e;if("hidden"!==b.visibility&&b.opacity>0){if(this._blitcontext.clearRect(0,0,this._width,this._height),b.doFill&&a.length>1){for(this._blitcontext.globalCompositeOperation="source-out",this._blitcontext.globalAlpha=1,this._blitcontext.beginPath(),d=1;d1))for(d=1;d'+b+""},resize:function(a,b){this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10)),this._trueCanvas?(this._$canvas[0].width=this._width,this._$canvas[0].height=this._height,this._$canvasSceneFront.css({left:a,top:b}),this._$canvasSceneBack.css({width:this._width,height:this._height})):this._$canvas.css({width:this._width,height:this._height});var c=this._$labelsContainerFront.position();this._$labelsContainerFront.css({left:c.left+a,top:c.top+b,width:this._width,height:this._height}),this._$labelsContainerBack.css({width:this._width,height:this._height})},interactiveTransform:function(a,b){if(this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._trueCanvas)if(this._options.doubleBuffer&&this._trueDoubleBuffer){var c=this;if(this._requireFlip){c._requireFlip=!1;var d=c._$canvasSceneFront;c._$canvasSceneFront=c._$canvasSceneBack.css({left:0,top:0,width:c._width,height:c._height}).prop("src",c._$canvas[0].toDataURL()).prependTo(c._$elem),c._$canvasSceneBack=d.prop("src","").detach()}this._$canvasSceneFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})}else this._context.clearRect(0,0,this._width,this._height);else this._context.clearRect(0,0,this._width,this._height);this._$labelsContainerFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})},_canvasSceneLoad:function(){var a=this;if(a._requireFlip){a._requireFlip=!1;var b=a._$canvasSceneFront;a._$canvasSceneFront=a._$canvasSceneBack.css({left:0,top:0,width:a._width,height:a._height}).prependTo(a._$elem),a._$canvasSceneBack=b.prop("src","").detach()}},_endCallback:function(){var a=this;if(a._timeoutEnd){a._trueCanvas&&a._options.doubleBuffer&&a._trueDoubleBuffer&&(a._$canvasSceneBack.prop("src",a._$canvas[0].toDataURL()),this._canvasSceneLoad()),a._$labelsContainerBack.html(b.toStaticHTML(a._labelsHtml)).find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"});var c=a._$labelsContainerFront;a._$labelsContainerFront=a._$labelsContainerBack.css({left:0,top:0,width:a._width,height:a._height}).appendTo(a._$elem),a._$labelsContainerBack=c.detach(),a._timeoutEnd=null}},_end:function(){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._requireFlip=!0,this._timeoutEnd=setTimeout(a.proxy(this._endCallback,this),20)},_getGraphicStyle:function(b){function c(a){return a=parseInt(a,10),+a+""===a?+a:a}return b=a.extend({},this._options.style,b),b.borderRadiusValue=c(b.borderRadius),b.fill=b.fill||b.color,b.doFill=b.fill&&b.fillOpacity>0,b.stroke=b.stroke||b.color,b.strokeWidthValue=c(b.strokeWidth),b.doStroke=b.stroke&&b.strokeOpacity>0&&b.strokeWidthValue>0,b.widthValue=c(b.width),b.heightValue=c(b.height),b},_drawLines:function(a,b,c){if(a&&a.length&&!(a[0].length<2)){var d,e;if(c=this._getGraphicStyle(c),"hidden"!==c.visibility&&c.opacity>0){for(this._context.beginPath(),d=0;d
            ";while(c[0]);return a>6?a:!a}(),f={bbox:[-180,-85,180,85],bboxMax:[-180,-85,180,85],center:[0,0],cursors:{"static":"default",pan:"url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move",click:"crosshair",zoom:"crosshair",dragBox:"crosshair",dragCircle:"crosshair",drawPoint:"crosshair",drawLineString:"crosshair",drawPolygon:"crosshair",measureLength:"crosshair",measureArea:"crosshair"},measureLabels:{length:"{{:length.toFixed( 2 )}} m",area:"{{:area.toFixed( 2 )}} sq m"},drawStyle:{},shapeStyle:{},mode:"pan",pannable:!0,scroll:"default",shift:"default",services:[{"class":"osm",type:"tiled",src:function(a){return"//otile"+(a.index%4+1)+("https:"===location.protocol?"-s":"")+".mqcdn.com/tiles/1.0.0/osm/"+a.zoom+"/"+a.tile.column+"/"+a.tile.row+".png"},attr:'Tiles Courtesy of MapQuest '}],tilingScheme:{tileWidth:256,tileHeight:256,levels:18,basePixelSize:156543.03392799935,origin:[-20037508.342787,20037508.342787]},axisLayout:"map",zoom:0,zoomMin:0,zoomMax:Number.POSITIVE_INFINITY,zoomFactor:2,pixelSize:0};a.widget("geo.geomap",{_$elem:c,_map:c,_created:!1,_createdGraphics:!1,_widgetId:0,_tmplLengthId:"",_tmplAreaId:"",_contentBounds:{},_$resizeContainer:c,_$eventTarget:c,_$contentFrame:c,_$existingChildren:c,_$attrList:c,_$servicesContainer:c,_$shapesContainers:c,_$panContainer:c,_$shapesContainer:c,_$drawContainer:c,_$measureContainer:c,_$measureLabel:c,_dpi:96,_currentServices:[],_center:c,_pixelSize:c,_centerMax:c,_pixelSizeMax:c,_pixelSizeMin:c,_userGeodetic:!0,_centerInteractive:c,_pixelSizeInteractive:c,_timeoutInteractive:null,_triggerInteractive:!1,_timeoutRefreshShapes:null,_loadCount:0,_wheelLevel:0,_fullZoomFactor:2,_partialZoomFactor:1.18920711500273,_mouseDown:c,_inOp:c,_toolPan:c,_shiftDown:c,_anchor:c,_current:c,_downDate:c,_moveDate:c,_clickDate:c,_lastMove:c,_lastDrag:c,_windowHandler:null,_resizeTimeout:null,_panning:c,_velocity:c,_friction:c,_pointerEvents:c,_supportTouch:c,_softDblClick:c,_isTap:c,_isDbltap:c,_isMultiTouch:c,_multiTouchAnchor:[],_multiTouchAnchorBbox:c,_multiTouchCurrentBbox:c,_drawTimeout:null,_drawPixels:[],_drawCoords:[],_graphicShapes:[],_initOptions:{},_options:{},options:a.extend({},f),_createWidget:function(b,c){if(this._$elem=a(c),this._$elem.is(".geo-service"))return this._graphicShapes=[],void a.Widget.prototype._createWidget.apply(this,arguments);this._widgetId=d++,this._serviceIdSeed=0,this._tmplLengthId="geoMeasureLength"+this._widgetId,this._tmplAreaId="geoMeasureArea"+this._widgetId,this._$elem.addClass("geo-map").css({webkitTransform:"translateZ(0)",touchAction:"none"}),this._initOptions=b||{},this._forcePosition(this._$elem),this._$elem.css("text-align","left");var e=this._findMapSize();this._contentBounds={x:parseInt(this._$elem.css("padding-left"),10),y:parseInt(this._$elem.css("padding-top"),10),width:e.width,height:e.height},this._createChildren(),this._center=[0,0],this._centerMax=[0,0],this._centerInteractive=[0,0],this.options.pixelSize=this._pixelSize=this._pixelSizeMax=156543.03392799935,this._pixelSizeMin=this._pixelSizeMax/Math.pow(2,17),this._mouseDown=this._inOp=this._toolPan=this._shiftDown=this._panning=this._isTap=this._isDbltap=!1,this._anchor=[0,0],this._current=[0,0],this._lastMove=[0,0],this._lastDrag=[0,0],this._velocity=[0,0],this._friction=[.8,.8],this._downDate=this._moveDate=this._clickDate=0,this._drawPixels=[],this._drawCoords=[],this._graphicShapes=[],a.Widget.prototype._createWidget.apply(this,arguments)},_create:function(){if(this._options=this.options,this._$elem.is(".geo-service"))return this._map=this._$elem.data("geoMap"),void this._$elem.data("geoService",this);this._map=this,this._pointerEvents=b.PointerEvent,this._supportTouch="ontouchend"in document,this._softDblClick=this._supportTouch||7===e;var d=this,f=this._pointerEvents?"pointerdown":this._supportTouch?"touchstart mousedown":"mousedown",g=this._pointerEvents?"pointerup pointercancel":this._supportTouch?"touchend touchcancel mouseup":"mouseup",h=this._pointerEvents?"pointermove":this._supportTouch?"touchmove mousemove":"mousemove";a(document).keydown(a.proxy(this._document_keydown,this)),this._$eventTarget.dblclick(a.proxy(this._eventTarget_dblclick,this)),this._$eventTarget.bind(f,a.proxy(this._eventTarget_touchstart,this));var i=this._$eventTarget[0].setCapture?this._$eventTarget:a(document);i.bind(h,a.proxy(this._dragTarget_touchmove,this)),i.bind(g,a.proxy(this._dragTarget_touchstop,this)),this._$eventTarget.mousewheel(a.proxy(this._eventTarget_mousewheel,this)),this._windowHandler=function(){d._resizeTimeout&&clearTimeout(d._resizeTimeout),d._resizeTimeout=setTimeout(function(){d._created&&d._$elem.geomap("resize",!0)},500)},a(b).resize(this._windowHandler),this._$drawContainer.geographics({style:this._initOptions.drawStyle||{},doubleBuffer:!1}),this._options.drawStyle=this._$drawContainer.geographics("option","style"),this._$shapesContainer.geographics({style:this._initOptions.shapeStyle||{}}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style"),this._initOptions&&(this._initOptions.tilingScheme!==c&&this._setOption("tilingScheme",this._initOptions.tilingScheme||null,!1),this._initOptions.services&&(this._options.services=a.merge([],this._initOptions.services)),this._initOptions.bboxMax&&(this._setOption("bboxMax",this._initOptions.bboxMax,!1),this._setOption("bbox",this._initOptions.bboxMax,!1)),this._initOptions.zoomMin!==c&&this._setOption("zoomMin",this._initOptions.zoomMin,!1),this._initOptions.zoomMax!==c&&this._setOption("zoomMax",this._initOptions.zoomMax,!1),this._initOptions.zoomFactor!==c&&(this._setOption("zoomFactor",this._initOptions.zoomFactor,!1),this._fullZoomFactor=this._initOptions.zoomFactor,this._partialZoomFactor=Math.pow(4,1/this._fullZoomFactor)),this._initOptions.bbox&&this._setOption("bbox",this._initOptions.bbox,!1),this._initOptions.center&&this._setOption("center",this._initOptions.center,!1),this._initOptions.zoom!==c&&this._setOption("zoom",this._initOptions.zoom,!1)),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area),this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._createServices(),this._refresh(),this._created=!0},_setOption:function(b,d,e){if("pixelSize"!==b){e=e===c||e,this._$elem.is(".geo-map")&&this._panFinalize();var f,g,h,i;switch(b){case"bbox":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),f=[d[0]+(d[2]-d[0])/2,d[1]+(d[3]-d[1])/2],g=Math.max(a.geo.width(d,!0)/this._contentBounds.width,a.geo.height(d,!0)/this._contentBounds.height),i=this._getZoom(f,g),this._options.tilingScheme?g=this._getPixelSize(Math.min(Math.max(i,this._options.zoomMin),this._options.zoomMax)):ithis._options.zoomMax&&(g=this._getPixelSize(this._options.zoomMax)),this._created?(this._setInteractiveCenterAndSize(f,g),this._setInteractiveTimeout(!1)):this._setCenterAndSize(f,g,!1,e),d=this._getBbox(f,g);break;case"bboxMax":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d);break;case"center":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),this._created?(this._setInteractiveCenterAndSize(d,this._pixelSizeInteractive),this._interactiveTransform(),this._setInteractiveTimeout(!1)):this._setCenterAndSize(d,this._pixelSize,!1,e);break;case"measureLabels":d=a.extend(this._options.measureLabels,d),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area);break;case"drawStyle":this._$drawContainer&&(this._$drawContainer.geographics("option","style",d),d=this._$drawContainer.geographics("option","style"));break;case"shapeStyle":this._$elem.is(".geo-service")&&!this._createdGraphics&&this._createServiceGraphics(),this._createdGraphics&&(this._$shapesContainer.geographics("option","style",d),d=this._$shapesContainer.geographics("option","style"));break;case"mode":this._resetDrawing(),this._$eventTarget.css("cursor",this._options.cursors[d]);break;case"zoom":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj,this._created?this._setZoom(d,!1,e):(d=Math.max(d,0),this._setCenterAndSize(this._center,this._getPixelSize(d),!1,e))}switch(a.Widget.prototype._setOption.apply(this,arguments),b){case"bbox":case"center":this._userGeodetic&&(this._options.bbox=a.geo.proj.toGeodetic(this._options.bbox),this._options.center=a.geo.proj.toGeodetic(this._center));break;case"tilingScheme":null!==d&&(this._pixelSizeMax=this._getPixelSize(0),this._pixelSizeMin=this._getPixelSize(d.pixelSizes?d.pixelSizes.length-1:d.levels-1),this._centerMax=[d.origin[0]+this._pixelSizeMax*d.tileWidth/2,d.origin[1]+this._pixelSizeMax*d.tileHeight/2]);break;case"bboxMax":h=this._userGeodetic?a.geo.proj.fromGeodetic(d):d,this._centerMax=a.geo.center(h),this._pixelSizeMax=Math.max(a.geo.width(h,!0)/this._contentBounds.width,a.geo.height(h,!0)/this._contentBounds.height);break;case"services":this._createServices(),e&&(this._refresh(),this._refreshAllShapes());break;case"shapeStyle":e&&this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))}}},destroy:function(){if(this._$elem.is(".geo-service"))this._createdGraphics&&(this._$shapesContainer.geographics("destroy"),this._$shapesContainer=c,this._createdGraphics=!1);else{clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,this._created=!1,a(b).unbind("resize",this._windowHandler);for(var d=0;d=0||1>=b)for(var d=0;d0)){this._createdGraphics||this._createServiceGraphics();var d,e,f,g,h,i;for(d=a.isArray(b)?b:"FeatureCollection"===b.type?b.features:[b],f=1;f=0;g--)if(d=this._graphicShapes[g],h)if("Point"===d.shape.type)a.geo.distance(d.shape,b)<=i&&j.push(d.shape);else{var k=a.data(d.shape,"geoBbox"),l={type:"Polygon",coordinates:[[[k[0],k[1]],[k[0],k[3]],[k[2],k[3]],[k[2],k[1]],[k[0],k[1]]]]},m={type:"Point",coordinates:a.geo.proj&&a.geo._isGeodetic(b.coordinates)?a.geo.proj.fromGeodetic(b.coordinates):b.coordinates};if(a.geo.distance(l,m,!0)<=i)for(e=a.geo._basic(d.shape),f=0;f0)){for(var e,f=a.isArray(b)?b:[b],g=0;g=0&&(e=this._graphicShapes.slice(g+1),this._graphicShapes.length=g,this._graphicShapes.push.apply(this._graphicShapes,e),g--);(d===c||d)&&(this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh(),this._refreshAllShapes())}},_getBbox:function(a,b){a=a||this._center,b=b||this._pixelSize;var c=this._contentBounds.width/2*b,d=this._contentBounds.height/2*b;return[a[0]-c,a[1]-d,a[0]+c,a[1]+d]},_setBbox:function(b){var c=[b[0]+(b[2]-b[0])/2,b[1]+(b[3]-b[1])/2],d=Math.max(a.geo.width(b,!0)/this._contentBounds.width,a.geo.height(b,!0)/this._contentBounds.height),e=this._getZoom(c,d);this._options.tilingScheme?d=this._getPixelSize(Math.min(Math.max(e,this._options.zoomMin),this._options.zoomMax)):ethis._options.zoomMax&&(d=this._getPixelSize(this._options.zoomMax)),this._setInteractiveCenterAndSize(c,d),this._interactiveTransform()},_getBboxMax:function(){var a=this._contentBounds.width/2*this._pixelSizeMax,b=this._contentBounds.height/2*this._pixelSizeMax;return[this._centerMax[0]-a,this._centerMax[1]-b,this._centerMax[0]+a,this._centerMax[1]+b]},_getCenter:function(){return this._center},_getContentBounds:function(){return this._contentBounds},_getServicesContainer:function(){return this._$servicesContainer},_getZoom:function(b,c){b=b||this._center,c=c||this._pixelSize;var d=this._options.tilingScheme;if(d){if(d.pixelSizes){for(var e=Math.floor(1e3*c),f=d.pixelSizes.length,g=f-1;g>=0;g--)if(Math.floor(1e3*d.pixelSizes[g])>=e)return g;return 0}return Math.round(Math.log(d.basePixelSize/c)/Math.log(2))}var h=this._contentBounds.width/this._contentBounds.height,i=a.geo.reaspect(this._getBbox(b,c),h,!0),j=a.geo.reaspect(this._getBboxMax(),h,!0);return Math.round(Math.log(a.geo.width(j,!0)/a.geo.width(i,!0))/Math.log(this._fullZoomFactor))},_setZoom:function(a,b){this._clearInteractiveTimeout(),a=Math.min(Math.max(a,this._options.zoomMin),this._options.zoomMax),this._setInteractiveCenterAndSize(this._centerInteractive,this._getPixelSize(a)),this._interactiveTransform(),this._setInteractiveTimeout(b)},_createChildren:function(){this._$existingChildren=this._$elem.children(),this._forcePosition(this._$existingChildren),this._$existingChildren.detach().css({mozUserSelect:"none"});var c="width:"+this._contentBounds.width+"px; height:"+this._contentBounds.height+"px; margin:0; padding:0;",d="position:absolute; left:0; top:0;";this._$elem.prepend(b.toStaticHTML('
            ')),this._$eventTarget=this._$contentFrame=this._$elem.children(":first"),this._$contentFrame.append('
            '),this._$servicesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
              '),this._$attrList=this._$contentFrame.children(":last"),this._$contentFrame.append('
              '),this._$drawContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
              '),this._$measureContainer=this._$contentFrame.children(":last"),this._$measureLabel=this._$measureContainer.children(),this._$contentFrame.append('
              '),this._$shapesContainer=this._$contentFrame.children(":last"),this._$panContainer=a([this._$shapesContainer[0],this._$drawContainer[0],this._$measureContainer[0]]),this._$resizeContainer=a([this._$contentFrame[0],this._$servicesContainer[0],this._$eventTarget[0],this._$measureContainer[0]]),this._$contentFrame.append(this._$existingChildren),a("#geo-measure-style").length||a("head").prepend(b.toStaticHTML('")) -},_createServices:function(){var c,d;for(d=0;d';this._$servicesContainer.append(b.toStaticHTML(h)),e=this._$servicesContainer.children(":last"),c.serviceContainer=e,a.geo._serviceTypes[c.type].create(this,e,c,d),e.data("geoMap",this).geomap(),c.attr&&this._$attrList.append("
            • "+c.attr+"
            • ")}this._$shapesContainers=this._$shapesContainer,this._$attrList.find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"})},_createServiceGraphics:function(){var a=this._$elem.closest(".geo-content-frame");this._$elem.append('
              '),this._$shapesContainer=this._$elem.children(":last"),this._map._$shapesContainers=this._map._$shapesContainers.add(this._$shapesContainer),this._$shapesContainer.geographics(),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style")},_refreshDrawing:function(){if(this._$drawContainer.geographics("clear"),this._drawPixels.length>0){var b,c,d,e,f,g=this._options.mode,h=this._drawPixels,i=this._drawCoords;switch(g){case"measureLength":g="drawLineString",c={type:"LineString",coordinates:i},b=a.render[this._tmplLengthId]({length:a.geo.length(c,!0)}),d=a.merge([],h[h.length-1]);break;case"measureArea":g="drawPolygon",c={type:"Polygon",coordinates:[a.merge([],i)]},c.coordinates[0].push(i[0]),b=a.render[this._tmplAreaId]({area:a.geo.area(c,!0)}),d=this._toPixel(a.geo.centroid(c).coordinates),h=[h];break;case"drawPolygon":h=[h]}this._$drawContainer.geographics(g,h),b&&(this._$measureLabel.html(b),e=this._contentBounds.width-(this._$measureLabel.outerWidth(!0)+d[0]),f=this._contentBounds.height-(this._$measureLabel.outerHeight(!0)+d[1]),0>e&&(d[0]+=e),0>f&&(d[1]+=f),this._$measureLabel.css({left:Math.max(d[0],0),top:Math.max(d[1],0)}).show())}},_resetDrawing:function(){this._drawPixels=[],this._drawCoords=[],this._$drawContainer.geographics("clear"),this._$measureLabel.hide()},_refreshAllShapes:function(a){this._timeoutRefreshShapes=null;for(var b,c,d=0;d0&&c._refreshShapes(c._$shapesContainer,c._graphicShapes,c._graphicShapes,c._graphicShapes)));this._createdGraphics&&!a&&(this._$shapesContainer.geographics("clear"),this._graphicShapes.length>0&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))},_refreshShapes:function(b,d,e,f,g,h){var i,j,k,l,m,n,o,p,q,r=this._map._getBbox(g,h);for(i=0;i0&&a.height>0);)a={width:b.width(),height:b.height()},(a.width<=0||a.height<=0)&&(a={width:parseInt(b.css("width"),10),height:parseInt(b.css("height"),10)}),b=b.parent();return a},_forcePosition:function(a){var b=a.css("position");"relative"!==b&&"absolute"!==b&&"fixed"!==b&&a.css("position","relative")},_getPixelSize:function(b){var c=this._options.tilingScheme;if(null!==c){if(0===b)return c.pixelSizes?c.pixelSizes[0]:c.basePixelSize;b=Math.round(b),b=Math.max(b,0);var d=c.pixelSizes?c.pixelSizes.length:c.levels;return b=Math.min(b,d-1),c.pixelSizes?c.pixelSizes[b]:c.basePixelSize/Math.pow(2,b)}var e=a.geo.scaleBy(this._getBboxMax(),1/Math.pow(this._fullZoomFactor,b),!0);return Math.max(a.geo.width(e,!0)/this._contentBounds.width,a.geo.height(e,!0)/this._contentBounds.height)},_getZoomCenterAndSize:function(a,b,c){var d=c?this._fullZoomFactor:this._partialZoomFactor,e=Math.pow(d,-b),f=this._pixelSizeInteractive*e;this._options.tilingScheme&&(f=Math.min(Math.max(f,this._pixelSizeMin),this._pixelSizeMax));var g=this._getZoom(this._centerInteractive,f);c&&this._options.tilingScheme?f=this._getPixelSize(Math.min(Math.max(g,this._options.zoomMin),this._options.zoomMax)):0>b&&g0&&g>this._options.zoomMax&&(f=this._pixelSizeInteractive);var h=f/this._pixelSizeInteractive,i=this._toMap(a,this._centerInteractive,this._pixelSizeInteractive),j=[(this._centerInteractive[0]-i[0])*h,(this._centerInteractive[1]-i[1])*h],k=[i[0]+j[0],i[1]+j[1]];return{pixelSize:f,center:k}},_panFinalize:function(){this._panning&&(this._velocity=[0,0],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._inOp=!1,this._anchor=this._current,this._mouseDown=this._toolPan=this._panning=!1)},_panMove:function(){if(this._options.pannable){var a=this._current[0]-this._lastDrag[0],b=this._current[1]-this._lastDrag[1];(this._toolPan||a>3||-3>a||b>3||-3>b)&&(this._toolPan||(this._toolPan=!0,this._$eventTarget.css("cursor",this._options.cursors.pan)),this._mouseDown&&(this._velocity=[a,b]),(0!==a||0!==b)&&(this._panning=!0,this._lastDrag=this._current,this._centerInteractive[0]-=a*this._pixelSizeInteractive,this._centerInteractive[1]+=("image"===this._options.axisLayout?-1:1)*b*this._pixelSizeInteractive,this._setInteractiveCenterAndSize(this._centerInteractive,this._pixelSizeInteractive),this._interactiveTransform()))}},_clearInteractiveTimeout:function(){return this._timeoutRefreshShapes&&(clearTimeout(this._timeoutRefreshShapes),this._timeoutRefreshShapes=null),this._timeoutInteractive?(clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,!0):(this._centerInteractive[0]=this._center[0],this._centerInteractive[1]=this._center[1],this._pixelSizeInteractive=this._pixelSize,!1)},_interactiveTransform:function(){var b,c=this._pixelSize,d=c/this._pixelSizeInteractive;if(c>0){d=Math.round(1e3*d)/1e3;var e=this._toMap([0,0]),f=this._toPixel(e,this._centerInteractive,this._pixelSizeInteractive);this._$shapesContainers.geographics("interactiveTransform",f,d)}for(var g=0;g0&&(this._drawPixels=this._toPixel(this._drawCoords,this._centerInteractive,this._pixelSizeInteractive),this._refreshDrawing())},_interactiveTimeout:function(){this._isMultiTouch?this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128):this._created&&this._timeoutInteractive&&(this._setCenterAndSize(this._centerInteractive,this._pixelSizeInteractive,this._triggerInteractive,!0),this._timeoutInteractive=null,this._triggerInteractive=!1,this._timeoutRefreshShapes=setTimeout(a.proxy(this._refreshAllShapes,this),128))},_setInteractiveTimeout:function(b){this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128),this._triggerInteractive|=b},_refresh:function(b,c){for(var d,e=0;ethis._options.zoomMax&&(this._pixelSizeInteractive=d=this._getPixelSize(this._options.zoomMax)),this._centerInteractive[0]=c[0],this._centerInteractive[1]=c[1],this._created&&this._interactiveTransform(),this._options.pixelSize=this._pixelSize=d,this._center[0]=c[0],this._center[1]=c[1],this._userGeodetic?(this._options.bbox=a.geo.proj.toGeodetic(this._getBbox()),this._options.center=a.geo.proj.toGeodetic(this._center)):(this._options.bbox=this._getBbox(),this._options.center=a.merge([],c)),this._options.zoom=g,e&&this._trigger("bboxchange",b.event,{bbox:a.merge([],this._options.bbox)}),f&&(this._refresh(),this._refreshAllShapes(),this._refreshDrawing())}},_requestQueued:function(){0===this._loadCount&&this._trigger("loadstart",b.event),this._loadCount++},_requestComplete:function(){this._loadCount--,this._loadCount<=0&&(this._loadCount=0,this._trigger("loadend",b.event))},_toMap:function(b,c,d){c=c||this._center,d=d||this._pixelSize;var e,f,g,h,i=a.isArray(b[0]),j=i&&a.isArray(b[0][0]),k=j&&a.isArray(b[0][0][0]),l=this._contentBounds.width,m=this._contentBounds.height,n=l/2*d,o=m/2*d,p=[c[0]-n,c[1]-o,c[0]+n,c[1]+o],q=a.geo.width(p,!0)/l,r=a.geo.height(p,!0)/m,s="image"===this._options.axisLayout,t=[];for(k||(j||(i||(b=[b]),b=[b]),b=[b]),f=0;f0&&27===b.which&&(2>=c?(this._resetDrawing(),this._inOp=!1):(this._drawCoords[c-2]=a.merge([],this._drawCoords[c-1]),this._drawPixels[c-2]=a.merge([],this._drawPixels[c-1]),this._drawCoords.length--,this._drawPixels.length--,this._refreshDrawing()))},_eventTarget_dblclick_zoom:function(a){var b=this._clearInteractiveTimeout();if(this._trigger("dblclick",a,{type:"Point",coordinates:this._toMap(this._current,this._centerInteractive,this._pixelSizeInteractive)}),!a.isDefaultPrevented()){var c=this._getZoomCenterAndSize(this._current,1,!0);this._setInteractiveCenterAndSize(c.center,c.pixelSize),this._interactiveTransform(),b=!0}b&&this._setInteractiveTimeout(!0)},_eventTarget_dblclick:function(c){if("static"!==this._options.mode){switch(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),this._options.mode){case"drawLineString":case"measureLength":this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])?(this._drawCoords.length--,this._trigger("shape",c,{type:"LineString",coordinates:this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords})):this._eventTarget_dblclick_zoom(c),this._resetDrawing();break;case"drawPolygon":case"measureArea":if(this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])){var d=this._drawCoords.length-1;d>2&&(this._drawCoords[d]=a.merge([],this._drawCoords[0]),this._trigger("shape",c,{type:"Polygon",coordinates:[this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords]}))}else this._eventTarget_dblclick_zoom(c);this._resetDrawing();break;default:this._eventTarget_dblclick_zoom(c)}this._inOp=!1}},_eventTarget_touchstart:function(b){if("undefined"!=typeof document.elementFromPoint){var c=document.elementFromPoint(b.pageX,b.pageY);if(c&&"A"===c.nodeName)return}var d=this._options.mode,e=this._options.shift,f="dragBox"===d?"dragBox":"zoom";if("static"!==d&&(this._pointerEvents||this._supportTouch||1===b.which)){this._pointerEvents&&console.log("PointerEvent touchstart");var g=this._clearInteractiveTimeout(),h=a(b.currentTarget).offset(),i=b.originalEvent.changedTouches;if(this._pointerEvents){if(b.currentTarget.setPointerCapture(b.originalEvent.pointerId),!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&b.originalEvent.pointerId!==this._multiTouchAnchor[0].pointerId)return this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-h.left,this._multiTouchAnchor[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=a.geo.center(this._multiTouchCurrentBbox,!0),this._current=a.merge([],this._anchor),g&&this._setInteractiveTimeout(!0),!1;this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top,0/0,0/0],this._current=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top]}else this._supportTouch&&i?(this._multiTouchAnchor=a.merge([],i),this._isMultiTouch=this._multiTouchAnchor.length>1,this._isMultiTouch?(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,i[1].pageX-h.left,i[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._current=a.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,0/0,0/0],this._current=[i[0].pageX-h.left,i[0].pageY-h.top])):this._current=[b.pageX-h.left,b.pageY-h.top];if(this._softDblClick){var j=a.now();if(j-this._downDate<750){if(this._isTap){var k=this._current[0]-this._anchor[0],l=this._current[1]-this._anchor[1],m=Math.sqrt(k*k+l*l);m>8?this._isTap=!1:this._current=a.merge([],this._anchor)}this._isDbltap=this._isDbltap?!1:this._isTap}else this._isDbltap=!1;this._isTap=!0,this._downDate=j}return this._mouseDown=!0,this._anchor=a.merge([],this._current),!this._inOp&&b.shiftKey&&"off"!==e?(this._shiftDown=!0,this._$eventTarget.css("cursor",this._options.cursors["default"===e?f:e])):this._isMultiTouch||!this._options.pannable&&"dragBox"!==d&&"dragCircle"!==d||(this._inOp=!0,"zoom"!==d&&"dragBox"!==d&&"dragCircle"!==d&&(this._lastDrag=this._current,b.currentTarget.setCapture&&b.currentTarget.setCapture())),b.preventDefault(),g&&this._setInteractiveTimeout(!0),!1}},_dragTarget_touchmove:function(b){if("static"!==this._options.mode){var c=!1;this._mouseDown&&(c=this._clearInteractiveTimeout());var d,f,g,h,i,j,k,l=this._$eventTarget.offset(),m=this._drawCoords.length,n=b.originalEvent.changedTouches;if(this._pointerEvents)this._isMultiTouch?(b.originalEvent.pointerId===this._multiTouchAnchor[0].pointerId?(this._multiTouchCurrentBbox[0]=b.originalEvent.pageX-l.left,this._multiTouchCurrentBbox[1]=b.originalEvent.pageY-l.top):b.originalEvent.pointerId===this._multiTouchAnchor[1].pointerId&&(this._multiTouchCurrentBbox[2]=b.originalEvent.pageX-l.left,this._multiTouchCurrentBbox[3]=b.originalEvent.pageY-l.top),f=a.geo._distancePointPoint([this._multiTouchAnchorBbox[0],this._multiTouchAnchorBbox[1]],[this._multiTouchAnchorBbox[2],this._multiTouchAnchorBbox[3]]),g=a.geo._distancePointPoint([this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1]],[this._multiTouchCurrentBbox[2],this._multiTouchCurrentBbox[3]]),d=a.geo.center(this._multiTouchCurrentBbox,!0),h=(g-f)/f,h*=h>0?5:10,i=h-this._wheelLevel,this._wheelLevel=h,j=this._getZoomCenterAndSize(this._anchor,i,!1),this._setInteractiveCenterAndSize(j.center,j.pixelSize),this._interactiveTransform(),c=!0,d=a.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchAnchor[0]=b.originalEvent,this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-l.left,this._multiTouchAnchor[0].pageY-l.top,0/0,0/0],d=[b.originalEvent.pageX-l.left,b.originalEvent.pageY-l.top]);else if(this._supportTouch&&n){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&n[0].identifier!==this._multiTouchAnchor[0].identifier)return this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(n[0]),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-l.left,this._multiTouchAnchor[1].pageY-l.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=this._current=a.geo.center(this._multiTouchCurrentBbox,!0),c&&this._setInteractiveTimeout(!0),!1;if(this._isMultiTouch){for(k=0;k0?5:10,i=h-this._wheelLevel,this._wheelLevel=h,j=this._getZoomCenterAndSize(this._anchor,i,!1),this._setInteractiveCenterAndSize(j.center,j.pixelSize),this._interactiveTransform(),c=!0,d=a.geo.center(this._multiTouchCurrentBbox,!0)}else d=[b.originalEvent.changedTouches[0].pageX-l.left,b.originalEvent.changedTouches[0].pageY-l.top]}else d=[b.pageX-l.left,b.pageY-l.top];if(d[0]===this._lastMove[0]&&d[1]===this._lastMove[1])return this._inOp?(b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1):!1;if(7===e&&(this._isDbltap=this._isTap=!1),this._mouseDown&&(this._current=d,this._moveDate=a.now()),this._isMultiTouch)return b.preventDefault(),this._isDbltap=this._isTap=!1,c&&this._setInteractiveTimeout(!0),!1;var o,p,q,r=this._options.mode,s=this._options.shift,t="dragBox"===r?"dragBox":"zoom";switch(this._shiftDown&&(r="default"===s?t:s),r){case"zoom":case"dragBox":this._mouseDown?(this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawBbox",[this._anchor[0],this._anchor[1],d[0],d[1]])):this._trigger("move",b,{type:"Point",coordinates:this.toMap(d)});break;case"dragCircle":this._mouseDown?(o=d[0]-this._anchor[0],p=d[1]-this._anchor[1],q=2*Math.sqrt(o*o+p*p),this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawArc",this._anchor,0,360,{width:q,height:q})):this._trigger("move",b,{type:"Point",coordinates:this.toMap(d)});break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":this._mouseDown||this._toolPan?(this._panMove(),c=!0):(m>0&&(this._drawCoords[m-1]=this._toMap(d,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[m-1]=d,this._refreshDrawing()),this._trigger("move",b,{type:"Point",coordinates:this.toMap(d)}));break;default:this._mouseDown||this._toolPan?(this._panMove(),c=!0):this._trigger("move",b,{type:"Point",coordinates:this.toMap(d)})}return this._lastMove=d,c&&this._setInteractiveTimeout(!0),this._inOp?(b.preventDefault(),!1):void 0}},_dragTarget_touchstop:function(c){if("static"!==this._options.mode){if(this._pointerEvents&&console.log("PointerEvent touchstop"),!this._mouseDown){if(7!==e)return;this._eventTarget_touchstart(c)}var d,f,g,h,i,j,k,l=this._clearInteractiveTimeout(),m=this._mouseDown,n=this._toolPan,o=this._$eventTarget.offset(),p=this._options.mode,q=this._options.shift,r="dragBox"===p?"dragBox":"zoom";if(this._shiftDown&&(p="default"===q?r:q),this._pointerEvents){for(d=[c.pageX-o.left,c.pageY-o.top],f=0;ff;f++)v=360*f/y*(Math.PI/180),this._drawPixels[f]=[this._anchor[0]+Math.cos(v)*x,this._anchor[1]+Math.sin(v)*x];this._drawPixels[y]=[this._drawPixels[0][0],this._drawPixels[0][1]],j=this._toMap([[this._anchor[0]-x,this._anchor[1]+(w?-x:x)],[this._anchor[0]+x,this._anchor[1]+(w?x:-x)]]),k={type:"Polygon",coordinates:[this._toMap(this._drawPixels)],bbox:[j[0][0],j[0][1],j[1][0],j[1][1]]},this._userGeodetic&&(k.coordinates=a.geo.proj.toGeodetic(k.coordinates),k.bbox=a.geo.proj.toGeodetic(k.bbox)),this._trigger("shape",c,k),this._resetDrawing()}else j=this._toMap(d),k={type:"Point",coordinates:[j[0],j[1]],bbox:[j[0],j[1],j[0],j[1]]},this._userGeodetic&&(k.coordinates=a.geo.proj.toGeodetic(k.coordinates),k.bbox=a.geo.proj.toGeodetic(k.bbox)),this._trigger("shape",c,k);break;case"drawPoint":if(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),n)this._panFinalize();else if(g-this._clickDate>100){var z=this;this._drawTimeout=setTimeout(function(){z._drawTimeout&&(z._trigger("shape",c,{type:"Point",coordinates:z.toMap(d)}),z._inOp=!1,z._drawTimeout=null)},250)}break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":n?this._panFinalize():(this._trigger("click",c,{type:"Point",coordinates:this.toMap(d)}),c.isDefaultPrevented()||(f=0===this._drawCoords.length?0:this._drawCoords.length-1,this._drawCoords[f]=this._toMap(d),this._drawPixels[f]=d,(2>f||this._drawCoords[f][0]!==this._drawCoords[f-1][0]||this._drawCoords[f][1]!==this._drawCoords[f-1][1])&&(this._drawCoords[f+1]=this._toMap(d,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[f+1]=d),this._refreshDrawing()));break;default:n?this._panFinalize():g-this._clickDate>100&&(this._trigger("click",c,{type:"Point",coordinates:this.toMap(d)}),this._inOp=!1)}if(this._clickDate=g,this._softDblClick&&this._isDbltap)return this._isDbltap=this._isTap=!1,l&&this._setInteractiveTimeout(!0),this._$eventTarget.trigger("dblclick",c),!1}return l&&this._setInteractiveTimeout(!0),this._inOp?(c.preventDefault(),!1):void 0}},_eventTarget_mousewheel:function(b){if("static"!==this._options.mode&&"off"!==this._options.scroll){if(b.preventDefault(),this._mouseDown)return!1;if(0!==b.deltaY){this._clearInteractiveTimeout();var c=b.deltaY>0?1:-1,d=a(b.currentTarget).offset();this._anchor=[b.pageX-d.left,b.pageY-d.top];var e=this._getZoomCenterAndSize(this._anchor,c,null!==this._options.tilingScheme);this._setInteractiveCenterAndSize(e.center,e.pixelSize),this._interactiveTransform(),this._setInteractiveTimeout(!0)}return!1}}})}(jQuery,window),function(a,b){a.geo._serviceTypes.tiled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0,reloadTiles:!1};var g='
              ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b.options.tilingScheme;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),h=f/e;if(f>0){h=Math.round(1e3*h)/1e3;var i=c.data("scaleOrigin"),j=b._toPixel(i,d,e);c.css({left:Math.round(j[0])+"px",top:Math.round(j[1])+"px",width:g.tileWidth*h,height:g.tileHeight*h})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&f&&(g.reloadTiles=!0),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i,j=d._getBbox(),k=d._pixelSize,l=this,m=g.serviceContainer,n="image"===d.options.axisLayout,o=n?1:-1,p=d.options.tilingScheme,q=p.tileWidth,r=p.tileHeight,s=Math.floor((j[0]-p.origin[0])/(k*q)),t=Math.max(Math.floor((n?j[1]-p.origin[1]:p.origin[1]-j[3])/(k*r)),0),u=Math.ceil((j[2]-p.origin[0])/(k*q)),v=Math.ceil((n?j[3]-p.origin[1]:p.origin[1]-j[1])/(k*r)),w=d._getBboxMax(),x=d._getPixelSize(0),y=x/k,z=Math.floor((w[0]-p.origin[0])/(x*q))*y,A=Math.floor((p.origin[1]+o*w[3])/(x*r))*y,B=p.origin[0]+z*q*k,C=p.origin[1]+o*A*r*k,D=Math.round((B-j[0])/k),E=Math.round((n?C-j[1]:j[3]-C)/k),F=m.children().show(),G=F.filter("[data-pixel-size='"+k+"']").appendTo(m),H=e.style.opacity,I=function(a){l._loadImage(this.img,a,k,d,g,H)},J=function(){delete this.img,g.loadCount--,d._requestComplete()};for(g.reloadTiles&&F.find("img").attr("data-dirty","true"),G.size()?(G.css({left:D%q+"px",top:E%r+"px"}).data("scaleOrigin",d._toMap([D%q,E%r])),G.children().each(function(){var b=a(this),c=b.attr("data-tile").split(",");b.css({left:Math.round(100*(parseInt(c[0],10)-z)+(D-D%q)/q*100)+"%",top:Math.round(100*(parseInt(c[1],10)-A)+(E-E%r)/r*100)+"%"}),1>H&&b.fadeTo(0,H)})):(m.append(b.toStaticHTML("
              ")),G=m.children(":last").data("scaleOrigin",d._toMap([D%q,E%r]))),h=s;u>h;h++)for(i=t;v>i;i++){var K=""+h+","+i,L=G.children("[data-tile='"+K+"']").removeAttr("data-dirty");if(0===L.size()||g.reloadTiles){var M,N=[p.origin[0]+h*q*k,p.origin[1]+o*i*r*k],O=[p.origin[0]+((h+1)*q-1)*k,p.origin[1]+o*((i+1)*r-1)*k],P=[N[0],N[1],O[0],O[1]],Q={bbox:P,width:q,height:r,zoom:d._getZoom(),tile:{row:i,column:h},index:Math.abs(i+h)},R=a.isFunction(e.src);if(R?M=e.src(Q):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),M=a.render[this._tmplGeoSrcId](Q)):M=e.src,g.loadCount++,d._requestQueued(),g.reloadTiles&&L.size()>0)L.attr("src",M);else{var S="",G.append(b.toStaticHTML(S)),L=G.children(":last")}"string"==typeof M?l._loadImage(L,M,k,d,g,H):M&&a.isFunction(M.promise)?(a.extend(M.promise(),{img:L}),M.done(I).fail(J)):L.remove()}}F.find("[data-dirty]").remove(),g.reloadTiles=!1}},resize:function(){},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--,b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){1>g?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).error(function(b){a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).attr("src",c)}}}()}(jQuery,window),function(a,b){a.geo._serviceTypes.shingled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0};var g='
              ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b._getContentBounds(),h=g.width,i=g.height;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),g=f/e;if(f>0){g=Math.round(1e3*g)/1e3; -var j=c.data("origin"),k=b._toPixel(j,d,e);c.css({left:Math.round(k[0]),top:Math.round(k[1]),width:h*g,height:i*g})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i=d._getBbox(),j=d._pixelSize,k=this,l=g.serviceContainer,m=d._getContentBounds(),n=m.width,o=m.height,p=l.children('[data-pixel-size="'+j+'"]'),q=e.style.opacity;1>q||f||1===e.shinglesMax?l.find("img").attr("data-keep-alive","0"):e.shinglesMax>1&&l.find("img").slice(0,-(e.shinglesMax-1)).attr("data-keep-alive","0"),p.size()||(l.append(b.toStaticHTML('
              ')),p=l.children(":last"));var r,s={bbox:i,width:n,height:o,zoom:d._getZoom(),tile:null,index:0},t=a.isFunction(e.src),u=p.position();u.left=-u.left,u.top=-u.top,t?r=e.src(s):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),r=a.render[this._tmplGeoSrcId](s)):r=e.src,g.loadCount++,d._requestQueued(),p.append(b.toStaticHTML('')),h=p.children(":last").data("center",d._center),"string"==typeof r?k._loadImage(h,r,j,d,g,q):r&&r.done(function(a){k._loadImage(h,a,j,d,g,q)}).fail(function(){h.remove(),g.loadCount--,d._requestComplete()})}},resize:function(b,c){var d=a.data(c,"geoServiceState");if(d&&c&&"visible"===c.style.visibility){this._cancelUnloaded(b,c);var e=d.serviceContainer,f=b._getContentBounds(),g=f.width,h=f.height,i=e.children();i.attr("data-pixel-size","0"),i.each(function(){var b=a(this),c=b.position();b.css({left:c.left+(g-b.width())/2,top:c.top+(h-b.height())/2})})}},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--,b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(1>g?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(':not([data-pixel-size="'+d+'"])').remove(),h.find("img[data-keep-alive]").remove(),f.loadCount=0))}).error(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0))}).attr("src",c)}}}()}(jQuery,window); \ No newline at end of file diff --git a/dist/jquery.geo-1.0.0-b3.js b/dist/jquery.geo-1.0.0-b3.js deleted file mode 100644 index 0e6d22c..0000000 --- a/dist/jquery.geo-1.0.0-b3.js +++ /dev/null @@ -1,7515 +0,0 @@ -/*! jQuery Geo - v1.0.0-b3 - 2015-10-17 -* http://jquerygeo.com -* Copyright (c) 2015 Ryan Morrison-Westphal; Licensed MIT */ -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -// Known Issues: -// -// * Patterns only support repeat. -// * Radial gradient are not implemented. The VML version of these look very -// different from the canvas one. -// * Clipping paths are not implemented. -// * Coordsize. The width and height attribute have higher priority than the -// width and height style values which isn't correct. -// * Painting mode isn't implemented. -// * Canvas width/height should is using content-box by default. IE in -// Quirks mode will draw the canvas using border-box. Either change your -// doctype to HTML5 -// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) -// or use Box Sizing Behavior from WebFX -// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) -// * Non uniform scaling does not correctly scale strokes. -// * Optimize. There is always room for speed improvements. - -// Only add this code if we do not already have a canvas implementation -if (!document.createElement('canvas').getContext) { - - (function () { - - // alias some functions to make (compiled) code shorter - var m = Math; - var mr = m.round; - var ms = m.sin; - var mc = m.cos; - var abs = m.abs; - var sqrt = m.sqrt; - - // this is used for sub pixel precision - var Z = 10; - var Z2 = Z / 2; - - var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; - - /** - * This funtion is assigned to the elements as element.getContext(). - * @this {HTMLElement} - * @return {CanvasRenderingContext2D_} - */ - function getContext() { - return this.context_ || - (this.context_ = new CanvasRenderingContext2D_(this)); - } - - var slice = Array.prototype.slice; - - /** - * Binds a function to an object. The returned function will always use the - * passed in {@code obj} as {@code this}. - * - * Example: - * - * g = bind(f, obj, a, b) - * g(c, d) // will do f.call(obj, a, b, c, d) - * - * @param {Function} f The function to bind the object to - * @param {Object} obj The object that should act as this when the function - * is called - * @param {*} var_args Rest arguments that will be used as the initial - * arguments when the function is called - * @return {Function} A new function that has bound this - */ - function bind(f, obj, var_args) { - var a = slice.call(arguments, 2); - return function () { - return f.apply(obj, a.concat(slice.call(arguments))); - }; - } - - function encodeHtmlAttribute(s) { - return String(s).replace(/&/g, '&').replace(/"/g, '"'); - } - - function addNamespace(doc, prefix, urn) { - if (!doc.namespaces[prefix]) { - doc.namespaces.add(prefix, urn, '#default#VML'); - } - } - - function addNamespacesAndStylesheet(doc) { - addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); - addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); - - // Setup default CSS. Only add one style sheet per document - if (!doc.styleSheets['ex_canvas_']) { - var ss = doc.createStyleSheet(); - ss.owningElement.id = 'ex_canvas_'; - ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + - // default size is 300x150 in Gecko and Opera - 'text-align:left;width:300px;height:150px}'; - } - } - - // Add namespaces and stylesheet at startup. - addNamespacesAndStylesheet(document); - - var G_vmlCanvasManager_ = { - init: function (opt_doc) { - var doc = opt_doc || document; - // Create a dummy element so that IE will allow canvas elements to be - // recognized. - doc.createElement('canvas'); - doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); - }, - - init_: function (doc) { - // find all canvas elements - var els = doc.getElementsByTagName('canvas'); - for (var i = 0; i < els.length; i++) { - this.initElement(els[i]); - } - }, - - /** - * Public initializes a canvas element so that it can be used as canvas - * element from now on. This is called automatically before the page is - * loaded but if you are creating elements using createElement you need to - * make sure this is called on the element. - * @param {HTMLElement} el The canvas element to initialize. - * @return {HTMLElement} the element that was created. - */ - initElement: function (el) { - if (!el.getContext) { - el.getContext = getContext; - - // Add namespaces and stylesheet to document of the element. - addNamespacesAndStylesheet(el.ownerDocument); - - // Remove fallback content. There is no way to hide text nodes so we - // just remove all childNodes. We could hide all elements and remove - // text nodes but who really cares about the fallback content. - el.innerHTML = ''; - - // do not use inline function because that will leak memory - el.attachEvent('onpropertychange', onPropertyChange); - el.attachEvent('onresize', onResize); - - var attrs = el.attributes; - if (attrs.width && attrs.width.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setWidth_(attrs.width.nodeValue); - el.style.width = attrs.width.nodeValue + 'px'; - } else { - el.width = el.clientWidth; - } - if (attrs.height && attrs.height.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setHeight_(attrs.height.nodeValue); - el.style.height = attrs.height.nodeValue + 'px'; - } else { - el.height = el.clientHeight; - } - //el.getContext().setCoordsize_() - } - return el; - } - }; - - function onPropertyChange(e) { - var el = e.srcElement; - - switch (e.propertyName) { - case 'width': - el.getContext().clearRect(); - el.style.width = el.attributes.width.nodeValue + 'px'; - // In IE8 this does not trigger onresize. - el.firstChild.style.width = el.clientWidth + 'px'; - break; - case 'height': - el.getContext().clearRect(); - el.style.height = el.attributes.height.nodeValue + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - break; - } - } - - function onResize(e) { - var el = e.srcElement; - if (el.firstChild) { - el.firstChild.style.width = el.clientWidth + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - } - } - - G_vmlCanvasManager_.init(); - - // precompute "00" to "FF" - var decToHex = []; - for (var i = 0; i < 16; i++) { - for (var j = 0; j < 16; j++) { - decToHex[i * 16 + j] = i.toString(16) + j.toString(16); - } - } - - function createMatrixIdentity() { - return [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1] - ]; - } - - function matrixMultiply(m1, m2) { - var result = createMatrixIdentity(); - - for (var x = 0; x < 3; x++) { - for (var y = 0; y < 3; y++) { - var sum = 0; - - for (var z = 0; z < 3; z++) { - sum += m1[x][z] * m2[z][y]; - } - - result[x][y] = sum; - } - } - return result; - } - - function copyState(o1, o2) { - o2.fillStyle = o1.fillStyle; - o2.lineCap = o1.lineCap; - o2.lineJoin = o1.lineJoin; - o2.lineWidth = o1.lineWidth; - o2.miterLimit = o1.miterLimit; - o2.shadowBlur = o1.shadowBlur; - o2.shadowColor = o1.shadowColor; - o2.shadowOffsetX = o1.shadowOffsetX; - o2.shadowOffsetY = o1.shadowOffsetY; - o2.strokeStyle = o1.strokeStyle; - o2.globalAlpha = o1.globalAlpha; - o2.font = o1.font; - o2.textAlign = o1.textAlign; - o2.textBaseline = o1.textBaseline; - o2.arcScaleX_ = o1.arcScaleX_; - o2.arcScaleY_ = o1.arcScaleY_; - o2.lineScale_ = o1.lineScale_; - } - - // var colorData = { - // aliceblue: '#F0F8FF', - // antiquewhite: '#FAEBD7', - // aquamarine: '#7FFFD4', - // azure: '#F0FFFF', - // beige: '#F5F5DC', - // bisque: '#FFE4C4', - // black: '#000000', - // blanchedalmond: '#FFEBCD', - // blueviolet: '#8A2BE2', - // brown: '#A52A2A', - // burlywood: '#DEB887', - // cadetblue: '#5F9EA0', - // chartreuse: '#7FFF00', - // chocolate: '#D2691E', - // coral: '#FF7F50', - // cornflowerblue: '#6495ED', - // cornsilk: '#FFF8DC', - // crimson: '#DC143C', - // cyan: '#00FFFF', - // darkblue: '#00008B', - // darkcyan: '#008B8B', - // darkgoldenrod: '#B8860B', - // darkgray: '#A9A9A9', - // darkgreen: '#006400', - // darkgrey: '#A9A9A9', - // darkkhaki: '#BDB76B', - // darkmagenta: '#8B008B', - // darkolivegreen: '#556B2F', - // darkorange: '#FF8C00', - // darkorchid: '#9932CC', - // darkred: '#8B0000', - // darksalmon: '#E9967A', - // darkseagreen: '#8FBC8F', - // darkslateblue: '#483D8B', - // darkslategray: '#2F4F4F', - // darkslategrey: '#2F4F4F', - // darkturquoise: '#00CED1', - // darkviolet: '#9400D3', - // deeppink: '#FF1493', - // deepskyblue: '#00BFFF', - // dimgray: '#696969', - // dimgrey: '#696969', - // dodgerblue: '#1E90FF', - // firebrick: '#B22222', - // floralwhite: '#FFFAF0', - // forestgreen: '#228B22', - // gainsboro: '#DCDCDC', - // ghostwhite: '#F8F8FF', - // gold: '#FFD700', - // goldenrod: '#DAA520', - // grey: '#808080', - // greenyellow: '#ADFF2F', - // honeydew: '#F0FFF0', - // hotpink: '#FF69B4', - // indianred: '#CD5C5C', - // indigo: '#4B0082', - // ivory: '#FFFFF0', - // khaki: '#F0E68C', - // lavender: '#E6E6FA', - // lavenderblush: '#FFF0F5', - // lawngreen: '#7CFC00', - // lemonchiffon: '#FFFACD', - // lightblue: '#ADD8E6', - // lightcoral: '#F08080', - // lightcyan: '#E0FFFF', - // lightgoldenrodyellow: '#FAFAD2', - // lightgreen: '#90EE90', - // lightgrey: '#D3D3D3', - // lightpink: '#FFB6C1', - // lightsalmon: '#FFA07A', - // lightseagreen: '#20B2AA', - // lightskyblue: '#87CEFA', - // lightslategray: '#778899', - // lightslategrey: '#778899', - // lightsteelblue: '#B0C4DE', - // lightyellow: '#FFFFE0', - // limegreen: '#32CD32', - // linen: '#FAF0E6', - // magenta: '#FF00FF', - // mediumaquamarine: '#66CDAA', - // mediumblue: '#0000CD', - // mediumorchid: '#BA55D3', - // mediumpurple: '#9370DB', - // mediumseagreen: '#3CB371', - // mediumslateblue: '#7B68EE', - // mediumspringgreen: '#00FA9A', - // mediumturquoise: '#48D1CC', - // mediumvioletred: '#C71585', - // midnightblue: '#191970', - // mintcream: '#F5FFFA', - // mistyrose: '#FFE4E1', - // moccasin: '#FFE4B5', - // navajowhite: '#FFDEAD', - // oldlace: '#FDF5E6', - // olivedrab: '#6B8E23', - // orange: '#FFA500', - // orangered: '#FF4500', - // orchid: '#DA70D6', - // palegoldenrod: '#EEE8AA', - // palegreen: '#98FB98', - // paleturquoise: '#AFEEEE', - // palevioletred: '#DB7093', - // papayawhip: '#FFEFD5', - // peachpuff: '#FFDAB9', - // peru: '#CD853F', - // pink: '#FFC0CB', - // plum: '#DDA0DD', - // powderblue: '#B0E0E6', - // rosybrown: '#BC8F8F', - // royalblue: '#4169E1', - // saddlebrown: '#8B4513', - // salmon: '#FA8072', - // sandybrown: '#F4A460', - // seagreen: '#2E8B57', - // seashell: '#FFF5EE', - // sienna: '#A0522D', - // skyblue: '#87CEEB', - // slateblue: '#6A5ACD', - // slategray: '#708090', - // slategrey: '#708090', - // snow: '#FFFAFA', - // springgreen: '#00FF7F', - // steelblue: '#4682B4', - // tan: '#D2B48C', - // thistle: '#D8BFD8', - // tomato: '#FF6347', - // turquoise: '#40E0D0', - // violet: '#EE82EE', - // wheat: '#F5DEB3', - // whitesmoke: '#F5F5F5', - // yellowgreen: '#9ACD32' - // }; - - - function getRgbHslContent(styleString) { - var start = styleString.indexOf('(', 3); - var end = styleString.indexOf(')', start + 1); - var parts = styleString.substring(start + 1, end).split(','); - // add alpha if needed - if (parts.length != 4 || styleString.charAt(3) != 'a') { - parts[3] = 1; - } - return parts; - } - - function percent(s) { - return parseFloat(s) / 100; - } - - function clamp(v, min, max) { - return Math.min(max, Math.max(min, v)); - } - - function hslToRgb(parts) { - var r, g, b, h, s, l; - h = parseFloat(parts[0]) / 360 % 360; - if (h < 0) - h++; - s = clamp(percent(parts[1]), 0, 1); - l = clamp(percent(parts[2]), 0, 1); - if (s == 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1 / 3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1 / 3); - } - - return '#' + decToHex[Math.floor(r * 255)] + - decToHex[Math.floor(g * 255)] + - decToHex[Math.floor(b * 255)]; - } - - function hueToRgb(m1, m2, h) { - if (h < 0) - h++; - if (h > 1) - h--; - - if (6 * h < 1) - return m1 + (m2 - m1) * 6 * h; - else if (2 * h < 1) - return m2; - else if (3 * h < 2) - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - else - return m1; - } - - var processStyleCache = {}; - - function processStyle(styleString) { - if (styleString in processStyleCache) { - return processStyleCache[styleString]; - } - - var str, alpha = 1; - - styleString = String(styleString); - if (styleString.charAt(0) == '#') { - str = styleString; - } else if (/^rgb/.test(styleString)) { - var parts = getRgbHslContent(styleString); - var str = '#', n; - for (var i = 0; i < 3; i++) { - if (parts[i].indexOf('%') != -1) { - n = Math.floor(percent(parts[i]) * 255); - } else { - n = +parts[i]; - } - str += decToHex[clamp(n, 0, 255)]; - } - alpha = +parts[3]; - } else if (/^hsl/.test(styleString)) { - var parts = getRgbHslContent(styleString); - str = hslToRgb(parts); - alpha = parts[3]; - } else { - str = /*colorData[styleString] ||*/styleString; - } - return processStyleCache[styleString] = { color: str, alpha: alpha }; - } - - var DEFAULT_STYLE = { - style: 'normal', - variant: 'normal', - weight: 'normal', - size: 10, - family: 'sans-serif' - }; - - // Internal text style cache - // var fontStyleCache = {}; - - // function processFontStyle(styleString) { - // if (fontStyleCache[styleString]) { - // return fontStyleCache[styleString]; - // } - - // var el = document.createElement('div'); - // var style = el.style; - // try { - // style.font = styleString; - // } catch (ex) { - // // Ignore failures to set to invalid font. - // } - - // return fontStyleCache[styleString] = { - // style: style.fontStyle || DEFAULT_STYLE.style, - // variant: style.fontVariant || DEFAULT_STYLE.variant, - // weight: style.fontWeight || DEFAULT_STYLE.weight, - // size: style.fontSize || DEFAULT_STYLE.size, - // family: style.fontFamily || DEFAULT_STYLE.family - // }; - // } - - // function getComputedStyle(style, element) { - // var computedStyle = {}; - - // for (var p in style) { - // computedStyle[p] = style[p]; - // } - - // // Compute the size - // var canvasFontSize = parseFloat(element.currentStyle.fontSize), - // fontSize = parseFloat(style.size); - - // if (typeof style.size == 'number') { - // computedStyle.size = style.size; - // } else if (style.size.indexOf('px') != -1) { - // computedStyle.size = fontSize; - // } else if (style.size.indexOf('em') != -1) { - // computedStyle.size = canvasFontSize * fontSize; - // } else if(style.size.indexOf('%') != -1) { - // computedStyle.size = (canvasFontSize / 100) * fontSize; - // } else if (style.size.indexOf('pt') != -1) { - // computedStyle.size = fontSize / .75; - // } else { - // computedStyle.size = canvasFontSize; - // } - - // // Different scaling between normal text and VML text. This was found using - // // trial and error to get the same size as non VML text. - // computedStyle.size *= 0.981; - - // return computedStyle; - // } - - // function buildStyle(style) { - // return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + - // style.size + 'px ' + style.family; - // } - - var lineCapMap = { - 'butt': 'flat', - 'round': 'round' - }; - - function processLineCap(lineCap) { - return lineCapMap[lineCap] || 'square'; - } - - /** - * This class implements CanvasRenderingContext2D interface as described by - * the WHATWG. - * @param {HTMLElement} canvasElement The element that the 2D context should - * be associated with - */ - function CanvasRenderingContext2D_(canvasElement) { - this.m_ = createMatrixIdentity(); - - this.mStack_ = []; - this.aStack_ = []; - this.currentPath_ = []; - - // Canvas context properties - this.strokeStyle = '#000'; - this.fillStyle = '#000'; - - this.lineWidth = 1; - this.lineJoin = 'miter'; - this.lineCap = 'butt'; - this.miterLimit = Z * 1; - this.globalAlpha = 1; - //this.font = '10px sans-serif'; - //this.textAlign = 'left'; - //this.textBaseline = 'alphabetic'; - this.canvas = canvasElement; - - var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + - canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; - var el = canvasElement.ownerDocument.createElement('div'); - el.style.cssText = cssText; - canvasElement.appendChild(el); - - var overlayEl = el.cloneNode(false); - // Use a non transparent background. - overlayEl.style.backgroundColor = 'red'; - overlayEl.style.filter = 'alpha(opacity=0)'; - canvasElement.appendChild(overlayEl); - - this.element_ = el; - this.arcScaleX_ = 1; - this.arcScaleY_ = 1; - this.lineScale_ = 1; - } - - var contextPrototype = CanvasRenderingContext2D_.prototype; - contextPrototype.clearRect = function () { - if (this.textMeasureEl_) { - this.textMeasureEl_.removeNode(true); - this.textMeasureEl_ = null; - } - this.element_.innerHTML = ''; - }; - - contextPrototype.beginPath = function () { - // TODO: Branch current matrix so that save/restore has no effect - // as per safari docs. - this.currentPath_ = []; - }; - - contextPrototype.moveTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'moveTo', x: p.x, y: p.y }); - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.lineTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'lineTo', x: p.x, y: p.y }); - - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY) { - var p = getCoords(this, aX, aY); - var cp1 = getCoords(this, aCP1x, aCP1y); - var cp2 = getCoords(this, aCP2x, aCP2y); - bezierCurveTo(this, cp1, cp2, p); - }; - - // Helper function that takes the already fixed cordinates. - function bezierCurveTo(self, cp1, cp2, p) { - self.currentPath_.push({ - type: 'bezierCurveTo', - cp1x: cp1.x, - cp1y: cp1.y, - cp2x: cp2.x, - cp2y: cp2.y, - x: p.x, - y: p.y - }); - self.currentX_ = p.x; - self.currentY_ = p.y; - } - - contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { - // the following is lifted almost directly from - // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes - - var cp = getCoords(this, aCPx, aCPy); - var p = getCoords(this, aX, aY); - - var cp1 = { - x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), - y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) - }; - var cp2 = { - x: cp1.x + (p.x - this.currentX_) / 3.0, - y: cp1.y + (p.y - this.currentY_) / 3.0 - }; - - bezierCurveTo(this, cp1, cp2, p); - }; - - contextPrototype.arc = function (aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise) { - aRadius *= Z; - var arcType = aClockwise ? 'at' : 'wa'; - - var xStart = aX + mc(aStartAngle) * aRadius - Z2; - var yStart = aY + ms(aStartAngle) * aRadius - Z2; - - var xEnd = aX + mc(aEndAngle) * aRadius - Z2; - var yEnd = aY + ms(aEndAngle) * aRadius - Z2; - - // IE won't render arches drawn counter clockwise if xStart == xEnd. - if (xStart == xEnd && !aClockwise) { - xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something - // that can be represented in binary - } - - var p = getCoords(this, aX, aY); - var pStart = getCoords(this, xStart, yStart); - var pEnd = getCoords(this, xEnd, yEnd); - - this.currentPath_.push({ type: arcType, - x: p.x, - y: p.y, - radius: aRadius, - xStart: pStart.x, - yStart: pStart.y, - xEnd: pEnd.x, - yEnd: pEnd.y - }); - - }; - - // contextPrototype.rect = function(aX, aY, aWidth, aHeight) { - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // }; - - // contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.stroke(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.fill(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { - // var gradient = new CanvasGradient_('gradient'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // return gradient; - // }; - - // contextPrototype.createRadialGradient = function(aX0, aY0, aR0, - // aX1, aY1, aR1) { - // var gradient = new CanvasGradient_('gradientradial'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.r0_ = aR0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // gradient.r1_ = aR1; - // return gradient; - // }; - - // contextPrototype.drawImage = function(image, var_args) { - // var dx, dy, dw, dh, sx, sy, sw, sh; - - // // to find the original width we overide the width and height - // var oldRuntimeWidth = image.runtimeStyle.width; - // var oldRuntimeHeight = image.runtimeStyle.height; - // image.runtimeStyle.width = 'auto'; - // image.runtimeStyle.height = 'auto'; - - // // get the original size - // var w = image.width; - // var h = image.height; - - // // and remove overides - // image.runtimeStyle.width = oldRuntimeWidth; - // image.runtimeStyle.height = oldRuntimeHeight; - - // if (arguments.length == 3) { - // dx = arguments[1]; - // dy = arguments[2]; - // sx = sy = 0; - // sw = dw = w; - // sh = dh = h; - // } else if (arguments.length == 5) { - // dx = arguments[1]; - // dy = arguments[2]; - // dw = arguments[3]; - // dh = arguments[4]; - // sx = sy = 0; - // sw = w; - // sh = h; - // } else if (arguments.length == 9) { - // sx = arguments[1]; - // sy = arguments[2]; - // sw = arguments[3]; - // sh = arguments[4]; - // dx = arguments[5]; - // dy = arguments[6]; - // dw = arguments[7]; - // dh = arguments[8]; - // } else { - // throw Error('Invalid number of arguments'); - // } - - // var d = getCoords(this, dx, dy); - - // var w2 = sw / 2; - // var h2 = sh / 2; - - // var vmlStr = []; - - // var W = 10; - // var H = 10; - - // // For some reason that I've now forgotten, using divs didn't work - // vmlStr.push(' ' , - // '', - // ''); - - // this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); - // }; - - contextPrototype.stroke = function (aFill) { - var lineStr = []; - var lineOpen = false; - - var W = 10; - var H = 10; - - lineStr.push(''); - - if (!aFill) { - appendStroke(this, lineStr); - } else { - appendFill(this, lineStr, min, max); - } - - lineStr.push(''); - - this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - }; - - function appendStroke(ctx, lineStr) { - var a = processStyle(ctx.strokeStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - var lineWidth = ctx.lineScale_ * ctx.lineWidth; - - // VML cannot correctly render a line if the width is less than 1px. - // In that case, we dilute the color to make the line look thinner. - if (lineWidth < 1) { - opacity *= lineWidth; - } - - lineStr.push( - '' - ); - } - - function appendFill(ctx, lineStr, min, max) { - var fillStyle = ctx.fillStyle; - var arcScaleX = ctx.arcScaleX_; - var arcScaleY = ctx.arcScaleY_; - var width = max.x - min.x; - var height = max.y - min.y; - // if (fillStyle instanceof CanvasGradient_) { - // // TODO: Gradients transformed with the transformation matrix. - // var angle = 0; - // var focus = {x: 0, y: 0}; - - // // additional offset - // var shift = 0; - // // scale factor for offset - // var expansion = 1; - - // if (fillStyle.type_ == 'gradient') { - // var x0 = fillStyle.x0_ / arcScaleX; - // var y0 = fillStyle.y0_ / arcScaleY; - // var x1 = fillStyle.x1_ / arcScaleX; - // var y1 = fillStyle.y1_ / arcScaleY; - // var p0 = getCoords(ctx, x0, y0); - // var p1 = getCoords(ctx, x1, y1); - // var dx = p1.x - p0.x; - // var dy = p1.y - p0.y; - // angle = Math.atan2(dx, dy) * 180 / Math.PI; - - // // The angle should be a non-negative number. - // if (angle < 0) { - // angle += 360; - // } - - // // Very small angles produce an unexpected result because they are - // // converted to a scientific notation string. - // if (angle < 1e-6) { - // angle = 0; - // } - // } else { - // var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); - // focus = { - // x: (p0.x - min.x) / width, - // y: (p0.y - min.y) / height - // }; - - // width /= arcScaleX * Z; - // height /= arcScaleY * Z; - // var dimension = m.max(width, height); - // shift = 2 * fillStyle.r0_ / dimension; - // expansion = 2 * fillStyle.r1_ / dimension - shift; - // } - - // // We need to sort the color stops in ascending order by offset, - // // otherwise IE won't interpret it correctly. - // var stops = fillStyle.colors_; - // stops.sort(function(cs1, cs2) { - // return cs1.offset - cs2.offset; - // }); - - // var length = stops.length; - // var color1 = stops[0].color; - // var color2 = stops[length - 1].color; - // var opacity1 = stops[0].alpha * ctx.globalAlpha; - // var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; - - // var colors = []; - // for (var i = 0; i < length; i++) { - // var stop = stops[i]; - // colors.push(stop.offset * expansion + shift + ' ' + stop.color); - // } - - // // When colors attribute is used, the meanings of opacity and o:opacity2 - // // are reversed. - // lineStr.push(''); - // } else if (fillStyle instanceof CanvasPattern_) { - // if (width && height) { - // var deltaLeft = -min.x; - // var deltaTop = -min.y; - // lineStr.push(''); - // } - // } else { - var a = processStyle(ctx.fillStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - lineStr.push(''); - // } - } - - contextPrototype.fill = function () { - this.stroke(true); - }; - - contextPrototype.closePath = function () { - this.currentPath_.push({ type: 'close' }); - }; - - function getCoords(ctx, aX, aY) { - var m = ctx.m_; - return { - x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, - y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 - }; - }; - - contextPrototype.save = function () { - var o = {}; - copyState(this, o); - this.aStack_.push(o); - this.mStack_.push(this.m_); - this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); - }; - - contextPrototype.restore = function () { - if (this.aStack_.length) { - copyState(this.aStack_.pop(), this); - this.m_ = this.mStack_.pop(); - } - }; - - function matrixIsFinite(m) { - return isFinite(m[0][0]) && isFinite(m[0][1]) && - isFinite(m[1][0]) && isFinite(m[1][1]) && - isFinite(m[2][0]) && isFinite(m[2][1]); - } - - function setM(ctx, m, updateLineScale) { - if (!matrixIsFinite(m)) { - return; - } - ctx.m_ = m; - - if (updateLineScale) { - // Get the line scale. - // Determinant of this.m_ means how much the area is enlarged by the - // transformation. So its square root can be used as a scale factor - // for width. - var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; - ctx.lineScale_ = sqrt(abs(det)); - } - } - - contextPrototype.translate = function (aX, aY) { - var m1 = [ - [1, 0, 0], - [0, 1, 0], - [aX, aY, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), false); - }; - - // contextPrototype.rotate = function(aRot) { - // var c = mc(aRot); - // var s = ms(aRot); - - // var m1 = [ - // [c, s, 0], - // [-s, c, 0], - // [0, 0, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), false); - // }; - - contextPrototype.scale = function (aX, aY) { - this.arcScaleX_ *= aX; - this.arcScaleY_ *= aY; - var m1 = [ - [aX, 0, 0], - [0, aY, 0], - [0, 0, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), true); - }; - - // contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { - // var m1 = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), true); - // }; - - // contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { - // var m = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, m, true); - // }; - - /** - * The text drawing function. - * The maxWidth argument isn't taken in account, since no browser supports - * it yet. - */ - // contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { - // var m = this.m_, - // delta = 1000, - // left = 0, - // right = delta, - // offset = {x: 0, y: 0}, - // lineStr = []; - - // var fontStyle = getComputedStyle(processFontStyle(this.font), - // this.element_); - - // var fontStyleString = buildStyle(fontStyle); - - // var elementStyle = this.element_.currentStyle; - // var textAlign = this.textAlign.toLowerCase(); - // switch (textAlign) { - // case 'left': - // case 'center': - // case 'right': - // break; - // case 'end': - // textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; - // break; - // case 'start': - // textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; - // break; - // default: - // textAlign = 'left'; - // } - - // // 1.75 is an arbitrary number, as there is no info about the text baseline - // switch (this.textBaseline) { - // case 'hanging': - // case 'top': - // offset.y = fontStyle.size / 1.75; - // break; - // case 'middle': - // break; - // default: - // case null: - // case 'alphabetic': - // case 'ideographic': - // case 'bottom': - // offset.y = -fontStyle.size / 2.25; - // break; - // } - - // switch(textAlign) { - // case 'right': - // left = delta; - // right = 0.05; - // break; - // case 'center': - // left = right = delta / 2; - // break; - // } - - // var d = getCoords(this, x + offset.x, y + offset.y); - - // lineStr.push(''); - - // if (stroke) { - // appendStroke(this, lineStr); - // } else { - // // TODO: Fix the min and max params. - // appendFill(this, lineStr, {x: -left, y: 0}, - // {x: right, y: fontStyle.size}); - // } - - // var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + - // m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; - - // var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); - - // lineStr.push('', - // '', - // ''); - - // this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - // }; - - // contextPrototype.fillText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, false); - // }; - - // contextPrototype.strokeText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, true); - // }; - - // contextPrototype.measureText = function(text) { - // if (!this.textMeasureEl_) { - // var s = ''; - // this.element_.insertAdjacentHTML('beforeEnd', s); - // this.textMeasureEl_ = this.element_.lastChild; - // } - // var doc = this.element_.ownerDocument; - // this.textMeasureEl_.innerHTML = ''; - // this.textMeasureEl_.style.font = this.font; - // // Don't use innerHTML or innerText because they allow markup/whitespace. - // this.textMeasureEl_.appendChild(doc.createTextNode(text)); - // return {width: this.textMeasureEl_.offsetWidth}; - // }; - - /******** STUBS ********/ - // contextPrototype.clip = function() { - // // TODO: Implement - // }; - - // contextPrototype.arcTo = function() { - // // TODO: Implement - // }; - - // contextPrototype.createPattern = function(image, repetition) { - // return new CanvasPattern_(image, repetition); - // }; - - // // Gradient / Pattern Stubs - // function CanvasGradient_(aType) { - // this.type_ = aType; - // this.x0_ = 0; - // this.y0_ = 0; - // this.r0_ = 0; - // this.x1_ = 0; - // this.y1_ = 0; - // this.r1_ = 0; - // this.colors_ = []; - // } - - // CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { - // aColor = processStyle(aColor); - // this.colors_.push({offset: aOffset, - // color: aColor.color, - // alpha: aColor.alpha}); - // }; - - // function CanvasPattern_(image, repetition) { - // assertImageIsValid(image); - // switch (repetition) { - // case 'repeat': - // case null: - // case '': - // this.repetition_ = 'repeat'; - // break - // case 'repeat-x': - // case 'repeat-y': - // case 'no-repeat': - // this.repetition_ = repetition; - // break; - // default: - // throwException('SYNTAX_ERR'); - // } - - // this.src_ = image.src; - // this.width_ = image.width; - // this.height_ = image.height; - // } - - function throwException(s) { - throw new DOMException_(s); - } - - // function assertImageIsValid(img) { - // if (!img || img.nodeType != 1 || img.tagName != 'IMG') { - // throwException('TYPE_MISMATCH_ERR'); - // } - // if (img.readyState != 'complete') { - // throwException('INVALID_STATE_ERR'); - // } - // } - - function DOMException_(s) { - this.code = this[s]; - this.message = s + ': DOM Exception ' + this.code; - } - var p = DOMException_.prototype = new Error; - p.INDEX_SIZE_ERR = 1; - p.DOMSTRING_SIZE_ERR = 2; - p.HIERARCHY_REQUEST_ERR = 3; - p.WRONG_DOCUMENT_ERR = 4; - p.INVALID_CHARACTER_ERR = 5; - p.NO_DATA_ALLOWED_ERR = 6; - p.NO_MODIFICATION_ALLOWED_ERR = 7; - p.NOT_FOUND_ERR = 8; - p.NOT_SUPPORTED_ERR = 9; - p.INUSE_ATTRIBUTE_ERR = 10; - p.INVALID_STATE_ERR = 11; - p.SYNTAX_ERR = 12; - p.INVALID_MODIFICATION_ERR = 13; - p.NAMESPACE_ERR = 14; - p.INVALID_ACCESS_ERR = 15; - p.VALIDATION_ERR = 16; - p.TYPE_MISMATCH_ERR = 17; - - // set up externs - G_vmlCanvasManager = G_vmlCanvasManager_; - CanvasRenderingContext2D = CanvasRenderingContext2D_; - //CanvasGradient = CanvasGradient_; - //CanvasPattern = CanvasPattern_; - DOMException = DOMException_; - })(); - -} // if - -/*! JsRender v1.0pre: http://github.com/BorisMoore/jsrender */ -/* - * Optimized version of jQuery Templates, for rendering to string. - * Does not require jQuery, or HTML DOM - * Integrates with JsViews (http://github.com/BorisMoore/jsviews) - * Copyright 2012, Boris Moore - * Released under the MIT License. - */ -// informal pre beta commit counter: 3 - -this.jsviews || this.jQuery && jQuery.views || (function( window, undefined ) { - -//========================== Top-level vars ========================== - -var versionNumber = "v1.0pre", - - $, rTag, rTmplString, extend, - sub = {}, - FALSE = false, TRUE = true, - jQuery = window.jQuery, - - rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // nil object helper view viewProperty pathTokens leafToken string - - rParams = /(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - - rNewLine = /\r?\n/g, - rUnescapeQuotes = /\\(['"])/g, - rEscapeQuotes = /\\?(['"])/g, - rBuildHash = /\x08(~)?([^\x08]+)\x08/g, - - autoViewKey = 0, - autoTmplName = 0, - escapeMapForHtml = { - "&": "&", - "<": "<", - ">": ">" - }, - tmplAttr = "data-jsv-tmpl", - fnDeclStr = "var j=j||" + (jQuery ? "jQuery." : "js") + "views,", - htmlSpecialChar = /[\x00"&'<>]/g, - slice = Array.prototype.slice, - - render = {}, - - // jsviews object ($.views if jQuery is loaded) - jsv = { - jsviews: versionNumber, - sub: sub, // subscription, e.g. JsViews integration - debugMode: TRUE, - err: function( e ) { - return jsv.debugMode ? ("
              Error: " + (e.message || e) + ". ") : '""'; - }, - tmplFn: tmplFn, - render: render, - templates: templates, - tags: tags, - helpers: helpers, - converters: converters, - View: View, - convert: convert, - delimiters: setDelimiters, - tag: renderTag - }; - -//========================== Top-level functions ========================== - -//=================== -// jsviews.delimiters -//=================== - -function setDelimiters( openChars, closeChars ) { - // Set the tag opening and closing delimiters. Default is "{{" and "}}" - // openChar, closeChars: opening and closing strings, each with two characters - var firstOpenChar = "\\" + openChars.charAt( 0 ), // Escape the characters - since they could be regex special characters - secondOpenChar = "\\" + openChars.charAt( 1 ), - firstCloseChar = "\\" + closeChars.charAt( 0 ), - secondCloseChar = "\\" + closeChars.charAt( 1 ); - // Build regex with new delimiters - jsv.rTag = rTag // make rTag available to JsViews (or other components) for parsing binding expressions - = secondOpenChar - // tag (followed by / space or }) or colon or html or code - + "(?:(?:(\\w+(?=[\\/\\s" + firstCloseChar + "]))|(?:(\\w+)?(:)|(>)|(\\*)))" - // params - + "\\s*((?:[^" + firstCloseChar + "]|" + firstCloseChar + "(?!" + secondCloseChar + "))*?)" - // slash or closeBlock - + "(\\/)?|(?:\\/(\\w+)))" - // }} - + firstCloseChar; - - // Default rTag: tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/\s\}]))|(?:(\w+)?(:)|(>)|(\*)))\s*((?:[^}]|}(?!\}))*?)(\/)?|(?:\/(\w+)))}} - - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - rTag = new RegExp( firstOpenChar + rTag + secondCloseChar, "g" ); - rTmplString = new RegExp( "<.*>|" + openChars + ".*" + closeChars ); - return this; -} - -//================= -// View.hlp -//================= - -function getHelper( helper ) { - // Helper method called as view.hlp() from compiled template, for helper functions or template parameters ~foo - var view = this, - tmplHelpers = view.tmpl.helpers || {}; - helper = (view.ctx[ helper ] !== undefined ? view.ctx : tmplHelpers[ helper ] !== undefined ? tmplHelpers : helpers[ helper ] !== undefined ? helpers : {})[ helper ]; - return typeof helper !== "function" ? helper : function() { - return helper.apply(view, arguments); - }; -} - -//================= -// jsviews.convert -//================= - -function convert( converter, view, text ) { - var tmplConverters = view.tmpl.converters; - converter = tmplConverters && tmplConverters[ converter ] || converters[ converter ]; - return converter ? converter.call( view, text ) : text; -} - -//================= -// jsviews.tag -//================= - -function renderTag( tag, parentView, converter, content, tagObject ) { - // Called from within compiled template function, to render a nested tag - // Returns the rendered tag - tagObject.props = tagObject.props || {}; - var ret, - tmpl = tagObject.props.tmpl, - tmplTags = parentView.tmpl.tags, - nestedTemplates = parentView.tmpl.templates, - args = arguments, - tagFn = tmplTags && tmplTags[ tag ] || tags[ tag ]; - - if ( !tagFn ) { - return ""; - } - // Set the tmpl property to the content of the block tag, unless set as an override property on the tag - content = content && parentView.tmpl.tmpls[ content - 1 ]; - tmpl = tmpl || content || undefined; - tagObject.tmpl = - "" + tmpl === tmpl // if a string - ? nestedTemplates && nestedTemplates[ tmpl ] || templates[ tmpl ] || templates( tmpl ) - : tmpl; - - tagObject.isTag = TRUE; - tagObject.converter = converter; - tagObject.view = parentView; - tagObject.renderContent = renderContent; - if ( parentView.ctx ) { - extend( tagObject.ctx, parentView.ctx); - } - - ret = tagFn.apply( tagObject, args.length > 5 ? slice.call( args, 5 ) : [] ); - return ret || ( ret == undefined ? "" : ret.toString()); // (If ret is the value 0 or false, will render to string) -} - -//================= -// View constructor -//================= - -function View( context, path, parentView, data, template, index ) { - // Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded) - var views = parentView.views, -// TODO: add this, as part of smart re-linking on existing content ($.link method), or remove completely -// self = parentView.views[ index ]; -// if ( !self ) { ... } - self = { - tmpl: template, - path: path, - parent: parentView, - data: data, - ctx: context, - views: $.isArray( data ) ? [] : {}, - hlp: getHelper - }; - - if ( $.isArray( views )) { - views.splice( - self.index = index !== undefined - ? index - : views.length, 0, self - ); - } else { - views[ self.index = "_" + autoViewKey++ ] = self; - } - return self; -} - -//================= -// Registration -//================= - -function addToStore( self, store, name, item, process ) { - // Add item to named store such as templates, helpers, converters... - var key, onStore; - if ( name && typeof name === "object" && !name.nodeType ) { - // If name is a map, iterate over map and call store for key - for ( key in name ) { - store( key, name[ key ]); - } - return self; - } - if ( !name || item === undefined ) { - if ( process ) { - item = process( undefined, item || name ); - } - } else if ( "" + name === name ) { // name must be a string - if ( item === null ) { - // If item is null, delete this entry - delete store[name]; - } else if ( item = process ? process( name, item ) : item ) { - store[ name ] = item; - } - } - if ( onStore = sub.onStoreItem ) { - // e.g. JsViews integration - onStore( store, name, item, process ); - } - return item; -} - -function templates( name, tmpl ) { - // Register templates - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, templates, name, tmpl, compile ); -} - -function tags( name, tagFn ) { - // Register template tags - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, tags, name, tagFn ); -} - -function helpers( name, helperFn ) { - // Register helper functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.helpers( name, helperFn ) or $.view.helpers({ name: helperFn, ... }) to add additional helpers to the registered helpers collection. - // Getter: Use var helperFn = $.views.helpers( name ) or $.views.helpers[name] or $.views.helpers.name to return the function. - // Remove: Use $.view.helpers( name, null ) to remove a registered helper function from $.view.helpers. - // Within a template, access the helper using the syntax: {{... ~myHelper(...) ...}}. - return addToStore( this, helpers, name, helperFn ); -} - -function converters( name, converterFn ) { - // Register converter functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.converters( name, converterFn ) or $.view.converters({ name: converterFn, ... }) to add additional converters to the registered converters collection. - // Getter: Use var converterFn = $.views.converters( name ) or $.views.converters[name] or $.views.converters.name to return the converter function. - // Remove: Use $.view.converters( name, null ) to remove a registered converter from $.view.converters. - // Within a template, access the converter using the syntax: {{myConverter:...}}. - return addToStore( this, converters, name, converterFn ); -} - -//================= -// renderContent -//================= - -function renderContent( data, context, parentView, path, index ) { - // Render template against data as a tree of subviews (nested template), or as a string (top-level template). - // tagName parameter for internal use only. Used for rendering templates registered as tags (which may have associated presenter objects) - var i, l, dataItem, newView, itemWrap, itemsWrap, itemResult, parentContext, tmpl, layout, - props = {}, - swapContent = index === TRUE, - self = this, - result = ""; - - if ( self.isTag ) { - // This is a call from renderTag - tmpl = self.tmpl; - context = context || self.ctx; - parentView = parentView || self.view; - path = path || self.path; - index = index || self.index; - props = self.props; - } else { - tmpl = self.jquery && self[0] // This is a call $.fn.render - || self; // This is a call from tmpl.render - } - parentView = parentView || jsv.topView; - parentContext = parentView.ctx; - layout = tmpl.layout; - if ( data === parentView ) { - // Inherit the data from the parent view. - // This may be the contents of an {{if}} block - data = parentView.data; - layout = TRUE; - } - - // Set additional context on views created here, (as modified context inherited from the parent, and be inherited by child views) - // Note: If no jQuery, extend does not support chained copies - so limit extend() to two parameters - context = (context && context === parentContext) - ? parentContext - : (parentContext - // if parentContext, make copy - ? ((parentContext = extend( {}, parentContext ), context) - // If context, merge context with copied parentContext - ? extend( parentContext, context ) - : parentContext) - // if no parentContext, use context, or default to {} - : context || {}); - - if ( props.link === FALSE ) { - // Override inherited value of link by an explicit setting in props: link=false - // The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect. - context.link = FALSE; - } - if ( !tmpl.fn ) { - tmpl = templates[ tmpl ] || templates( tmpl ); - } - itemWrap = context.link && sub.onRenderItem; - itemsWrap = context.link && sub.onRenderItems; - - if ( tmpl ) { - if ( $.isArray( data ) && !layout ) { - // Create a view for the array, whose child views correspond to each data item. - // (Note: if index and parentView are passed in along with parent view, treat as - // insert -e.g. from view.addViews - so parentView is already the view item for array) - newView = swapContent ? parentView : (index !== undefined && parentView) || View( context, path, parentView, data, tmpl, index ); - - for ( i = 0, l = data.length; i < l; i++ ) { - // Create a view for each data item. - dataItem = data[ i ]; - itemResult = tmpl.fn( dataItem, View( context, path, newView, dataItem, tmpl, (index||0) + i ), jsv ); - result += itemWrap ? itemWrap( itemResult, props ) : itemResult; - } - } else { - // Create a view for singleton data object. - newView = swapContent ? parentView : View( context, path, parentView, data, tmpl, index ); - result += (data || layout) ? tmpl.fn( data, newView, jsv ) : ""; - } - parentView.topKey = newView.index; - return itemsWrap ? itemsWrap( result, path, newView.index, tmpl, props ) : result; - } - return ""; // No tmpl. Could throw... -} - -//=========================== -// Build and compile template -//=========================== - -// Generate a reusable function that will serve to render a template against data -// (Compile AST then build template function) - -function syntaxError() { - throw "Syntax error"; -} - -function tmplFn( markup, tmpl, bind ) { - // Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes - // Used for compiling templates, and also by JsViews to build functions for data link expressions - var newNode, node, i, l, code, hasTag, hasEncoder, getsValue, hasConverter, hasViewPath, tag, converter, params, hash, nestedTmpl, allowCode, - tmplOptions = tmpl ? { - allowCode: allowCode = tmpl.allowCode, - debug: tmpl.debug - } : {}, - nested = tmpl && tmpl.tmpls, - astTop = [], - loc = 0, - stack = [], - content = astTop, - current = [,,,astTop], - nestedIndex = 0; - - //==== nested functions ==== - function pushPreceedingContent( shift ) { - shift -= loc; - if ( shift ) { - content.push( markup.substr( loc, shift ).replace( rNewLine, "\\n" )); - } - } - - function parseTag( all, tagName, converter, colon, html, code, params, slash, closeBlock, index ) { - // tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(?:(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - // Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, contentMarkup ] - if ( html ) { - colon = ":"; - converter = "html"; - } - var hash = "", - passedCtx = "", - block = !slash && !colon; // Block tag if not self-closing and not {{:}} or {{>}} (special case) - - //==== nested helper function ==== - - tagName = tagName || colon; - pushPreceedingContent( index ); - loc = index + all.length; // location marker - parsed up to here - if ( code ) { - if ( allowCode ) { - content.push([ "*", params.replace( rUnescapeQuotes, "$1" ) ]); - } - } else if ( tagName ) { - if ( tagName === "else" ) { - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - content = current[ 3 ]; - block = TRUE; - } - params = (params - ? parseParams( params, bind ) - .replace( rBuildHash, function( all, isCtx, keyValue ) { - if ( isCtx ) { - passedCtx += keyValue + ","; - } else { - hash += keyValue + ","; - } - return ""; - }) - : ""); - hash = hash.slice( 0, -1 ); - params = params.slice( 0, -1 ); - newNode = [ - tagName, - converter || "", - params, - block && [], - "{" + (hash ? ("props:{" + hash + "},"): "") + "path:'" + params + "'" + (passedCtx ? ",ctx:{" + passedCtx.slice( 0, -1 ) + "}" : "") + "}" - ]; - if ( block ) { - stack.push( current ); - current = newNode; - current[ 5 ] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag - } - content.push( newNode ); - } else if ( closeBlock ) { - //if ( closeBlock !== current[ 0 ]) { - // throw "unmatched close tag: /" + closeBlock + ". Expected /" + current[ 0 ]; - //} - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - } - if ( !current ) { - throw "Expected block tag"; - } - content = current[ 3 ]; - } - //==== /end of nested functions ==== - - markup = markup.replace( rEscapeQuotes, "\\$1" ); - - // Build the AST (abstract syntax tree) under astTop - markup.replace( rTag, parseTag ); - - pushPreceedingContent( markup.length ); - - // Use the AST (astTop) to build the template function - l = astTop.length; - code = (l ? "" : '"";'); - - for ( i = 0; i < l; i++ ) { - // AST nodes: [ tagName, converter, params, content, hash, contentMarkup ] - node = astTop[ i ]; - if ( node[ 0 ] === "*" ) { - code = code.slice( 0, i ? -1 : -3 ) + ";" + node[ 1 ] + (i + 1 < l ? "ret+=" : ""); - } else if ( "" + node === node ) { // type string - code += '"' + node + '"+'; - } else { - tag = node[ 0 ]; - converter = node[ 1 ]; - params = node[ 2 ]; - content = node[ 3 ]; - hash = node[ 4 ]; - markup = node[ 5 ]; - if ( content ) { - // Create template object for nested template - nestedTmpl = TmplObject( markup, tmplOptions, tmpl, nestedIndex++ ); - // Compile to AST and then to compiled function - tmplFn( markup, nestedTmpl); - nested.push( nestedTmpl ); - } - hasViewPath = hasViewPath || hash.indexOf( "view" ) > -1; - code += (tag === ":" - ? (converter === "html" - ? (hasEncoder = TRUE, "e(" + params) - : converter - ? (hasConverter = TRUE, 'c("' + converter + '",view,' + params) - : (getsValue = TRUE, "((v=" + params + ')!=u?v:""') - ) - : (hasTag = TRUE, 't("' + tag + '",view,"' + (converter || "") + '",' - + (content ? nested.length : '""') // For block tags, pass in the key (nested.length) to the nested content template - + "," + hash + (params ? "," : "") + params)) - + ")+"; - } - } - code = new Function( "data, view, j, b, u", fnDeclStr - + (getsValue ? "v," : "") - + (hasTag ? "t=j.tag," : "") - + (hasConverter ? "c=j.convert," : "") - + (hasEncoder ? "e=j.converters.html," : "") - + "ret; try{\n\n" - + (tmplOptions.debug ? "debugger;" : "") - + (allowCode ? 'ret=' : 'return ') - + code.slice( 0, -1 ) + ";\n\n" - + (allowCode ? "return ret;" : "") - + "}catch(e){return j.err(e);}" - ); - - // Include only the var references that are needed in the code - if ( tmpl ) { - tmpl.fn = code; - tmpl.useVw = hasConverter || hasViewPath || hasTag; - } - return code; -} - -function parseParams( params, bind ) { - var named, - fnCall = {}, - parenDepth = 0, - quoted = FALSE, // boolean for string content in double quotes - aposed = FALSE; // or in single quotes - - function parseTokens( all, lftPrn0, lftPrn, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, prn2, space ) { - // rParams = /(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn path operator err eq path2 prn comma lftPrn3 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - operator = operator || ""; - lftPrn = lftPrn || lftPrn0 || lftPrn2; - path = path || path2; - prn = prn || prn2 || ""; - operator = operator || ""; - - function parsePath( all, object, helper, view, viewProperty, pathTokens, leafToken ) { - // rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // object helper view viewProperty pathTokens leafToken string - if ( object ) { - var ret = (helper - ? 'view.hlp("' + helper + '")' - : view - ? "view" - : "data") - + (leafToken - ? (viewProperty - ? "." + viewProperty - : helper - ? "" - : (view ? "" : "." + object) - ) + (pathTokens || "") - : (leafToken = helper ? "" : view ? viewProperty || "" : object, "")); - - if ( bind && prn !== "(" ) { - ret = "b(" + ret + ',"' + leafToken + '")'; - } - return ret + (leafToken ? "." + leafToken : ""); - } - return all; - } - - if ( err ) { - syntaxError(); - } else { - return (aposed - // within single-quoted string - ? (aposed = !apos, (aposed ? all : '"')) - : quoted - // within double-quoted string - ? (quoted = !quot, (quoted ? all : '"')) - : - ( - (lftPrn - ? (parenDepth++, lftPrn) - : "") - + (space - ? (parenDepth - ? "" - : named - ? (named = FALSE, "\b") - : "," - ) - : eq - // named param - ? (parenDepth && syntaxError(), named = TRUE, '\b' + path + ':') - : path - // path - ? (path.replace( rPath, parsePath ) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : operator) - ) - : operator - ? all - : rtPrn - // function - ? ((fnCall[ parenDepth-- ] = FALSE, rtPrn) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : "") - ) - : comma - ? (fnCall[ parenDepth ] || syntaxError(), ",") // We don't allow top-level literal arrays or objects - : lftPrn0 - ? "" - : (aposed = apos, quoted = quot, '"') - )) - ); - } - } - params = (params + " " ).replace( rParams, parseTokens ); - return params; -} - -function compile( name, tmpl, parent, options ) { - // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object - // options is the set of template properties, c - var tmplOrMarkup, elem, key, nested, nestedItem; - - //==== nested functions ==== - function tmplOrMarkupFromStr( value ) { - // If value is of type string - treat as selector, or name of compiled template - // Return the template object, if already compiled, or the markup string - - if ( ("" + value === value) || value.nodeType > 0 ) { - // If selector is valid and returns at least one element, get first element - elem = value.nodeType > 0 ? value : !rTmplString.test( value ) && jQuery && jQuery( value )[0]; - if ( elem && elem.type ) { - // It is a script element - // Create a name for data linking if none provided - value = templates[ elem.getAttribute( tmplAttr )]; - if ( !value ) { - // Not already compiled and cached, so compile and cache the name - name = name || "_" + autoTmplName++; - elem.setAttribute( tmplAttr, name ); - value = compile( name, elem.innerHTML, parent, options ); // Use tmpl as options - templates[ name ] = value; - } - } - return value; - } - // If value is not a string or dom element, return undefined - } - - //==== Compile the template ==== - tmplOrMarkup = tmplOrMarkupFromStr( tmpl ); - - // If tmpl is a template object, use it for options - options = options || (tmpl.markup ? tmpl : {}); - options.name = name; - nested = options.templates; - - // If tmpl is not a markup string or a selector string, then it must be a template object - // In that case, get it from the markup property of the object - if ( !tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr( tmpl.markup ))) { - if ( tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode )) { - // if the string references a compiled template object, but the debug or allowCode props are different, need to recompile - tmplOrMarkup = tmplOrMarkup.markup; - } - } - if ( tmplOrMarkup !== undefined ) { - if ( name && !parent ) { - render[ name ] = function() { - return tmpl.render.apply( tmpl, arguments ); - }; - } - if ( tmplOrMarkup.fn || tmpl.fn ) { - // tmpl is already compiled, so use it, or if different name is provided, clone it - if ( tmplOrMarkup.fn ) { - if ( name && name !== tmplOrMarkup.name ) { - tmpl = extend( extend( {}, tmplOrMarkup ), options); - } else { - tmpl = tmplOrMarkup; - } - } - } else { - // tmplOrMarkup is a markup string, not a compiled template - // Create template object - tmpl = TmplObject( tmplOrMarkup, options, parent, 0 ); - // Compile to AST and then to compiled function - tmplFn( tmplOrMarkup, tmpl ); - } - for ( key in nested ) { - // compile nested template declarations - nestedItem = nested[ key ]; - if ( nestedItem.name !== key ) { - nested[ key ] = compile( key, nestedItem, tmpl ); - } - } - return tmpl; - } -} -//==== /end of function compile ==== - -function TmplObject( markup, options, parent, index ) { - // Template object constructor - - // nested helper function - function extendStore( storeName ) { - if ( parent[ storeName ]) { - // Include parent items except if overridden by item of same name in options - tmpl[ storeName ] = extend( extend( {}, parent[ storeName ] ), options[ storeName ] ); - } - } - - options = options || {}; - var tmpl = { - markup: markup, - tmpls: [], - links: [], - render: renderContent - }; - if ( parent ) { - if ( parent.templates ) { - tmpl.templates = extend( extend( {}, parent.templates ), options.templates ); - } - tmpl.parent = parent; - tmpl.name = parent.name + "[" + index + "]"; - tmpl.index = index; - } - - extend( tmpl, options ); - if ( parent ) { - extendStore( "templates" ); - extendStore( "tags" ); - extendStore( "helpers" ); - extendStore( "converters" ); - } - return tmpl; -} - -//========================== Initialize ========================== - -if ( jQuery ) { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is loaded, so make $ the jQuery object - $ = jQuery; - $.templates = templates; - $.render = render; - $.views = jsv; - $.fn.render = renderContent; - -} else { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is not loaded. - - $ = window.jsviews = jsv; - $.extend = function( target, source ) { - var name; - target = target || {}; - for ( name in source ) { - target[ name ] = source[ name ]; - } - return target; - }; - - $.isArray = Array && Array.isArray || function( obj ) { - return Object.prototype.toString.call( obj ) === "[object Array]"; - }; -} - -extend = $.extend; - -jsv.topView = { views: {}, tmpl: {}, hlp: getHelper, ctx: jsv.helpers }; - -function replacerForHtml( ch ) { - // Original code from Mike Samuel - return escapeMapForHtml[ ch ] - // Intentional assignment that caches the result of encoding ch. - || (escapeMapForHtml[ ch ] = "&#" + ch.charCodeAt( 0 ) + ";"); -} - -//========================== Register tags ========================== - -tags({ - "if": function() { - var ifTag = this, - view = ifTag.view; - - view.onElse = function( tagObject, args ) { - var i = 0, - l = args.length; - - while ( l && !args[ i++ ]) { - // Only render content if args.length === 0 (i.e. this is an else with no condition) or if a condition argument is truey - if ( i === l ) { - return ""; - } - } - view.onElse = undefined; // If condition satisfied, so won't run 'else'. - tagObject.path = ""; - return tagObject.renderContent( view ); - // Test is satisfied, so render content, while remaining in current data context - // By passing the view, we inherit data context from the parent view, and the content is treated as a layout template - // (so if the data is an array, it will not iterate over the data - }; - return view.onElse( this, arguments ); - }, - "else": function() { - var view = this.view; - return view.onElse ? view.onElse( this, arguments ) : ""; - }, - "for": function() { - var i, - self = this, - result = "", - args = arguments, - l = args.length; - if ( self.props.layout ) { - self.tmpl.layout = TRUE; - } - for ( i = 0; i < l; i++ ) { - result += self.renderContent( args[ i ]); - } - return result; - }, - "=": function( value ) { - return value; - }, - "*": function( value ) { - return value; - } -}); - -//========================== Register global helpers ========================== - -// helpers({ // Global helper functions -// // TODO add any useful built-in helper functions -// }); - -//========================== Register converters ========================== - -converters({ - html: function( text ) { - // HTML encoding helper: Replace < > & and ' and " by corresponding entities. - // inspired by Mike Samuel - return text != undefined ? String( text ).replace( htmlSpecialChar, replacerForHtml ) : ""; - } -}); - -//========================== Define default delimiters ========================== -setDelimiters( "{{", "}}" ); - -})( this ); - -/*! - * jQuery Mousewheel 3.1.13 - * - * Copyright jQuery Foundation and other contributors - * Released under the MIT license - * http://jquery.org/license - */ - -(function (factory) { - if ( typeof define === 'function' && define.amd ) { - // AMD. Register as an anonymous module. - define(['jquery'], factory); - } else if (typeof exports === 'object') { - // Node/CommonJS style for Browserify - module.exports = factory; - } else { - // Browser globals - factory(jQuery); - } -}(function ($) { - - var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], - toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? - ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], - slice = Array.prototype.slice, - nullLowestDeltaTimeout, lowestDelta; - - if ( $.event.fixHooks ) { - for ( var i = toFix.length; i; ) { - $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; - } - } - - var special = $.event.special.mousewheel = { - version: '3.1.12', - - setup: function() { - if ( this.addEventListener ) { - for ( var i = toBind.length; i; ) { - this.addEventListener( toBind[--i], handler, false ); - } - } else { - this.onmousewheel = handler; - } - // Store the line height and page height for this particular element - $.data(this, 'mousewheel-line-height', special.getLineHeight(this)); - $.data(this, 'mousewheel-page-height', special.getPageHeight(this)); - }, - - teardown: function() { - if ( this.removeEventListener ) { - for ( var i = toBind.length; i; ) { - this.removeEventListener( toBind[--i], handler, false ); - } - } else { - this.onmousewheel = null; - } - // Clean up the data we added to the element - $.removeData(this, 'mousewheel-line-height'); - $.removeData(this, 'mousewheel-page-height'); - }, - - getLineHeight: function(elem) { - var $elem = $(elem), - $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent'](); - if (!$parent.length) { - $parent = $('body'); - } - return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16; - }, - - getPageHeight: function(elem) { - return $(elem).height(); - }, - - settings: { - adjustOldDeltas: true, // see shouldAdjustOldDeltas() below - normalizeOffset: true // calls getBoundingClientRect for each event - } - }; - - $.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); - }, - - unmousewheel: function(fn) { - return this.unbind('mousewheel', fn); - } - }); - - - function handler(event) { - var orgEvent = event || window.event, - args = slice.call(arguments, 1), - delta = 0, - deltaX = 0, - deltaY = 0, - absDelta = 0, - offsetX = 0, - offsetY = 0; - event = $.event.fix(orgEvent); - event.type = 'mousewheel'; - - // Old school scrollwheel delta - if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } - if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } - if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } - if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } - - // Firefox < 17 horizontal scrolling related to DOMMouseScroll event - if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { - deltaX = deltaY * -1; - deltaY = 0; - } - - // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy - delta = deltaY === 0 ? deltaX : deltaY; - - // New school wheel delta (wheel event) - if ( 'deltaY' in orgEvent ) { - deltaY = orgEvent.deltaY * -1; - delta = deltaY; - } - if ( 'deltaX' in orgEvent ) { - deltaX = orgEvent.deltaX; - if ( deltaY === 0 ) { delta = deltaX * -1; } - } - - // No change actually happened, no reason to go any further - if ( deltaY === 0 && deltaX === 0 ) { return; } - - // Need to convert lines and pages to pixels if we aren't already in pixels - // There are three delta modes: - // * deltaMode 0 is by pixels, nothing to do - // * deltaMode 1 is by lines - // * deltaMode 2 is by pages - if ( orgEvent.deltaMode === 1 ) { - var lineHeight = $.data(this, 'mousewheel-line-height'); - delta *= lineHeight; - deltaY *= lineHeight; - deltaX *= lineHeight; - } else if ( orgEvent.deltaMode === 2 ) { - var pageHeight = $.data(this, 'mousewheel-page-height'); - delta *= pageHeight; - deltaY *= pageHeight; - deltaX *= pageHeight; - } - - // Store lowest absolute delta to normalize the delta values - absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) ); - - if ( !lowestDelta || absDelta < lowestDelta ) { - lowestDelta = absDelta; - - // Adjust older deltas if necessary - if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { - lowestDelta /= 40; - } - } - - // Adjust older deltas if necessary - if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { - // Divide all the things by 40! - delta /= 40; - deltaX /= 40; - deltaY /= 40; - } - - // Get a whole, normalized value for the deltas - delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); - deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); - deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); - - // Normalise offsetX and offsetY properties - if ( special.settings.normalizeOffset && this.getBoundingClientRect ) { - var boundingRect = this.getBoundingClientRect(); - offsetX = event.clientX - boundingRect.left; - offsetY = event.clientY - boundingRect.top; - } - - // Add information to the event object - event.deltaX = deltaX; - event.deltaY = deltaY; - event.deltaFactor = lowestDelta; - event.offsetX = offsetX; - event.offsetY = offsetY; - // Go ahead and set deltaMode to 0 since we converted to pixels - // Although this is a little odd since we overwrite the deltaX/Y - // properties with normalized deltas. - event.deltaMode = 0; - - // Add event and delta to the front of the arguments - args.unshift(event, delta, deltaX, deltaY); - - // Clearout lowestDelta after sometime to better - // handle multiple device types that give different - // a different lowestDelta - // Ex: trackpad = 3 and mouse wheel = 120 - if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } - nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); - - return ($.event.dispatch || $.event.handle).apply(this, args); - } - - function nullLowestDelta() { - lowestDelta = null; - } - - function shouldAdjustOldDeltas(orgEvent, absDelta) { - // If this is an older event and the delta is divisable by 120, - // then we are assuming that the browser is treating this as an - // older mouse wheel event and that we should divide the deltas - // by 40 to try and get a more usable deltaFactor. - // Side note, this actually impacts the reported scroll distance - // in older browsers and can cause scrolling to be slower than native. - // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. - return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; - } - -})); - -/*! - * jQuery UI Widget 1.8.18 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ - -if ( ! $.widget ) { - -(function( $, undefined ) { - -// jQuery 1.4+ -if ( $.cleanData ) { - var _cleanData = $.cleanData; - $.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); - }; -} else { - var _remove = $.fn.remove; - $.fn.remove = function( selector, keepData ) { - return this.each(function() { - if ( !keepData ) { - if ( !selector || $.filter( selector, [ this ] ).length ) { - $( "*", this ).add( [ this ] ).each(function() { - try { - $( this ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - }); - } - } - return _remove.call( $(this), selector, keepData ); - }); - }; -} - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from -// $.each( basePrototype, function( key, val ) { -// if ( $.isPlainObject(val) ) { -// basePrototype[ key ] = $.extend( {}, val ); -// } -// }); - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = Array.prototype.slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - // prevent calls to internal methods - if ( isMethodCall && options.charAt( 0 ) === "_" ) { - return returnValue; - } - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ), - methodValue = instance && $.isFunction( instance[options] ) ? - instance[ options ].apply( instance, args ) : - instance; - // TODO: add this back in 1.9 and use $.error() (see #5972) -// if ( !instance ) { -// throw "cannot call methods on " + name + " prior to initialization; " + -// "attempted to call method '" + options + "'"; -// } -// if ( !$.isFunction( instance[options] ) ) { -// throw "no such method '" + options + "' for " + name + " widget instance"; -// } -// var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, name, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - // $.widget.bridge stores the plugin instance, but we do it anyway - // so that it's stored even before the _create function runs - $.data( element, this.widgetName, this ); - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - var self = this; - this.element.bind( "remove." + this.widgetName, function() { - self.destroy(); - }); - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: function() {}, - _init: function() {}, - - destroy: function() { - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - }, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - [ value ? "addClass" : "removeClass"]( - this.widgetBaseClass + "-disabled" + " " + - "ui-state-disabled" ) - .attr( "aria-disabled", value ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - - return !( $.isFunction(callback) && - callback.call( this.element[0], event, data ) === false || - event.isDefaultPrevented() ); - } -}; - -})( jQuery ); - -}; - - -(function ($, window, undefined) { - window.toStaticHTML = window.toStaticHTML || function ( x ) { return x; }; - - var pos_oo = Number.POSITIVE_INFINITY, - neg_oo = Number.NEGATIVE_INFINITY; - - $.geo = { - // - // utility functions - // - - _allCoordinates: function (geom) { - // return array of all positions in all geometries of geom - // not in JTS - var geometries = this._flatten(geom), - curGeom = 0, - result = []; - - for (; curGeom < geometries.length; curGeom++) { - var coordinates = geometries[curGeom].coordinates, - isArray = coordinates && $.isArray(coordinates[0]), - isDblArray = isArray && $.isArray(coordinates[0][0]), - isTriArray = isDblArray && $.isArray(coordinates[0][0][0]), - i, j, k; - - if (!isTriArray) { - if (!isDblArray) { - if (!isArray) { - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - for (k = 0; k < coordinates[i][j].length; k++) { - result.push(coordinates[i][j][k]); - } - } - } - } - return result; - }, - - _isGeodetic: function( coords ) { - // returns true if the first coordinate it can find is geodetic - - while ( $.isArray( coords ) ) { - if ( coords.length > 1 && ! $.isArray( coords[ 0 ] ) ) { - return ( coords[ 0 ] >= -180.001 && coords[ 0 ] <= 180.001 && coords[ 1 ] >= -90.001 && coords[ 1 ] <= 90.001 ); - } else { - coords = coords[ 0 ]; - } - } - - return false; - }, - - // - // bbox functions - // - - center: function (bbox, _ignoreGeo /* Internal Use Only */) { - // Envelope.centre in JTS - // bbox only, use centroid for geom - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return wasGeodetic ? $.geo.proj.toGeodetic(center) : center; - }, - - expandBy: function (bbox, dx, dy, _ignoreGeo /* Internal Use Only */) { - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - bbox = [bbox[0] - dx, bbox[1] - dy, bbox[2] + dx, bbox[3] + dy]; - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - height: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[3] - bbox[1]; - }, - - _in: function(bbox1, bbox2) { - return bbox1[0] <= bbox2[0] && - bbox1[1] <= bbox2[1] && - bbox1[2] >= bbox2[2] && - bbox1[3] >= bbox2[3]; - }, - - _bboxDisjoint: function( bbox1, bbox2 ) { - return bbox2[ 0 ] > bbox1[ 2 ] || - bbox2[ 2 ] < bbox1[ 0 ] || - bbox2[ 1 ] > bbox1[ 3 ] || - bbox2[ 3 ] < bbox1[ 1 ]; - }, - - include: function( bbox, value, _ignoreGeo /* Internal Use Only */ ) { - // similar to Envelope.expandToInclude in JTS - if ( !value || !$.isArray( value ) ) { - return bbox; - } - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox || value ) ) { - wasGeodetic = true; - } - - if ( !bbox ) { - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - } else if ( wasGeodetic ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - - if ( value.length === 2 ) { - value = [ value[ 0 ], value[ 1 ], value[ 0 ], value[ 1 ] ]; - } - - if ( $.geo.proj ) { - value = $.geo.proj.fromGeodetic( value ); - } - - bbox[0] = Math.min( value[ 0 ], bbox[ 0 ] ); - bbox[1] = Math.min( value[ 1 ], bbox[ 1 ] ); - bbox[2] = Math.max( value[ 2 ], bbox[ 2 ] ); - bbox[3] = Math.max( value[ 3 ], bbox[ 3 ] ); - - return wasGeodetic ? $.geo.proj.toGeodetic( bbox ) : bbox; - }, - - polygonize: function( bbox, _ignoreGeo /* Internal Use Only */ ) { - // adaptation of Polygonizer class in JTS for use with bboxes - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var polygon = { - type: "Polygon", - coordinates: [ [ - [ bbox[ 0 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 1 ] ] - ] ] - }; - - if ( wasGeodetic ) { - polygon.coordinates = $.geo.proj.toGeodetic( polygon.coordinates ); - } - - return polygon; - }, - - reaspect: function (bbox, ratio, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var width = this.width(bbox, true), - height = this.height(bbox, true), - center = this.center(bbox, true), - dx, dy; - - if (width !== 0 && height !== 0 && ratio > 0) { - if (width / height > ratio) { - dx = width / 2; - dy = dx / ratio; - } else { - dy = height / 2; - dx = dy * ratio; - } - - bbox = [center[0] - dx, center[1] - dy, center[0] + dx, center[1] + dy]; - } - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - recenter: function( bbox, center, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj ) { - if ( this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - if ( this._isGeodetic( center ) ) { - center = $.geo.proj.fromGeodetic(center); - } - } - - var halfWidth = ( bbox[ 2 ] - bbox[ 0 ] ) / 2, - halfHeight = ( bbox[ 3 ] - bbox[ 1 ] ) / 2; - - bbox = [ - center[ 0 ] - halfWidth, - center[ 1 ] - halfHeight, - center[ 0 ] + halfWidth, - center[ 1 ] + halfHeight - ]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - scaleBy: function ( bbox, scale, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var c = this.center(bbox, true), - dx = (bbox[2] - bbox[0]) * scale / 2, - dy = (bbox[3] - bbox[1]) * scale / 2; - - bbox = [c[0] - dx, c[1] - dy, c[0] + dx, c[1] + dy]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - width: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[2] - bbox[0]; - }, - - // - // geometry functions - // - - // bbox (Geometry.getEnvelope in JTS) - - bbox: function ( geom, _ignoreGeo /* Internal Use Only */ ) { - var result, wasGeodetic = false; - if ( !geom ) { - return undefined; - } else if ( geom.bbox ) { - result = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.bbox ) ) ? $.geo.proj.fromGeodetic( geom.bbox ) : geom.bbox; - } else { - result = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var coordinates = this._allCoordinates( geom ), - curCoord = 0; - - if ( coordinates.length === 0 ) { - return undefined; - } - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coordinates ) ) { - wasGeodetic = true; - coordinates = $.geo.proj.fromGeodetic( coordinates ); - } - - for ( ; curCoord < coordinates.length; curCoord++ ) { - result[0] = Math.min(coordinates[curCoord][0], result[0]); - result[1] = Math.min(coordinates[curCoord][1], result[1]); - result[2] = Math.max(coordinates[curCoord][0], result[2]); - result[3] = Math.max(coordinates[curCoord][1], result[3]); - } - } - - return wasGeodetic ? $.geo.proj.toGeodetic(result) : result; - }, - - // centroid - - centroid: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var c; //< temp storage for any coordinate during centroid op - - switch (geom.type) { - case "Point": - return $.extend({}, geom); - - case "LineString": - case "Polygon": - var a = 0, - coords = $.merge( [ ], geom.type === "Polygon" ? geom.coordinates[0] : geom.coordinates ), - i = 1, j, n, - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - c = [ 0, 0 ]; - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coords ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic(coords); - } - - //if (coords[0][0] != coords[coords.length - 1][0] || coords[0][1] != coords[coords.length - 1][1]) { - // coords.push(coords[0]); - //} - - for (; i <= coords.length; i++) { - j = i % coords.length; - - bbox[0] = Math.min(coords[j][0], bbox[0]); - bbox[1] = Math.min(coords[j][1], bbox[1]); - bbox[2] = Math.max(coords[j][0], bbox[2]); - bbox[3] = Math.max(coords[j][1], bbox[3]); - - n = (coords[i - 1][0] * coords[j][1]) - (coords[j][0] * coords[i - 1][1]); - a += n; - c[0] += (coords[i - 1][0] + coords[j][0]) * n; - c[1] += (coords[i - 1][1] + coords[j][1]) * n; - } - - if (a === 0) { - if (coords.length > 0) { - c[0] = Math.min( Math.max( coords[0][0], bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( coords[0][1], bbox[ 1 ] ), bbox[ 3 ] ); - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } else { - return undefined; - } - } - - a *= 3; - //c[0] /= a; - //c[1] /= a; - - c[0] = Math.min( Math.max( c[0] / a, bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( c[1] / a, bbox[ 1 ] ), bbox[ 3 ] ); - - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - - case "MultiPoint": - // should return center of mass for point cluster but just return first point for now - if ( geom.coordinates.length > 0 ) { - c = geom.coordinates[ 0 ]; - return { - type: "Point", - coordinates: [ c[ 0 ], c[ 1 ] ] - }; - } - break; - - case "MultiLineString": - case "MultiPolygon": - if ( geom.coordinates.length > 0 ) { - return this.centroid( { - type: geom.type.substr( 5 ), - coordinates: geom.coordinates[ 0 ] - }, _ignoreGeo ); - } - break; - - } - return undefined; - }, - - // contains - - contains: function (geom1, geom2) { - if (geom1.type !== "Polygon") { - return false; - } - - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1.coordinates, geom2.coordinates); - - case "LineString": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates); - - case "Polygon": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates[0]); - - default: - return false; - } - }, - - _containsPolygonPoint: function (polygonCoordinates, pointCoordinate) { - if (polygonCoordinates.length === 0 || polygonCoordinates[0].length < 4) { - return false; - } - - var rayCross = 0, - a = polygonCoordinates[0][0], - i = 1, - b, - x; - - for (; i < polygonCoordinates[0].length; i++) { - b = polygonCoordinates[0][i]; - - if ((a[1] <= pointCoordinate[1] && pointCoordinate[1] < b[1]) || (b[1] <= pointCoordinate[1] && pointCoordinate[1] < a[1]) && (pointCoordinate[0] < a[0] || pointCoordinate[0] < b[0])) { - x = a[0] + (b[0] - a[0]) * (pointCoordinate[1] - a[1]) / (b[1] - a[1]); - - if (x > pointCoordinate[0]) { - rayCross++; - } - } - - a = b; - } - - return rayCross % 2 === 1; - }, - - _containsPolygonLineString: function (polygonCoordinates, lineStringCoordinates) { - for (var i = 0; i < lineStringCoordinates.length; i++) { - if (!this._containsPolygonPoint(polygonCoordinates, lineStringCoordinates[i])) { - return false; - } - } - return true; - }, - - // distance - - distance: function ( geom1, geom2, _ignoreGeo /* Internal Use Only */ ) { - var geom1CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom1.coordinates ) ) ? $.geo.proj.fromGeodetic(geom1.coordinates) : geom1.coordinates, - geom2CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom2.coordinates ) ) ? $.geo.proj.fromGeodetic(geom2.coordinates) : geom2.coordinates; - - switch (geom1.type) { - case "Point": - switch (geom2.type) { - case "Point": - return this._distancePointPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "LineString": - return this._distanceLineStringPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "Polygon": - return this._containsPolygonPoint(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "LineString": - switch (geom2.type) { - case "Point": - return this._distanceLineStringPoint(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "LineString": - return this._distanceLineStringLineString(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "Polygon": - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "LineString": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected[0]) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected[0]); - default: - return undefined; - } - break; - } - }, - - _distancePointPoint: function (coordinate1, coordinate2) { - var dx = coordinate2[0] - coordinate1[0], - dy = coordinate2[1] - coordinate1[1]; - return Math.sqrt((dx * dx) + (dy * dy)); - }, - - _distanceLineStringPoint: function (lineStringCoordinates, pointCoordinate) { - var minDist = pos_oo; - - if (lineStringCoordinates.length > 0) { - var a = lineStringCoordinates[0], - - apx = pointCoordinate[0] - a[0], - apy = pointCoordinate[1] - a[1]; - - if (lineStringCoordinates.length === 1) { - return Math.sqrt(apx * apx + apy * apy); - } else { - for (var i = 1; i < lineStringCoordinates.length; i++) { - var b = lineStringCoordinates[i], - - abx = b[0] - a[0], - aby = b[1] - a[1], - bpx = pointCoordinate[0] - b[0], - bpy = pointCoordinate[1] - b[1], - - d = this._distanceSegmentPoint(abx, aby, apx, apy, bpx, bpy); - - if (d === 0) { - return 0; - } - - if (d < minDist) { - minDist = d; - } - - a = b; - apx = bpx; - apy = bpy; - } - } - } - - return Math.sqrt(minDist); - }, - - _distanceSegmentPoint: function (abx, aby, apx, apy, bpx, bpy) { - var dot1 = abx * apx + aby * apy; - - if (dot1 <= 0) { - return apx * apx + apy * apy; - } - - var dot2 = abx * abx + aby * aby; - - if (dot1 >= dot2) { - return bpx * bpx + bpy * bpy; - } - - return apx * apx + apy * apy - dot1 * dot1 / dot2; - }, - - _distanceLineStringLineString: function (lineStringCoordinates1, lineStringCoordinates2) { - var minDist = pos_oo; - for (var i = 0; i < lineStringCoordinates2.length; i++) { - minDist = Math.min(minDist, this._distanceLineStringPoint(lineStringCoordinates1, lineStringCoordinates2[i])); - } - return minDist; - }, - - // buffer - - _buffer: function( geom, distance, _ignoreGeo /* Internal Use Only */ ) { - var wasGeodetic = false, - coords = geom.coordinates; - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.coordinates ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic( geom.coordinates ); - } - - if ( geom.type === "Point" ) { - var resultCoords = [], - slices = 180, - i = 0, - a; - - for ( ; i <= slices; i++ ) { - a = ( i * 360 / slices ) * ( Math.PI / 180 ); - resultCoords.push( [ - coords[ 0 ] + Math.cos( a ) * distance, - coords[ 1 ] + Math.sin( a ) * distance - ] ); - } - - return { - type: "Polygon", - coordinates: [ ( wasGeodetic ? $.geo.proj.toGeodetic( resultCoords ) : resultCoords ) ] - }; - } else { - return undefined; - } - }, - - - // - // feature - // - - _basic: function( geom ) { - // return an array of all basic geometries - // e.g., MultiPolygons become multiple Polygons - // coordinate arrays are kept as references for speed & should not be altered - // not in JTS - var geometries = [ ]; - var multiType; - var i = 0; - var j; - - var flat = this._flatten( geom ); - - for ( ; i < flat.length; i++ ) { - if ( flat[ i ].type.substring( 0, 5 ) === "Multi" ) { - multiType = flat[ i ].type.substring( 5 ); - - for ( j = 0; j < flat[ i ].coordinates.length; j++ ) { - geometries.push( { - type: multiType, - coordinates: flat[ i ].coordinates[ j ] - } ); - } - } else { - geometries.push( flat[ i ] ); - } - } - - return geometries; - }, - - _flatten: function (geom) { - // return an array of only geometries - // will extract geometries from Feature, FeatureCollection, & GeometryCollection - // not in JTS - var geometries = [], - curGeom = 0; - switch (geom.type) { - case "Feature": - $.merge(geometries, this._flatten(geom.geometry)); - break; - - case "FeatureCollection": - for (; curGeom < geom.features.length; curGeom++) { - $.merge(geometries, this._flatten(geom.features[curGeom].geometry)); - } - break; - - case "GeometryCollection": - for (; curGeom < geom.geometries.length; curGeom++) { - $.merge(geometries, this._flatten(geom.geometries[curGeom])); - } - break; - - default: - geometries[0] = geom; - break; - } - return geometries; - }, - - length: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - lineStringCoordinates, - i = 1, dx, dy; - - switch ( geom.type ) { - case "Point": - return 0; - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][0] - lineStringCoordinates[ i - 1 ][0]; - dy = lineStringCoordinates[ i ][1] - lineStringCoordinates[ i - 1 ][1]; - sum += Math.sqrt((dx * dx) + (dy * dy)); - } - - return sum; - } - - // return undefined; - }, - - area: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - polygonCoordinates, - i = 1, j; - - switch ( geom.type ) { - case "Point": - case "LineString": - return 0; - - case "Polygon": - polygonCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( polygonCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( polygonCoordinates ) ) { - polygonCoordinates = $.geo.proj.fromGeodetic( polygonCoordinates ); - } - - for ( ; i <= polygonCoordinates.length; i++) { - j = i % polygonCoordinates.length; - sum += ( polygonCoordinates[ i - 1 ][ 0 ] - polygonCoordinates[ j ][ 0 ] ) * ( polygonCoordinates[ i - 1 ][ 1 ] + polygonCoordinates[ j ][ 1 ] ) / 2; - } - - return Math.abs( sum ); - } - }, - - pointAlong: function( geom, percentage, _ignoreGeo /* Internal Use Only */ ) { - var totalLength = 0, - previousPercentageSum = 0, - percentageSum = 0, - remainderPercentageSum, - len, - lineStringCoordinates, - segmentLengths = [], - i = 1, dx, dy, - c, c0, c1, - wasGeodetic = false; - - switch ( geom.type ) { - case "Point": - return $.extend( { }, geom ); - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( percentage === 0 ) { - return { - type: "Point", - coordinates: [ lineStringCoordinates[ 0 ][ 0 ], lineStringCoordinates[ 0 ][ 1 ] ] - }; - } else if ( percentage === 1 ) { - i = lineStringCoordinates.length - 1; - return { - type: "Point", - coordinates: [ lineStringCoordinates[ i ][ 0 ], lineStringCoordinates[ i ][ 1 ] ] - }; - } else { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - wasGeodetic = true; - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][ 0 ] - lineStringCoordinates[ i - 1 ][ 0 ]; - dy = lineStringCoordinates[ i ][ 1 ] - lineStringCoordinates[ i - 1 ][ 1 ]; - len = Math.sqrt((dx * dx) + (dy * dy)); - segmentLengths.push( len ); - totalLength += len; - } - - for ( i = 0; i < segmentLengths.length && percentageSum < percentage; i++ ) { - previousPercentageSum = percentageSum; - percentageSum += ( segmentLengths[ i ] / totalLength ); - } - - remainderPercentageSum = percentage - previousPercentageSum; - - c0 = lineStringCoordinates[ i - 1 ]; - c1 = lineStringCoordinates[ i ]; - - c = [ - c0[ 0 ] + ( remainderPercentageSum * ( c1[ 0 ] - c0[ 0 ] ) ), - c0[ 1 ] + ( remainderPercentageSum * ( c1[ 1 ] - c0[ 1 ] ) ) - ]; - - return { - type: "Point", - coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c - }; - } - } - }, - - // - // WKT functions - // - - WKT: (function () { - function pointToString(value) { - return "POINT " + pointToUntaggedString(value.coordinates); - } - - function pointToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - return "(" + coordinates.join(" ") + ")"; - } - } - - function lineStringToString(value) { - return "LINESTRING " + lineStringToUntaggedString(value.coordinates); - } - - function lineStringToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var points = []; - - for (var i = 0; i < coordinates.length; i++) { - points.push(coordinates[i].join(" ")); - } - - return "(" + points + ")"; - } - } - - function polygonToString(value) { - return "POLYGON " + polygonToUntaggedString(value.coordinates); - } - - function polygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMTPY"; - } else { - var lineStrings = []; - - for (var i = 0; i < coordinates.length; i++) { - lineStrings.push(lineStringToUntaggedString(coordinates[i])); - } - - return "(" + lineStrings + ")"; - } - } - - function multiPointToString(value) { - return "MULTIPOINT " + lineStringToUntaggedString(value.coordinates); - } - - function multiLineStringToString(value) { - return "MULTILINSTRING " + polygonToUntaggedString(value.coordinates); - } - - function multiPolygonToString(value) { - return "MULTIPOLYGON " + multiPolygonToUntaggedString(value.coordinates); - } - - function multiPolygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var polygons = []; - for (var i = 0; i < coordinates.length; i++) { - polygons.push(polygonToUntaggedString(coordinates[i])); - } - return "(" + polygons + ")"; - } - } - - function geometryCollectionToString(value) { - return "GEOMETRYCOLLECTION " + geometryCollectionToUntaggedString(value.geometries); - } - - function geometryCollectionToUntaggedString(geometries) { - if (!(geometries && geometries.length)) { - return "EMPTY"; - } else { - var geometryText = []; - for (var i = 0; i < geometries.length; i++) { - geometryText.push(stringify(geometries[i])); - } - return "(" + geometries + ")"; - } - } - - function stringify(value) { - if (!(value && value.type)) { - return ""; - } else { - switch (value.type) { - case "Point": - return pointToString(value); - - case "LineString": - return lineStringToString(value); - - case "Polygon": - return polygonToString(value); - - case "MultiPoint": - return multiPointToString(value); - - case "MultiLineString": - return multiLineStringToString(value); - - case "MultiPolygon": - return multiPolygonToString(value); - - case "GeometryCollection": - return geometryCollectionToString(value); - - default: - return ""; - } - } - } - - function pointParseUntagged(wkt) { - var pointString = wkt.match( /\(\s*([\d\.\-]+)\s+([\d\.\-]+)\s*\)/ ); - return pointString && pointString.length > 2 ? { - type: "Point", - coordinates: [ - parseFloat(pointString[1]), - parseFloat(pointString[2]) - ] - } : null; - } - - function lineStringParseUntagged(wkt) { - var lineString = wkt.match( /\s*\((.*)\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( lineString && lineString.length > 1 ) { - pointStrings = lineString[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "LineString", - coordinates: coords - }; - } else { - return null; - } - } - - function polygonParseUntagged(wkt) { - var polygon = wkt.match( /\s*\(\s*\((.*)\)\s*\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( polygon && polygon.length > 1 ) { - pointStrings = polygon[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "Polygon", - coordinates: [ coords ] - }; - } else { - return null; - } - } - - function multiPointParseUntagged(wkt) { - var multiSomething; - - if ( wkt.indexOf( "((" ) === -1 ) { - multiSomething = lineStringParseUntagged( wkt ); - } else { - multiSomething = multiLineStringParseUntagged( wkt ); - multiSomething.coordinates = $.geo._allCoordinates( multiSomething ); - } - - multiSomething.type = "MultiPoint"; - - return multiSomething; - } - - function multiLineStringParseUntagged(wkt) { - var lineStringsWkt = wkt.substr( 2, wkt.length - 4 ), - lineString, - lineStrings = lineStringsWkt.split( /\),\s*\(/ ), - i = 0, - multiLineString = { - type: "MultiLineString", - coordinates: [ ] - }; - - for ( ; i < lineStrings.length; i++ ) { - lineString = lineStringParseUntagged( "(" + lineStrings[ i ] + ")" ); - if ( lineString ) { - multiLineString.coordinates.push( lineString.coordinates ); - } - } - - return multiLineString; - } - - function multiPolygonParseUntagged(wkt) { - var polygonsWkt = wkt.substr( 1, wkt.length - 2 ), - polygon, - polygons = polygonsWkt.split( /\),\s*\(/ ), - i = 0, - multiPolygon = { - type: "MultiPolygon", - coordinates: [ ] - }; - - for ( ; i < polygons.length; i++ ) { - polygon = polygonParseUntagged( "(" + polygons[ i ] + ")" ); - if ( polygon ) { - multiPolygon.coordinates.push( polygon.coordinates ); - } - } - - return multiPolygon; - } - - function geometryCollectionParseUntagged( wkt ) { - var geometriesWkt = wkt.substr( 1, wkt.length - 2 ), - geometries = geometriesWkt.match( /\),[a-zA-Z]/g ), - geometryCollection = { - type: "GeometryCollection", - geometries: [ ] - }, - curGeom, - i = 0, curStart = 0, curLen; - - if ( geometries && geometries.length > 0 ) { - for ( ; i < geometries.length; i++ ) { - curLen = geometriesWkt.indexOf( geometries[ i ], curStart ) - curStart + 1; - curGeom = parse( geometriesWkt.substr( curStart, curLen ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - curStart += curLen + 1; - } - - // one more - curGeom = parse( geometriesWkt.substr( curStart ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - - return geometryCollection; - } else { - return null; - } - } - - function parse(wkt) { - wkt = $.trim(wkt); - - var typeIndex = wkt.indexOf( "(" ), - untagged = wkt.substr( typeIndex ); - - switch ($.trim(wkt.substr(0, typeIndex)).toUpperCase()) { - case "POINT": - return pointParseUntagged( untagged ); - - case "LINESTRING": - return lineStringParseUntagged( untagged ); - - case "POLYGON": - return polygonParseUntagged( untagged ); - - case "MULTIPOINT": - return multiPointParseUntagged( untagged ); - - case "MULTILINESTRING": - return multiLineStringParseUntagged( untagged ); - - case "MULTIPOLYGON": - return multiPolygonParseUntagged( untagged ); - - case "GEOMETRYCOLLECTION": - return geometryCollectionParseUntagged( untagged ); - - default: - return null; - } - } - - return { - stringify: stringify, - - parse: parse - }; - }()), - - // - // projection functions - // - - proj: (function () { - var halfPi = 1.5707963267948966192, - quarterPi = 0.7853981633974483096, - radiansPerDegree = 0.0174532925199432958, - degreesPerRadian = 57.295779513082320877, - semiMajorAxis = 6378137; - - return { - fromGeodeticPos: function (coordinate) { - return [ - semiMajorAxis * coordinate[ 0 ] * radiansPerDegree, - semiMajorAxis * Math.log(Math.tan(quarterPi + coordinate[ 1 ] * radiansPerDegree / 2)) - ]; - }, - - fromGeodetic: function ( coordinates ) { - if ( ! $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - fromGeodeticPos = this.fromGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length === 4) { - // bbox - var min = fromGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = fromGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = fromGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - }, - - toGeodeticPos: function (coordinate) { - return [ - (coordinate[ 0 ] / semiMajorAxis) * degreesPerRadian, - (halfPi - 2 * Math.atan(1 / Math.exp(coordinate[ 1 ] / semiMajorAxis))) * degreesPerRadian - ]; - }, - - toGeodetic: function (coordinates) { - if ( $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - toGeodeticPos = this.toGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length === 4) { - // bbox - var min = toGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = toGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = toGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - } - }; - }()), - - // - // service types (defined in other files) - // - - _serviceTypes: {} - }; -}(jQuery, this)); - -(function ($, window, undefined) { - var _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ); - - $.widget("geo.geographics", { - _$elem: undefined, - _options: {}, - _trueCanvas: true, - _trueDoubleBuffer: true, - - _width: 0, - _height: 0, - - _$canvas: undefined, - _context: undefined, - - _$canvasSceneFront: undefined, //< if _trueCanvas, where canvas images get written (front buffer) - _$canvasSceneBack: undefined, //< if _trueCanvas, where canvas images get written (back buffer) - _timeoutEnd: null, - _requireFlip: false, - - _blitcanvas: undefined, - _blitcontext: undefined, - - _$labelsContainerFront: undefined, - _$labelsContainerBack: undefined, - _labelsHtml: "", - - options: { - style: { - borderRadius: "8px", - color: "#7f0000", - //fill: undefined, - fillOpacity: 0.2, - height: "8px", - opacity: 1, - //stroke: undefined, - strokeOpacity: 1, - strokeWidth: "2px", - visibility: "visible", - width: "8px" - }, - - doubleBuffer: true - }, - - _create: function () { - this._$elem = this.element; - this._options = this.options; - - this._$elem.css( { - webkitTransform: "translateZ(0)", - display: "inline-block", - overflow: "hidden", - textAlign: "left" - } ); - - if (this._$elem.css("position") === "static") { - this._$elem.css("position", "relative"); - } - - this._$elem.addClass( "geo-graphics" ); - - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - var posCss = 'position:absolute;left:0;top:0;margin:0;padding:0;', - sizeCss = 'width:' + this._width + 'px;height:' + this._height + 'px;', - sizeAttr = 'width="' + this._width + '" height="' + this._height + '"'; - - this._blitcanvas = document.createElement( "canvas" ); - - if ( this._blitcanvas.getContext ) { - this._$canvas = $( window.toStaticHTML( '' ) ); - - // test _trueDoubleBuffer - this._blitcanvas.width = 1; - this._blitcanvas.height = 1; - this._trueDoubleBuffer = this._blitcanvas.toDataURL().length > 6; - - if ( !(this._options.doubleBuffer && this._trueDoubleBuffer) ) { - this._$elem.append( this._$canvas ); - } - - this._context = this._$canvas[0].getContext("2d"); - - this._blitcanvas.width = this._width; - this._blitcanvas.height = this._height; - this._blitcontext = this._blitcanvas.getContext("2d"); - - // create our front & back buffers - // though, at any time either one can be in front - this._$canvasSceneFront = $( window.toStaticHTML( '' ) ); //.load($.proxy(this._canvasSceneLoad, this)); - this._$canvasSceneBack = $( window.toStaticHTML( '' ) ); //.load($.proxy(this._canvasSceneLoad, this)); - - } else if (_ieVersion <= 8) { - this._trueCanvas = false; - this._$elem.append( '
              '); - this._$canvas = this._$elem.children(':last'); - - G_vmlCanvasManager.initElement(this._$canvas[0]); - this._context = this._$canvas[0].getContext("2d"); - this._$canvas.children().css({ backgroundColor: "transparent", width: this._width, height: this._height }); - } - - // create our front & back label containers - this._$labelsContainerFront = $( window.toStaticHTML( '
              ' ) ); - this._$labelsContainerBack = $( window.toStaticHTML( '
              ' ) ); - }, - - _setOption: function (key, value) { - if (key === "style") { - value = $.extend({}, this._options.style, value); - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - destroy: function () { - $.Widget.prototype.destroy.apply(this, arguments); - this._$elem.html(""); - this._$elem.removeClass( "geo-graphics" ); - }, - - clear: function () { - this._context.clearRect(0, 0, this._width, this._height); - this._labelsHtml = ""; - this._end( ); - }, - - drawArc: function (coordinates, startAngle, sweepAngle, style) { - style = this._getGraphicStyle(style); - - if (style.visibility !== "hidden" && style.opacity > 0 && style.widthValue > 0 && style.heightValue > 0) { - var r = Math.min(style.widthValue, style.heightValue) / 2; - - startAngle = (startAngle * Math.PI / 180); - sweepAngle = (sweepAngle * Math.PI / 180); - - this._context.save(); - this._context.translate(coordinates[0], coordinates[1]); - if (style.widthValue > style.heightValue) { - this._context.scale(style.widthValue / style.heightValue, 1); - } else { - this._context.scale(1, style.heightValue / style.widthValue); - } - - this._context.beginPath(); - this._context.arc(0, 0, r, startAngle, sweepAngle, false); - - if (this._trueCanvas) { - this._context.restore(); - } - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - if (!this._trueCanvas) { - this._context.restore(); - } - } - - this._end( ); - }, - - drawPoint: function (coordinates, style) { - style = this._getGraphicStyle(style); - if (style.widthValue === style.heightValue && style.heightValue === style.borderRadiusValue) { - this.drawArc(coordinates, 0, 360, style); - } else if (style.visibility !== "hidden" && style.opacity > 0) { - style.borderRadiusValue = Math.min(Math.min(style.widthValue, style.heightValue) / 2, style.borderRadiusValue); - coordinates[0] -= style.widthValue / 2; - coordinates[1] -= style.heightValue / 2; - this._context.beginPath(); - this._context.moveTo(coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.lineTo(coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1]); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1], coordinates[0] + style.widthValue, coordinates[1] + style.borderRadiusValue); - this._context.lineTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue, coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.lineTo(coordinates[0] + style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1] + style.heightValue, coordinates[0], coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.lineTo(coordinates[0], coordinates[1] + style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1], coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.closePath(); - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - - this._context.stroke(); - } - - this._end( ); - } - }, - - drawLineString: function (coordinates, style) { - this._drawLines([coordinates], false, style); - }, - - drawPolygon: function (coordinates, style) { - if ( !this._trueCanvas || coordinates.length === 1 ) { - // either we don't have fancy rendering or there's no need for it (no holes) - this._drawLines( coordinates, true, style ); - } else { - if ( !coordinates || !coordinates.length || coordinates[ 0 ].length < 3 ) { - // this is not a Polygon or it doesn't have a proper outer ring - return; - } - - style = this._getGraphicStyle(style); - this._blitcontext.globalCompositeOperation = "copy"; - - var pixelBbox, i, j; - - if ( style.visibility !== "hidden" && style.opacity > 0 ) { - this._blitcontext.clearRect(0, 0, this._width, this._height); - - if ( style.doFill ) { - if ( coordinates.length > 1 ) { - // stencil inner rings - this._blitcontext.globalCompositeOperation = "source-out"; - this._blitcontext.globalAlpha = 1; - - this._blitcontext.beginPath(); - - for ( i = 1; i < coordinates.length; i++ ) { - // start drawing inner rings, i - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - - for ( j = 0; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - } - - this._blitcontext.closePath(); - - this._blitcontext.fill( ); - } - } - - // path outer ring - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ 0 ][ 0 ][ 0 ], coordinates[ 0 ][ 0 ][ 1 ] ); - - pixelBbox = [ coordinates[ 0 ][ 0 ][ 0 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 0 ] + style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] + style.strokeWidthValue ]; - - for ( i = 1; i < coordinates[ 0 ].length - 1; i++ ) { - this._blitcontext.lineTo( coordinates[ 0 ][ i ][ 0 ], coordinates[ 0 ][ i ][ 1 ] ); - - pixelBbox[ 0 ] = Math.min( coordinates[ 0 ][ i ][ 0 ] - style.strokeWidthValue, pixelBbox[ 0 ] ); - pixelBbox[ 1 ] = Math.min( coordinates[ 0 ][ i ][ 1 ] - style.strokeWidthValue, pixelBbox[ 1 ] ); - pixelBbox[ 2 ] = Math.max( coordinates[ 0 ][ i ][ 0 ] + style.strokeWidthValue, pixelBbox[ 2 ] ); - pixelBbox[ 3 ] = Math.max( coordinates[ 0 ][ i ][ 1 ] + style.strokeWidthValue, pixelBbox[ 3 ] ); - } - - this._blitcontext.closePath(); - - if ( style.doFill ) { - // fill outer ring - this._blitcontext.fillStyle = style.fill; - this._blitcontext.globalAlpha = style.opacity * style.fillOpacity; - this._blitcontext.fill( ); - } - - this._blitcontext.globalCompositeOperation = "source-over"; - if ( style.doStroke ) { - // stroke outer ring - this._blitcontext.lineCap = this._blitcontext.lineJoin = "round"; - this._blitcontext.lineWidth = style.strokeWidthValue; - this._blitcontext.strokeStyle = style.stroke; - - this._blitcontext.globalAlpha = style.opacity * style.strokeOpacity; - this._blitcontext.stroke( ); - - if ( coordinates.length > 1 ) { - // stroke inner rings - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.stroke( ); - } - } - } - - // blit - pixelBbox[ 0 ] = Math.min( Math.max( pixelBbox[ 0 ], 0), this._width ); - pixelBbox[ 1 ] = Math.min( Math.max( pixelBbox[ 1 ], 0), this._height ); - pixelBbox[ 2 ] = Math.min( Math.max( pixelBbox[ 2 ], 0), this._width ); - pixelBbox[ 3 ] = Math.min( Math.max( pixelBbox[ 3 ], 0), this._height ); - - if ( pixelBbox[ 0 ] !== pixelBbox[ 2 ] && pixelBbox[ 1 ] !== pixelBbox[ 3 ] ) { - this._context.drawImage(this._blitcanvas, pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ], pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ] ); - - this._end( ); - } - } - } - }, - - drawBbox: function (bbox, style) { - this._drawLines([[ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ]], true, style); - }, - - drawLabel: function( coordinates, label ) { - this._labelsHtml += '
              ' + label + '
              '; - }, - - resize: function( dx, dy ) { - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - if ( this._trueCanvas ) { - this._$canvas[0].width = this._width; - this._$canvas[0].height = this._height; - - this._$canvasSceneFront.css( { - left: dx, - top: dy - } ); - - this._$canvasSceneBack.css( { - width: this._width, - height: this._height - } ); - } else { - this._$canvas.css( { - width: this._width, - height: this._height - } ); - } - - var labelPositionFront = this._$labelsContainerFront.position(); - - this._$labelsContainerFront.css( { - left: labelPositionFront.left + dx, - top: labelPositionFront.top + dy, - width: this._width, - height: this._height - } ); - - this._$labelsContainerBack.css( { - width: this._width, - height: this._height - } ); - }, - - interactiveTransform: function( origin, scale ) { - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - if ( this._trueCanvas ) { - if ( this._options.doubleBuffer && this._trueDoubleBuffer ) { - - var geographics = this; - - if ( this._requireFlip ) { - geographics._requireFlip = false; - - var oldCanvasScene = geographics._$canvasSceneFront; - - geographics._$canvasSceneFront = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ).prependTo( geographics._$elem ); - - geographics._$canvasSceneBack = oldCanvasScene.prop( "src", "" ).detach(); - } - - // transform a finished scene, can assume no drawing during these calls - this._$canvasSceneFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - - // transform labels - this._$labelsContainerFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - }, - - _canvasSceneLoad: function() { - var geographics = this; - if ( geographics._requireFlip ) { - geographics._requireFlip = false; - var oldCanvasScene = geographics._$canvasSceneFront; - - geographics._$canvasSceneFront = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prependTo( geographics._$elem ); - - geographics._$canvasSceneBack = oldCanvasScene.prop( "src", "" ).detach(); - } - }, - - _endCallback: function() { - var geographics = this; - - if ( !geographics._timeoutEnd ) { - // something has canceled the draw - return; - } - - if ( geographics._trueCanvas && geographics._options.doubleBuffer && geographics._trueDoubleBuffer ) { - geographics._$canvasSceneBack.prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ); - this._canvasSceneLoad( ); - } - - - geographics._$labelsContainerBack.html( window.toStaticHTML( geographics._labelsHtml ) ).find("a").css({ - position: "relative", - zIndex: 1, - display: "inline-block", - webkitTransform: "translateZ(0)" - }); - - var oldLabelsContainer = geographics._$labelsContainerFront; - - geographics._$labelsContainerFront = geographics._$labelsContainerBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).appendTo( geographics._$elem ); - - geographics._$labelsContainerBack = oldLabelsContainer.detach(); - - geographics._timeoutEnd = null; - }, - - _end: function( ) { - // end/finalize a scene - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - this._requireFlip = true; - - this._timeoutEnd = setTimeout( $.proxy(this._endCallback, this), 20 ); - }, - - _getGraphicStyle: function (style) { - function safeParse(value) { - value = parseInt(value, 10); - return (+value + '') === value ? +value : value; - } - - style = $.extend({}, this._options.style, style); - style.borderRadiusValue = safeParse(style.borderRadius); - style.fill = style.fill || style.color; - style.doFill = style.fill && style.fillOpacity > 0; - style.stroke = style.stroke || style.color; - style.strokeWidthValue = safeParse(style.strokeWidth); - style.doStroke = style.stroke && style.strokeOpacity > 0 && style.strokeWidthValue > 0; - style.widthValue = safeParse(style.width); - style.heightValue = safeParse(style.height); - return style; - }, - - _drawLines: function (coordinates, close, style) { - if (!coordinates || !coordinates.length || coordinates[0].length < 2) { - return; - } - - var i, j; - style = this._getGraphicStyle(style); - - if (style.visibility !== "hidden" && style.opacity > 0) { - this._context.beginPath(); - - for (i = 0; i < coordinates.length; i++) { - this._context.moveTo(coordinates[i][0][0], coordinates[i][0][1]); - for (j = 1; j < coordinates[i].length; j++) { - this._context.lineTo(coordinates[i][j][0], coordinates[i][j][1]); - } - } - - if (close) { - this._context.closePath(); - } - - if (close && style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineCap = this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - this._end( ); - } - } - }); -}(jQuery, window)); - - -(function ($, window, undefined) { - var _widgetIdSeed = 0, - _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ), - - _defaultOptions = { - bbox: [-180, -85, 180, 85], - bboxMax: [-180, -85, 180, 85], - center: [0, 0], - cursors: { - "static": "default", - pan: "url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move", - click: "crosshair", - zoom: "crosshair", - dragBox: "crosshair", - dragCircle: "crosshair", - drawPoint: "crosshair", - drawLineString: "crosshair", - drawPolygon: "crosshair", - measureLength: "crosshair", - measureArea: "crosshair" - }, - measureLabels: { - length: "{{:length.toFixed( 2 )}} m", - area: "{{:area.toFixed( 2 )}} sq m" - }, - drawStyle: {}, - shapeStyle: {}, - mode: "pan", - pannable: true, - scroll: "default", - shift: "default", - services: [ - { - "class": "osm", - type: "tiled", - src: function (view) { - return "//otile" + ((view.index % 4) + 1) + ((location.protocol === 'https:') ? "-s" : "") + ".mqcdn.com/tiles/1.0.0/osm/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; - }, - attr: 'Tiles Courtesy of MapQuest ' - } - ], - tilingScheme: { - tileWidth: 256, - tileHeight: 256, - levels: 18, - basePixelSize: 156543.03392799936, - origin: [-20037508.342787, 20037508.342787] - }, - axisLayout: "map", - zoom: 0, - zoomMin: 0, - zoomMax: Number.POSITIVE_INFINITY, - zoomFactor: 2, //< determines what a zoom level means - pixelSize: 0 - }; - - $.widget("geo.geomap", { - // private widget members - _$elem: undefined, //< map div for maps, service div for services - _map: undefined, //< only defined in services - _created: false, - _createdGraphics: false, - _widgetId: 0, - _tmplLengthId: "", - _tmplAreaId: "", - - _contentBounds: {}, - - _$resizeContainer: undefined, //< all elements that should match _contentBounds' size - - _$eventTarget: undefined, - _$contentFrame: undefined, - _$existingChildren: undefined, - _$attrList: undefined, - _$servicesContainer: undefined, - _$shapesContainers: undefined, //< all shapesContainer divs (map only) - - _$panContainer: undefined, //< all non-service elements that move while panning - _$shapesContainer: undefined, //< just "our" shapesContainer div (map & service) - _$drawContainer: undefined, - _$measureContainer: undefined, - _$measureLabel: undefined, - - _dpi: 96, - - _currentServices: [], //< internal copy - - _center: undefined, - _pixelSize: undefined, - _centerMax: undefined, - _pixelSizeMax: undefined, - _pixelSizeMin: undefined, - - _userGeodetic: true, - - _centerInteractive: undefined, - _pixelSizeInteractive: undefined, - _timeoutInteractive: null, - _triggerInteractive: false, - - _timeoutRefreshShapes: null, - - _loadCount: 0, - - _wheelLevel: 0, - - _fullZoomFactor: 2, //< interactiveScale factor needed to zoom a whole level - _partialZoomFactor: 1.18920711500273, //< interactiveScale factor needed to zoom a fraction of a level (the fourth root of 2) - - _mouseDown: undefined, - _inOp: undefined, - _toolPan: undefined, - _shiftDown: undefined, - _anchor: undefined, - _current: undefined, - _downDate: undefined, - _moveDate: undefined, - _clickDate: undefined, - _lastMove: undefined, - _lastDrag: undefined, - - _windowHandler: null, - _resizeTimeout: null, - - _panning: undefined, - _velocity: undefined, - _friction: undefined, - - _pointerEvents: undefined, - _supportTouch: undefined, - _softDblClick: undefined, - _isTap: undefined, - _isDbltap: undefined, - - _isMultiTouch: undefined, - _multiTouchAnchor: [], //< TouchList - _multiTouchAnchorBbox: undefined, //< bbox - _multiTouchCurrentBbox: undefined, //< bbox - - _drawTimeout: null, //< used in drawPoint mode so we don't send two shape events on dbltap - _drawPixels: [], //< an array of coordinate arrays for drawing lines & polygons, in pixel coordinates - _drawCoords: [], - - _graphicShapes: [], //< an array of objects containing style object refs & GeoJSON object refs - - _initOptions: {}, - - _options: {}, - - options: $.extend({}, _defaultOptions), - - _createWidget: function (options, element) { - this._$elem = $(element); - - if (this._$elem.is(".geo-service")) { - this._graphicShapes = []; - $.Widget.prototype._createWidget.apply(this, arguments); - return; - } - - this._widgetId = _widgetIdSeed++; - this._serviceIdSeed = 0; - this._tmplLengthId = "geoMeasureLength" + this._widgetId; - this._tmplAreaId = "geoMeasureArea" + this._widgetId; - - this._$elem.addClass("geo-map").css( { - webkitTransform: "translateZ(0)", - touchAction: 'none' - } ); - - - this._initOptions = options || {}; - - this._forcePosition(this._$elem); - - this._$elem.css("text-align", "left"); - - var size = this._findMapSize(); - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._createChildren(); - - this._center = [ 0, 0 ]; - this._centerMax = [ 0, 0 ]; - this._centerInteractive = [ 0, 0 ]; - - this.options["pixelSize"] = this._pixelSize = this._pixelSizeMax = 156543.03392799936; - this._pixelSizeMin = this._pixelSizeMax / Math.pow( 2, 17 ); - - this._mouseDown = - this._inOp = - this._toolPan = - this._shiftDown = - this._panning = - this._isTap = - this._isDbltap = false; - - this._anchor = [ 0, 0 ]; /* mouse down */ - this._current = [ 0, 0 ]; /* mouse move no matter what */ - this._lastMove = [ 0, 0 ]; - this._lastDrag = [ 0, 0 ]; - this._velocity = [ 0, 0 ]; - - this._friction = [0.8, 0.8]; - - this._downDate = - this._moveDate = - this._clickDate = 0; - - this._drawPixels = []; - this._drawCoords = []; - this._graphicShapes = []; - - - $.Widget.prototype._createWidget.apply(this, arguments); - }, - - _create: function () { - this._options = this.options; - - if (this._$elem.is(".geo-service")) { - this._map = this._$elem.data( "geoMap" ); - this._$elem.data( "geoService", this ); - return; - } - - this._map = this; - - this._pointerEvents = window.PointerEvent; - this._supportTouch = ("ontouchend" in document); - this._softDblClick = this._supportTouch || _ieVersion === 7; - - var geomap = this, - touchStartEvent = this._pointerEvents ? 'pointerdown' : ( this._supportTouch ? "touchstart mousedown" : "mousedown" ), - touchStopEvent = this._pointerEvents ? 'pointerup pointercancel' : ( this._supportTouch ? "touchend touchcancel mouseup" : "mouseup" ), - touchMoveEvent = this._pointerEvents ? 'pointermove' : ( this._supportTouch ? "touchmove mousemove" : "mousemove" ); - - $(document).keydown($.proxy(this._document_keydown, this)); - - this._$eventTarget.dblclick($.proxy(this._eventTarget_dblclick, this)); - - this._$eventTarget.bind(touchStartEvent, $.proxy(this._eventTarget_touchstart, this)); - - var dragTarget = (this._$eventTarget[0].setCapture) ? this._$eventTarget : $(document); - dragTarget.bind(touchMoveEvent, $.proxy(this._dragTarget_touchmove, this)); - dragTarget.bind(touchStopEvent, $.proxy(this._dragTarget_touchstop, this)); - - this._$eventTarget.mousewheel($.proxy(this._eventTarget_mousewheel, this)); - - this._windowHandler = function () { - if (geomap._resizeTimeout) { - clearTimeout(geomap._resizeTimeout); - } - geomap._resizeTimeout = setTimeout(function () { - if (geomap._created) { - geomap._$elem.geomap( "resize", true ); - } - }, 500); - }; - - $(window).resize(this._windowHandler); - - this._$drawContainer.geographics({ style: this._initOptions.drawStyle || {}, doubleBuffer: false }); - this._options["drawStyle"] = this._$drawContainer.geographics("option", "style"); - - this._$shapesContainer.geographics( { style: this._initOptions.shapeStyle || { } } ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - - if (this._initOptions) { - // always init tilingScheme right away, even if it's null - if ( this._initOptions.tilingScheme !== undefined ) { - this._setOption("tilingScheme", this._initOptions.tilingScheme || null, false); - } - - if ( this._initOptions.services ) { - // jQuery UI Widget Factory merges user services with our default, we want to clobber the default - this._options[ "services" ] = $.merge( [ ], this._initOptions.services ); - } - if (this._initOptions.bboxMax) { - this._setOption("bboxMax", this._initOptions.bboxMax, false); - this._setOption("bbox", this._initOptions.bboxMax, false); - } - if (this._initOptions.zoomMin !== undefined) { - this._setOption("zoomMin", this._initOptions.zoomMin, false); - } - if (this._initOptions.zoomMax !== undefined) { - this._setOption("zoomMax", this._initOptions.zoomMax, false); - } - if (this._initOptions.zoomFactor !== undefined) { - this._setOption("zoomFactor", this._initOptions.zoomFactor, false); - this._fullZoomFactor = this._initOptions.zoomFactor; - this._partialZoomFactor = Math.pow(4, 1 / this._fullZoomFactor); // 4th root of full - } - if (this._initOptions.bbox) { - this._setOption("bbox", this._initOptions.bbox, false); - } - if (this._initOptions.center) { - this._setOption("center", this._initOptions.center, false); - } - if (this._initOptions.zoom !== undefined) { - this._setOption("zoom", this._initOptions.zoom, false); - } - } - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._createServices(); - this._refresh(); - - this._created = true; - }, - - _setOption: function (key, value, refresh) { - if ( key === "pixelSize" ) { - return; - } - - refresh = (refresh === undefined || refresh); - - if ( this._$elem.is( ".geo-map" ) ) { - this._panFinalize(); - } - - var center, pixelSize, bbox, zoom; - - switch (key) { - case "bbox": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2]; - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height); - - // clamp to zoom - zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( center, pixelSize ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( center, pixelSize, false, refresh ); - } - - value = this._getBbox( center, pixelSize ); - break; - - case "bboxMax": - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - break; - - case "center": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( value, this._pixelSizeInteractive ); - this._interactiveTransform( ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( value, this._pixelSize, false, refresh ); - } - break; - - case "measureLabels": - value = $.extend( this._options[ "measureLabels" ], value ); - - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - break; - - case "drawStyle": - if (this._$drawContainer) { - this._$drawContainer.geographics("option", "style", value); - value = this._$drawContainer.geographics("option", "style"); - } - break; - - case "shapeStyle": - if ( this._$elem.is( ".geo-service" ) && !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("option", "style", value); - value = this._$shapesContainer.geographics("option", "style"); - } - break; - - case "mode": - this._resetDrawing( ); - this._$eventTarget.css("cursor", this._options["cursors"][value]); - break; - - case "zoom": - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj; - if ( this._created ) { - this._setZoom(value, false, refresh); - } else { - value = Math.max( value, 0 ); - this._setCenterAndSize( this._center, this._getPixelSize( value ), false, refresh ); - } - break; - } - - $.Widget.prototype._setOption.apply(this, arguments); - - switch ( key ) { - case "bbox": - case "center": - if ( this._userGeodetic ) { - this._options[ "bbox" ] = $.geo.proj.toGeodetic( this._options[ "bbox" ] ); - this._options[ "center" ] = $.geo.proj.toGeodetic( this._center ); - } - break; - - case "tilingScheme": - if ( value !== null ) { - this._pixelSizeMax = this._getPixelSize( 0 ); - this._pixelSizeMin = this._getPixelSize( value.pixelSizes ? value.pixelSizes.length - 1 : value.levels - 1 ); - this._centerMax = [ - value.origin[ 0 ] + this._pixelSizeMax * value.tileWidth / 2, - value.origin[ 1 ] + this._pixelSizeMax * value.tileHeight / 2 - ]; - } - break; - - case "bboxMax": - if ( this._userGeodetic ) { - bbox = $.geo.proj.fromGeodetic( value ); - } else { - bbox = value; - } - - this._centerMax = $.geo.center( bbox ); - this._pixelSizeMax = Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - break; - - case "services": - this._createServices(); - if (refresh) { - this._refresh(); - this._refreshAllShapes(); - } - break; - - case "shapeStyle": - if ( refresh && this._createdGraphics ) { - this._$shapesContainer.geographics("clear"); - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - break; - } - }, - - destroy: function () { - if ( this._$elem.is(".geo-service") ) { - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - } - } else { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - - this._created = false; - - $(window).unbind("resize", this._windowHandler); - - for ( var i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - - this._$drawContainer.geographics("destroy"); - this._$drawContainer = undefined; - - this._$existingChildren.detach(); - this._$elem.html(""); - this._$elem.append(this._$existingChildren); - this._$elem.removeClass("geo-map"); - } - - $.Widget.prototype.destroy.apply(this, arguments); - }, - - toMap: function (p) { - p = this._toMap(p); - return this._userGeodetic ? $.geo.proj.toGeodetic(p) : p; - }, - - toPixel: function ( p, _center /* Internal Use Only */, _pixelSize /* Internal Use Only */ ) { - return this._toPixel( $.geo.proj ? $.geo.proj.fromGeodetic( p ) : p, _center, _pixelSize ); - }, - - opacity: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "opacity", value, this._$elem ); - } else { - if ( value >= 0 || value <= 1 ) { - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - service.style.opacity = value; - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - $.geo[ "_serviceTypes" ][ service.type ].opacity( this, service ); - } - } - } - } - }, - - toggle: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "toggle", value, this._$elem ); - } else { - - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - if ( value === undefined ) { - // toggle visibility - value = ( service.style.visibility !== "visible" ); - } - - service.style.visibility = ( value ? "visible" : "hidden" ); - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - service.serviceContainer.toggle( value ); - - if ( value ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service ); - } - } - } - } - }, - - zoom: function (numberOfLevels) { - if (numberOfLevels !== null) { - this._setZoom(this._options["zoom"] + numberOfLevels, false, true); - } - }, - - refresh: function ( force, _serviceContainer ) { - if ( !this._panning ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "refresh", force, this._$elem ); - } else { - this._refresh( force, _serviceContainer ); - this._refreshAllShapes( _serviceContainer ); - } - } - }, - - resize: function ( _trigger /* Internal Use Only */ ) { - var size = this._findMapSize(), - dx = size["width"]/2 - this._contentBounds.width/2, - dy = size["height"]/2 - this._contentBounds.height/2, - i; - - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._$resizeContainer.css( { - width: size["width"], - height: size["height"] - } ); - - for (i = 0; i < this._currentServices.length; i++) { - $.geo["_serviceTypes"][this._currentServices[i].type].resize(this, this._currentServices[i], dx, dy); - } - - this._$elem.find( ".geo-graphics" ).css( { - width: size["width"], - height: size["height"] - }).geographics( "resize", dx, dy ); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._setCenterAndSize(this._center, this._pixelSize, _trigger, true); - }, - - append: function ( shape /* , style, label, refresh */ ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - if ( !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - var shapes, arg, i, realStyle, realLabel, realRefresh; - - if ( $.isArray( shape ) ) { - shapes = shape; - } else if ( shape.type === "FeatureCollection" ) { - shapes = shape.features; - } else { - shapes = [ shape ]; - } - - for ( i = 1; i < arguments.length; i++ ) { - arg = arguments[ i ]; - - if ( arg !== null ) { - if ( typeof arg === "object" ) { - realStyle = arg; - } else if ( typeof arg === "number" || typeof arg === "string" ) { - realLabel = arg; - } else if ( typeof arg === "boolean" ) { - realRefresh = arg; - } - } - } - - for ( i = 0; i < shapes.length; i++ ) { - if ( !$.data( shapes[ i ], "geoBbox" ) ) { - var bbox = $.geo.bbox( shapes[ i ] ); - if ( $.geo.proj && $.geo._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - $.data( shapes[ i ], "geoBbox", bbox ); - } - - this._graphicShapes.push( { - shape: shapes[ i ], - style: realStyle, - label: realLabel - } ); - } - - if ( realRefresh === undefined || realRefresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - empty: function ( refresh ) { - this._graphicShapes = []; - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - }, - - find: function ( selector, pixelTolerance ) { - if ( this._timeoutInteractive ) { - return []; - } - - var isPoint = $.isPlainObject( selector ), - //searchPixel = isPoint ? this._map.toPixel( selector.coordinates ) : undefined, - mapTol = this._map._pixelSize * pixelTolerance, - result = [], - graphicShape, - geometries, - curGeom, - i; - - if ( this._$elem.is( ".geo-map" ) ) { - $( this._$elem.find( ".geo-service" ).get().reverse() ).each( function( ) { - result = $.merge( result, $( this ).geomap( "find", selector, pixelTolerance ) ); - } ); - } - - for ( i = this._graphicShapes.length - 1; i >= 0; i-- ) { - graphicShape = this._graphicShapes[ i ]; - - if ( isPoint ) { - if ( graphicShape.shape.type === "Point" ) { - if ( $.geo.distance( graphicShape.shape, selector ) <= mapTol ) { - result.push( graphicShape.shape ); - } - } else { - var bbox = $.data( graphicShape.shape, "geoBbox" ), - bboxPolygon = { - type: "Polygon", - coordinates: [ [ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ] ] - }, - projectedPoint = { - type: "Point", - coordinates: $.geo.proj && $.geo._isGeodetic( selector.coordinates ) ? $.geo.proj.fromGeodetic( selector.coordinates ) : selector.coordinates - }; - - if ( $.geo.distance( bboxPolygon, projectedPoint, true ) <= mapTol ) { - geometries = $.geo._basic( graphicShape.shape ); - for ( curGeom = 0; curGeom < geometries.length; curGeom++ ) { - if ( $.geo.distance( geometries[ curGeom ], selector ) <= mapTol ) { - result.push( graphicShape.shape ); - break; - } - } - } - } - } else { - result.push( graphicShape.shape ); - } - } - - return result; - }, - - remove: function ( shape, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - var shapes = $.isArray( shape ) ? shape : [ shape ], - rest; - - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - if ( $.inArray( this._graphicShapes[ i ].shape, shapes ) >= 0 ) { - rest = this._graphicShapes.slice( i + 1 ); - this._graphicShapes.length = i; - this._graphicShapes.push.apply( this._graphicShapes, rest ); - i--; - } - } - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - _getBbox: function (center, pixelSize) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - // calculate the internal bbox - var halfWidth = this._contentBounds[ "width" ] / 2 * pixelSize, - halfHeight = this._contentBounds[ "height" ] / 2 * pixelSize; - return [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - }, - - _setBbox: function (value /* , trigger, refresh */ ) { - var center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2], - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height), - zoom = this._getZoom( center, pixelSize ); - - // clamp to zoom - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._setInteractiveCenterAndSize( center, pixelSize ); - this._interactiveTransform( ); - }, - - _getBboxMax: function () { - // calculate the internal bboxMax - var halfWidth = this._contentBounds["width"] / 2 * this._pixelSizeMax, - halfHeight = this._contentBounds["height"] / 2 * this._pixelSizeMax; - return [this._centerMax[0] - halfWidth, this._centerMax[1] - halfHeight, this._centerMax[0] + halfWidth, this._centerMax[1] + halfHeight]; - }, - - _getCenter: function () { - return this._center; - }, - - _getContentBounds: function () { - return this._contentBounds; - }, - - _getServicesContainer: function () { - return this._$servicesContainer; - }, - - _getZoom: function ( center, pixelSize ) { - // calculate the internal zoom level, vs. public zoom property - // this does not take zoomMin or zoomMax into account - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var tilingScheme = this._options["tilingScheme"]; - if ( tilingScheme ) { - if ( tilingScheme.pixelSizes ) { - var roundedPixelSize = Math.floor(pixelSize * 1000), - levels = tilingScheme.pixelSizes.length, - i = levels - 1; - - for ( ; i >= 0; i-- ) { - if ( Math.floor( tilingScheme.pixelSizes[ i ] * 1000 ) >= roundedPixelSize ) { - return i; - } - } - - return 0; - } else { - return Math.round( Math.log( tilingScheme.basePixelSize / pixelSize) / Math.log( 2 ) ); - } - } else { - var ratio = this._contentBounds["width"] / this._contentBounds["height"], - bbox = $.geo.reaspect( this._getBbox( center, pixelSize ), ratio, true ), - bboxMax = $.geo.reaspect(this._getBboxMax(), ratio, true); - - return Math.round( Math.log($.geo.width(bboxMax, true) / $.geo.width(bbox, true)) / Math.log(this._fullZoomFactor) ); - } - }, - - _setZoom: function ( value, trigger /* , refresh */ ) { - // set the map widget's zoom, taking zoomMin and zoomMax into account - this._clearInteractiveTimeout( ); - - value = Math.min( Math.max( value, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ); - - this._setInteractiveCenterAndSize( this._centerInteractive, this._getPixelSize( value ) ); - this._interactiveTransform( ); - this._setInteractiveTimeout( trigger ); - }, - - _createChildren: function () { - this._$existingChildren = this._$elem.children(); - - this._forcePosition(this._$existingChildren); - - this._$existingChildren.detach().css( { - mozUserSelect: "none" - } ); - - - var contentSizeCss = "width:" + this._contentBounds["width"] + "px; height:" + this._contentBounds["height"] + "px; margin:0; padding:0;", - contentPosCss = "position:absolute; left:0; top:0;"; - - this._$elem.prepend( window.toStaticHTML( '
              ' ) ); - this._$eventTarget = this._$contentFrame = this._$elem.children(':first'); - - this._$contentFrame.append('
              '); - this._$servicesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append( '
                ' ); - this._$attrList = this._$contentFrame.children( ":last" ); - - this._$contentFrame.append('
                '); - this._$drawContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                '); - this._$measureContainer = this._$contentFrame.children(':last'); - this._$measureLabel = this._$measureContainer.children(); - - this._$contentFrame.append('
                '); - this._$shapesContainer = this._$contentFrame.children(':last'); - - this._$panContainer = $( [ this._$shapesContainer[ 0 ], this._$drawContainer[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$resizeContainer = $( [ this._$contentFrame[ 0 ], this._$servicesContainer[ 0 ], this._$eventTarget[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$contentFrame.append(this._$existingChildren); - - if ( ! $("#geo-measure-style").length ) { - $("head").prepend( window.toStaticHTML( '' ) ); - } - }, - - _createServices: function () { - var service, i; - - for ( i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap( "destroy" ); - $.geo[ "_serviceTypes" ][ this._currentServices[ i ].type ].destroy( this, this._$servicesContainer, this._currentServices[ i ] ); - } - - this._currentServices = [ ]; - this._$servicesContainer.html( "" ); - this._$attrList.html( "" ); - - for ( i = 0; i < this._options[ "services" ].length; i++ ) { - service = this._currentServices[ i ] = $.extend( { }, this._options[ "services" ][ i ] ); - - // keep a reference to the original - service.serviceObject = this._options[ "services" ][ i ]; - - // default the service style property on our copy - service.style = $.extend( { - visibility: "visible", - opacity: 1 - }, service.style ); - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = 'class="geo-service ' + ( service["class"] ? service["class"] : '' ) + '"', - scHtml = '
                ', - serviceContainer; - - this._$servicesContainer.append( window.toStaticHTML( scHtml ) ); - serviceContainer = this._$servicesContainer.children( ":last" ); - service.serviceContainer = serviceContainer; - - $.geo[ "_serviceTypes" ][ service.type ].create( this, serviceContainer, service, i ); - - serviceContainer.data( "geoMap", this ).geomap(); - - if ( service.attr ) { - this._$attrList.append( '
              • ' + service.attr + '
              • ' ); - } - } - - // start with our map-level shapesContainer - this._$shapesContainers = this._$shapesContainer; - - this._$attrList.find( "a" ).css( { - position: "relative", - zIndex: 1, - display: "inline-block", - webkitTransform: "translateZ(0)" - } ); - }, - - _createServiceGraphics: function( ) { - // only called in the context of a service-level geomap - var $contentFrame = this._$elem.closest( ".geo-content-frame" ); - this._$elem.append('
                '); - this._$shapesContainer = this._$elem.children(':last'); - - this._map._$shapesContainers = this._map._$shapesContainers.add( this._$shapesContainer ); - - this._$shapesContainer.geographics( ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - }, - - _refreshDrawing: function ( ) { - this._$drawContainer.geographics("clear"); - - if ( this._drawPixels.length > 0 ) { - var mode = this._options[ "mode" ], - pixels = this._drawPixels, - coords = this._drawCoords, - label, - labelShape, - labelPixel, - widthOver, - heightOver; - - switch ( mode ) { - case "measureLength": - mode = "drawLineString"; - labelShape = { - type: "LineString", - coordinates: coords - }; - label = $.render[ this._tmplLengthId ]( { length: $.geo.length( labelShape, true ) } ); - labelPixel = $.merge( [], pixels[ pixels.length - 1 ] ); - break; - - case "measureArea": - mode = "drawPolygon"; - - labelShape = { - type: "Polygon", - coordinates: [ $.merge( [ ], coords ) ] - }; - labelShape.coordinates[ 0 ].push( coords[ 0 ] ); - - label = $.render[ this._tmplAreaId ]( { area: $.geo.area( labelShape, true ) } ); - labelPixel = this._toPixel( $.geo.centroid( labelShape ).coordinates ); - pixels = [ pixels ]; - break; - - case "drawPolygon": - pixels = [ pixels ]; - break; - } - - this._$drawContainer.geographics( mode, pixels ); - - if ( label ) { - this._$measureLabel.html( label ); - - widthOver = this._contentBounds.width - ( this._$measureLabel.outerWidth( true ) + labelPixel[ 0 ] ); - heightOver = this._contentBounds.height - ( this._$measureLabel.outerHeight( true ) + labelPixel[ 1 ] ); - - if ( widthOver < 0 ) { - labelPixel[ 0 ] += widthOver; - } - - if ( heightOver < 0 ) { - labelPixel[ 1 ] += heightOver; - } - - this._$measureLabel.css( { - left: Math.max( labelPixel[ 0 ], 0 ), - top: Math.max( labelPixel[ 1 ], 0 ) - } ).show(); - } - } - }, - - _resetDrawing: function () { - this._drawPixels = []; - this._drawCoords = []; - this._$drawContainer.geographics("clear"); - this._$measureLabel.hide(); - }, - - _refreshAllShapes: function ( _serviceContainer ) { - this._timeoutRefreshShapes = null; - - var service, - geoService, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - geoService = service.serviceContainer.data( "geoService" ); - - if ( geoService._createdGraphics ) { - geoService._$shapesContainer.geographics( "clear" ); - if ( geoService._graphicShapes.length > 0 ) { - geoService._refreshShapes( geoService._$shapesContainer, geoService._graphicShapes, geoService._graphicShapes, geoService._graphicShapes ); - } - } - } - } - - if ( this._createdGraphics && !_serviceContainer ) { - this._$shapesContainer.geographics( "clear" ); - if ( this._graphicShapes.length > 0 ) { - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - } - }, - - - _refreshShapes: function (geographics, shapes, styles, labels, center, pixelSize) { - var i, mgi, - shape, - shapeBbox, - style, - label, - hasLabel, - labelPixel, - centroid, - bbox = this._map._getBbox(center, pixelSize); - - for (i = 0; i < shapes.length; i++) { - shape = shapes[i].shape || shapes[i]; - shape = shape.geometry || shape; - shapeBbox = $.data(shape, "geoBbox"); - - if ( shapeBbox && $.geo._bboxDisjoint( bbox, shapeBbox ) ) { - continue; - } - - style = $.isArray(styles) ? styles[i].style : styles; - label = $.isArray(labels) ? labels[i].label : labels; - hasLabel = ( label !== undefined ); - labelPixel = undefined; - centroid = $.geo.centroid( shape ); - - switch (shape.type) { - case "Point": - labelPixel = this._map.toPixel( shape.coordinates, center, pixelSize ); - this._$shapesContainer.geographics("drawPoint", labelPixel, style); - break; - case "LineString": - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.pointAlong( shape, 0.5 ).coordinates, center, pixelSize ); - } - break; - case "Polygon": - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiPoint": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPoint", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiLineString": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiPolygon": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - - case "GeometryCollection": - this._refreshShapes(geographics, shape.geometries, style, label, center, pixelSize); - break; - } - - if ( hasLabel && labelPixel ) { - this._$shapesContainer.geographics( "drawLabel", labelPixel, label ); - } - } - }, - - _findMapSize: function () { - // really, really attempt to find a size for this thing - // even if it's hidden (look at parents) - var size = { width: 0, height: 0 }, - sizeContainer = this._$elem; - - while (sizeContainer.size() && !(size["width"] > 0 && size["height"] > 0)) { - size = { width: sizeContainer.width(), height: sizeContainer.height() }; - if (size["width"] <= 0 || size["height"] <= 0) { - size = { width: parseInt(sizeContainer.css("width"), 10), height: parseInt(sizeContainer.css("height"), 10) }; - } - sizeContainer = sizeContainer.parent(); - } - return size; - }, - - _forcePosition: function (elem) { - var cssPosition = elem.css("position"); - if (cssPosition !== "relative" && cssPosition !== "absolute" && cssPosition !== "fixed") { - elem.css("position", "relative"); - } - }, - - _getPixelSize: function ( zoom ) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme !== null) { - if (zoom === 0) { - return tilingScheme.pixelSizes ? tilingScheme.pixelSizes[0] : tilingScheme.basePixelSize; - } - - zoom = Math.round(zoom); - zoom = Math.max(zoom, 0); - var levels = tilingScheme.pixelSizes ? tilingScheme.pixelSizes.length : tilingScheme.levels; - zoom = Math.min(zoom, levels - 1); - - if ( tilingScheme.pixelSizes ) { - return tilingScheme.pixelSizes[zoom]; - } else { - return tilingScheme.basePixelSize / Math.pow(2, zoom); - } - } else { - var bbox = $.geo.scaleBy( this._getBboxMax(), 1 / Math.pow( this._fullZoomFactor, zoom ), true ); - return Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - } - }, - - _getZoomCenterAndSize: function ( anchor, zoomDelta, full ) { - var zoomFactor = ( full ? this._fullZoomFactor : this._partialZoomFactor ), - scale = Math.pow( zoomFactor, -zoomDelta ), - pixelSize = this._pixelSizeInteractive * scale; - - if ( this._options[ "tilingScheme" ] ) { - // clamp to min/max pixelSize - pixelSize = Math.min( Math.max( pixelSize, this._pixelSizeMin ), this._pixelSizeMax ); - } - - var zoom = this._getZoom(this._centerInteractive, pixelSize); - - // clamp to zoom - if ( full && this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoomDelta < 0 && zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._pixelSizeInteractive; - } else if ( zoomDelta > 0 && zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._pixelSizeInteractive; - } - } - - var ratio = pixelSize / this._pixelSizeInteractive, - anchorMapCoord = this._toMap( anchor, this._centerInteractive, this._pixelSizeInteractive ), - centerDelta = [(this._centerInteractive[0] - anchorMapCoord[0]) * ratio, (this._centerInteractive[1] - anchorMapCoord[1]) * ratio], - scaleCenter = [anchorMapCoord[0] + centerDelta[0], anchorMapCoord[1] + centerDelta[1]]; - - return { pixelSize: pixelSize, center: scaleCenter }; - }, - - _panFinalize: function () { - if (this._panning) { - this._velocity = [0, 0]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._inOp = false; - this._anchor = this._current; - this._mouseDown = this._toolPan = this._panning = false; - } - }, - - _panMove: function () { - if ( ! this._options[ "pannable" ] ) { - return; - } - - var dx = this._current[0] - this._lastDrag[0], - dy = this._current[1] - this._lastDrag[1]; - - if (this._toolPan || dx > 3 || dx < -3 || dy > 3 || dy < -3) { - if (!this._toolPan) { - this._toolPan = true; - this._$eventTarget.css("cursor", this._options["cursors"]["pan"]); - } - - if (this._mouseDown) { - this._velocity = [dx, dy]; - } - - if (dx !== 0 || dy !== 0) { - this._panning = true; - this._lastDrag = this._current; - - this._centerInteractive[ 0 ] -= ( dx * this._pixelSizeInteractive ); - this._centerInteractive[ 1 ] += ( ( this._options[ "axisLayout" ] === "image" ? -1 : 1 ) * dy * this._pixelSizeInteractive ); - this._setInteractiveCenterAndSize( this._centerInteractive, this._pixelSizeInteractive ); - this._interactiveTransform( ); - } - } - }, - - _clearInteractiveTimeout: function() { - if ( this._timeoutRefreshShapes ) { - clearTimeout( this._timeoutRefreshShapes ); - this._timeoutRefreshShapes = null; - } - - if ( this._timeoutInteractive ) { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - return true; - } else { - this._centerInteractive[ 0 ] = this._center[ 0 ]; - this._centerInteractive[ 1 ] = this._center[ 1 ]; - this._pixelSizeInteractive = this._pixelSize; - return false; - } - }, - - _interactiveTransform: function( ) { - var service, - - scalePixelSize = this._pixelSize, - scaleRatio = scalePixelSize / this._pixelSizeInteractive; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = this._toMap( [ 0, 0 ] ), - newPixelPoint = this._toPixel( oldMapOrigin, this._centerInteractive, this._pixelSizeInteractive ); - - - this._$shapesContainers.geographics("interactiveTransform", newPixelPoint, scaleRatio); - } - - for ( var i = 0; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo[ "_serviceTypes" ][ service.type ].interactiveTransform( this, service, this._centerInteractive, this._pixelSizeInteractive ); - } - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel( this._drawCoords, this._centerInteractive, this._pixelSizeInteractive ); - this._refreshDrawing(); - } - }, - - _interactiveTimeout: function( ) { - if ( this._isMultiTouch ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - } else if ( this._created && this._timeoutInteractive ) { - this._setCenterAndSize( this._centerInteractive, this._pixelSizeInteractive, this._triggerInteractive, true ); - this._timeoutInteractive = null; - this._triggerInteractive = false; - - this._timeoutRefreshShapes = setTimeout( $.proxy( this._refreshAllShapes, this ), 128 ); - } - }, - - _setInteractiveTimeout: function( trigger ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - this._triggerInteractive |= trigger; - }, - - _refresh: function ( force, _serviceContainer ) { - var service, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service, force ); - } - } - }, - - _setInteractiveCenterAndSize: function ( center, pixelSize ) { - // set the temporary (interactive) center & size - // also, update the public-facing options - // this does not take zoomMin or zoomMax into account - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - this._pixelSizeInteractive = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox( center, pixelSize ) ); - this._options["center"] = $.geo.proj.toGeodetic( center ); - } else { - this._options["bbox"] = this._getBbox( center, pixelSize ); - this._options["center"][ 0 ] = center[ 0 ]; - this._options["center"][ 1 ] = center[ 1 ]; - } - - this._options["pixelSize"] = pixelSize; - this._options["zoom"] = this._getZoom( center, pixelSize ); - }, - - _setCenterAndSize: function (center, pixelSize, trigger, refresh) { - if ( ! $.isArray( center ) || center.length !== 2 || typeof center[ 0 ] !== "number" || typeof center[ 1 ] !== "number" ) { - return; - } - - // the final call during any extent change - // only called by timeoutInteractive & resize - // clamp to zoom - var zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - - if ( this._created ) { - // one last interactiveTransform to put pinched map into place - this._interactiveTransform( ); - } - - this._options["pixelSize"] = this._pixelSize = pixelSize; - - this._center[ 0 ] = center[ 0 ]; - this._center[ 1 ] = center[ 1 ]; - - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox() ); - this._options["center"] = $.geo.proj.toGeodetic( this._center ); - } else { - this._options["bbox"] = this._getBbox(); - this._options["center"] = $.merge( [ ], center ); - } - - this._options["zoom"] = zoom; - - if (trigger) { - this._trigger("bboxchange", window.event, { bbox: $.merge( [ ], this._options["bbox"] ) }); - } - - if (refresh) { - this._refresh(); - this._refreshAllShapes( ); - this._refreshDrawing(); - } - }, - - _requestQueued: function ( ) { - if ( this._loadCount === 0 ) { - this._trigger( "loadstart", window.event ); - } - this._loadCount++; - }, - - _requestComplete: function ( ) { - this._loadCount--; - if ( this._loadCount <= 0 ) { - this._loadCount = 0; - this._trigger( "loadend", window.event ); - } - }, - - _toMap: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - xRatio = $.geo.width(bbox, true) / width, - yRatio = $.geo.height(bbox, true) / height, - yOffset, - image = this._options[ "axisLayout" ] === "image", - result = [], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - yOffset = (p[ i ][ j ][ k ][1] * yRatio); - result[ i ][ j ][ k ] = [ - bbox[ 0 ] + ( p[ i ][ j ][ k ][ 0 ] * xRatio ), - image ? bbox[ 1 ] + yOffset : bbox[ 3 ] - yOffset - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _toPixel: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - bboxWidth = $.geo.width(bbox, true), - bboxHeight = $.geo.height(bbox, true), - image = this._options[ "axisLayout" ] === "image", - xRatio = width / bboxWidth, - yRatio = height / bboxHeight, - result = [ ], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = [ - Math.round( ( p[ i ][ j ][ k ][ 0 ] - bbox[ 0 ] ) * xRatio ), - Math.round( ( image ? p[ i ][ j ][ k ][ 1 ] - bbox[ 1 ] : bbox[ 3 ] - p[ i ][ j ][ k ][ 1 ] ) * yRatio ) - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _document_keydown: function (e) { - var len = this._drawCoords.length; - if (len > 0 && e.which === 27) { - if (len <= 2) { - this._resetDrawing(); - this._inOp = false; - } else { - this._drawCoords[len - 2] = $.merge( [], this._drawCoords[ len - 1 ] ); - this._drawPixels[len - 2] = $.merge( [], this._drawPixels[ len - 1 ] ); - - this._drawCoords.length--; - this._drawPixels.length--; - - this._refreshDrawing(); - } - } - }, - - _eventTarget_dblclick_zoom: function(e) { - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - this._trigger("dblclick", e, { type: "Point", coordinates: this._toMap(this._current, this._centerInteractive, this._pixelSizeInteractive ) }); - - if (!e.isDefaultPrevented()) { - var centerAndSize = this._getZoomCenterAndSize(this._current, 1, true ); - - this._setInteractiveCenterAndSize( centerAndSize.center, centerAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - }, - - _eventTarget_dblclick: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - switch (this._options["mode"]) { - case "drawLineString": - case "measureLength": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] === this._drawCoords[1][0] && - this._drawCoords[0][1] === this._drawCoords[1][1] ) ) { - this._drawCoords.length--; - this._trigger( "shape", e, { - type: "LineString", - coordinates: this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords - } ); - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "drawPolygon": - case "measureArea": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] === this._drawCoords[1][0] && - this._drawCoords[0][1] === this._drawCoords[1][1] ) ) { - var endIndex = this._drawCoords.length - 1; - if (endIndex > 2) { - this._drawCoords[endIndex] = $.merge( [], this._drawCoords[0] ); - this._trigger( "shape", e, { - type: "Polygon", - coordinates: [ this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords ] - } ); - } - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - default: - this._eventTarget_dblclick_zoom(e); - break; - } - - this._inOp = false; - }, - - _eventTarget_touchstart: function (e) { - if ( typeof( document.elementFromPoint ) !== "undefined" ) { - var elFromPt = document.elementFromPoint( e.pageX, e.pageY ); - if ( elFromPt && elFromPt.nodeName === "A" ) { - return; - } - } - - var mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ); - - if ( mode === "static" ) { - return; - } - - if ( !this._pointerEvents && !this._supportTouch && e.which !== 1 ) { - return; - } - - if ( this._pointerEvents ) { - console.log( 'PointerEvent touchstart' ); - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var offset = $(e.currentTarget).offset(), - touches = e.originalEvent.changedTouches; - - if ( this._pointerEvents ) { - e.currentTarget.setPointerCapture( e.originalEvent.pointerId ); - - - - - - - - - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 && e.originalEvent.pointerId !== this._multiTouchAnchor[ 0 ].pointerId ) { - // switch to multitouch - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( e.originalEvent ); - - - - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._anchor = $.geo.center( this._multiTouchCurrentBbox, true ); - this._current = $.merge( [], this._anchor ); - - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - } else { - this._multiTouchAnchor.push( e.originalEvent ); - - this._multiTouchCurrentBbox = [ - this._multiTouchAnchor[0].pageX - offset.left, - this._multiTouchAnchor[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ this._multiTouchAnchor[0].pageX - offset.left, this._multiTouchAnchor[0].pageY - offset.top ]; - } - } else if ( this._supportTouch && touches ) { - this._multiTouchAnchor = $.merge( [ ], touches ); - - this._isMultiTouch = this._multiTouchAnchor.length > 1; - - if ( this._isMultiTouch ) { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - touches[1].pageX - offset.left, - touches[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ touches[0].pageX - offset.left, touches[0].pageY - offset.top ]; - } - } else { - this._current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - var downDate = $.now(); - if (downDate - this._downDate < 750) { - if (this._isTap) { - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance > 8) { - this._isTap = false; - } else { - this._current = $.merge( [ ], this._anchor ); - } - } - - if (this._isDbltap) { - this._isDbltap = false; - } else { - this._isDbltap = this._isTap; - } - } else { - this._isDbltap = false; - } - this._isTap = true; - this._downDate = downDate; - } - - this._mouseDown = true; - this._anchor = $.merge( [ ], this._current ); - - if (!this._inOp && e.shiftKey && shift !== "off") { - this._shiftDown = true; - this._$eventTarget.css( "cursor", this._options[ "cursors" ][ shift === "default" ? defaultShift : shift ] ); - } else if ( !this._isMultiTouch && ( this._options[ "pannable" ] || mode === "dragBox" || mode === "dragCircle" ) ) { - this._inOp = true; - - if ( mode !== "zoom" && mode !== "dragBox" && mode !== "dragCircle" ) { - this._lastDrag = this._current; - - if (e.currentTarget.setCapture) { - e.currentTarget.setCapture(); - } - } - } - - e.preventDefault(); - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - }, - - _dragTarget_touchmove: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - var doInteractiveTimeout = false; - if ( this._mouseDown ) { - doInteractiveTimeout = this._clearInteractiveTimeout( ); - } - - var offset = this._$eventTarget.offset(), - drawCoordsLen = this._drawCoords.length, - touches = e.originalEvent.changedTouches, - current, - anchorDistance, - currentDistance, - wheelLevel, - delta, - pinchCenterAndSize, - i; - - if ( this._pointerEvents ) { - - if ( this._isMultiTouch ) { - - if ( e.originalEvent.pointerId === this._multiTouchAnchor[ 0 ].pointerId ) { - this._multiTouchCurrentBbox[ 0 ] = e.originalEvent.pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = e.originalEvent.pageY - offset.top; - } else if ( e.originalEvent.pointerId === this._multiTouchAnchor[ 1 ].pointerId ) { - this._multiTouchCurrentBbox[ 2 ] = e.originalEvent.pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = e.originalEvent.pageY - offset.top; - } - - anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ); - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchAnchor[ 0 ] = e.originalEvent; - - this._multiTouchCurrentBbox = [ - this._multiTouchAnchor[0].pageX - offset.left, - this._multiTouchAnchor[0].pageY - offset.top, - NaN, - NaN - ]; - - current = [e.originalEvent.pageX - offset.left, e.originalEvent.pageY - offset.top]; - } - } else if ( this._supportTouch && touches ) { - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 && touches[ 0 ].identifier !== this._multiTouchAnchor[ 0 ].identifier ) { - // switch to multitouch - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( touches[ 0 ] ); - - - - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._anchor = this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - if ( this._isMultiTouch ) { - - for ( i = 0; i < touches.length; i++ ) { - if ( touches[ i ].identifier === this._multiTouchAnchor[ 0 ].identifier ) { - this._multiTouchCurrentBbox[ 0 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = touches[ i ].pageY - offset.top; - } else if ( touches[ i ].identifier === this._multiTouchAnchor[ 1 ].identifier ) { - this._multiTouchCurrentBbox[ 2 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = touches[ i ].pageY - offset.top; - } - } - - anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ); - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (current[0] === this._lastMove[0] && current[1] === this._lastMove[1]) { - if ( this._inOp ) { - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } else { - // fixes: [bug] highlight pop - return false; - } - } - - if ( _ieVersion === 7 ) { - this._isDbltap = this._isTap = false; - } - - if (this._mouseDown) { - this._current = current; - this._moveDate = $.now(); - } - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - var mode = this._options["mode"], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - dx, dy, circleSize; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - switch (mode) { - case "zoom": - case "dragBox": - if ( this._mouseDown ) { - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawBbox", [ - this._anchor[ 0 ], - this._anchor[ 1 ], - current[ 0 ], - current[ 1 ] - ] ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "dragCircle": - if ( this._mouseDown ) { - dx = current[ 0 ] - this._anchor[ 0 ]; - dy = current[ 1 ] - this._anchor[ 1 ]; - circleSize = Math.sqrt( ( dx * dx) + ( dy * dy ) ) * 2; - //circleSize = Math.max( Math.abs( current[ 0 ] - this._anchor[ 0 ] ), Math.abs( current[ 1 ] - this._anchor[ 1 ] ) ) * 2; - - // not part of _refreshDrawing - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawArc", this._anchor, 0, 360, { - width: circleSize, - height: circleSize - } ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - if (drawCoordsLen > 0) { - this._drawCoords[drawCoordsLen - 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[drawCoordsLen - 1] = current; - - this._refreshDrawing(); - } - - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - default: - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - } - - this._lastMove = current; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchstop: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if ( this._pointerEvents ) { - console.log( 'PointerEvent touchstop' ); - } - - if ( !this._mouseDown ) { - if ( _ieVersion === 7 ) { - // ie7 doesn't appear to trigger dblclick on this._$eventTarget, - // we fake regular click here to cause soft dblclick - this._eventTarget_touchstart(e); - } else { - // Chrome & Firefox trigger a rogue mouseup event when doing a dblclick maximize in Windows(/Linux?) - // ignore it - return; - } - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var mouseWasDown = this._mouseDown, - wasToolPan = this._toolPan, - offset = this._$eventTarget.offset(), - mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - current, i, clickDate, - dx, dy, - coordBuffer, - triggerShape; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - if ( this._pointerEvents ) { - current = [e.pageX - offset.left, e.pageY - offset.top]; - - for ( i = 0; i < this._multiTouchAnchor.length; i++ ) { - e.currentTarget.releasePointerCapture( this._multiTouchAnchor[ i ].pointerId ); - } - - this._multiTouchAnchor = []; - this._inOp = false; - } else if (this._supportTouch && e.originalEvent.changedTouches) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - this._multiTouchAnchor = []; - this._inOp = false; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - if (this._isTap) { - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - if (Math.sqrt((dx * dx) + (dy * dy)) <= 8) { - current = $.merge( [ ], this._anchor ); - } - } - } - - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._shiftDown = this._mouseDown = this._toolPan = false; - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isMultiTouch = false; - - this._wheelLevel = 0; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return; - } - - if (document.releaseCapture) { - document.releaseCapture(); - } - - if (mouseWasDown) { - clickDate = $.now(); - this._current = current; - - switch ( mode ) { - case "zoom": - case "dragBox": - if ( dx !== 0 || dy !== 0 ) { - var minSize = this._pixelSize * 6, - bboxCoords = this._toMap( [ this._anchor, current ] ), - bbox = [ - Math.min( bboxCoords[0][0], bboxCoords[1][0] ), - Math.min( bboxCoords[0][1], bboxCoords[1][1] ), - Math.max( bboxCoords[0][0], bboxCoords[1][0] ), - Math.max( bboxCoords[0][1], bboxCoords[1][1] ) - ]; - - if ( mode === "zoom" ) { - if ( ( bbox[2] - bbox[0] ) < minSize && ( bbox[3] - bbox[1] ) < minSize ) { - bbox = $.geo.scaleBy( this._getBbox( $.geo.center( bbox, true ) ), 0.5, true ); - } - - this._setBbox(bbox, true, true); - doInteractiveTimeout = true; - } else { - triggerShape = $.geo.polygonize( bbox, true ); - triggerShape.bbox = bbox; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - this._trigger( "shape", e, triggerShape ); - } - } else { - if ( mode === "dragBox" ) { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - } - - this._resetDrawing(); - break; - - case "dragCircle": - if ( dx !== 0 || dy !== 0 ) { - var image = this._options[ "axisLayout" ] === "image", - d = Math.sqrt( ( dx * dx) + ( dy * dy ) ), - n = 180, - a; - - this._drawPixels.length = n + 1; - - for ( i = 0; i < n; i++ ) { - a = ( i * 360 / n ) * ( Math.PI / 180 ); - this._drawPixels[ i ] = [ - this._anchor[ 0 ] + Math.cos( a ) * d, - this._anchor[ 1 ] + Math.sin( a ) * d - ]; - } - - this._drawPixels[ n ] = [ - this._drawPixels[ 0 ][ 0 ], - this._drawPixels[ 0 ][ 1 ] - ]; - - // using coordBuffer for bbox coords - coordBuffer = this._toMap( [ - [ this._anchor[ 0 ] - d, this._anchor[ 1 ] + ( image ? -d : d ) ], - [ this._anchor[ 0 ] + d, this._anchor[ 1 ] + ( image ? d : -d ) ] - ] ); - - triggerShape = { - type: "Polygon", - coordinates: [ this._toMap( this._drawPixels ) ], - bbox: [ coordBuffer[ 0 ][ 0 ], coordBuffer[ 0 ][ 1 ], coordBuffer[ 1 ][ 0 ], coordBuffer[ 1 ][ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - - this._resetDrawing(); - } else { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - break; - - case "drawPoint": - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - var geomap = this; - this._drawTimeout = setTimeout(function () { - if (geomap._drawTimeout) { - geomap._trigger("shape", e, { type: "Point", coordinates: geomap.toMap(current) }); - geomap._inOp = false; - geomap._drawTimeout = null; - } - }, 250); - } - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (wasToolPan) { - this._panFinalize(); - } else { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - - if (!e.isDefaultPrevented()) { - i = (this._drawCoords.length === 0 ? 0 : this._drawCoords.length - 1); - - this._drawCoords[i] = this._toMap(current); - this._drawPixels[i] = current; - - if (i < 2 || !(this._drawCoords[i][0] === this._drawCoords[i-1][0] && - this._drawCoords[i][1] === this._drawCoords[i-1][1])) { - this._drawCoords[i + 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[i + 1] = current; - } - - this._refreshDrawing(); - } - } - break; - - default: - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - this._inOp = false; - } - } - break; - } - - this._clickDate = clickDate; - - if (this._softDblClick && this._isDbltap) { - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - this._$eventTarget.trigger("dblclick", e); - return false; - } - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _eventTarget_mousewheel: function ( e ) { - if ( this._options[ "mode" ] === "static" || this._options[ "scroll" ] === "off" ) { - return; - } - - e.preventDefault(); - - if ( this._mouseDown ) { - return false; - } - - if (e.deltaY !== 0) { - this._clearInteractiveTimeout( ); - - var delta = e.deltaY > 0 ? 1 : -1; - - var offset = $(e.currentTarget).offset(); - this._anchor = [e.pageX - offset.left, e.pageY - offset.top]; - - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, this._options[ "tilingScheme" ] !== null ); - - this._setInteractiveCenterAndSize( wheelCenterAndSize.center, wheelCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - this._setInteractiveTimeout( true ); - } - - return false; - } - } - ); -}(jQuery, window)); - - -(function ($, window, undefined) { - $.geo._serviceTypes.tiled = (function () { - var rTmplString = new RegExp( "<.*>|{{.*}}" ); - - return { - _serviceId: 0, - _tmplGeoSrcId: "", - - - create: function (map, serviceContainer, service /* , index */) { - this._serviceId = map._serviceIdSeed++; - this._tmplGeoSrcId = "geoSrc" + this._serviceId; - - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0, - reloadTiles: false - }; - - var scHtml = '
                '; - - serviceContainer.append( window.toStaticHTML( scHtml ) ); - - serviceState.serviceContainer = serviceContainer.children( ":last" ); - - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - //console.log( "tiled.interactiveTransform( " + center.join( ", " ) + ", " + pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ), - tilingScheme = map.options[ "tilingScheme" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data("pixelSize"), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapCoord = $scaleContainer.data("scaleOrigin"), - newPixelPoint = map._toPixel(oldMapCoord, center, pixelSize); - - $scaleContainer.css( { - left: Math.round(newPixelPoint[0]) + "px", - top: Math.round(newPixelPoint[1]) + "px", - width: tilingScheme.tileWidth * scaleRatio, - height: tilingScheme.tileHeight * scaleRatio - } ); - - /* - if ( $("body")[0].filters !== undefined ) { - $scaleContainer.children().each( function ( i ) { - $( this ).css( "filter", "progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11=" + scaleRatio + ",M22=" + scaleRatio + ",sizingmethod='auto expand')" ); - } ); - } - */ - } - }); - } - }, - - refresh: function (map, service, force) { - //console.log( "tiled.refresh( " + map._center.join( ", " ) + ", " + map._pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ); - - this._cancelUnloaded(map, service); - - if ( serviceState && force ) { - // if hidden atm, we want to make sure we reload this service after it becomes visible - serviceState.reloadTiles = true; - } - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - $serviceContainer = serviceState.serviceContainer, - - image = map.options[ "axisLayout" ] === "image", - ySign = image ? +1 : -1, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - - tileX = Math.floor((bbox[0] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.max( Math.floor( ( image ? bbox[1] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 3 ] ) / (pixelSize * tileHeight) ), 0 ), - tileX2 = Math.ceil((bbox[2] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil( ( image ? bbox[3] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 1 ] ) / (pixelSize * tileHeight) ), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] + ySign * bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMinOrMaxY = tilingScheme.origin[1] + ySign * (fullYAtScale * tileHeight) * pixelSize, - - serviceLeft = Math.round((fullXMinX - bbox[0]) / pixelSize), - serviceTop = Math.round( ( image ? fullYMinOrMaxY - bbox[1] : bbox[3] - fullYMinOrMaxY ) / pixelSize), - - scaleContainers = $serviceContainer.children().show(), - scaleContainer = scaleContainers.filter("[data-pixel-size='" + pixelSize + "']").appendTo($serviceContainer), - - opacity = service.style.opacity, - - x, y, - - loadImageDeferredDone = function( url ) { - // when a Deferred call is done, add the image to the map - // a reference to the correct img element is on the Deferred object itself - serviceObj._loadImage( this.img, url, pixelSize, map, serviceState, opacity ); - }, - - loadImageDeferredFail = function( ) { - delete this.img; - serviceState.loadCount--; - map._requestComplete(); - }; - - if (serviceState.reloadTiles) { - scaleContainers.find("img").attr("data-dirty", "true"); - } - - if (!scaleContainer.size()) { - $serviceContainer.append( window.toStaticHTML( "
                " ) ); - scaleContainer = $serviceContainer.children(":last").data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - } else { - scaleContainer.css({ - left: (serviceLeft % tileWidth) + "px", - top: (serviceTop % tileHeight) + "px" - }).data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - - scaleContainer.children().each( function () { - var $img = $(this), - tile = $img.attr("data-tile").split(","); - - $img.css({ - left: Math.round(((parseInt(tile[0], 10) - fullXAtScale) * 100) + (serviceLeft - (serviceLeft % tileWidth)) / tileWidth * 100) + "%", - top: Math.round(((parseInt(tile[1], 10) - fullYAtScale) * 100) + (serviceTop - (serviceTop % tileHeight)) / tileHeight * 100) + "%" - }); - - if (opacity < 1) { - $img.fadeTo(0, opacity); - } - } ); - } - - for (x = tileX; x < tileX2; x++) { - for (y = tileY; y < tileY2; y++) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ($img.size() === 0 || serviceState.reloadTiles) { - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] + ySign * (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] + ySign * ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - urlArgs = { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }, - isFunc = $.isFunction( service[ 'src' ] ), - imageUrl; - - if ( isFunc ) { - imageUrl = service[ 'src' ]( urlArgs ); - } else { - if ( rTmplString.test( service[ 'src' ] ) ) { - $.templates( this._tmplGeoSrcId, service[ 'src' ] ); - imageUrl = $.render[ this._tmplGeoSrcId ]( urlArgs ); - } else { - imageUrl = service[ 'src' ]; - } - } - - serviceState.loadCount++; - map._requestQueued(); - - if (serviceState.reloadTiles && $img.size() > 0) { - $img.attr("src", imageUrl); - } else { - var imgMarkup = ""; - - scaleContainer.append( window.toStaticHTML( imgMarkup ) ); - $img = scaleContainer.children(":last"); - } - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl && $.isFunction( imageUrl.promise ) ) { - // assume Deferred - $.extend( imageUrl.promise( ), { img: $img } ); - imageUrl.done( loadImageDeferredDone ).fail( loadImageDeferredFail ); - } else { - $img.remove( ); - } - } - } - } - - scaleContainers.find("[data-dirty]").remove(); - serviceState.reloadTiles = false; - } - }, - - resize: function ( /* map, service, dx, dy */ ) { - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.css( "display", service.style.visibility === "visible" ? "block" : "none" ); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if (serviceState && serviceState.loadCount > 0) { - /* - * #193 - disabled until we can do this without canceling all AJAX requests - * - if ( window.stop !== undefined ) { - window.stop(); - } else if( document.execCommand !== undefined ) { - document.execCommand("Stop", false); - } - */ - - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery, window)); - -(function ($, window, undefined) { - $.geo._serviceTypes.shingled = (function () { - var rTmplString = new RegExp( "<.*>|{{.*}}" ); - - return { - _serviceId: 0, - _tmplGeoSrcId: "", - - create: function ( map, serviceContainer, service /* , index */ ) { - this._serviceId = map._serviceIdSeed++; - this._tmplGeoSrcId = "geoSrc" + this._serviceId; - - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0 - }; - - var scHtml = '
                '; - - serviceContainer.append( window.toStaticHTML( scHtml ) ); - - serviceState.serviceContainer = serviceContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - var serviceState = $.data( service, "geoServiceState" ), - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds[ "width" ], - mapHeight = contentBounds[ "height" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data( "pixelSize" ), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin, center, pixelSize ); - - $scaleContainer.css( { - left: Math.round( newPixelPoint[ 0 ] ), - top: Math.round( newPixelPoint[ 1 ] ), - width: mapWidth * scaleRatio, - height: mapHeight * scaleRatio - } ); - } - }); - } - }, - - refresh: function (map, service, force) { - var serviceState = $.data(service, "geoServiceState"); - - this._cancelUnloaded(map, service); - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainer = serviceContainer.children('[data-pixel-size="' + pixelSize + '"]'), - - opacity = service.style.opacity, - - $img; - - if (opacity < 1 || force || service.shinglesMax === 1) { - serviceContainer.find("img").attr("data-keep-alive", "0"); - } else if ( service.shinglesMax > 1 ) { - serviceContainer.find("img").slice( 0, -( service.shinglesMax - 1 ) ).attr("data-keep-alive", "0"); - } - - if ( !scaleContainer.size() ) { - serviceContainer.append( window.toStaticHTML( '
                ' ) ); - scaleContainer = serviceContainer.children(":last"); - } - - var urlArgs = { - bbox: bbox, - width: mapWidth, - height: mapHeight, - zoom: map._getZoom(), - tile: null, - index: 0 - }, - isFunc = $.isFunction( service[ 'src' ] ), - imageUrl, - imagePos = scaleContainer.position( ); - - imagePos.left = - ( imagePos.left ); - imagePos.top = - ( imagePos.top ); - - if ( isFunc ) { - imageUrl = service[ 'src' ]( urlArgs ); - } else { - if ( rTmplString.test( service[ 'src' ] ) ) { - $.templates( this._tmplGeoSrcId, service[ 'src' ] ); - imageUrl = $.render[ this._tmplGeoSrcId ]( urlArgs ); - } else { - imageUrl = service[ 'src' ]; - } - } - - serviceState.loadCount++; - map._requestQueued(); - - scaleContainer.append( window.toStaticHTML( '' ) ); - $img = scaleContainer.children(":last").data("center", map._center); - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl ) { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, map, serviceState, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - map._requestComplete(); - } ); - } - - } - }, - - resize: function ( map, service /* , dx, dy */ ) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState && service && service.style.visibility === "visible" ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainers = serviceContainer.children(); - - scaleContainers.attr("data-pixel-size", "0"); - - scaleContainers.each( function ( ) { - var $scaleContainer = $(this), - position = $scaleContainer.position( ); - - $scaleContainer.css( { - left: position.left + ( mapWidth - $scaleContainer.width( ) ) / 2, - top: position.top + ( mapHeight - $scaleContainer.height( ) ) / 2 - } ); - - } ); - } - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.css("display", service.style.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - // #newpanzoom - serviceContainer.children(':not([data-pixel-size="' + pixelSize + '"])').remove(); - - serviceContainer.find( "img[data-keep-alive]" ).remove( ); - - serviceState.loadCount = 0; - } - }).error(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery, window)); diff --git a/dist/jquery.geo-1.0.0-b3.min.js b/dist/jquery.geo-1.0.0-b3.min.js deleted file mode 100644 index 4ac9134..0000000 --- a/dist/jquery.geo-1.0.0-b3.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! jQuery Geo - v1.0.0-b3 - 2015-10-17 -* http://jquerygeo.com -* Copyright (c) 2015 Ryan Morrison-Westphal; Licensed MIT */ -document.createElement("canvas").getContext||!function(){function a(){return this.context_||(this.context_=new q(this))}function b(a,b){var c=G.call(arguments,2);return function(){return a.apply(b,c.concat(G.call(arguments)))}}function c(a,b,c){a.namespaces[b]||a.namespaces.add(b,c,"#default#VML")}function d(a){if(c(a,"g_vml_","urn:schemas-microsoft-com:vml"),c(a,"g_o_","urn:schemas-microsoft-com:office:office"),!a.styleSheets.ex_canvas_){var b=a.createStyleSheet();b.owningElement.id="ex_canvas_",b.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function e(a){var b=a.srcElement;switch(a.propertyName){case"width":b.getContext().clearRect(),b.style.width=b.attributes.width.nodeValue+"px",b.firstChild.style.width=b.clientWidth+"px";break;case"height":b.getContext().clearRect(),b.style.height=b.attributes.height.nodeValue+"px",b.firstChild.style.height=b.clientHeight+"px"}}function f(a){var b=a.srcElement;b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px",b.firstChild.style.height=b.clientHeight+"px")}function g(){return[[1,0,0],[0,1,0],[0,0,1]]}function h(a,b){for(var c=g(),d=0;3>d;d++)for(var e=0;3>e;e++){for(var f=0,h=0;3>h;h++)f+=a[d][h]*b[h][e];c[d][e]=f}return c}function i(a,b){b.fillStyle=a.fillStyle,b.lineCap=a.lineCap,b.lineJoin=a.lineJoin,b.lineWidth=a.lineWidth,b.miterLimit=a.miterLimit,b.shadowBlur=a.shadowBlur,b.shadowColor=a.shadowColor,b.shadowOffsetX=a.shadowOffsetX,b.shadowOffsetY=a.shadowOffsetY,b.strokeStyle=a.strokeStyle,b.globalAlpha=a.globalAlpha,b.font=a.font,b.textAlign=a.textAlign,b.textBaseline=a.textBaseline,b.arcScaleX_=a.arcScaleX_,b.arcScaleY_=a.arcScaleY_,b.lineScale_=a.lineScale_}function j(a){var b=a.indexOf("(",3),c=a.indexOf(")",b+1),d=a.substring(b+1,c).split(",");return(4!=d.length||"a"!=a.charAt(3))&&(d[3]=1),d}function k(a){return parseFloat(a)/100}function l(a,b,c){return Math.min(c,Math.max(b,a))}function m(a){var b,c,d,e,f,g;if(e=parseFloat(a[0])/360%360,0>e&&e++,f=l(k(a[1]),0,1),g=l(k(a[2]),0,1),0==f)b=c=d=g;else{var h=.5>g?g*(1+f):g+f-g*f,i=2*g-h;b=n(i,h,e+1/3),c=n(i,h,e),d=n(i,h,e-1/3)}return"#"+I[Math.floor(255*b)]+I[Math.floor(255*c)]+I[Math.floor(255*d)]}function n(a,b,c){return 0>c&&c++,c>1&&c--,1>6*c?a+6*(b-a)*c:1>2*c?b:2>3*c?a+(b-a)*(2/3-c)*6:a}function o(a){if(a in L)return L[a];var b,c=1;if(a=String(a),"#"==a.charAt(0))b=a;else if(/^rgb/.test(a)){for(var d,e=j(a),b="#",f=0;3>f;f++)d=-1!=e[f].indexOf("%")?Math.floor(255*k(e[f])):+e[f],b+=I[l(d,0,255)];c=+e[3]}else if(/^hsl/.test(a)){var e=j(a);b=m(e),c=e[3]}else b=a;return L[a]={color:b,alpha:c}}function p(a){return M[a]||"square"}function q(a){this.m_=g(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.strokeStyle="#000",this.fillStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=1*E,this.globalAlpha=1,this.canvas=a;var b="width:"+a.clientWidth+"px;height:"+a.clientHeight+"px;overflow:hidden;position:absolute",c=a.ownerDocument.createElement("div");c.style.cssText=b,a.appendChild(c);var d=c.cloneNode(!1);d.style.backgroundColor="red",d.style.filter="alpha(opacity=0)",a.appendChild(d),this.element_=c,this.arcScaleX_=1,this.arcScaleY_=1,this.lineScale_=1}function r(a,b,c,d){a.currentPath_.push({type:"bezierCurveTo",cp1x:b.x,cp1y:b.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y}),a.currentX_=d.x,a.currentY_=d.y}function s(a,b){var c=o(a.strokeStyle),d=c.color,e=c.alpha*a.globalAlpha,f=a.lineScale_*a.lineWidth;1>f&&(e*=f),b.push("')}function t(a,b,c,d){var e=(a.fillStyle,a.arcScaleX_,a.arcScaleY_,d.x-c.x,d.y-c.y,o(a.fillStyle)),f=e.color,g=e.alpha*a.globalAlpha;b.push('')}function u(a,b,c){var d=a.m_;return{x:E*(b*d[0][0]+c*d[1][0]+d[2][0])-F,y:E*(b*d[0][1]+c*d[1][1]+d[2][1])-F}}function v(a){return isFinite(a[0][0])&&isFinite(a[0][1])&&isFinite(a[1][0])&&isFinite(a[1][1])&&isFinite(a[2][0])&&isFinite(a[2][1])}function w(a,b,c){if(v(b)&&(a.m_=b,c)){var d=b[0][0]*b[1][1]-b[0][1]*b[1][0];a.lineScale_=D(C(d))}}function x(a){this.code=this[a],this.message=a+": DOM Exception "+this.code}var y=Math,z=y.round,A=y.sin,B=y.cos,C=y.abs,D=y.sqrt,E=10,F=E/2,G=(+navigator.userAgent.match(/MSIE ([\d.]+)?/)[1],Array.prototype.slice);d(document);var H={init:function(a){var c=a||document;c.createElement("canvas"),c.attachEvent("onreadystatechange",b(this.init_,this,c))},init_:function(a){for(var b=a.getElementsByTagName("canvas"),c=0;cJ;J++)for(var K=0;16>K;K++)I[16*J+K]=J.toString(16)+K.toString(16);var L={},M={butt:"flat",round:"round"},N=q.prototype;N.clearRect=function(){this.textMeasureEl_&&(this.textMeasureEl_.removeNode(!0),this.textMeasureEl_=null),this.element_.innerHTML=""},N.beginPath=function(){this.currentPath_=[]},N.moveTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"moveTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.lineTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"lineTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.bezierCurveTo=function(a,b,c,d,e,f){var g=u(this,e,f),h=u(this,a,b),i=u(this,c,d);r(this,h,i,g)},N.quadraticCurveTo=function(a,b,c,d){var e=u(this,a,b),f=u(this,c,d),g={x:this.currentX_+2/3*(e.x-this.currentX_),y:this.currentY_+2/3*(e.y-this.currentY_)},h={x:g.x+(f.x-this.currentX_)/3,y:g.y+(f.y-this.currentY_)/3};r(this,g,h,f)},N.arc=function(a,b,c,d,e,f){c*=E;var g=f?"at":"wa",h=a+B(d)*c-F,i=b+A(d)*c-F,j=a+B(e)*c-F,k=b+A(e)*c-F;h!=j||f||(h+=.125);var l=u(this,a,b),m=u(this,h,i),n=u(this,j,k);this.currentPath_.push({type:g,x:l.x,y:l.y,radius:c,xStart:m.x,yStart:m.y,xEnd:n.x,yEnd:n.y})},N.stroke=function(a){var b=[],c=10,d=10;b.push("f.x)&&(f.x=i.x),(null==e.y||i.yf.y)&&(f.y=i.y))}b.push(' ">'),a?t(this,b,e,f):s(this,b),b.push(""),this.element_.insertAdjacentHTML("beforeEnd",b.join(""))},N.fill=function(){this.stroke(!0)},N.closePath=function(){this.currentPath_.push({type:"close"})},N.save=function(){var a={};i(this,a),this.aStack_.push(a),this.mStack_.push(this.m_),this.m_=h(g(),this.m_)},N.restore=function(){this.aStack_.length&&(i(this.aStack_.pop(),this),this.m_=this.mStack_.pop())},N.translate=function(a,b){var c=[[1,0,0],[0,1,0],[a,b,1]];w(this,h(c,this.m_),!1)},N.scale=function(a,b){this.arcScaleX_*=a,this.arcScaleY_*=b;var c=[[a,0,0],[0,b,0],[0,0,1]];w(this,h(c,this.m_),!0)};var O=x.prototype=new Error;O.INDEX_SIZE_ERR=1,O.DOMSTRING_SIZE_ERR=2,O.HIERARCHY_REQUEST_ERR=3,O.WRONG_DOCUMENT_ERR=4,O.INVALID_CHARACTER_ERR=5,O.NO_DATA_ALLOWED_ERR=6,O.NO_MODIFICATION_ALLOWED_ERR=7,O.NOT_FOUND_ERR=8,O.NOT_SUPPORTED_ERR=9,O.INUSE_ATTRIBUTE_ERR=10,O.INVALID_STATE_ERR=11,O.SYNTAX_ERR=12,O.INVALID_MODIFICATION_ERR=13,O.NAMESPACE_ERR=14,O.INVALID_ACCESS_ERR=15,O.VALIDATION_ERR=16,O.TYPE_MISMATCH_ERR=17,G_vmlCanvasManager=H,CanvasRenderingContext2D=q,DOMException=x}(),this.jsviews||this.jQuery&&jQuery.views||function(a,b){function c(a,b){var c="\\"+a.charAt(0),d="\\"+a.charAt(1),e="\\"+b.charAt(0),f="\\"+b.charAt(1);return Q.rTag=u=d+"(?:(?:(\\w+(?=[\\/\\s"+e+"]))|(?:(\\w+)?(:)|(>)|(\\*)))\\s*((?:[^"+e+"]|"+e+"(?!"+f+"))*?)(\\/)?|(?:\\/(\\w+)))"+e,u=new RegExp(c+u+f,"g"),v=new RegExp("<.*>|"+a+".*"+b),this}function d(a){var c=this,d=c.tmpl.helpers||{};return a=(c.ctx[a]!==b?c.ctx:d[a]!==b?d:k[a]!==b?k:{})[a],"function"!=typeof a?a:function(){return a.apply(c,arguments)}}function e(a,b,c){var d=b.tmpl.converters;return a=d&&d[a]||l[a],a?a.call(b,c):c}function f(a,c,d,e,f){f.props=f.props||{};var g,h=f.props.tmpl,k=c.tmpl.tags,l=c.tmpl.templates,n=arguments,o=k&&k[a]||j[a];return o?(e=e&&c.tmpl.tmpls[e-1],h=h||e||b,f.tmpl=""+h===h?l&&l[h]||i[h]||i(h):h,f.isTag=A,f.converter=d,f.view=c,f.renderContent=m,c.ctx&&w(f.ctx,c.ctx),g=o.apply(f,n.length>5?O.call(n,5):[]),g||(g==b?"":g.toString())):""}function g(a,c,e,f,g,h){var i=e.views,j={tmpl:g,path:c,parent:e,data:f,ctx:a,views:t.isArray(f)?[]:{},hlp:d};return t.isArray(i)?i.splice(j.index=h!==b?h:i.length,0,j):i[j.index="_"+I++]=j,j}function h(a,c,d,e,f){var g,h;if(d&&"object"==typeof d&&!d.nodeType){for(g in d)c(g,d[g]);return a}return d&&e!==b?""+d===d&&(null===e?delete c[d]:(e=f?f(d,e):e)&&(c[d]=e)):f&&(e=f(b,e||d)),(h=y.onStoreItem)&&h(c,d,e,f),e}function i(a,b){return h(this,i,a,b,q)}function j(a,b){return h(this,j,a,b)}function k(a,b){return h(this,k,a,b)}function l(a,b){return h(this,l,a,b)}function m(a,c,d,e,f){var h,j,k,l,m,n,o,p,q,r,s={},u=f===A,v=this,x="";if(v.isTag?(q=v.tmpl,c=c||v.ctx,d=d||v.view,e=e||v.path,f=f||v.index,s=v.props):q=v.jquery&&v[0]||v,d=d||Q.topView,p=d.ctx,r=q.layout,a===d&&(a=d.data,r=A),c=c&&c===p?p:p?(p=w({},p),c?w(p,c):p):c||{},s.link===z&&(c.link=z),q.fn||(q=i[q]||i(q)),m=c.link&&y.onRenderItem,n=c.link&&y.onRenderItems,q){if(t.isArray(a)&&!r)for(l=u?d:f!==b&&d||g(c,e,d,a,q,f),h=0,j=a.length;j>h;h++)k=a[h],o=q.fn(k,g(c,e,l,k,q,(f||0)+h),Q),x+=m?m(o,s):o;else l=u?d:g(c,e,d,a,q,f),x+=a||r?q.fn(a,l,Q):"";return d.topKey=l.index,n?n(x,e,l.index,q,s):x}return""}function n(){throw"Syntax error"}function o(a,b,c){function d(b){b-=D,b&&J.push(a.substr(D,b).replace(E,"\\n"))}function e(b,e,g,h,i,j,k,l,m,n){i&&(h=":",g="html");var o="",q="",r=!l&&!h;if(e=e||h,d(n),D=n+b.length,j?y&&J.push(["*",k.replace(F,"$1")]):e?("else"===e&&(K[5]=a.substring(K[5],n),K=I.pop(),J=K[3],r=A),k=k?p(k,c).replace(H,function(a,b,c){return b?q+=c+",":o+=c+",",""}):"",o=o.slice(0,-1),k=k.slice(0,-1),f=[e,g||"",k,r&&[],"{"+(o?"props:{"+o+"},":"")+"path:'"+k+"'"+(q?",ctx:{"+q.slice(0,-1)+"}":"")+"}"],r&&(I.push(K),K=f,K[5]=D),J.push(f)):m&&(K[5]=a.substring(K[5],n),K=I.pop()),!K)throw"Expected block tag";J=K[3]}var f,g,h,i,j,k,l,m,n,q,s,t,v,w,x,y,z=b?{allowCode:y=b.allowCode,debug:b.debug}:{},B=b&&b.tmpls,C=[],D=0,I=[],J=C,K=[,,,C],L=0;for(a=a.replace(G,"\\$1"),a.replace(u,e),d(a.length),i=C.length,j=i?"":'"";',h=0;i>h;h++)g=C[h],"*"===g[0]?j=j.slice(0,h?-1:-3)+";"+g[1]+(i>h+1?"ret+=":""):""+g===g?j+='"'+g+'"+':(s=g[0],t=g[1],v=g[2],J=g[3],w=g[4],a=g[5],J&&(x=r(a,z,b,L++),o(a,x),B.push(x)),q=q||w.indexOf("view")>-1,j+=(":"===s?"html"===t?(l=A,"e("+v):t?(n=A,'c("'+t+'",view,'+v):(m=A,"((v="+v+')!=u?v:""'):(k=A,'t("'+s+'",view,"'+(t||"")+'",'+(J?B.length:'""')+","+w+(v?",":"")+v))+")+");return j=new Function("data, view, j, b, u",M+(m?"v,":"")+(k?"t=j.tag,":"")+(n?"c=j.convert,":"")+(l?"e=j.converters.html,":"")+"ret; try{\n\n"+(z.debug?"debugger;":"")+(y?"ret=":"return ")+j.slice(0,-1)+";\n\n"+(y?"return ret;":"")+"}catch(e){return j.err(e);}"),b&&(b.fn=j,b.useVw=n||q||k),j}function p(a,b){function c(a,c,i,j,k,l,m,o,p,q,r,s,t,u,v,w){function x(a,c,d,e,f,g,h){if(c){var i=(d?'view.hlp("'+d+'")':e?"view":"data")+(h?(f?"."+f:d?"":e?"":"."+c)+(g||""):(h=d?"":e?f||"":c,""));return b&&"("!==p&&(i="b("+i+',"'+h+'")'),i+(h?"."+h:"")}return a}return k=k||"",i=i||c||r,j=j||o,p=p||v||"",k=k||"",l?void n():h?(h=!s,h?a:'"'):g?(g=!t,g?a:'"'):(i?(f++,i):"")+(w?f?"":d?(d=z,"\b"):",":m?(f&&n(),d=A,"\b"+j+":"):j?j.replace(C,x)+(p?(e[++f]=A,p):k):k?a:u?(e[f--]=z,u+(p?(e[++f]=A,p):"")):q?(e[f]||n(),","):c?"":(h=s,g=t,'"'))}var d,e={},f=0,g=z,h=z;return a=(a+" ").replace(D,c)}function q(a,c,d,e){function f(b){return""+b===b||b.nodeType>0?(h=b.nodeType>0?b:!v.test(b)&&B&&B(b)[0],h&&h.type&&(b=i[h.getAttribute(L)],b||(a=a||"_"+J++,h.setAttribute(L,a),b=q(a,h.innerHTML,d,e),i[a]=b)),b):void 0}var g,h,j,k,l;if(g=f(c),e=e||(c.markup?c:{}),e.name=a,k=e.templates,!g&&c.markup&&(g=f(c.markup))&&(!g.fn||g.debug===c.debug&&g.allowCode===c.allowCode||(g=g.markup)),g!==b){a&&!d&&(P[a]=function(){return c.render.apply(c,arguments)}),g.fn||c.fn?g.fn&&(c=a&&a!==g.name?w(w({},g),e):g):(c=r(g,e,d,0),o(g,c));for(j in k)l=k[j],l.name!==j&&(k[j]=q(j,l,c));return c}}function r(a,b,c,d){function e(a){c[a]&&(f[a]=w(w({},c[a]),b[a]))}b=b||{};var f={markup:a,tmpls:[],links:[],render:m};return c&&(c.templates&&(f.templates=w(w({},c.templates),b.templates)),f.parent=c,f.name=c.name+"["+d+"]",f.index=d),w(f,b),c&&(e("templates"),e("tags"),e("helpers"),e("converters")),f}function s(a){return K[a]||(K[a]="&#"+a.charCodeAt(0)+";")}var t,u,v,w,x="v1.0pre",y={},z=!1,A=!0,B=a.jQuery,C=/^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g,D=/(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,E=/\r?\n/g,F=/\\(['"])/g,G=/\\?(['"])/g,H=/\x08(~)?([^\x08]+)\x08/g,I=0,J=0,K={"&":"&","<":"<",">":">"},L="data-jsv-tmpl",M="var j=j||"+(B?"jQuery.":"js")+"views,",N=/[\x00"&'<>]/g,O=Array.prototype.slice,P={},Q={jsviews:x,sub:y,debugMode:A,err:function(a){return Q.debugMode?"
                Error: "+(a.message||a)+". ":'""'},tmplFn:o,render:P,templates:i,tags:j,helpers:k,converters:l,View:g,convert:e,delimiters:c,tag:f};B?(t=B,t.templates=i,t.render=P,t.views=Q,t.fn.render=m):(t=a.jsviews=Q,t.extend=function(a,b){var c;a=a||{};for(c in b)a[c]=b[c];return a},t.isArray=Array&&Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)}),w=t.extend,Q.topView={views:{},tmpl:{},hlp:d,ctx:Q.helpers},j({"if":function(){var a=this,c=a.view;return c.onElse=function(a,d){for(var e=0,f=d.length;f&&!d[e++];)if(e===f)return"";return c.onElse=b,a.path="",a.renderContent(c)},c.onElse(this,arguments)},"else":function(){var a=this.view;return a.onElse?a.onElse(this,arguments):""},"for":function(){var a,b=this,c="",d=arguments,e=d.length;for(b.props.layout&&(b.tmpl.layout=A),a=0;e>a;a++)c+=b.renderContent(d[a]);return c},"=":function(a){return a},"*":function(a){return a}}),l({html:function(a){return a!=b?String(a).replace(N,s):""}}),c("{{","}}")}(this),function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})}),$.widget||!function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d,e=0;null!=(d=b[e]);e++)try{a(d).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){return c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}}),d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e,f=b.split(".")[0];b=b.split(".")[1],e=f+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][e]=function(c){return!!a.data(c,b)},a[f]=a[f]||{},a[f][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[f][b].prototype=a.extend(!0,g,{namespace:f,widgetName:b,widgetEventPrefix:a[f][b].prototype.widgetEventPrefix||b,widgetBaseClass:e},d),a.widget.bridge(b,a[f][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f="string"==typeof e,g=Array.prototype.slice.call(arguments,1),h=this;return e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e,f&&"_"===e.charAt(0)?h:(this.each(f?function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;return f!==d&&f!==b?(h=f,!1):void 0}:function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))}),h)}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(0===arguments.length)return a.extend({},this.options);if("string"==typeof c){if(d===b)return this.options[c];e={},e[c]=d}return this._setOptions(e),this},_setOptions:function(b){var c=this;return a.each(b,function(a,b){c._setOption(a,b)}),this},_setOption:function(a,b){return this.options[a]=b,"disabled"===a&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",b),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];if(d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}}(jQuery),function(a,b,c){b.toStaticHTML=b.toStaticHTML||function(a){return a};var d=Number.POSITIVE_INFINITY,e=Number.NEGATIVE_INFINITY;a.geo={_allCoordinates:function(b){for(var c=this._flatten(b),d=0,e=[];d1&&!a.isArray(b[0]))return b[0]>=-180.001&&b[0]<=180.001&&b[1]>=-90.001&&b[1]<=90.001;b=b[0]}return!1},center:function(b,c){var d=!1;!c&&a.geo.proj&&this._isGeodetic(b)&&(d=!0,b=a.geo.proj.fromGeodetic(b));var e=[(b[0]+b[2])/2,(b[1]+b[3])/2];return d?a.geo.proj.toGeodetic(e):e},expandBy:function(b,c,d,e){var f=!1;return!e&&a.geo.proj&&this._isGeodetic(b)&&(f=!0,b=a.geo.proj.fromGeodetic(b)),b=[b[0]-c,b[1]-d,b[2]+c,b[3]+d],f?a.geo.proj.toGeodetic(b):b},height:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[3]-b[1]},_in:function(a,b){return a[0]<=b[0]&&a[1]<=b[1]&&a[2]>=b[2]&&a[3]>=b[3]},_bboxDisjoint:function(a,b){return b[0]>a[2]||b[2]a[3]||b[3]0&&(h/i>c?(f=h/2,g=f/c):(g=i/2,f=g*c),b=[j[0]-f,j[1]-g,j[0]+f,j[1]+g]),e?a.geo.proj.toGeodetic(b):b},recenter:function(b,c,d){var e=!1;!d&&a.geo.proj&&(this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b)),this._isGeodetic(c)&&(c=a.geo.proj.fromGeodetic(c)));var f=(b[2]-b[0])/2,g=(b[3]-b[1])/2;return b=[c[0]-f,c[1]-g,c[0]+f,c[1]+g],e?a.geo.proj.toGeodetic(b):b},scaleBy:function(b,c,d){var e=!1;!d&&a.geo.proj&&this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b));var f=this.center(b,!0),g=(b[2]-b[0])*c/2,h=(b[3]-b[1])*c/2;return b=[f[0]-g,f[1]-h,f[0]+g,f[1]+h],e?a.geo.proj.toGeodetic(b):b},width:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[2]-b[0]},bbox:function(b,f){var g,h=!1;if(!b)return c;if(b.bbox)g=!f&&a.geo.proj&&this._isGeodetic(b.bbox)?a.geo.proj.fromGeodetic(b.bbox):b.bbox;else{g=[d,d,e,e];var i=this._allCoordinates(b),j=0;if(0===i.length)return c;for(!f&&a.geo.proj&&this._isGeodetic(i)&&(h=!0,i=a.geo.proj.fromGeodetic(i));j0?(g[0]=Math.min(Math.max(k[0][0],m[0]),m[2]),g[1]=Math.min(Math.max(k[0][1],m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g}):c:(j*=3,g[0]=Math.min(Math.max(g[0]/j,m[0]),m[2]),g[1]=Math.min(Math.max(g[1]/j,m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g});case"MultiPoint":if(b.coordinates.length>0)return g=b.coordinates[0],{type:"Point",coordinates:[g[0],g[1]]};break;case"MultiLineString":case"MultiPolygon":if(b.coordinates.length>0)return this.centroid({type:b.type.substr(5),coordinates:b.coordinates[0]},f)}return c},contains:function(a,b){if("Polygon"!==a.type)return!1;switch(b.type){case"Point":return this._containsPolygonPoint(a.coordinates,b.coordinates);case"LineString":return this._containsPolygonLineString(a.coordinates,b.coordinates);case"Polygon":return this._containsPolygonLineString(a.coordinates,b.coordinates[0]);default:return!1}},_containsPolygonPoint:function(a,b){if(0===a.length||a[0].length<4)return!1;for(var c,d,e=0,f=a[0][0],g=1;gb[0]&&e++),f=c;return e%2===1},_containsPolygonLineString:function(a,b){for(var c=0;c0){var e=a[0],f=b[0]-e[0],g=b[1]-e[1];if(1===a.length)return Math.sqrt(f*f+g*g);for(var h=1;hn&&(c=n),e=i,f=l,g=m}}return Math.sqrt(c)},_distanceSegmentPoint:function(a,b,c,d,e,f){var g=a*c+b*d;if(0>=g)return c*c+d*d;var h=a*a+b*b;return g>=h?e*e+f*f:c*c+d*d-g*g/h},_distanceLineStringLineString:function(a,b){for(var c=d,e=0;e=k;k++)h=360*k/j*(Math.PI/180),i.push([g[0]+Math.cos(h)*d,g[1]+Math.sin(h)*d]);return{type:"Polygon",coordinates:[f?a.geo.proj.toGeodetic(i):i]}}return c},_basic:function(a){for(var b,c,d=[],e=0,f=this._flatten(a);eo;q++)n=o,o+=p[q]/m;return e=c-n,k=g[q-1],l=g[q],j=[k[0]+e*(l[0]-k[0]),k[1]+e*(l[1]-k[1])],{type:"Point",coordinates:r?a.geo.proj.toGeodetic(j):j}}},WKT:function(){function b(a){return"POINT "+c(a.coordinates)}function c(a){return a&&a.length?"("+a.join(" ")+")":"EMPTY"}function d(a){return"LINESTRING "+e(a.coordinates)}function e(a){if(a&&a.length){for(var b=[],c=0;c2?{type:"Point",coordinates:[parseFloat(b[1]),parseFloat(b[2])]}:null}function p(a){var b,c,d=a.match(/\s*\((.*)\)/),e=[],f=0;if(d&&d.length>1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f0){for(;g
                ";while(c[0]);return a>6?a:!a}();a.widget("geo.geographics",{_$elem:c,_options:{},_trueCanvas:!0,_trueDoubleBuffer:!0,_width:0,_height:0,_$canvas:c,_context:c,_$canvasSceneFront:c,_$canvasSceneBack:c,_timeoutEnd:null,_requireFlip:!1,_blitcanvas:c,_blitcontext:c,_$labelsContainerFront:c,_$labelsContainerBack:c,_labelsHtml:"",options:{style:{borderRadius:"8px",color:"#7f0000",fillOpacity:.2,height:"8px",opacity:1,strokeOpacity:1,strokeWidth:"2px",visibility:"visible",width:"8px"},doubleBuffer:!0},_create:function(){this._$elem=this.element,this._options=this.options,this._$elem.css({webkitTransform:"translateZ(0)",display:"inline-block",overflow:"hidden",textAlign:"left"}),"static"===this._$elem.css("position")&&this._$elem.css("position","relative"),this._$elem.addClass("geo-graphics"),this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10));var c="position:absolute;left:0;top:0;margin:0;padding:0;",e="width:"+this._width+"px;height:"+this._height+"px;",f='width="'+this._width+'" height="'+this._height+'"';this._blitcanvas=document.createElement("canvas"),this._blitcanvas.getContext?(this._$canvas=a(b.toStaticHTML("')),this._blitcanvas.width=1,this._blitcanvas.height=1,this._trueDoubleBuffer=this._blitcanvas.toDataURL().length>6,this._options.doubleBuffer&&this._trueDoubleBuffer||this._$elem.append(this._$canvas),this._context=this._$canvas[0].getContext("2d"),this._blitcanvas.width=this._width,this._blitcanvas.height=this._height,this._blitcontext=this._blitcanvas.getContext("2d"),this._$canvasSceneFront=a(b.toStaticHTML('')),this._$canvasSceneBack=a(b.toStaticHTML(''))):8>=d&&(this._trueCanvas=!1,this._$elem.append("
                '),this._$canvas=this._$elem.children(":last"),G_vmlCanvasManager.initElement(this._$canvas[0]),this._context=this._$canvas[0].getContext("2d"),this._$canvas.children().css({backgroundColor:"transparent",width:this._width,height:this._height})),this._$labelsContainerFront=a(b.toStaticHTML('
                ')),this._$labelsContainerBack=a(b.toStaticHTML('
                '))},_setOption:function(b,c){"style"===b&&(c=a.extend({},this._options.style,c)),a.Widget.prototype._setOption.apply(this,arguments)},destroy:function(){a.Widget.prototype.destroy.apply(this,arguments),this._$elem.html(""),this._$elem.removeClass("geo-graphics")},clear:function(){this._context.clearRect(0,0,this._width,this._height),this._labelsHtml="",this._end()},drawArc:function(a,b,c,d){if(d=this._getGraphicStyle(d),"hidden"!==d.visibility&&d.opacity>0&&d.widthValue>0&&d.heightValue>0){var e=Math.min(d.widthValue,d.heightValue)/2;b=b*Math.PI/180,c=c*Math.PI/180,this._context.save(),this._context.translate(a[0],a[1]),d.widthValue>d.heightValue?this._context.scale(d.widthValue/d.heightValue,1):this._context.scale(1,d.heightValue/d.widthValue),this._context.beginPath(),this._context.arc(0,0,e,b,c,!1),this._trueCanvas&&this._context.restore(),d.doFill&&(this._context.fillStyle=d.fill,this._context.globalAlpha=d.opacity*d.fillOpacity,this._context.fill()),d.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=d.strokeWidthValue,this._context.strokeStyle=d.stroke,this._context.globalAlpha=d.opacity*d.strokeOpacity,this._context.stroke()),this._trueCanvas||this._context.restore()}this._end()},drawPoint:function(a,b){b=this._getGraphicStyle(b),b.widthValue===b.heightValue&&b.heightValue===b.borderRadiusValue?this.drawArc(a,0,360,b):"hidden"!==b.visibility&&b.opacity>0&&(b.borderRadiusValue=Math.min(Math.min(b.widthValue,b.heightValue)/2,b.borderRadiusValue),a[0]-=b.widthValue/2,a[1]-=b.heightValue/2,this._context.beginPath(),this._context.moveTo(a[0]+b.borderRadiusValue,a[1]),this._context.lineTo(a[0]+b.widthValue-b.borderRadiusValue,a[1]),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1],a[0]+b.widthValue,a[1]+b.borderRadiusValue),this._context.lineTo(a[0]+b.widthValue,a[1]+b.heightValue-b.borderRadiusValue),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1]+b.heightValue,a[0]+b.widthValue-b.borderRadiusValue,a[1]+b.heightValue),this._context.lineTo(a[0]+b.borderRadiusValue,a[1]+b.heightValue),this._context.quadraticCurveTo(a[0],a[1]+b.heightValue,a[0],a[1]+b.heightValue-b.borderRadiusValue),this._context.lineTo(a[0],a[1]+b.borderRadiusValue),this._context.quadraticCurveTo(a[0],a[1],a[0]+b.borderRadiusValue,a[1]),this._context.closePath(),b.doFill&&(this._context.fillStyle=b.fill,this._context.globalAlpha=b.opacity*b.fillOpacity,this._context.fill()),b.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=b.strokeWidthValue,this._context.strokeStyle=b.stroke,this._context.globalAlpha=b.opacity*b.strokeOpacity,this._context.stroke()),this._end())},drawLineString:function(a,b){this._drawLines([a],!1,b)},drawPolygon:function(a,b){if(this._trueCanvas&&1!==a.length){if(!a||!a.length||a[0].length<3)return;b=this._getGraphicStyle(b),this._blitcontext.globalCompositeOperation="copy";var c,d,e;if("hidden"!==b.visibility&&b.opacity>0){if(this._blitcontext.clearRect(0,0,this._width,this._height),b.doFill&&a.length>1){for(this._blitcontext.globalCompositeOperation="source-out",this._blitcontext.globalAlpha=1,this._blitcontext.beginPath(),d=1;d1))for(d=1;d'+b+""},resize:function(a,b){this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10)),this._trueCanvas?(this._$canvas[0].width=this._width,this._$canvas[0].height=this._height,this._$canvasSceneFront.css({left:a,top:b}),this._$canvasSceneBack.css({width:this._width,height:this._height})):this._$canvas.css({width:this._width,height:this._height});var c=this._$labelsContainerFront.position();this._$labelsContainerFront.css({left:c.left+a,top:c.top+b,width:this._width,height:this._height}),this._$labelsContainerBack.css({width:this._width,height:this._height})},interactiveTransform:function(a,b){if(this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._trueCanvas)if(this._options.doubleBuffer&&this._trueDoubleBuffer){var c=this;if(this._requireFlip){c._requireFlip=!1;var d=c._$canvasSceneFront;c._$canvasSceneFront=c._$canvasSceneBack.css({left:0,top:0,width:c._width,height:c._height}).prop("src",c._$canvas[0].toDataURL()).prependTo(c._$elem),c._$canvasSceneBack=d.prop("src","").detach()}this._$canvasSceneFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})}else this._context.clearRect(0,0,this._width,this._height);else this._context.clearRect(0,0,this._width,this._height);this._$labelsContainerFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})},_canvasSceneLoad:function(){var a=this;if(a._requireFlip){a._requireFlip=!1;var b=a._$canvasSceneFront;a._$canvasSceneFront=a._$canvasSceneBack.css({left:0,top:0,width:a._width,height:a._height}).prependTo(a._$elem),a._$canvasSceneBack=b.prop("src","").detach()}},_endCallback:function(){var a=this;if(a._timeoutEnd){a._trueCanvas&&a._options.doubleBuffer&&a._trueDoubleBuffer&&(a._$canvasSceneBack.prop("src",a._$canvas[0].toDataURL()),this._canvasSceneLoad()),a._$labelsContainerBack.html(b.toStaticHTML(a._labelsHtml)).find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"});var c=a._$labelsContainerFront;a._$labelsContainerFront=a._$labelsContainerBack.css({left:0,top:0,width:a._width,height:a._height}).appendTo(a._$elem),a._$labelsContainerBack=c.detach(),a._timeoutEnd=null}},_end:function(){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._requireFlip=!0,this._timeoutEnd=setTimeout(a.proxy(this._endCallback,this),20)},_getGraphicStyle:function(b){function c(a){return a=parseInt(a,10),+a+""===a?+a:a}return b=a.extend({},this._options.style,b),b.borderRadiusValue=c(b.borderRadius),b.fill=b.fill||b.color,b.doFill=b.fill&&b.fillOpacity>0,b.stroke=b.stroke||b.color,b.strokeWidthValue=c(b.strokeWidth),b.doStroke=b.stroke&&b.strokeOpacity>0&&b.strokeWidthValue>0,b.widthValue=c(b.width),b.heightValue=c(b.height),b},_drawLines:function(a,b,c){if(a&&a.length&&!(a[0].length<2)){var d,e;if(c=this._getGraphicStyle(c),"hidden"!==c.visibility&&c.opacity>0){for(this._context.beginPath(),d=0;d
                ";while(c[0]);return a>6?a:!a}(),f={bbox:[-180,-85,180,85],bboxMax:[-180,-85,180,85],center:[0,0],cursors:{"static":"default",pan:"url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move",click:"crosshair",zoom:"crosshair",dragBox:"crosshair",dragCircle:"crosshair",drawPoint:"crosshair",drawLineString:"crosshair",drawPolygon:"crosshair",measureLength:"crosshair",measureArea:"crosshair"},measureLabels:{length:"{{:length.toFixed( 2 )}} m",area:"{{:area.toFixed( 2 )}} sq m"},drawStyle:{},shapeStyle:{},mode:"pan",pannable:!0,scroll:"default",shift:"default",services:[{"class":"osm",type:"tiled",src:function(a){return"//otile"+(a.index%4+1)+("https:"===location.protocol?"-s":"")+".mqcdn.com/tiles/1.0.0/osm/"+a.zoom+"/"+a.tile.column+"/"+a.tile.row+".png"},attr:'Tiles Courtesy of MapQuest '}],tilingScheme:{tileWidth:256,tileHeight:256,levels:18,basePixelSize:156543.03392799935,origin:[-20037508.342787,20037508.342787]},axisLayout:"map",zoom:0,zoomMin:0,zoomMax:Number.POSITIVE_INFINITY,zoomFactor:2,pixelSize:0};a.widget("geo.geomap",{_$elem:c,_map:c,_created:!1,_createdGraphics:!1,_widgetId:0,_tmplLengthId:"",_tmplAreaId:"",_contentBounds:{},_$resizeContainer:c,_$eventTarget:c,_$contentFrame:c,_$existingChildren:c,_$attrList:c,_$servicesContainer:c,_$shapesContainers:c,_$panContainer:c,_$shapesContainer:c,_$drawContainer:c,_$measureContainer:c,_$measureLabel:c,_dpi:96,_currentServices:[],_center:c,_pixelSize:c,_centerMax:c,_pixelSizeMax:c,_pixelSizeMin:c,_userGeodetic:!0,_centerInteractive:c,_pixelSizeInteractive:c,_timeoutInteractive:null,_triggerInteractive:!1,_timeoutRefreshShapes:null,_loadCount:0,_wheelLevel:0,_fullZoomFactor:2,_partialZoomFactor:1.18920711500273,_mouseDown:c,_inOp:c,_toolPan:c,_shiftDown:c,_anchor:c,_current:c,_downDate:c,_moveDate:c,_clickDate:c,_lastMove:c,_lastDrag:c,_windowHandler:null,_resizeTimeout:null,_panning:c,_velocity:c,_friction:c,_pointerEvents:c,_supportTouch:c,_softDblClick:c,_isTap:c,_isDbltap:c,_isMultiTouch:c,_multiTouchAnchor:[],_multiTouchAnchorBbox:c,_multiTouchCurrentBbox:c,_drawTimeout:null,_drawPixels:[],_drawCoords:[],_graphicShapes:[],_initOptions:{},_options:{},options:a.extend({},f),_createWidget:function(b,c){if(this._$elem=a(c),this._$elem.is(".geo-service"))return this._graphicShapes=[],void a.Widget.prototype._createWidget.apply(this,arguments);this._widgetId=d++,this._serviceIdSeed=0,this._tmplLengthId="geoMeasureLength"+this._widgetId,this._tmplAreaId="geoMeasureArea"+this._widgetId,this._$elem.addClass("geo-map").css({webkitTransform:"translateZ(0)",touchAction:"none"}),this._initOptions=b||{},this._forcePosition(this._$elem),this._$elem.css("text-align","left");var e=this._findMapSize();this._contentBounds={x:parseInt(this._$elem.css("padding-left"),10),y:parseInt(this._$elem.css("padding-top"),10),width:e.width,height:e.height},this._createChildren(),this._center=[0,0],this._centerMax=[0,0],this._centerInteractive=[0,0],this.options.pixelSize=this._pixelSize=this._pixelSizeMax=156543.03392799935,this._pixelSizeMin=this._pixelSizeMax/Math.pow(2,17),this._mouseDown=this._inOp=this._toolPan=this._shiftDown=this._panning=this._isTap=this._isDbltap=!1,this._anchor=[0,0],this._current=[0,0],this._lastMove=[0,0],this._lastDrag=[0,0],this._velocity=[0,0],this._friction=[.8,.8],this._downDate=this._moveDate=this._clickDate=0,this._drawPixels=[],this._drawCoords=[],this._graphicShapes=[],a.Widget.prototype._createWidget.apply(this,arguments)},_create:function(){if(this._options=this.options,this._$elem.is(".geo-service"))return this._map=this._$elem.data("geoMap"),void this._$elem.data("geoService",this);this._map=this,this._pointerEvents=b.PointerEvent,this._supportTouch="ontouchend"in document,this._softDblClick=this._supportTouch||7===e;var d=this,f=this._pointerEvents?"pointerdown":this._supportTouch?"touchstart mousedown":"mousedown",g=this._pointerEvents?"pointerup pointercancel":this._supportTouch?"touchend touchcancel mouseup":"mouseup",h=this._pointerEvents?"pointermove":this._supportTouch?"touchmove mousemove":"mousemove";a(document).keydown(a.proxy(this._document_keydown,this)),this._$eventTarget.dblclick(a.proxy(this._eventTarget_dblclick,this)),this._$eventTarget.bind(f,a.proxy(this._eventTarget_touchstart,this));var i=this._$eventTarget[0].setCapture?this._$eventTarget:a(document);i.bind(h,a.proxy(this._dragTarget_touchmove,this)),i.bind(g,a.proxy(this._dragTarget_touchstop,this)),this._$eventTarget.mousewheel(a.proxy(this._eventTarget_mousewheel,this)),this._windowHandler=function(){d._resizeTimeout&&clearTimeout(d._resizeTimeout),d._resizeTimeout=setTimeout(function(){d._created&&d._$elem.geomap("resize",!0)},500)},a(b).resize(this._windowHandler),this._$drawContainer.geographics({style:this._initOptions.drawStyle||{},doubleBuffer:!1}),this._options.drawStyle=this._$drawContainer.geographics("option","style"),this._$shapesContainer.geographics({style:this._initOptions.shapeStyle||{}}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style"),this._initOptions&&(this._initOptions.tilingScheme!==c&&this._setOption("tilingScheme",this._initOptions.tilingScheme||null,!1),this._initOptions.services&&(this._options.services=a.merge([],this._initOptions.services)),this._initOptions.bboxMax&&(this._setOption("bboxMax",this._initOptions.bboxMax,!1),this._setOption("bbox",this._initOptions.bboxMax,!1)),this._initOptions.zoomMin!==c&&this._setOption("zoomMin",this._initOptions.zoomMin,!1),this._initOptions.zoomMax!==c&&this._setOption("zoomMax",this._initOptions.zoomMax,!1),this._initOptions.zoomFactor!==c&&(this._setOption("zoomFactor",this._initOptions.zoomFactor,!1),this._fullZoomFactor=this._initOptions.zoomFactor,this._partialZoomFactor=Math.pow(4,1/this._fullZoomFactor)),this._initOptions.bbox&&this._setOption("bbox",this._initOptions.bbox,!1),this._initOptions.center&&this._setOption("center",this._initOptions.center,!1),this._initOptions.zoom!==c&&this._setOption("zoom",this._initOptions.zoom,!1)),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area),this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._createServices(),this._refresh(),this._created=!0},_setOption:function(b,d,e){if("pixelSize"!==b){e=e===c||e,this._$elem.is(".geo-map")&&this._panFinalize();var f,g,h,i;switch(b){case"bbox":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),f=[d[0]+(d[2]-d[0])/2,d[1]+(d[3]-d[1])/2],g=Math.max(a.geo.width(d,!0)/this._contentBounds.width,a.geo.height(d,!0)/this._contentBounds.height),i=this._getZoom(f,g),this._options.tilingScheme?g=this._getPixelSize(Math.min(Math.max(i,this._options.zoomMin),this._options.zoomMax)):ithis._options.zoomMax&&(g=this._getPixelSize(this._options.zoomMax)),this._created?(this._setInteractiveCenterAndSize(f,g),this._setInteractiveTimeout(!1)):this._setCenterAndSize(f,g,!1,e),d=this._getBbox(f,g);break;case"bboxMax":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d);break;case"center":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),this._created?(this._setInteractiveCenterAndSize(d,this._pixelSizeInteractive),this._interactiveTransform(),this._setInteractiveTimeout(!1)):this._setCenterAndSize(d,this._pixelSize,!1,e);break;case"measureLabels":d=a.extend(this._options.measureLabels,d),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area);break;case"drawStyle":this._$drawContainer&&(this._$drawContainer.geographics("option","style",d),d=this._$drawContainer.geographics("option","style"));break;case"shapeStyle":this._$elem.is(".geo-service")&&!this._createdGraphics&&this._createServiceGraphics(),this._createdGraphics&&(this._$shapesContainer.geographics("option","style",d),d=this._$shapesContainer.geographics("option","style"));break;case"mode":this._resetDrawing(),this._$eventTarget.css("cursor",this._options.cursors[d]);break;case"zoom":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj,this._created?this._setZoom(d,!1,e):(d=Math.max(d,0),this._setCenterAndSize(this._center,this._getPixelSize(d),!1,e))}switch(a.Widget.prototype._setOption.apply(this,arguments),b){case"bbox":case"center":this._userGeodetic&&(this._options.bbox=a.geo.proj.toGeodetic(this._options.bbox),this._options.center=a.geo.proj.toGeodetic(this._center));break;case"tilingScheme":null!==d&&(this._pixelSizeMax=this._getPixelSize(0),this._pixelSizeMin=this._getPixelSize(d.pixelSizes?d.pixelSizes.length-1:d.levels-1),this._centerMax=[d.origin[0]+this._pixelSizeMax*d.tileWidth/2,d.origin[1]+this._pixelSizeMax*d.tileHeight/2]);break;case"bboxMax":h=this._userGeodetic?a.geo.proj.fromGeodetic(d):d,this._centerMax=a.geo.center(h),this._pixelSizeMax=Math.max(a.geo.width(h,!0)/this._contentBounds.width,a.geo.height(h,!0)/this._contentBounds.height);break;case"services":this._createServices(),e&&(this._refresh(),this._refreshAllShapes());break;case"shapeStyle":e&&this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))}}},destroy:function(){if(this._$elem.is(".geo-service"))this._createdGraphics&&(this._$shapesContainer.geographics("destroy"),this._$shapesContainer=c,this._createdGraphics=!1);else{clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,this._created=!1,a(b).unbind("resize",this._windowHandler);for(var d=0;d=0||1>=b)for(var d=0;d0)){this._createdGraphics||this._createServiceGraphics();var d,e,f,g,h,i;for(d=a.isArray(b)?b:"FeatureCollection"===b.type?b.features:[b],f=1;f=0;g--)if(d=this._graphicShapes[g],h)if("Point"===d.shape.type)a.geo.distance(d.shape,b)<=i&&j.push(d.shape);else{var k=a.data(d.shape,"geoBbox"),l={type:"Polygon",coordinates:[[[k[0],k[1]],[k[0],k[3]],[k[2],k[3]],[k[2],k[1]],[k[0],k[1]]]]},m={type:"Point",coordinates:a.geo.proj&&a.geo._isGeodetic(b.coordinates)?a.geo.proj.fromGeodetic(b.coordinates):b.coordinates};if(a.geo.distance(l,m,!0)<=i)for(e=a.geo._basic(d.shape),f=0;f0)){for(var e,f=a.isArray(b)?b:[b],g=0;g=0&&(e=this._graphicShapes.slice(g+1),this._graphicShapes.length=g,this._graphicShapes.push.apply(this._graphicShapes,e),g--);(d===c||d)&&(this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh(),this._refreshAllShapes())}},_getBbox:function(a,b){a=a||this._center,b=b||this._pixelSize;var c=this._contentBounds.width/2*b,d=this._contentBounds.height/2*b;return[a[0]-c,a[1]-d,a[0]+c,a[1]+d]},_setBbox:function(b){var c=[b[0]+(b[2]-b[0])/2,b[1]+(b[3]-b[1])/2],d=Math.max(a.geo.width(b,!0)/this._contentBounds.width,a.geo.height(b,!0)/this._contentBounds.height),e=this._getZoom(c,d);this._options.tilingScheme?d=this._getPixelSize(Math.min(Math.max(e,this._options.zoomMin),this._options.zoomMax)):ethis._options.zoomMax&&(d=this._getPixelSize(this._options.zoomMax)),this._setInteractiveCenterAndSize(c,d),this._interactiveTransform()},_getBboxMax:function(){var a=this._contentBounds.width/2*this._pixelSizeMax,b=this._contentBounds.height/2*this._pixelSizeMax;return[this._centerMax[0]-a,this._centerMax[1]-b,this._centerMax[0]+a,this._centerMax[1]+b]},_getCenter:function(){return this._center},_getContentBounds:function(){return this._contentBounds},_getServicesContainer:function(){return this._$servicesContainer},_getZoom:function(b,c){b=b||this._center,c=c||this._pixelSize;var d=this._options.tilingScheme;if(d){if(d.pixelSizes){for(var e=Math.floor(1e3*c),f=d.pixelSizes.length,g=f-1;g>=0;g--)if(Math.floor(1e3*d.pixelSizes[g])>=e)return g;return 0}return Math.round(Math.log(d.basePixelSize/c)/Math.log(2))}var h=this._contentBounds.width/this._contentBounds.height,i=a.geo.reaspect(this._getBbox(b,c),h,!0),j=a.geo.reaspect(this._getBboxMax(),h,!0);return Math.round(Math.log(a.geo.width(j,!0)/a.geo.width(i,!0))/Math.log(this._fullZoomFactor))},_setZoom:function(a,b){this._clearInteractiveTimeout(),a=Math.min(Math.max(a,this._options.zoomMin),this._options.zoomMax),this._setInteractiveCenterAndSize(this._centerInteractive,this._getPixelSize(a)),this._interactiveTransform(),this._setInteractiveTimeout(b)},_createChildren:function(){this._$existingChildren=this._$elem.children(),this._forcePosition(this._$existingChildren),this._$existingChildren.detach().css({mozUserSelect:"none"});var c="width:"+this._contentBounds.width+"px; height:"+this._contentBounds.height+"px; margin:0; padding:0;",d="position:absolute; left:0; top:0;";this._$elem.prepend(b.toStaticHTML('
                ')),this._$eventTarget=this._$contentFrame=this._$elem.children(":first"),this._$contentFrame.append('
                '),this._$servicesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                  '),this._$attrList=this._$contentFrame.children(":last"),this._$contentFrame.append('
                  '),this._$drawContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                  '),this._$measureContainer=this._$contentFrame.children(":last"),this._$measureLabel=this._$measureContainer.children(),this._$contentFrame.append('
                  '),this._$shapesContainer=this._$contentFrame.children(":last"),this._$panContainer=a([this._$shapesContainer[0],this._$drawContainer[0],this._$measureContainer[0]]),this._$resizeContainer=a([this._$contentFrame[0],this._$servicesContainer[0],this._$eventTarget[0],this._$measureContainer[0]]),this._$contentFrame.append(this._$existingChildren),a("#geo-measure-style").length||a("head").prepend(b.toStaticHTML('")) -},_createServices:function(){var c,d;for(d=0;d';this._$servicesContainer.append(b.toStaticHTML(h)),e=this._$servicesContainer.children(":last"),c.serviceContainer=e,a.geo._serviceTypes[c.type].create(this,e,c,d),e.data("geoMap",this).geomap(),c.attr&&this._$attrList.append("
                • "+c.attr+"
                • ")}this._$shapesContainers=this._$shapesContainer,this._$attrList.find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"})},_createServiceGraphics:function(){var a=this._$elem.closest(".geo-content-frame");this._$elem.append('
                  '),this._$shapesContainer=this._$elem.children(":last"),this._map._$shapesContainers=this._map._$shapesContainers.add(this._$shapesContainer),this._$shapesContainer.geographics(),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style")},_refreshDrawing:function(){if(this._$drawContainer.geographics("clear"),this._drawPixels.length>0){var b,c,d,e,f,g=this._options.mode,h=this._drawPixels,i=this._drawCoords;switch(g){case"measureLength":g="drawLineString",c={type:"LineString",coordinates:i},b=a.render[this._tmplLengthId]({length:a.geo.length(c,!0)}),d=a.merge([],h[h.length-1]);break;case"measureArea":g="drawPolygon",c={type:"Polygon",coordinates:[a.merge([],i)]},c.coordinates[0].push(i[0]),b=a.render[this._tmplAreaId]({area:a.geo.area(c,!0)}),d=this._toPixel(a.geo.centroid(c).coordinates),h=[h];break;case"drawPolygon":h=[h]}this._$drawContainer.geographics(g,h),b&&(this._$measureLabel.html(b),e=this._contentBounds.width-(this._$measureLabel.outerWidth(!0)+d[0]),f=this._contentBounds.height-(this._$measureLabel.outerHeight(!0)+d[1]),0>e&&(d[0]+=e),0>f&&(d[1]+=f),this._$measureLabel.css({left:Math.max(d[0],0),top:Math.max(d[1],0)}).show())}},_resetDrawing:function(){this._drawPixels=[],this._drawCoords=[],this._$drawContainer.geographics("clear"),this._$measureLabel.hide()},_refreshAllShapes:function(a){this._timeoutRefreshShapes=null;for(var b,c,d=0;d0&&c._refreshShapes(c._$shapesContainer,c._graphicShapes,c._graphicShapes,c._graphicShapes)));this._createdGraphics&&!a&&(this._$shapesContainer.geographics("clear"),this._graphicShapes.length>0&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))},_refreshShapes:function(b,d,e,f,g,h){var i,j,k,l,m,n,o,p,q,r=this._map._getBbox(g,h);for(i=0;i0&&a.height>0);)a={width:b.width(),height:b.height()},(a.width<=0||a.height<=0)&&(a={width:parseInt(b.css("width"),10),height:parseInt(b.css("height"),10)}),b=b.parent();return a},_forcePosition:function(a){var b=a.css("position");"relative"!==b&&"absolute"!==b&&"fixed"!==b&&a.css("position","relative")},_getPixelSize:function(b){var c=this._options.tilingScheme;if(null!==c){if(0===b)return c.pixelSizes?c.pixelSizes[0]:c.basePixelSize;b=Math.round(b),b=Math.max(b,0);var d=c.pixelSizes?c.pixelSizes.length:c.levels;return b=Math.min(b,d-1),c.pixelSizes?c.pixelSizes[b]:c.basePixelSize/Math.pow(2,b)}var e=a.geo.scaleBy(this._getBboxMax(),1/Math.pow(this._fullZoomFactor,b),!0);return Math.max(a.geo.width(e,!0)/this._contentBounds.width,a.geo.height(e,!0)/this._contentBounds.height)},_getZoomCenterAndSize:function(a,b,c){var d=c?this._fullZoomFactor:this._partialZoomFactor,e=Math.pow(d,-b),f=this._pixelSizeInteractive*e;this._options.tilingScheme&&(f=Math.min(Math.max(f,this._pixelSizeMin),this._pixelSizeMax));var g=this._getZoom(this._centerInteractive,f);c&&this._options.tilingScheme?f=this._getPixelSize(Math.min(Math.max(g,this._options.zoomMin),this._options.zoomMax)):0>b&&g0&&g>this._options.zoomMax&&(f=this._pixelSizeInteractive);var h=f/this._pixelSizeInteractive,i=this._toMap(a,this._centerInteractive,this._pixelSizeInteractive),j=[(this._centerInteractive[0]-i[0])*h,(this._centerInteractive[1]-i[1])*h],k=[i[0]+j[0],i[1]+j[1]];return{pixelSize:f,center:k}},_panFinalize:function(){this._panning&&(this._velocity=[0,0],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._inOp=!1,this._anchor=this._current,this._mouseDown=this._toolPan=this._panning=!1)},_panMove:function(){if(this._options.pannable){var a=this._current[0]-this._lastDrag[0],b=this._current[1]-this._lastDrag[1];(this._toolPan||a>3||-3>a||b>3||-3>b)&&(this._toolPan||(this._toolPan=!0,this._$eventTarget.css("cursor",this._options.cursors.pan)),this._mouseDown&&(this._velocity=[a,b]),(0!==a||0!==b)&&(this._panning=!0,this._lastDrag=this._current,this._centerInteractive[0]-=a*this._pixelSizeInteractive,this._centerInteractive[1]+=("image"===this._options.axisLayout?-1:1)*b*this._pixelSizeInteractive,this._setInteractiveCenterAndSize(this._centerInteractive,this._pixelSizeInteractive),this._interactiveTransform()))}},_clearInteractiveTimeout:function(){return this._timeoutRefreshShapes&&(clearTimeout(this._timeoutRefreshShapes),this._timeoutRefreshShapes=null),this._timeoutInteractive?(clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,!0):(this._centerInteractive[0]=this._center[0],this._centerInteractive[1]=this._center[1],this._pixelSizeInteractive=this._pixelSize,!1)},_interactiveTransform:function(){var b,c=this._pixelSize,d=c/this._pixelSizeInteractive;if(c>0){d=Math.round(1e3*d)/1e3;var e=this._toMap([0,0]),f=this._toPixel(e,this._centerInteractive,this._pixelSizeInteractive);this._$shapesContainers.geographics("interactiveTransform",f,d)}for(var g=0;g0&&(this._drawPixels=this._toPixel(this._drawCoords,this._centerInteractive,this._pixelSizeInteractive),this._refreshDrawing())},_interactiveTimeout:function(){this._isMultiTouch?this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128):this._created&&this._timeoutInteractive&&(this._setCenterAndSize(this._centerInteractive,this._pixelSizeInteractive,this._triggerInteractive,!0),this._timeoutInteractive=null,this._triggerInteractive=!1,this._timeoutRefreshShapes=setTimeout(a.proxy(this._refreshAllShapes,this),128))},_setInteractiveTimeout:function(b){this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128),this._triggerInteractive|=b},_refresh:function(b,c){for(var d,e=0;ethis._options.zoomMax&&(this._pixelSizeInteractive=d=this._getPixelSize(this._options.zoomMax)),this._centerInteractive[0]=c[0],this._centerInteractive[1]=c[1],this._created&&this._interactiveTransform(),this._options.pixelSize=this._pixelSize=d,this._center[0]=c[0],this._center[1]=c[1],this._userGeodetic?(this._options.bbox=a.geo.proj.toGeodetic(this._getBbox()),this._options.center=a.geo.proj.toGeodetic(this._center)):(this._options.bbox=this._getBbox(),this._options.center=a.merge([],c)),this._options.zoom=g,e&&this._trigger("bboxchange",b.event,{bbox:a.merge([],this._options.bbox)}),f&&(this._refresh(),this._refreshAllShapes(),this._refreshDrawing())}},_requestQueued:function(){0===this._loadCount&&this._trigger("loadstart",b.event),this._loadCount++},_requestComplete:function(){this._loadCount--,this._loadCount<=0&&(this._loadCount=0,this._trigger("loadend",b.event))},_toMap:function(b,c,d){c=c||this._center,d=d||this._pixelSize;var e,f,g,h,i=a.isArray(b[0]),j=i&&a.isArray(b[0][0]),k=j&&a.isArray(b[0][0][0]),l=this._contentBounds.width,m=this._contentBounds.height,n=l/2*d,o=m/2*d,p=[c[0]-n,c[1]-o,c[0]+n,c[1]+o],q=a.geo.width(p,!0)/l,r=a.geo.height(p,!0)/m,s="image"===this._options.axisLayout,t=[];for(k||(j||(i||(b=[b]),b=[b]),b=[b]),f=0;f0&&27===b.which&&(2>=c?(this._resetDrawing(),this._inOp=!1):(this._drawCoords[c-2]=a.merge([],this._drawCoords[c-1]),this._drawPixels[c-2]=a.merge([],this._drawPixels[c-1]),this._drawCoords.length--,this._drawPixels.length--,this._refreshDrawing()))},_eventTarget_dblclick_zoom:function(a){var b=this._clearInteractiveTimeout();if(this._trigger("dblclick",a,{type:"Point",coordinates:this._toMap(this._current,this._centerInteractive,this._pixelSizeInteractive)}),!a.isDefaultPrevented()){var c=this._getZoomCenterAndSize(this._current,1,!0);this._setInteractiveCenterAndSize(c.center,c.pixelSize),this._interactiveTransform(),b=!0}b&&this._setInteractiveTimeout(!0)},_eventTarget_dblclick:function(c){if("static"!==this._options.mode){switch(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),this._options.mode){case"drawLineString":case"measureLength":this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])?(this._drawCoords.length--,this._trigger("shape",c,{type:"LineString",coordinates:this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords})):this._eventTarget_dblclick_zoom(c),this._resetDrawing();break;case"drawPolygon":case"measureArea":if(this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])){var d=this._drawCoords.length-1;d>2&&(this._drawCoords[d]=a.merge([],this._drawCoords[0]),this._trigger("shape",c,{type:"Polygon",coordinates:[this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords]}))}else this._eventTarget_dblclick_zoom(c);this._resetDrawing();break;default:this._eventTarget_dblclick_zoom(c)}this._inOp=!1}},_eventTarget_touchstart:function(b){if("undefined"!=typeof document.elementFromPoint){var c=document.elementFromPoint(b.pageX,b.pageY);if(c&&"A"===c.nodeName)return}var d=this._options.mode,e=this._options.shift,f="dragBox"===d?"dragBox":"zoom";if("static"!==d&&(this._pointerEvents||this._supportTouch||1===b.which)){this._pointerEvents&&console.log("PointerEvent touchstart");var g=this._clearInteractiveTimeout(),h=a(b.currentTarget).offset(),i=b.originalEvent.changedTouches;if(this._pointerEvents){if(b.currentTarget.setPointerCapture(b.originalEvent.pointerId),!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&b.originalEvent.pointerId!==this._multiTouchAnchor[0].pointerId)return this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-h.left,this._multiTouchAnchor[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=a.geo.center(this._multiTouchCurrentBbox,!0),this._current=a.merge([],this._anchor),g&&this._setInteractiveTimeout(!0),!1;this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top,0/0,0/0],this._current=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top]}else this._supportTouch&&i?(this._multiTouchAnchor=a.merge([],i),this._isMultiTouch=this._multiTouchAnchor.length>1,this._isMultiTouch?(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,i[1].pageX-h.left,i[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._current=a.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,0/0,0/0],this._current=[i[0].pageX-h.left,i[0].pageY-h.top])):this._current=[b.pageX-h.left,b.pageY-h.top];if(this._softDblClick){var j=a.now();if(j-this._downDate<750){if(this._isTap){var k=this._current[0]-this._anchor[0],l=this._current[1]-this._anchor[1],m=Math.sqrt(k*k+l*l);m>8?this._isTap=!1:this._current=a.merge([],this._anchor)}this._isDbltap=this._isDbltap?!1:this._isTap}else this._isDbltap=!1;this._isTap=!0,this._downDate=j}return this._mouseDown=!0,this._anchor=a.merge([],this._current),!this._inOp&&b.shiftKey&&"off"!==e?(this._shiftDown=!0,this._$eventTarget.css("cursor",this._options.cursors["default"===e?f:e])):this._isMultiTouch||!this._options.pannable&&"dragBox"!==d&&"dragCircle"!==d||(this._inOp=!0,"zoom"!==d&&"dragBox"!==d&&"dragCircle"!==d&&(this._lastDrag=this._current,b.currentTarget.setCapture&&b.currentTarget.setCapture())),b.preventDefault(),g&&this._setInteractiveTimeout(!0),!1}},_dragTarget_touchmove:function(b){if("static"!==this._options.mode){var c=!1;this._mouseDown&&(c=this._clearInteractiveTimeout());var d,f,g,h,i,j,k,l=this._$eventTarget.offset(),m=this._drawCoords.length,n=b.originalEvent.changedTouches;if(this._pointerEvents)this._isMultiTouch?(b.originalEvent.pointerId===this._multiTouchAnchor[0].pointerId?(this._multiTouchCurrentBbox[0]=b.originalEvent.pageX-l.left,this._multiTouchCurrentBbox[1]=b.originalEvent.pageY-l.top):b.originalEvent.pointerId===this._multiTouchAnchor[1].pointerId&&(this._multiTouchCurrentBbox[2]=b.originalEvent.pageX-l.left,this._multiTouchCurrentBbox[3]=b.originalEvent.pageY-l.top),f=a.geo._distancePointPoint([this._multiTouchAnchorBbox[0],this._multiTouchAnchorBbox[1]],[this._multiTouchAnchorBbox[2],this._multiTouchAnchorBbox[3]]),g=a.geo._distancePointPoint([this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1]],[this._multiTouchCurrentBbox[2],this._multiTouchCurrentBbox[3]]),d=a.geo.center(this._multiTouchCurrentBbox,!0),h=(g-f)/f,h*=h>0?5:10,i=h-this._wheelLevel,this._wheelLevel=h,j=this._getZoomCenterAndSize(this._anchor,i,!1),this._setInteractiveCenterAndSize(j.center,j.pixelSize),this._interactiveTransform(),c=!0,d=a.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchAnchor[0]=b.originalEvent,this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-l.left,this._multiTouchAnchor[0].pageY-l.top,0/0,0/0],d=[b.originalEvent.pageX-l.left,b.originalEvent.pageY-l.top]);else if(this._supportTouch&&n){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&n[0].identifier!==this._multiTouchAnchor[0].identifier)return this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(n[0]),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-l.left,this._multiTouchAnchor[1].pageY-l.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=this._current=a.geo.center(this._multiTouchCurrentBbox,!0),c&&this._setInteractiveTimeout(!0),!1;if(this._isMultiTouch){for(k=0;k0?5:10,i=h-this._wheelLevel,this._wheelLevel=h,j=this._getZoomCenterAndSize(this._anchor,i,!1),this._setInteractiveCenterAndSize(j.center,j.pixelSize),this._interactiveTransform(),c=!0,d=a.geo.center(this._multiTouchCurrentBbox,!0)}else d=[b.originalEvent.changedTouches[0].pageX-l.left,b.originalEvent.changedTouches[0].pageY-l.top]}else d=[b.pageX-l.left,b.pageY-l.top];if(d[0]===this._lastMove[0]&&d[1]===this._lastMove[1])return this._inOp?(b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1):!1;if(7===e&&(this._isDbltap=this._isTap=!1),this._mouseDown&&(this._current=d,this._moveDate=a.now()),this._isMultiTouch)return b.preventDefault(),this._isDbltap=this._isTap=!1,c&&this._setInteractiveTimeout(!0),!1;var o,p,q,r=this._options.mode,s=this._options.shift,t="dragBox"===r?"dragBox":"zoom";switch(this._shiftDown&&(r="default"===s?t:s),r){case"zoom":case"dragBox":this._mouseDown?(this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawBbox",[this._anchor[0],this._anchor[1],d[0],d[1]])):this._trigger("move",b,{type:"Point",coordinates:this.toMap(d)});break;case"dragCircle":this._mouseDown?(o=d[0]-this._anchor[0],p=d[1]-this._anchor[1],q=2*Math.sqrt(o*o+p*p),this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawArc",this._anchor,0,360,{width:q,height:q})):this._trigger("move",b,{type:"Point",coordinates:this.toMap(d)});break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":this._mouseDown||this._toolPan?(this._panMove(),c=!0):(m>0&&(this._drawCoords[m-1]=this._toMap(d,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[m-1]=d,this._refreshDrawing()),this._trigger("move",b,{type:"Point",coordinates:this.toMap(d)}));break;default:this._mouseDown||this._toolPan?(this._panMove(),c=!0):this._trigger("move",b,{type:"Point",coordinates:this.toMap(d)})}return this._lastMove=d,c&&this._setInteractiveTimeout(!0),this._inOp?(b.preventDefault(),!1):void 0}},_dragTarget_touchstop:function(c){if("static"!==this._options.mode){if(this._pointerEvents&&console.log("PointerEvent touchstop"),!this._mouseDown){if(7!==e)return;this._eventTarget_touchstart(c)}var d,f,g,h,i,j,k,l=this._clearInteractiveTimeout(),m=this._mouseDown,n=this._toolPan,o=this._$eventTarget.offset(),p=this._options.mode,q=this._options.shift,r="dragBox"===p?"dragBox":"zoom";if(this._shiftDown&&(p="default"===q?r:q),this._pointerEvents){for(d=[c.pageX-o.left,c.pageY-o.top],f=0;ff;f++)v=360*f/y*(Math.PI/180),this._drawPixels[f]=[this._anchor[0]+Math.cos(v)*x,this._anchor[1]+Math.sin(v)*x];this._drawPixels[y]=[this._drawPixels[0][0],this._drawPixels[0][1]],j=this._toMap([[this._anchor[0]-x,this._anchor[1]+(w?-x:x)],[this._anchor[0]+x,this._anchor[1]+(w?x:-x)]]),k={type:"Polygon",coordinates:[this._toMap(this._drawPixels)],bbox:[j[0][0],j[0][1],j[1][0],j[1][1]]},this._userGeodetic&&(k.coordinates=a.geo.proj.toGeodetic(k.coordinates),k.bbox=a.geo.proj.toGeodetic(k.bbox)),this._trigger("shape",c,k),this._resetDrawing()}else j=this._toMap(d),k={type:"Point",coordinates:[j[0],j[1]],bbox:[j[0],j[1],j[0],j[1]]},this._userGeodetic&&(k.coordinates=a.geo.proj.toGeodetic(k.coordinates),k.bbox=a.geo.proj.toGeodetic(k.bbox)),this._trigger("shape",c,k);break;case"drawPoint":if(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),n)this._panFinalize();else if(g-this._clickDate>100){var z=this;this._drawTimeout=setTimeout(function(){z._drawTimeout&&(z._trigger("shape",c,{type:"Point",coordinates:z.toMap(d)}),z._inOp=!1,z._drawTimeout=null)},250)}break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":n?this._panFinalize():(this._trigger("click",c,{type:"Point",coordinates:this.toMap(d)}),c.isDefaultPrevented()||(f=0===this._drawCoords.length?0:this._drawCoords.length-1,this._drawCoords[f]=this._toMap(d),this._drawPixels[f]=d,(2>f||this._drawCoords[f][0]!==this._drawCoords[f-1][0]||this._drawCoords[f][1]!==this._drawCoords[f-1][1])&&(this._drawCoords[f+1]=this._toMap(d,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[f+1]=d),this._refreshDrawing()));break;default:n?this._panFinalize():g-this._clickDate>100&&(this._trigger("click",c,{type:"Point",coordinates:this.toMap(d)}),this._inOp=!1)}if(this._clickDate=g,this._softDblClick&&this._isDbltap)return this._isDbltap=this._isTap=!1,l&&this._setInteractiveTimeout(!0),this._$eventTarget.trigger("dblclick",c),!1}return l&&this._setInteractiveTimeout(!0),this._inOp?(c.preventDefault(),!1):void 0}},_eventTarget_mousewheel:function(b){if("static"!==this._options.mode&&"off"!==this._options.scroll){if(b.preventDefault(),this._mouseDown)return!1;if(0!==b.deltaY){this._clearInteractiveTimeout();var c=b.deltaY>0?1:-1,d=a(b.currentTarget).offset();this._anchor=[b.pageX-d.left,b.pageY-d.top];var e=this._getZoomCenterAndSize(this._anchor,c,null!==this._options.tilingScheme);this._setInteractiveCenterAndSize(e.center,e.pixelSize),this._interactiveTransform(),this._setInteractiveTimeout(!0)}return!1}}})}(jQuery,window),function(a,b){a.geo._serviceTypes.tiled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0,reloadTiles:!1};var g='
                  ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b.options.tilingScheme;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),h=f/e;if(f>0){h=Math.round(1e3*h)/1e3;var i=c.data("scaleOrigin"),j=b._toPixel(i,d,e);c.css({left:Math.round(j[0])+"px",top:Math.round(j[1])+"px",width:g.tileWidth*h,height:g.tileHeight*h})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&f&&(g.reloadTiles=!0),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i,j=d._getBbox(),k=d._pixelSize,l=this,m=g.serviceContainer,n="image"===d.options.axisLayout,o=n?1:-1,p=d.options.tilingScheme,q=p.tileWidth,r=p.tileHeight,s=Math.floor((j[0]-p.origin[0])/(k*q)),t=Math.max(Math.floor((n?j[1]-p.origin[1]:p.origin[1]-j[3])/(k*r)),0),u=Math.ceil((j[2]-p.origin[0])/(k*q)),v=Math.ceil((n?j[3]-p.origin[1]:p.origin[1]-j[1])/(k*r)),w=d._getBboxMax(),x=d._getPixelSize(0),y=x/k,z=Math.floor((w[0]-p.origin[0])/(x*q))*y,A=Math.floor((p.origin[1]+o*w[3])/(x*r))*y,B=p.origin[0]+z*q*k,C=p.origin[1]+o*A*r*k,D=Math.round((B-j[0])/k),E=Math.round((n?C-j[1]:j[3]-C)/k),F=m.children().show(),G=F.filter("[data-pixel-size='"+k+"']").appendTo(m),H=e.style.opacity,I=function(a){l._loadImage(this.img,a,k,d,g,H)},J=function(){delete this.img,g.loadCount--,d._requestComplete()};for(g.reloadTiles&&F.find("img").attr("data-dirty","true"),G.size()?(G.css({left:D%q+"px",top:E%r+"px"}).data("scaleOrigin",d._toMap([D%q,E%r])),G.children().each(function(){var b=a(this),c=b.attr("data-tile").split(",");b.css({left:Math.round(100*(parseInt(c[0],10)-z)+(D-D%q)/q*100)+"%",top:Math.round(100*(parseInt(c[1],10)-A)+(E-E%r)/r*100)+"%"}),1>H&&b.fadeTo(0,H)})):(m.append(b.toStaticHTML("
                  ")),G=m.children(":last").data("scaleOrigin",d._toMap([D%q,E%r]))),h=s;u>h;h++)for(i=t;v>i;i++){var K=""+h+","+i,L=G.children("[data-tile='"+K+"']").removeAttr("data-dirty");if(0===L.size()||g.reloadTiles){var M,N=[p.origin[0]+h*q*k,p.origin[1]+o*i*r*k],O=[p.origin[0]+((h+1)*q-1)*k,p.origin[1]+o*((i+1)*r-1)*k],P=[N[0],N[1],O[0],O[1]],Q={bbox:P,width:q,height:r,zoom:d._getZoom(),tile:{row:i,column:h},index:Math.abs(i+h)},R=a.isFunction(e.src);if(R?M=e.src(Q):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),M=a.render[this._tmplGeoSrcId](Q)):M=e.src,g.loadCount++,d._requestQueued(),g.reloadTiles&&L.size()>0)L.attr("src",M);else{var S="",G.append(b.toStaticHTML(S)),L=G.children(":last")}"string"==typeof M?l._loadImage(L,M,k,d,g,H):M&&a.isFunction(M.promise)?(a.extend(M.promise(),{img:L}),M.done(I).fail(J)):L.remove()}}F.find("[data-dirty]").remove(),g.reloadTiles=!1}},resize:function(){},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--,b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){1>g?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).error(function(b){a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).attr("src",c)}}}()}(jQuery,window),function(a,b){a.geo._serviceTypes.shingled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0};var g='
                  ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b._getContentBounds(),h=g.width,i=g.height;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),g=f/e;if(f>0){g=Math.round(1e3*g)/1e3; -var j=c.data("origin"),k=b._toPixel(j,d,e);c.css({left:Math.round(k[0]),top:Math.round(k[1]),width:h*g,height:i*g})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i=d._getBbox(),j=d._pixelSize,k=this,l=g.serviceContainer,m=d._getContentBounds(),n=m.width,o=m.height,p=l.children('[data-pixel-size="'+j+'"]'),q=e.style.opacity;1>q||f||1===e.shinglesMax?l.find("img").attr("data-keep-alive","0"):e.shinglesMax>1&&l.find("img").slice(0,-(e.shinglesMax-1)).attr("data-keep-alive","0"),p.size()||(l.append(b.toStaticHTML('
                  ')),p=l.children(":last"));var r,s={bbox:i,width:n,height:o,zoom:d._getZoom(),tile:null,index:0},t=a.isFunction(e.src),u=p.position();u.left=-u.left,u.top=-u.top,t?r=e.src(s):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),r=a.render[this._tmplGeoSrcId](s)):r=e.src,g.loadCount++,d._requestQueued(),p.append(b.toStaticHTML('')),h=p.children(":last").data("center",d._center),"string"==typeof r?k._loadImage(h,r,j,d,g,q):r&&r.done(function(a){k._loadImage(h,a,j,d,g,q)}).fail(function(){h.remove(),g.loadCount--,d._requestComplete()})}},resize:function(b,c){var d=a.data(c,"geoServiceState");if(d&&c&&"visible"===c.style.visibility){this._cancelUnloaded(b,c);var e=d.serviceContainer,f=b._getContentBounds(),g=f.width,h=f.height,i=e.children();i.attr("data-pixel-size","0"),i.each(function(){var b=a(this),c=b.position();b.css({left:c.left+(g-b.width())/2,top:c.top+(h-b.height())/2})})}},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--,b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(1>g?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(':not([data-pixel-size="'+d+'"])').remove(),h.find("img[data-keep-alive]").remove(),f.loadCount=0))}).error(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0))}).attr("src",c)}}}()}(jQuery,window); \ No newline at end of file diff --git a/dist/jquery.geo-1.0.0-rc1.1.min.js b/dist/jquery.geo-1.0.0-rc1.1.min.js deleted file mode 100644 index 33a7ad7..0000000 --- a/dist/jquery.geo-1.0.0-rc1.1.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! jQuery Geo - v1.0.0-rc1.1 - 2016-06-05 -* http://jquerygeo.com -* Copyright (c) 2016 Ryan Morrison-Westphal; Licensed MIT */ -document.createElement("canvas").getContext||!function(){function a(){return this.context_||(this.context_=new q(this))}function b(a,b,c){var d=G.call(arguments,2);return function(){return a.apply(b,d.concat(G.call(arguments)))}}function c(a,b,c){a.namespaces[b]||a.namespaces.add(b,c,"#default#VML")}function d(a){if(c(a,"g_vml_","urn:schemas-microsoft-com:vml"),c(a,"g_o_","urn:schemas-microsoft-com:office:office"),!a.styleSheets.ex_canvas_){var b=a.createStyleSheet();b.owningElement.id="ex_canvas_",b.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function e(a){var b=a.srcElement;switch(a.propertyName){case"width":b.getContext().clearRect(),b.style.width=b.attributes.width.nodeValue+"px",b.firstChild.style.width=b.clientWidth+"px";break;case"height":b.getContext().clearRect(),b.style.height=b.attributes.height.nodeValue+"px",b.firstChild.style.height=b.clientHeight+"px"}}function f(a){var b=a.srcElement;b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px",b.firstChild.style.height=b.clientHeight+"px")}function g(){return[[1,0,0],[0,1,0],[0,0,1]]}function h(a,b){for(var c=g(),d=0;3>d;d++)for(var e=0;3>e;e++){for(var f=0,h=0;3>h;h++)f+=a[d][h]*b[h][e];c[d][e]=f}return c}function i(a,b){b.fillStyle=a.fillStyle,b.lineCap=a.lineCap,b.lineJoin=a.lineJoin,b.lineWidth=a.lineWidth,b.miterLimit=a.miterLimit,b.shadowBlur=a.shadowBlur,b.shadowColor=a.shadowColor,b.shadowOffsetX=a.shadowOffsetX,b.shadowOffsetY=a.shadowOffsetY,b.strokeStyle=a.strokeStyle,b.globalAlpha=a.globalAlpha,b.font=a.font,b.textAlign=a.textAlign,b.textBaseline=a.textBaseline,b.arcScaleX_=a.arcScaleX_,b.arcScaleY_=a.arcScaleY_,b.lineScale_=a.lineScale_}function j(a){var b=a.indexOf("(",3),c=a.indexOf(")",b+1),d=a.substring(b+1,c).split(",");return(4!=d.length||"a"!=a.charAt(3))&&(d[3]=1),d}function k(a){return parseFloat(a)/100}function l(a,b,c){return Math.min(c,Math.max(b,a))}function m(a){var b,c,d,e,f,g;if(e=parseFloat(a[0])/360%360,0>e&&e++,f=l(k(a[1]),0,1),g=l(k(a[2]),0,1),0==f)b=c=d=g;else{var h=.5>g?g*(1+f):g+f-g*f,i=2*g-h;b=n(i,h,e+1/3),c=n(i,h,e),d=n(i,h,e-1/3)}return"#"+I[Math.floor(255*b)]+I[Math.floor(255*c)]+I[Math.floor(255*d)]}function n(a,b,c){return 0>c&&c++,c>1&&c--,1>6*c?a+6*(b-a)*c:1>2*c?b:2>3*c?a+(b-a)*(2/3-c)*6:a}function o(a){if(a in L)return L[a];var b,c=1;if(a=String(a),"#"==a.charAt(0))b=a;else if(/^rgb/.test(a)){for(var d,e=j(a),b="#",f=0;3>f;f++)d=-1!=e[f].indexOf("%")?Math.floor(255*k(e[f])):+e[f],b+=I[l(d,0,255)];c=+e[3]}else if(/^hsl/.test(a)){var e=j(a);b=m(e),c=e[3]}else b=a;return L[a]={color:b,alpha:c}}function p(a){return M[a]||"square"}function q(a){this.m_=g(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.strokeStyle="#000",this.fillStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=1*E,this.globalAlpha=1,this.canvas=a;var b="width:"+a.clientWidth+"px;height:"+a.clientHeight+"px;overflow:hidden;position:absolute",c=a.ownerDocument.createElement("div");c.style.cssText=b,a.appendChild(c);var d=c.cloneNode(!1);d.style.backgroundColor="red",d.style.filter="alpha(opacity=0)",a.appendChild(d),this.element_=c,this.arcScaleX_=1,this.arcScaleY_=1,this.lineScale_=1}function r(a,b,c,d){a.currentPath_.push({type:"bezierCurveTo",cp1x:b.x,cp1y:b.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y}),a.currentX_=d.x,a.currentY_=d.y}function s(a,b){var c=o(a.strokeStyle),d=c.color,e=c.alpha*a.globalAlpha,f=a.lineScale_*a.lineWidth;1>f&&(e*=f),b.push("')}function t(a,b,c,d){var e=(a.fillStyle,a.arcScaleX_,a.arcScaleY_,d.x-c.x,d.y-c.y,o(a.fillStyle)),f=e.color,g=e.alpha*a.globalAlpha;b.push('')}function u(a,b,c){var d=a.m_;return{x:E*(b*d[0][0]+c*d[1][0]+d[2][0])-F,y:E*(b*d[0][1]+c*d[1][1]+d[2][1])-F}}function v(a){return isFinite(a[0][0])&&isFinite(a[0][1])&&isFinite(a[1][0])&&isFinite(a[1][1])&&isFinite(a[2][0])&&isFinite(a[2][1])}function w(a,b,c){if(v(b)&&(a.m_=b,c)){var d=b[0][0]*b[1][1]-b[0][1]*b[1][0];a.lineScale_=D(C(d))}}function x(a){this.code=this[a],this.message=a+": DOM Exception "+this.code}var y=Math,z=y.round,A=y.sin,B=y.cos,C=y.abs,D=y.sqrt,E=10,F=E/2,G=(+navigator.userAgent.match(/MSIE ([\d.]+)?/)[1],Array.prototype.slice);d(document);var H={init:function(a){var c=a||document;c.createElement("canvas"),c.attachEvent("onreadystatechange",b(this.init_,this,c))},init_:function(a){for(var b=a.getElementsByTagName("canvas"),c=0;cJ;J++)for(var K=0;16>K;K++)I[16*J+K]=J.toString(16)+K.toString(16);var L={},M={butt:"flat",round:"round"},N=q.prototype;N.clearRect=function(){this.textMeasureEl_&&(this.textMeasureEl_.removeNode(!0),this.textMeasureEl_=null),this.element_.innerHTML=""},N.beginPath=function(){this.currentPath_=[]},N.moveTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"moveTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.lineTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"lineTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.bezierCurveTo=function(a,b,c,d,e,f){var g=u(this,e,f),h=u(this,a,b),i=u(this,c,d);r(this,h,i,g)},N.quadraticCurveTo=function(a,b,c,d){var e=u(this,a,b),f=u(this,c,d),g={x:this.currentX_+2/3*(e.x-this.currentX_),y:this.currentY_+2/3*(e.y-this.currentY_)},h={x:g.x+(f.x-this.currentX_)/3,y:g.y+(f.y-this.currentY_)/3};r(this,g,h,f)},N.arc=function(a,b,c,d,e,f){c*=E;var g=f?"at":"wa",h=a+B(d)*c-F,i=b+A(d)*c-F,j=a+B(e)*c-F,k=b+A(e)*c-F;h!=j||f||(h+=.125);var l=u(this,a,b),m=u(this,h,i),n=u(this,j,k);this.currentPath_.push({type:g,x:l.x,y:l.y,radius:c,xStart:m.x,yStart:m.y,xEnd:n.x,yEnd:n.y})},N.stroke=function(a){var b=[],c=10,d=10;b.push("f.x)&&(f.x=i.x),(null==e.y||i.yf.y)&&(f.y=i.y))}b.push(' ">'),a?t(this,b,e,f):s(this,b),b.push(""),this.element_.insertAdjacentHTML("beforeEnd",b.join(""))},N.fill=function(){this.stroke(!0)},N.closePath=function(){this.currentPath_.push({type:"close"})},N.save=function(){var a={};i(this,a),this.aStack_.push(a),this.mStack_.push(this.m_),this.m_=h(g(),this.m_)},N.restore=function(){this.aStack_.length&&(i(this.aStack_.pop(),this),this.m_=this.mStack_.pop())},N.translate=function(a,b){var c=[[1,0,0],[0,1,0],[a,b,1]];w(this,h(c,this.m_),!1)},N.scale=function(a,b){this.arcScaleX_*=a,this.arcScaleY_*=b;var c=[[a,0,0],[0,b,0],[0,0,1]];w(this,h(c,this.m_),!0)};var O=x.prototype=new Error;O.INDEX_SIZE_ERR=1,O.DOMSTRING_SIZE_ERR=2,O.HIERARCHY_REQUEST_ERR=3,O.WRONG_DOCUMENT_ERR=4,O.INVALID_CHARACTER_ERR=5,O.NO_DATA_ALLOWED_ERR=6,O.NO_MODIFICATION_ALLOWED_ERR=7,O.NOT_FOUND_ERR=8,O.NOT_SUPPORTED_ERR=9,O.INUSE_ATTRIBUTE_ERR=10,O.INVALID_STATE_ERR=11,O.SYNTAX_ERR=12,O.INVALID_MODIFICATION_ERR=13,O.NAMESPACE_ERR=14,O.INVALID_ACCESS_ERR=15,O.VALIDATION_ERR=16,O.TYPE_MISMATCH_ERR=17,G_vmlCanvasManager=H,CanvasRenderingContext2D=q,DOMException=x}(),this.jsviews||this.jQuery&&jQuery.views||function(a,b){function c(a,b){var c="\\"+a.charAt(0),d="\\"+a.charAt(1),e="\\"+b.charAt(0),f="\\"+b.charAt(1);return Q.rTag=u=d+"(?:(?:(\\w+(?=[\\/\\s"+e+"]))|(?:(\\w+)?(:)|(>)|(\\*)))\\s*((?:[^"+e+"]|"+e+"(?!"+f+"))*?)(\\/)?|(?:\\/(\\w+)))"+e,u=new RegExp(c+u+f,"g"),v=new RegExp("<.*>|"+a+".*"+b),this}function d(a){var c=this,d=c.tmpl.helpers||{};return a=(c.ctx[a]!==b?c.ctx:d[a]!==b?d:k[a]!==b?k:{})[a],"function"!=typeof a?a:function(){return a.apply(c,arguments)}}function e(a,b,c){var d=b.tmpl.converters;return a=d&&d[a]||l[a],a?a.call(b,c):c}function f(a,c,d,e,f){f.props=f.props||{};var g,h=f.props.tmpl,k=c.tmpl.tags,l=c.tmpl.templates,n=arguments,o=k&&k[a]||j[a];return o?(e=e&&c.tmpl.tmpls[e-1],h=h||e||b,f.tmpl=""+h===h?l&&l[h]||i[h]||i(h):h,f.isTag=A,f.converter=d,f.view=c,f.renderContent=m,c.ctx&&w(f.ctx,c.ctx),g=o.apply(f,n.length>5?O.call(n,5):[]),g||(g==b?"":g.toString())):""}function g(a,c,e,f,g,h){var i=e.views,j={tmpl:g,path:c,parent:e,data:f,ctx:a,views:t.isArray(f)?[]:{},hlp:d};return t.isArray(i)?i.splice(j.index=h!==b?h:i.length,0,j):i[j.index="_"+I++]=j,j}function h(a,c,d,e,f){var g,h;if(d&&"object"==typeof d&&!d.nodeType){for(g in d)c(g,d[g]);return a}return d&&e!==b?""+d===d&&(null===e?delete c[d]:(e=f?f(d,e):e)&&(c[d]=e)):f&&(e=f(b,e||d)),(h=y.onStoreItem)&&h(c,d,e,f),e}function i(a,b){return h(this,i,a,b,q)}function j(a,b){return h(this,j,a,b)}function k(a,b){return h(this,k,a,b)}function l(a,b){return h(this,l,a,b)}function m(a,c,d,e,f){var h,j,k,l,m,n,o,p,q,r,s={},u=f===A,v=this,x="";if(v.isTag?(q=v.tmpl,c=c||v.ctx,d=d||v.view,e=e||v.path,f=f||v.index,s=v.props):q=v.jquery&&v[0]||v,d=d||Q.topView,p=d.ctx,r=q.layout,a===d&&(a=d.data,r=A),c=c&&c===p?p:p?(p=w({},p),c?w(p,c):p):c||{},s.link===z&&(c.link=z),q.fn||(q=i[q]||i(q)),m=c.link&&y.onRenderItem,n=c.link&&y.onRenderItems,q){if(t.isArray(a)&&!r)for(l=u?d:f!==b&&d||g(c,e,d,a,q,f),h=0,j=a.length;j>h;h++)k=a[h],o=q.fn(k,g(c,e,l,k,q,(f||0)+h),Q),x+=m?m(o,s):o;else l=u?d:g(c,e,d,a,q,f),x+=a||r?q.fn(a,l,Q):"";return d.topKey=l.index,n?n(x,e,l.index,q,s):x}return""}function n(){throw"Syntax error"}function o(a,b,c){function d(b){b-=D,b&&J.push(a.substr(D,b).replace(E,"\\n"))}function e(b,e,g,h,i,j,k,l,m,n){i&&(h=":",g="html");var o="",q="",r=!l&&!h;if(e=e||h,d(n),D=n+b.length,j?y&&J.push(["*",k.replace(F,"$1")]):e?("else"===e&&(K[5]=a.substring(K[5],n),K=I.pop(),J=K[3],r=A),k=k?p(k,c).replace(H,function(a,b,c){return b?q+=c+",":o+=c+",",""}):"",o=o.slice(0,-1),k=k.slice(0,-1),f=[e,g||"",k,r&&[],"{"+(o?"props:{"+o+"},":"")+"path:'"+k+"'"+(q?",ctx:{"+q.slice(0,-1)+"}":"")+"}"],r&&(I.push(K),K=f,K[5]=D),J.push(f)):m&&(K[5]=a.substring(K[5],n),K=I.pop()),!K)throw"Expected block tag";J=K[3]}var f,g,h,i,j,k,l,m,n,q,s,t,v,w,x,y,z=b?{allowCode:y=b.allowCode,debug:b.debug}:{},B=b&&b.tmpls,C=[],D=0,I=[],J=C,K=[,,,C],L=0;for(a=a.replace(G,"\\$1"),a.replace(u,e),d(a.length),i=C.length,j=i?"":'"";',h=0;i>h;h++)g=C[h],"*"===g[0]?j=j.slice(0,h?-1:-3)+";"+g[1]+(i>h+1?"ret+=":""):""+g===g?j+='"'+g+'"+':(s=g[0],t=g[1],v=g[2],J=g[3],w=g[4],a=g[5],J&&(x=r(a,z,b,L++),o(a,x),B.push(x)),q=q||w.indexOf("view")>-1,j+=(":"===s?"html"===t?(l=A,"e("+v):t?(n=A,'c("'+t+'",view,'+v):(m=A,"((v="+v+')!=u?v:""'):(k=A,'t("'+s+'",view,"'+(t||"")+'",'+(J?B.length:'""')+","+w+(v?",":"")+v))+")+");return j=new Function("data, view, j, b, u",M+(m?"v,":"")+(k?"t=j.tag,":"")+(n?"c=j.convert,":"")+(l?"e=j.converters.html,":"")+"ret; try{\n\n"+(z.debug?"debugger;":"")+(y?"ret=":"return ")+j.slice(0,-1)+";\n\n"+(y?"return ret;":"")+"}catch(e){return j.err(e);}"),b&&(b.fn=j,b.useVw=n||q||k),j}function p(a,b){function c(a,c,i,j,k,l,m,o,p,q,r,s,t,u,v,w){function x(a,c,d,e,f,g,h){if(c){var i=(d?'view.hlp("'+d+'")':e?"view":"data")+(h?(f?"."+f:d?"":e?"":"."+c)+(g||""):(h=d?"":e?f||"":c,""));return b&&"("!==p&&(i="b("+i+',"'+h+'")'),i+(h?"."+h:"")}return a}return k=k||"",i=i||c||r,j=j||o,p=p||v||"",k=k||"",l?void n():h?(h=!s,h?a:'"'):g?(g=!t,g?a:'"'):(i?(f++,i):"")+(w?f?"":d?(d=z,"\b"):",":m?(f&&n(),d=A,"\b"+j+":"):j?j.replace(C,x)+(p?(e[++f]=A,p):k):k?a:u?(e[f--]=z,u+(p?(e[++f]=A,p):"")):q?(e[f]||n(),","):c?"":(h=s,g=t,'"'))}var d,e={},f=0,g=z,h=z;return a=(a+" ").replace(D,c)}function q(a,c,d,e){function f(b){return""+b===b||b.nodeType>0?(h=b.nodeType>0?b:!v.test(b)&&B&&B(b)[0],h&&h.type&&(b=i[h.getAttribute(L)],b||(a=a||"_"+J++,h.setAttribute(L,a),b=q(a,h.innerHTML,d,e),i[a]=b)),b):void 0}var g,h,j,k,l;if(g=f(c),e=e||(c.markup?c:{}),e.name=a,k=e.templates,!g&&c.markup&&(g=f(c.markup))&&(!g.fn||g.debug===c.debug&&g.allowCode===c.allowCode||(g=g.markup)),g!==b){a&&!d&&(P[a]=function(){return c.render.apply(c,arguments)}),g.fn||c.fn?g.fn&&(c=a&&a!==g.name?w(w({},g),e):g):(c=r(g,e,d,0),o(g,c));for(j in k)l=k[j],l.name!==j&&(k[j]=q(j,l,c));return c}}function r(a,b,c,d){function e(a){c[a]&&(f[a]=w(w({},c[a]),b[a]))}b=b||{};var f={markup:a,tmpls:[],links:[],render:m};return c&&(c.templates&&(f.templates=w(w({},c.templates),b.templates)),f.parent=c,f.name=c.name+"["+d+"]",f.index=d),w(f,b),c&&(e("templates"),e("tags"),e("helpers"),e("converters")),f}function s(a){return K[a]||(K[a]="&#"+a.charCodeAt(0)+";")}var t,u,v,w,x="v1.0pre",y={},z=!1,A=!0,B=a.jQuery,C=/^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g,D=/(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,E=/\r?\n/g,F=/\\(['"])/g,G=/\\?(['"])/g,H=/\x08(~)?([^\x08]+)\x08/g,I=0,J=0,K={"&":"&","<":"<",">":">"},L="data-jsv-tmpl",M="var j=j||"+(B?"jQuery.":"js")+"views,",N=/[\x00"&'<>]/g,O=Array.prototype.slice,P={},Q={jsviews:x,sub:y,debugMode:A,err:function(a){return Q.debugMode?"
                  Error: "+(a.message||a)+". ":'""'},tmplFn:o,render:P,templates:i,tags:j,helpers:k,converters:l,View:g,convert:e,delimiters:c,tag:f};B?(t=B,t.templates=i,t.render=P,t.views=Q,t.fn.render=m):(t=a.jsviews=Q,t.extend=function(a,b){var c;a=a||{};for(c in b)a[c]=b[c];return a},t.isArray=Array&&Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)}),w=t.extend,Q.topView={views:{},tmpl:{},hlp:d,ctx:Q.helpers},j({"if":function(){var a=this,c=a.view;return c.onElse=function(a,d){for(var e=0,f=d.length;f&&!d[e++];)if(e===f)return"";return c.onElse=b,a.path="",a.renderContent(c)},c.onElse(this,arguments)},"else":function(){var a=this.view;return a.onElse?a.onElse(this,arguments):""},"for":function(){var a,b=this,c="",d=arguments,e=d.length;for(b.props.layout&&(b.tmpl.layout=A),a=0;e>a;a++)c+=b.renderContent(d[a]);return c},"=":function(a){return a},"*":function(a){return a}}),l({html:function(a){return a!=b?String(a).replace(N,s):""}}),c("{{","}}")}(this),function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})}),$.widget||!function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d,e=0;null!=(d=b[e]);e++)try{a(d).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){return c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}}),d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e,f=b.split(".")[0];b=b.split(".")[1],e=f+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][e]=function(c){return!!a.data(c,b)},a[f]=a[f]||{},a[f][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[f][b].prototype=a.extend(!0,g,{namespace:f,widgetName:b,widgetEventPrefix:a[f][b].prototype.widgetEventPrefix||b,widgetBaseClass:e},d),a.widget.bridge(b,a[f][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f="string"==typeof e,g=Array.prototype.slice.call(arguments,1),h=this;return e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e,f&&"_"===e.charAt(0)?h:(f?this.each(function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;return f!==d&&f!==b?(h=f,!1):void 0}):this.each(function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))}),h)}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(0===arguments.length)return a.extend({},this.options);if("string"==typeof c){if(d===b)return this.options[c];e={},e[c]=d}return this._setOptions(e),this},_setOptions:function(b){var c=this;return a.each(b,function(a,b){c._setOption(a,b)}),this},_setOption:function(a,b){return this.options[a]=b,"disabled"===a&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",b),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];if(d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}}(jQuery),function(a,b,c){b.toStaticHTML=b.toStaticHTML||function(a){return a};var d=Number.POSITIVE_INFINITY,e=Number.NEGATIVE_INFINITY;a.geo={_allCoordinates:function(b){for(var c=this._flatten(b),d=0,e=[];d1&&!a.isArray(b[0]))return b[0]>=-180.001&&b[0]<=180.001&&b[1]>=-90.001&&b[1]<=90.001;b=b[0]}return!1},center:function(b,c){var d=!1;!c&&a.geo.proj&&this._isGeodetic(b)&&(d=!0,b=a.geo.proj.fromGeodetic(b));var e=[(b[0]+b[2])/2,(b[1]+b[3])/2];return d?a.geo.proj.toGeodetic(e):e},expandBy:function(b,c,d,e){var f=!1;return!e&&a.geo.proj&&this._isGeodetic(b)&&(f=!0,b=a.geo.proj.fromGeodetic(b)),b=[b[0]-c,b[1]-d,b[2]+c,b[3]+d],f?a.geo.proj.toGeodetic(b):b},height:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[3]-b[1]},_in:function(a,b){return a[0]<=b[0]&&a[1]<=b[1]&&a[2]>=b[2]&&a[3]>=b[3]},_bboxDisjoint:function(a,b){return b[0]>a[2]||b[2]a[3]||b[3]0&&(h/i>c?(f=h/2,g=f/c):(g=i/2,f=g*c),b=[j[0]-f,j[1]-g,j[0]+f,j[1]+g]),e?a.geo.proj.toGeodetic(b):b},recenter:function(b,c,d){var e=!1;!d&&a.geo.proj&&(this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b)),this._isGeodetic(c)&&(c=a.geo.proj.fromGeodetic(c)));var f=(b[2]-b[0])/2,g=(b[3]-b[1])/2;return b=[c[0]-f,c[1]-g,c[0]+f,c[1]+g],e?a.geo.proj.toGeodetic(b):b},scaleBy:function(b,c,d){var e=!1;!d&&a.geo.proj&&this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b));var f=this.center(b,!0),g=(b[2]-b[0])*c/2,h=(b[3]-b[1])*c/2;return b=[f[0]-g,f[1]-h,f[0]+g,f[1]+h],e?a.geo.proj.toGeodetic(b):b},width:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[2]-b[0]},bbox:function(b,f){var g,h=!1;if(!b)return c;if(b.bbox)g=!f&&a.geo.proj&&this._isGeodetic(b.bbox)?a.geo.proj.fromGeodetic(b.bbox):b.bbox;else{g=[d,d,e,e];var i=this._allCoordinates(b),j=0;if(0===i.length)return c;for(!f&&a.geo.proj&&this._isGeodetic(i)&&(h=!0,i=a.geo.proj.fromGeodetic(i));j0?(g[0]=Math.min(Math.max(k[0][0],m[0]),m[2]),g[1]=Math.min(Math.max(k[0][1],m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g}):c:(j*=3,g[0]=Math.min(Math.max(g[0]/j,m[0]),m[2]),g[1]=Math.min(Math.max(g[1]/j,m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g});case"MultiPoint":if(b.coordinates.length>0)return g=b.coordinates[0],{type:"Point",coordinates:[g[0],g[1]]};break;case"MultiLineString":case"MultiPolygon":if(b.coordinates.length>0)return this.centroid({type:b.type.substr(5),coordinates:b.coordinates[0]},f)}return c},contains:function(a,b){if("Polygon"!==a.type)return!1;switch(b.type){case"Point":return this._containsPolygonPoint(a.coordinates,b.coordinates);case"LineString":return this._containsPolygonLineString(a.coordinates,b.coordinates);case"Polygon":return this._containsPolygonLineString(a.coordinates,b.coordinates[0]);default:return!1}},_containsPolygonPoint:function(a,b){if(0===a.length||a[0].length<4)return!1;for(var c,d,e=0,f=a[0][0],g=1;gb[0]&&e++),f=c;return e%2===1},_containsPolygonLineString:function(a,b){for(var c=0;c0){var e=a[0],f=b[0]-e[0],g=b[1]-e[1];if(1===a.length)return Math.sqrt(f*f+g*g);for(var h=1;hn&&(c=n),e=i,f=l,g=m}}return Math.sqrt(c)},_distanceSegmentPoint:function(a,b,c,d,e,f){var g=a*c+b*d;if(0>=g)return c*c+d*d;var h=a*a+b*b;return g>=h?e*e+f*f:c*c+d*d-g*g/h},_distanceLineStringLineString:function(a,b){for(var c=d,e=0;e=k;k++)h=360*k/j*(Math.PI/180),i.push([g[0]+Math.cos(h)*d,g[1]+Math.sin(h)*d]);return{type:"Polygon",coordinates:[f?a.geo.proj.toGeodetic(i):i]}}return c},_basic:function(a){for(var b,c,d=[],e=0,f=this._flatten(a);eo;q++)n=o,o+=p[q]/m;return e=c-n,k=g[q-1],l=g[q],j=[k[0]+e*(l[0]-k[0]),k[1]+e*(l[1]-k[1])],{type:"Point",coordinates:r?a.geo.proj.toGeodetic(j):j}}},WKT:function(){function b(a){return"POINT "+c(a.coordinates)}function c(a){return a&&a.length?"("+a.join(" ")+")":"EMPTY"}function d(a){return"LINESTRING "+e(a.coordinates)}function e(a){if(a&&a.length){for(var b=[],c=0;c2?{type:"Point",coordinates:[parseFloat(b[1]),parseFloat(b[2])]}:null}function p(a){var b,c,d=a.match(/\s*\((.*)\)/),e=[],f=0;if(d&&d.length>1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f0){for(;g
                  ";while(c[0]);return a>6?a:!a}();a.widget("geo.geographics",{_$elem:c,_options:{},_trueCanvas:!0,_trueDoubleBuffer:!0,_width:0,_height:0,_$canvas:c,_context:c,_$canvasSceneFront:c,_$canvasSceneBack:c,_$canvasSceneStale:c,_$canvasSceneDrawn:c,_timeoutEnd:null,_requireFlip:!1,_blitcanvas:c,_blitcontext:c,_$labelsContainerFront:c,_$labelsContainerBack:c,_labelsHtml:"",options:{style:{borderRadius:"8px",color:"#7f0000",fillOpacity:.2,height:"8px",opacity:1,strokeOpacity:1,strokeWidth:"2px",visibility:"visible",width:"8px"},doubleBuffer:!0},_create:function(){this._$elem=this.element,this._options=this.options,this._$elem.css({webkitTransform:"translateZ(0)",display:"inline-block",overflow:"hidden",textAlign:"left"}),"static"===this._$elem.css("position")&&this._$elem.css("position","relative"),this._$elem.addClass("geo-graphics"),this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10));var c="position:absolute;left:0;top:0;margin:0;padding:0;",e="width:"+this._width+"px;height:"+this._height+"px;",f='width="'+this._width+'" height="'+this._height+'"';this._blitcanvas=document.createElement("canvas"),this._blitcanvas.getContext?(this._$canvas=a(b.toStaticHTML("')),this._blitcanvas.width=1,this._blitcanvas.height=1,this._trueDoubleBuffer=this._blitcanvas.toDataURL().length>6,this._options.doubleBuffer&&this._trueDoubleBuffer||this._$elem.append(this._$canvas),this._context=this._$canvas[0].getContext("2d"),this._blitcanvas.width=this._width,this._blitcanvas.height=this._height,this._blitcontext=this._blitcanvas.getContext("2d"),this._$canvasSceneFront=a(b.toStaticHTML('')).on("load",a.proxy(this._canvasImgLoad,this)),this._$canvasSceneBack=a(b.toStaticHTML('')).on("load",a.proxy(this._canvasImgLoad,this))):8>=d&&(this._trueCanvas=!1,this._$elem.append("
                  '),this._$canvas=this._$elem.children(":last"),G_vmlCanvasManager.initElement(this._$canvas[0]),this._context=this._$canvas[0].getContext("2d"),this._$canvas.children().css({backgroundColor:"transparent",width:this._width,height:this._height})),this._$labelsContainerFront=a(b.toStaticHTML('
                  ')),this._$labelsContainerBack=a(b.toStaticHTML('
                  '))},_setOption:function(b,c){"style"===b&&(c=a.extend({},this._options.style,c)),a.Widget.prototype._setOption.apply(this,arguments)},destroy:function(){a.Widget.prototype.destroy.apply(this,arguments),this._$elem.html(""),this._$elem.removeClass("geo-graphics")},clear:function(){this._context.clearRect(0,0,this._width,this._height),this._labelsHtml="",this._end()},drawArc:function(a,b,c,d){if(d=this._getGraphicStyle(d),"hidden"!==d.visibility&&d.opacity>0&&d.widthValue>0&&d.heightValue>0){var e=Math.min(d.widthValue,d.heightValue)/2;b=b*Math.PI/180,c=c*Math.PI/180,this._context.save(),this._context.translate(a[0],a[1]),d.widthValue>d.heightValue?this._context.scale(d.widthValue/d.heightValue,1):this._context.scale(1,d.heightValue/d.widthValue),this._context.beginPath(),this._context.arc(0,0,e,b,c,!1),this._trueCanvas&&this._context.restore(),d.doFill&&(this._context.fillStyle=d.fill,this._context.globalAlpha=d.opacity*d.fillOpacity,this._context.fill()),d.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=d.strokeWidthValue,this._context.strokeStyle=d.stroke,this._context.globalAlpha=d.opacity*d.strokeOpacity,this._context.stroke()),this._trueCanvas||this._context.restore()}this._end()},drawPoint:function(a,b){b=this._getGraphicStyle(b),b.widthValue===b.heightValue&&b.heightValue===b.borderRadiusValue?this.drawArc(a,0,360,b):"hidden"!==b.visibility&&b.opacity>0&&(b.borderRadiusValue=Math.min(Math.min(b.widthValue,b.heightValue)/2,b.borderRadiusValue),a[0]-=b.widthValue/2,a[1]-=b.heightValue/2,this._context.beginPath(),this._context.moveTo(a[0]+b.borderRadiusValue,a[1]),this._context.lineTo(a[0]+b.widthValue-b.borderRadiusValue,a[1]),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1],a[0]+b.widthValue,a[1]+b.borderRadiusValue),this._context.lineTo(a[0]+b.widthValue,a[1]+b.heightValue-b.borderRadiusValue),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1]+b.heightValue,a[0]+b.widthValue-b.borderRadiusValue,a[1]+b.heightValue),this._context.lineTo(a[0]+b.borderRadiusValue,a[1]+b.heightValue),this._context.quadraticCurveTo(a[0],a[1]+b.heightValue,a[0],a[1]+b.heightValue-b.borderRadiusValue),this._context.lineTo(a[0],a[1]+b.borderRadiusValue),this._context.quadraticCurveTo(a[0],a[1],a[0]+b.borderRadiusValue,a[1]),this._context.closePath(),b.doFill&&(this._context.fillStyle=b.fill,this._context.globalAlpha=b.opacity*b.fillOpacity,this._context.fill()),b.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=b.strokeWidthValue,this._context.strokeStyle=b.stroke,this._context.globalAlpha=b.opacity*b.strokeOpacity,this._context.stroke()),this._end())},drawLineString:function(a,b){this._drawLines([a],!1,b)},drawPolygon:function(a,b){if(this._trueCanvas&&1!==a.length){if(!a||!a.length||a[0].length<3)return;b=this._getGraphicStyle(b),this._blitcontext.globalCompositeOperation="copy";var c,d,e;if("hidden"!==b.visibility&&b.opacity>0){if(this._blitcontext.clearRect(0,0,this._width,this._height),b.doFill&&a.length>1){for(this._blitcontext.globalCompositeOperation="source-out",this._blitcontext.globalAlpha=1,this._blitcontext.beginPath(),d=1;d1))for(d=1;d'+b+""},resize:function(a,b){this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10)),this._trueCanvas?(this._$canvas[0].width=this._width,this._$canvas[0].height=this._height,this._$canvasSceneFront.css({left:a,top:b}),this._$canvasSceneBack.css({width:this._width,height:this._height})):this._$canvas.css({width:this._width,height:this._height});var c=this._$labelsContainerFront.position();this._$labelsContainerFront.css({left:c.left+a,top:c.top+b,width:this._width,height:this._height}),this._$labelsContainerBack.css({width:this._width,height:this._height})},interactiveTransform:function(a,b){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._trueCanvas&&this._options.doubleBuffer&&this._trueDoubleBuffer?(this._canvasSceneLoad(),this._$canvasSceneFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})):this._context.clearRect(0,0,this._width,this._height),this._$labelsContainerFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})},_canvasImgLoad:function(){var a=this;a._$canvasSceneFront=a._$canvasSceneDrawn.prependTo(a._$elem),a._$canvasSceneBack=a._$canvasSceneStale,a._$canvasSceneBack.detach()},_canvasSceneLoad:function(){var a=this;a._requireFlip&&(a._requireFlip=!1,a._$canvasSceneStale=a._$canvasSceneFront,a._$canvasSceneDrawn=a._$canvasSceneBack.css({left:0,top:0,width:a._width,height:a._height}).prop("src",a._$canvas[0].toDataURL()))},_endCallback:function(){var a=this;if(a._timeoutEnd){a._trueCanvas&&a._options.doubleBuffer&&a._trueDoubleBuffer&&this._canvasSceneLoad(),a._$labelsContainerBack.html(b.toStaticHTML(a._labelsHtml)).find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"});var c=a._$labelsContainerFront;a._$labelsContainerFront=a._$labelsContainerBack.css({left:0,top:0,width:a._width,height:a._height}).appendTo(a._$elem),a._$labelsContainerBack=c.detach(),a._timeoutEnd=null}},_end:function(){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._requireFlip=!0,this._timeoutEnd=setTimeout(a.proxy(this._endCallback,this),20)},_getGraphicStyle:function(b){function c(a){return a=parseInt(a,10),+a+""===a?+a:a}return b=a.extend({},this._options.style,b),b.borderRadiusValue=c(b.borderRadius),b.fill=b.fill||b.color,b.doFill=b.fill&&b.fillOpacity>0,b.stroke=b.stroke||b.color,b.strokeWidthValue=c(b.strokeWidth),b.doStroke=b.stroke&&b.strokeOpacity>0&&b.strokeWidthValue>0,b.widthValue=c(b.width),b.heightValue=c(b.height),b},_drawLines:function(a,b,c){if(a&&a.length&&!(a[0].length<2)){var d,e;if(c=this._getGraphicStyle(c),"hidden"!==c.visibility&&c.opacity>0){for(this._context.beginPath(),d=0;d
                  ";while(c[0]);return a>6?a:!a}(),f=function(){return(navigator.userAgent.match(/gecko\/*\d/i)||[]).length>0}(),g={bbox:[-180,-85,180,85],bboxMax:[-180,-85,180,85],center:[0,0],cursors:{"static":"default",pan:"url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move",click:"crosshair",zoom:"crosshair",dragBox:"crosshair",dragCircle:"crosshair",drawPoint:"crosshair",drawLineString:"crosshair",drawPolygon:"crosshair",measureLength:"crosshair",measureArea:"crosshair"},measureLabels:{length:"{{:length.toFixed( 2 )}} m",area:"{{:area.toFixed( 2 )}} sq m"},drawStyle:{},shapeStyle:{},mode:"pan",pannable:!0,scroll:"default",shift:"default",services:[{"class":"osm",type:"tiled",src:function(a){return"//otile"+(a.index%4+1)+("https:"===location.protocol?"-s":"")+".mqcdn.com/tiles/1.0.0/osm/"+a.zoom+"/"+a.tile.column+"/"+a.tile.row+".png"},attr:'Tiles Courtesy of MapQuest '}],tilingScheme:{tileWidth:256,tileHeight:256,levels:18,basePixelSize:156543.03392799935,origin:[-20037508.342787,20037508.342787]},axisLayout:"map",zoom:0,zoomMin:0,zoomMax:Number.POSITIVE_INFINITY,zoomFactor:2,pixelSize:0};a.widget("geo.geomap",{_$elem:c,_map:c,_created:!1,_createdGraphics:!1,_widgetId:0,_tmplLengthId:"",_tmplAreaId:"",_contentBounds:{},_$resizeContainer:c,_$eventTarget:c,_$contentFrame:c,_$existingChildren:c,_$attrList:c,_$servicesContainer:c,_$shapesContainers:c,_$panContainer:c,_$shapesContainer:c,_$drawContainer:c,_$measureContainer:c,_$measureLabel:c,_dpi:96,_currentServices:[],_center:c,_pixelSize:c,_centerMax:c,_pixelSizeMax:c,_pixelSizeMin:c,_userGeodetic:!0,_centerInteractive:c,_pixelSizeInteractive:c,_timeoutInteractive:null,_timeoutWheel:null,_triggerInteractive:!1,_timeoutRefreshShapes:null,_loadCount:0,_wheelLevel:0,_fullZoomFactor:2,_partialZoomFactor:1.18920711500273,_mouseDown:c,_inOp:c,_toolPan:c,_shiftDown:c,_anchor:c,_current:c,_downDate:c,_moveDate:c,_clickDate:c,_lastMove:c,_lastDrag:c,_windowHandler:null,_resizeTimeout:null,_panning:c,_velocity:c,_friction:c,_pointerEvents:c,_supportTouch:c,_softDblClick:c,_isTap:c,_isDbltap:c,_isMultiTouch:c,_multiTouchAnchor:[],_multiTouchAnchorBbox:c,_multiTouchCurrentBbox:c,_drawTimeout:null,_drawPixels:[],_drawCoords:[],_graphicShapes:[],_initOptions:{},_options:{},options:a.extend({},g),_createWidget:function(b,c){if(this._$elem=a(c),this._$elem.is(".geo-service"))return this._graphicShapes=[],void a.Widget.prototype._createWidget.apply(this,arguments);this._widgetId=d++,this._serviceIdSeed=0,this._tmplLengthId="geoMeasureLength"+this._widgetId,this._tmplAreaId="geoMeasureArea"+this._widgetId,this._$elem.addClass("geo-map").css({webkitTransform:"translateZ(0)",touchAction:"none"}),this._initOptions=b||{},this._forcePosition(this._$elem),this._$elem.css("text-align","left");var e=this._findMapSize();this._contentBounds={x:parseInt(this._$elem.css("padding-left"),10),y:parseInt(this._$elem.css("padding-top"),10),width:e.width,height:e.height},this._createChildren(),this._center=[0,0],this._centerMax=[0,0],this._centerInteractive=[0,0],this.options.pixelSize=this._pixelSize=this._pixelSizeMax=156543.03392799935,this._pixelSizeMin=this._pixelSizeMax/Math.pow(2,17),this._mouseDown=this._inOp=this._toolPan=this._shiftDown=this._panning=this._isTap=this._isDbltap=this._isMultiTouch=!1,this._anchor=[0,0],this._current=[0,0],this._lastMove=[0,0],this._lastDrag=[0,0],this._velocity=[0,0],this._friction=[.8,.8],this._downDate=this._moveDate=this._clickDate=0,this._drawPixels=[],this._drawCoords=[],this._graphicShapes=[],a.Widget.prototype._createWidget.apply(this,arguments)},_create:function(){if(this._options=this.options,this._$elem.is(".geo-service"))return this._map=this._$elem.data("geoMap"),void this._$elem.data("geoService",this);this._map=this,this._pointerEvents=b.PointerEvent,this._supportTouch="ontouchend"in document,this._softDblClick=this._pointerEvents||this._supportTouch||7===e;var d=this,g=this._pointerEvents?"pointerdown":this._supportTouch?"touchstart mousedown":"mousedown",h=this._pointerEvents?"pointerup pointercancel":this._supportTouch?"touchend touchcancel mouseup":"mouseup",i=this._pointerEvents?"pointermove":this._supportTouch?"touchmove mousemove":"mousemove";a(document).keydown(a.proxy(this._document_keydown,this)),this._softDblClick?this._$eventTarget.on("softdblclick",a.proxy(this._eventTarget_dblclick,this)):this._$eventTarget.dblclick(a.proxy(this._eventTarget_dblclick,this)),this._$eventTarget.bind(g,a.proxy(this._eventTarget_touchstart,this));var j=this._$eventTarget[0].setCapture||this._pointerEvents?this._$eventTarget:a(document);j.bind(i,a.proxy(this._dragTarget_touchmove,this)),j.bind(h,a.proxy(this._dragTarget_touchstop,this)),this._$eventTarget.mousewheel(a.proxy(this._eventTarget_mousewheel,this)),this._windowHandler=function(){d._resizeTimeout&&clearTimeout(d._resizeTimeout),d._resizeTimeout=setTimeout(function(){d._created&&d._$elem.geomap("resize",!0)},500)},a(b).resize(this._windowHandler),this._$drawContainer.geographics({style:this._initOptions.drawStyle||{},doubleBuffer:!1}),this._options.drawStyle=this._$drawContainer.geographics("option","style"),this._$shapesContainer.geographics({style:this._initOptions.shapeStyle||{},doubleBuffer:!f}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style"),this._initOptions&&(this._initOptions.tilingScheme!==c&&this._setOption("tilingScheme",this._initOptions.tilingScheme||null,!1),this._initOptions.services&&(this._options.services=a.merge([],this._initOptions.services)),this._initOptions.bboxMax&&(this._setOption("bboxMax",this._initOptions.bboxMax,!1),this._setOption("bbox",this._initOptions.bboxMax,!1)),this._initOptions.zoomMin!==c&&this._setOption("zoomMin",this._initOptions.zoomMin,!1),this._initOptions.zoomMax!==c&&this._setOption("zoomMax",this._initOptions.zoomMax,!1),this._initOptions.zoomFactor!==c&&(this._setOption("zoomFactor",this._initOptions.zoomFactor,!1),this._fullZoomFactor=this._initOptions.zoomFactor,this._partialZoomFactor=Math.pow(4,1/this._fullZoomFactor)),this._initOptions.bbox&&this._setOption("bbox",this._initOptions.bbox,!1),this._initOptions.center&&this._setOption("center",this._initOptions.center,!1),this._initOptions.zoom!==c&&this._setOption("zoom",this._initOptions.zoom,!1)),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area),this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._createServices(),this._refresh(),this._created=!0},_setOption:function(b,d,e){if("pixelSize"!==b){e=e===c||e,this._$elem.is(".geo-map")&&this._panFinalize();var f,g,h,i;switch(b){case"bbox":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),f=[d[0]+(d[2]-d[0])/2,d[1]+(d[3]-d[1])/2],g=Math.max(a.geo.width(d,!0)/this._contentBounds.width,a.geo.height(d,!0)/this._contentBounds.height),i=this._getZoom(f,g),this._options.tilingScheme?g=this._getPixelSize(Math.min(Math.max(i,this._options.zoomMin),this._options.zoomMax)):ithis._options.zoomMax&&(g=this._getPixelSize(this._options.zoomMax)),this._created?(this._setInteractiveCenterAndSize(f,g),this._setInteractiveTimeout(!1)):this._setCenterAndSize(f,g,!1,e),d=this._getBbox(f,g);break;case"bboxMax":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d);break;case"center":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),this._created?(this._setInteractiveCenterAndSize(d,this._pixelSizeInteractive),this._interactiveTransform(),this._setInteractiveTimeout(!1)):this._setCenterAndSize(d,this._pixelSize,!1,e);break;case"measureLabels":d=a.extend(this._options.measureLabels,d),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area);break;case"drawStyle":this._$drawContainer&&(this._$drawContainer.geographics("option","style",d),d=this._$drawContainer.geographics("option","style"));break;case"shapeStyle":this._$elem.is(".geo-service")&&!this._createdGraphics&&this._createServiceGraphics(),this._createdGraphics&&(this._$shapesContainer.geographics("option","style",d),d=this._$shapesContainer.geographics("option","style"));break;case"mode":this._resetDrawing(),this._$eventTarget.css("cursor",this._options.cursors[d]);break;case"zoom":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj,this._created?this._setZoom(d,!1,e):(d=Math.max(d,0),this._setCenterAndSize(this._center,this._getPixelSize(d),!1,e))}switch(a.Widget.prototype._setOption.apply(this,arguments),b){case"bbox":case"center":this._userGeodetic&&(this._options.bbox=a.geo.proj.toGeodetic(this._options.bbox),this._options.center=a.geo.proj.toGeodetic(this._center));break;case"tilingScheme":null!==d&&(this._pixelSizeMax=this._getPixelSize(0),this._pixelSizeMin=this._getPixelSize(d.pixelSizes?d.pixelSizes.length-1:d.levels-1),this._centerMax=[d.origin[0]+this._pixelSizeMax*d.tileWidth/2,d.origin[1]+this._pixelSizeMax*d.tileHeight/2]);break;case"bboxMax":h=this._userGeodetic?a.geo.proj.fromGeodetic(d):d,this._centerMax=a.geo.center(h),this._pixelSizeMax=Math.max(a.geo.width(h,!0)/this._contentBounds.width,a.geo.height(h,!0)/this._contentBounds.height);break;case"services":this._createServices(),e&&(this._refresh(),this._refreshAllShapes());break;case"shapeStyle":e&&this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))}}},destroy:function(){if(this._$elem.is(".geo-service"))this._createdGraphics&&(this._$shapesContainer.geographics("destroy"),this._$shapesContainer=c,this._createdGraphics=!1);else{clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,this._created=!1,a(b).unbind("resize",this._windowHandler);for(var d=0;d=0||1>=b)for(var d=0;d0)){this._createdGraphics||this._createServiceGraphics();var d,e,f,g,h,i;for(d=a.isArray(b)?b:"FeatureCollection"===b.type?b.features:[b],f=1;f=0;g--)if(d=this._graphicShapes[g],h)if("Point"===d.shape.type)a.geo.distance(d.shape,b)<=i&&j.push(d.shape);else{var k=a.data(d.shape,"geoBbox"),l={type:"Polygon",coordinates:[[[k[0],k[1]],[k[0],k[3]],[k[2],k[3]],[k[2],k[1]],[k[0],k[1]]]]},m={type:"Point",coordinates:a.geo.proj&&a.geo._isGeodetic(b.coordinates)?a.geo.proj.fromGeodetic(b.coordinates):b.coordinates};if(a.geo.distance(l,m,!0)<=i)for(e=a.geo._basic(d.shape),f=0;f0)){for(var e,f=a.isArray(b)?b:[b],g=0;g=0&&(e=this._graphicShapes.slice(g+1),this._graphicShapes.length=g,this._graphicShapes.push.apply(this._graphicShapes,e),g--);(d===c||d)&&(this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh(),this._refreshAllShapes())}},_getBbox:function(a,b){a=a||this._center,b=b||this._pixelSize;var c=this._contentBounds.width/2*b,d=this._contentBounds.height/2*b;return[a[0]-c,a[1]-d,a[0]+c,a[1]+d]},_setBbox:function(b){var c=[b[0]+(b[2]-b[0])/2,b[1]+(b[3]-b[1])/2],d=Math.max(a.geo.width(b,!0)/this._contentBounds.width,a.geo.height(b,!0)/this._contentBounds.height),e=this._getZoom(c,d);this._options.tilingScheme?d=this._getPixelSize(Math.min(Math.max(e,this._options.zoomMin),this._options.zoomMax)):ethis._options.zoomMax&&(d=this._getPixelSize(this._options.zoomMax)),this._setInteractiveCenterAndSize(c,d),this._interactiveTransform()},_getBboxMax:function(){var a=this._contentBounds.width/2*this._pixelSizeMax,b=this._contentBounds.height/2*this._pixelSizeMax;return[this._centerMax[0]-a,this._centerMax[1]-b,this._centerMax[0]+a,this._centerMax[1]+b]},_getCenter:function(){return this._center},_getContentBounds:function(){return this._contentBounds},_getServicesContainer:function(){return this._$servicesContainer},_getZoom:function(b,c){b=b||this._center,c=c||this._pixelSize;var d=this._options.tilingScheme;if(d){if(d.pixelSizes){for(var e=Math.floor(1e3*c),f=d.pixelSizes.length,g=f-1;g>=0;g--)if(Math.floor(1e3*d.pixelSizes[g])>=e)return g;return 0}return Math.round(Math.log(d.basePixelSize/c)/Math.log(2))}var h=this._contentBounds.width/this._contentBounds.height,i=a.geo.reaspect(this._getBbox(b,c),h,!0),j=a.geo.reaspect(this._getBboxMax(),h,!0);return Math.round(Math.log(a.geo.width(j,!0)/a.geo.width(i,!0))/Math.log(this._fullZoomFactor))},_setZoom:function(a,b){this._clearInteractiveTimeout(),a=Math.min(Math.max(a,this._options.zoomMin),this._options.zoomMax),this._setInteractiveCenterAndSize(this._centerInteractive,this._getPixelSize(a)),this._interactiveTransform(),this._setInteractiveTimeout(b)},_createChildren:function(){this._$existingChildren=this._$elem.children(),this._forcePosition(this._$existingChildren),this._$existingChildren.detach().css({mozUserSelect:"none"});var c="width:"+this._contentBounds.width+"px; height:"+this._contentBounds.height+"px; margin:0; padding:0;",d="position:absolute; left:0; top:0;";this._$elem.prepend(b.toStaticHTML('
                  ')),this._$eventTarget=this._$contentFrame=this._$elem.children(":first"),this._$contentFrame.append('
                  '),this._$servicesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                    '),this._$attrList=this._$contentFrame.children(":last"),this._$contentFrame.append('
                    '),this._$drawContainer=this._$contentFrame.children(":last"), -this._$contentFrame.append('
                    '),this._$measureContainer=this._$contentFrame.children(":last"),this._$measureLabel=this._$measureContainer.children(),this._$contentFrame.append('
                    '),this._$shapesContainer=this._$contentFrame.children(":last"),this._$panContainer=a([this._$shapesContainer[0],this._$drawContainer[0],this._$measureContainer[0]]),this._$resizeContainer=a([this._$contentFrame[0],this._$servicesContainer[0],this._$eventTarget[0],this._$measureContainer[0]]),this._$contentFrame.append(this._$existingChildren),a("#geo-measure-style").length||a("head").prepend(b.toStaticHTML('"))},_createServices:function(){var c,d;for(d=0;d';this._$servicesContainer.append(b.toStaticHTML(h)),e=this._$servicesContainer.children(":last"),c.serviceContainer=e,a.geo._serviceTypes[c.type].create(this,e,c,d),e.data("geoMap",this).geomap(),c.attr&&this._$attrList.append("
                  • "+c.attr+"
                  • ")}this._$shapesContainers=this._$shapesContainer,this._$attrList.find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"})},_createServiceGraphics:function(){var a=this._$elem.closest(".geo-content-frame");this._$elem.append('
                    '),this._$shapesContainer=this._$elem.children(":last"),this._map._$shapesContainers=this._map._$shapesContainers.add(this._$shapesContainer),this._$shapesContainer.geographics({doubleBuffer:!f}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style")},_refreshDrawing:function(){if(this._$drawContainer.geographics("clear"),this._drawPixels.length>0){var b,c,d,e,f,g=this._options.mode,h=this._drawPixels,i=this._drawCoords;switch(g){case"measureLength":g="drawLineString",c={type:"LineString",coordinates:i},b=a.render[this._tmplLengthId]({length:a.geo.length(c,!0)}),d=a.merge([],h[h.length-1]);break;case"measureArea":g="drawPolygon",c={type:"Polygon",coordinates:[a.merge([],i)]},c.coordinates[0].push(i[0]),b=a.render[this._tmplAreaId]({area:a.geo.area(c,!0)}),d=this._toPixel(a.geo.centroid(c).coordinates),h=[h];break;case"drawPolygon":h=[h]}this._$drawContainer.geographics(g,h),b&&(this._$measureLabel.html(b),e=this._contentBounds.width-(this._$measureLabel.outerWidth(!0)+d[0]),f=this._contentBounds.height-(this._$measureLabel.outerHeight(!0)+d[1]),0>e&&(d[0]+=e),0>f&&(d[1]+=f),this._$measureLabel.css({left:Math.max(d[0],0),top:Math.max(d[1],0)}).show())}},_resetDrawing:function(){this._drawPixels=[],this._drawCoords=[],this._$drawContainer.geographics("clear"),this._$measureLabel.hide()},_refreshAllShapes:function(a){this._timeoutRefreshShapes=null;for(var b,c,d=0;d0&&c._refreshShapes(c._$shapesContainer,c._graphicShapes,c._graphicShapes,c._graphicShapes)));this._createdGraphics&&!a&&(this._$shapesContainer.geographics("clear"),this._graphicShapes.length>0&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))},_refreshShapes:function(b,d,e,f,g,h){var i,j,k,l,m,n,o,p,q,r=this._map._getBbox(g,h);for(i=0;i0&&a.height>0);)a={width:b.width(),height:b.height()},(a.width<=0||a.height<=0)&&(a={width:parseInt(b.css("width"),10),height:parseInt(b.css("height"),10)}),b=b.parent();return a},_forcePosition:function(a){var b=a.css("position");"relative"!==b&&"absolute"!==b&&"fixed"!==b&&a.css("position","relative")},_getPixelSize:function(b){var c=this._options.tilingScheme;if(null!==c){if(0===b)return c.pixelSizes?c.pixelSizes[0]:c.basePixelSize;b=Math.round(b),b=Math.max(b,0);var d=c.pixelSizes?c.pixelSizes.length:c.levels;return b=Math.min(b,d-1),c.pixelSizes?c.pixelSizes[b]:c.basePixelSize/Math.pow(2,b)}var e=a.geo.scaleBy(this._getBboxMax(),1/Math.pow(this._fullZoomFactor,b),!0);return Math.max(a.geo.width(e,!0)/this._contentBounds.width,a.geo.height(e,!0)/this._contentBounds.height)},_getZoomCenterAndSize:function(a,b,c){var d=c?this._fullZoomFactor:this._partialZoomFactor,e=Math.pow(d,-b),f=this._pixelSizeInteractive*e;this._options.tilingScheme&&(f=Math.min(Math.max(f,this._pixelSizeMin),this._pixelSizeMax));var g=this._getZoom(this._centerInteractive,f);c&&this._options.tilingScheme?f=this._getPixelSize(Math.min(Math.max(g,this._options.zoomMin),this._options.zoomMax)):0>b&&g0&&g>this._options.zoomMax&&(f=this._pixelSizeInteractive);var h=f/this._pixelSizeInteractive,i=this._toMap(a,this._centerInteractive,this._pixelSizeInteractive),j=[(this._centerInteractive[0]-i[0])*h,(this._centerInteractive[1]-i[1])*h],k=[i[0]+j[0],i[1]+j[1]];return{pixelSize:f,center:k}},_panFinalize:function(){this._panning&&(this._velocity=[0,0],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._inOp=!1,this._anchor=this._current,this._mouseDown=this._toolPan=this._panning=!1)},_panMove:function(){if(this._options.pannable){var a=this._current[0]-this._lastDrag[0],b=this._current[1]-this._lastDrag[1];(this._toolPan||a>3||-3>a||b>3||-3>b)&&(this._toolPan||(this._toolPan=!0,this._$eventTarget.css("cursor",this._options.cursors.pan)),this._mouseDown&&(this._velocity=[a,b]),(0!==a||0!==b)&&(this._panning=!0,this._lastDrag=this._current,this._centerInteractive[0]-=a*this._pixelSizeInteractive,this._centerInteractive[1]+=("image"===this._options.axisLayout?-1:1)*b*this._pixelSizeInteractive,this._setInteractiveCenterAndSize(this._centerInteractive,this._pixelSizeInteractive),this._interactiveTransform()))}},_clearInteractiveTimeout:function(){return this._timeoutRefreshShapes&&(clearTimeout(this._timeoutRefreshShapes),this._timeoutRefreshShapes=null),this._timeoutInteractive?(clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,!0):(this._centerInteractive[0]=this._center[0],this._centerInteractive[1]=this._center[1],this._pixelSizeInteractive=this._pixelSize,!1)},_interactiveTransform:function(){var b,c=this._pixelSize,d=c/this._pixelSizeInteractive;if(c>0){d=Math.round(1e3*d)/1e3;var e=this._toMap([0,0]),f=this._toPixel(e,this._centerInteractive,this._pixelSizeInteractive);this._$shapesContainers.geographics("interactiveTransform",f,d)}for(var g=0;g0&&(this._drawPixels=this._toPixel(this._drawCoords,this._centerInteractive,this._pixelSizeInteractive),this._refreshDrawing())},_interactiveTimeout:function(){this._isMultiTouch?this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128):this._created&&this._timeoutInteractive&&(this._setCenterAndSize(this._centerInteractive,this._pixelSizeInteractive,this._triggerInteractive,!0),this._timeoutInteractive=null,this._triggerInteractive=!1,this._timeoutRefreshShapes=setTimeout(a.proxy(this._refreshAllShapes,this),128))},_setInteractiveTimeout:function(b){this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128),this._triggerInteractive|=b},_refresh:function(b,c){for(var d,e=0;ethis._options.zoomMax&&(this._pixelSizeInteractive=d=this._getPixelSize(this._options.zoomMax)),this._centerInteractive[0]=c[0],this._centerInteractive[1]=c[1],this._created&&this._interactiveTransform(),this._options.pixelSize=this._pixelSize=d,this._center[0]=c[0],this._center[1]=c[1],this._userGeodetic?(this._options.bbox=a.geo.proj.toGeodetic(this._getBbox()),this._options.center=a.geo.proj.toGeodetic(this._center)):(this._options.bbox=this._getBbox(),this._options.center=a.merge([],c)),this._options.zoom=g,e&&this._trigger("bboxchange",b.event,{bbox:a.merge([],this._options.bbox)}),f&&(this._refresh(),this._refreshAllShapes(),this._refreshDrawing())}},_requestQueued:function(){0===this._loadCount&&this._trigger("loadstart",b.event),this._loadCount++},_requestComplete:function(){this._loadCount--,this._loadCount<=0&&(this._loadCount=0,this._trigger("loadend",b.event))},_toMap:function(b,c,d){c=c||this._center,d=d||this._pixelSize;var e,f,g,h,i=a.isArray(b[0]),j=i&&a.isArray(b[0][0]),k=j&&a.isArray(b[0][0][0]),l=this._contentBounds.width,m=this._contentBounds.height,n=l/2*d,o=m/2*d,p=[c[0]-n,c[1]-o,c[0]+n,c[1]+o],q=a.geo.width(p,!0)/l,r=a.geo.height(p,!0)/m,s="image"===this._options.axisLayout,t=[];for(k||(j||(i||(b=[b]),b=[b]),b=[b]),f=0;f0&&27===b.which&&(2>=c?(this._resetDrawing(),this._inOp=!1):(this._drawCoords[c-2]=a.merge([],this._drawCoords[c-1]),this._drawPixels[c-2]=a.merge([],this._drawPixels[c-1]),this._drawCoords.length--,this._drawPixels.length--,this._refreshDrawing()))},_eventTarget_dblclick_zoom:function(a){var b=this._clearInteractiveTimeout();if(this._trigger("dblclick",a,{type:"Point",coordinates:this._toMap(this._current,this._centerInteractive,this._pixelSizeInteractive)}),!a.isDefaultPrevented()){var c=this._getZoomCenterAndSize(this._current,1,!0);this._setInteractiveCenterAndSize(c.center,c.pixelSize),this._interactiveTransform(),b=!0}b&&this._setInteractiveTimeout(!0)},_eventTarget_dblclick:function(c){if("static"!==this._options.mode){switch(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),this._options.mode){case"drawLineString":case"measureLength":this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])?(this._drawCoords.length--,this._trigger("shape",c,{type:"LineString",coordinates:this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords})):this._eventTarget_dblclick_zoom(c),this._resetDrawing();break;case"drawPolygon":case"measureArea":if(this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])){var d=this._drawCoords.length-1;d>2&&(this._drawCoords[d]=a.merge([],this._drawCoords[0]),this._trigger("shape",c,{type:"Polygon",coordinates:[this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords]}))}else this._eventTarget_dblclick_zoom(c);this._resetDrawing();break;default:this._eventTarget_dblclick_zoom(c)}this._inOp=!1}},_eventTarget_touchstart:function(b){if("undefined"!=typeof document.elementFromPoint){var c=document.elementFromPoint(b.pageX,b.pageY);if(c&&"A"===c.nodeName)return}var d=this._options.mode,e=this._options.shift,f="dragBox"===d?"dragBox":"zoom";if("static"!==d&&(this._pointerEvents||this._supportTouch||1===b.which)){var g=this._clearInteractiveTimeout(),h=a(b.currentTarget).offset(),i=b.originalEvent.changedTouches;if(this._pointerEvents){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0)return b.currentTarget.setPointerCapture(b.originalEvent.pointerId),this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-h.left,this._multiTouchAnchor[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=a.geo.center(this._multiTouchCurrentBbox,!0),this._current=a.merge([],this._anchor),g&&this._setInteractiveTimeout(!0),!1;this._multiTouchAnchor.length<2&&(b.currentTarget.setPointerCapture(b.originalEvent.pointerId),this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top,NaN,NaN],this._current=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top])}else this._supportTouch&&i?(this._multiTouchAnchor=a.merge([],i),this._isMultiTouch=this._multiTouchAnchor.length>1,this._isMultiTouch?(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,i[1].pageX-h.left,i[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._current=a.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,NaN,NaN],this._current=[i[0].pageX-h.left,i[0].pageY-h.top])):this._current=[b.pageX-h.left,b.pageY-h.top];if(this._softDblClick){var j=a.now();if(j-this._downDate<750){if(this._isTap){var k=this._current[0]-this._anchor[0],l=this._current[1]-this._anchor[1],m=Math.sqrt(k*k+l*l);m>8?this._isTap=!1:this._current=a.merge([],this._anchor)}this._isDbltap?this._isDbltap=!1:this._isDbltap=this._isTap}else this._isDbltap=!1;this._isTap=!0,this._downDate=j}return this._mouseDown=!0,this._anchor=a.merge([],this._current),!this._inOp&&b.shiftKey&&"off"!==e?(this._shiftDown=!0,this._$eventTarget.css("cursor",this._options.cursors["default"===e?f:e])):this._isMultiTouch||!this._options.pannable&&"dragBox"!==d&&"dragCircle"!==d||(this._inOp=!0,"zoom"!==d&&"dragBox"!==d&&"dragCircle"!==d&&(this._lastDrag=this._current,b.currentTarget.setCapture&&b.currentTarget.setCapture())),b.preventDefault(),g&&this._setInteractiveTimeout(!0),!1}},_dragTarget_touchmove:function(b){if("static"!==this._options.mode){var c=!1;this._mouseDown&&(c=this._clearInteractiveTimeout());var d,f,g,h,i,j,k=this._$eventTarget.offset(),l=this._drawCoords.length,m=b.originalEvent.changedTouches,n=null;if(this._pointerEvents)if(this._isMultiTouch){if(b.originalEvent.pointerId===this._multiTouchAnchor[0].pointerId)this._multiTouchCurrentBbox[0]=b.originalEvent.pageX-k.left,this._multiTouchCurrentBbox[1]=b.originalEvent.pageY-k.top;else{if(b.originalEvent.pointerId!==this._multiTouchAnchor[1].pointerId)return b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1;this._multiTouchCurrentBbox[2]=b.originalEvent.pageX-k.left,this._multiTouchCurrentBbox[3]=b.originalEvent.pageY-k.top}d=a.geo._distancePointPoint([this._multiTouchAnchorBbox[0],this._multiTouchAnchorBbox[1]],[this._multiTouchAnchorBbox[2],this._multiTouchAnchorBbox[3]]),f=a.geo._distancePointPoint([this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1]],[this._multiTouchCurrentBbox[2],this._multiTouchCurrentBbox[3]]),g=(f-d)/d,g*=g>0?5:10,h=g-this._wheelLevel,this._wheelLevel=g,i=this._getZoomCenterAndSize(this._anchor,h,!1),this._setInteractiveCenterAndSize(i.center,i.pixelSize),this._interactiveTransform(),c=!0,n=a.geo.center(this._multiTouchCurrentBbox,!0)}else this._multiTouchAnchor[0]=b.originalEvent,this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-k.left,this._multiTouchAnchor[0].pageY-k.top,NaN,NaN],n=[b.originalEvent.pageX-k.left,b.originalEvent.pageY-k.top];else if(this._supportTouch&&m){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&m[0].identifier!==this._multiTouchAnchor[0].identifier)return this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(m[0]),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-k.left,this._multiTouchAnchor[1].pageY-k.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=this._current=a.geo.center(this._multiTouchCurrentBbox,!0),c&&this._setInteractiveTimeout(!0),!1;if(this._isMultiTouch){for(j=0;j0?5:10,h=g-this._wheelLevel,this._wheelLevel=g,i=this._getZoomCenterAndSize(this._anchor,h,!1),this._setInteractiveCenterAndSize(i.center,i.pixelSize),this._interactiveTransform(),c=!0,n=a.geo.center(this._multiTouchCurrentBbox,!0)}else n=[b.originalEvent.changedTouches[0].pageX-k.left,b.originalEvent.changedTouches[0].pageY-k.top]}else n=[b.pageX-k.left,b.pageY-k.top];if(null===n)return b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1;if(n[0]===this._lastMove[0]&&n[1]===this._lastMove[1])return this._inOp?(b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1):!1;if(7===e&&(this._isDbltap=this._isTap=!1),this._mouseDown&&(this._current=n,this._moveDate=a.now()),this._isMultiTouch)return b.preventDefault(),this._isDbltap=this._isTap=!1,c&&this._setInteractiveTimeout(!0),!1;var o,p,q,r=this._options.mode,s=this._options.shift,t="dragBox"===r?"dragBox":"zoom";switch(this._shiftDown&&(r="default"===s?t:s),r){case"zoom":case"dragBox":this._mouseDown?(this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawBbox",[this._anchor[0],this._anchor[1],n[0],n[1]])):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)});break;case"dragCircle":this._mouseDown?(o=n[0]-this._anchor[0],p=n[1]-this._anchor[1],q=2*Math.sqrt(o*o+p*p),this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawArc",this._anchor,0,360,{width:q,height:q})):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)});break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":this._mouseDown||this._toolPan?(this._panMove(),c=!0):(l>0&&(this._drawCoords[l-1]=this._toMap(n,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[l-1]=n,this._refreshDrawing()),this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)}));break;default:this._mouseDown||this._toolPan?(this._panMove(),c=!0):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)})}return this._lastMove=n,c&&this._setInteractiveTimeout(!0),this._inOp?(b.preventDefault(),!1):void 0}},_dragTarget_touchstop:function(c){if("static"!==this._options.mode){if(!this._mouseDown){if(7!==e)return;this._eventTarget_touchstart(c)}var d,f,g,h,i,j,k=this._clearInteractiveTimeout(),l=this._mouseDown,m=this._toolPan,n=this._$eventTarget.offset(),o=this._options.mode,p=this._options.shift,q="dragBox"===o?"dragBox":"zoom",r=null;if(this._shiftDown&&(o="default"===p?q:p),this._pointerEvents){if(c.originalEvent.pointerId!==this._multiTouchAnchor[0].pointerId&&c.originalEvent.pointerId!==this._multiTouchAnchor[1].pointerId)return c.preventDefault(),void(k&&this._setInteractiveTimeout(!0));c.currentTarget.releasePointerCapture(c.originalEvent.pointerId),r=[c.originalEvent.pageX-n.left,c.originalEvent.pageY-n.top],this._multiTouchAnchor=[],this._inOp=!1}else this._supportTouch&&c.originalEvent.changedTouches?(r=[c.originalEvent.changedTouches[0].pageX-n.left,c.originalEvent.changedTouches[0].pageY-n.top],this._multiTouchAnchor=[],this._inOp=!1):r=[c.pageX-n.left,c.pageY-n.top];if(this._softDblClick&&this._isTap&&(g=r[0]-this._anchor[0],h=r[1]-this._anchor[1],Math.sqrt(g*g+h*h)<=8&&(r=a.merge([],this._anchor))),g=r[0]-this._anchor[0],h=r[1]-this._anchor[1],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._shiftDown=this._mouseDown=this._toolPan=!1,this._isMultiTouch)return c.preventDefault(),this._isMultiTouch=!1,this._wheelLevel=0,void(k&&this._setInteractiveTimeout(!0));if(document.releaseCapture&&document.releaseCapture(),l){switch(f=a.now(),this._current=r,o){case"zoom":case"dragBox":if(0!==g||0!==h){var s=6*this._pixelSize,t=this._toMap([this._anchor,r]),u=[Math.min(t[0][0],t[1][0]),Math.min(t[0][1],t[1][1]),Math.max(t[0][0],t[1][0]),Math.max(t[0][1],t[1][1])];"zoom"===o?(u[2]-u[0]d;d++)v=360*d/y*(Math.PI/180),this._drawPixels[d]=[this._anchor[0]+Math.cos(v)*x,this._anchor[1]+Math.sin(v)*x];this._drawPixels[y]=[this._drawPixels[0][0],this._drawPixels[0][1]],i=this._toMap([[this._anchor[0]-x,this._anchor[1]+(w?-x:x)],[this._anchor[0]+x,this._anchor[1]+(w?x:-x)]]),j={type:"Polygon",coordinates:[this._toMap(this._drawPixels)],bbox:[i[0][0],i[0][1],i[1][0],i[1][1]]},this._userGeodetic&&(j.coordinates=a.geo.proj.toGeodetic(j.coordinates),j.bbox=a.geo.proj.toGeodetic(j.bbox)),this._trigger("shape",c,j),this._resetDrawing()}else i=this._toMap(r),j={type:"Point",coordinates:[i[0],i[1]],bbox:[i[0],i[1],i[0],i[1]]},this._userGeodetic&&(j.coordinates=a.geo.proj.toGeodetic(j.coordinates),j.bbox=a.geo.proj.toGeodetic(j.bbox)),this._trigger("shape",c,j);break;case"drawPoint":if(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),m)this._panFinalize();else if(f-this._clickDate>100){var z=this;this._drawTimeout=setTimeout(function(){z._drawTimeout&&(z._trigger("shape",c,{type:"Point",coordinates:z.toMap(r)}),z._inOp=!1,z._drawTimeout=null)},250)}break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":m?this._panFinalize():(this._trigger("click",c,{type:"Point",coordinates:this.toMap(r)}),c.isDefaultPrevented()||(d=0===this._drawCoords.length?0:this._drawCoords.length-1,this._drawCoords[d]=this._toMap(r),this._drawPixels[d]=r,(2>d||this._drawCoords[d][0]!==this._drawCoords[d-1][0]||this._drawCoords[d][1]!==this._drawCoords[d-1][1])&&(this._drawCoords[d+1]=this._toMap(r,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[d+1]=r),this._refreshDrawing()));break;default:m?this._panFinalize():f-this._clickDate>100&&(this._trigger("click",c,{type:"Point",coordinates:this.toMap(r)}),this._inOp=!1)}if(this._clickDate=f,this._softDblClick&&this._isDbltap)return this._isDbltap=this._isTap=!1,k&&this._setInteractiveTimeout(!0),this._$eventTarget.trigger("softdblclick",c),!1}return k&&this._setInteractiveTimeout(!0),this._inOp?(c.preventDefault(),!1):void 0}},_eventTarget_mousewheel:function(b){if("static"!==this._options.mode&&"off"!==this._options.scroll){if(b.preventDefault(),this._mouseDown)return!1;if(0!==b.deltaY){this._timeoutWheel&&(clearTimeout(this._timeoutWheel),this._timeoutWheel=null);var c=this,d=b.currentTarget,e=b.deltaY,f=b.pageX,g=b.pageY;this._timeoutWheel=setTimeout(function(){c._clearInteractiveTimeout();var b=e>0?1:-1,h=a(d).offset();c._anchor=[f-h.left,g-h.top];var i=c._getZoomCenterAndSize(c._anchor,b,null!==c._options.tilingScheme);c._setInteractiveCenterAndSize(i.center,i.pixelSize),c._interactiveTransform(),c._setInteractiveTimeout(!0)},30)}return!1}}})}(jQuery,window),function(a,b,c){a.geo._serviceTypes.tiled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0,reloadTiles:!1};var g='
                    ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b.options.tilingScheme;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),h=f/e;if(f>0){h=Math.round(1e3*h)/1e3;var i=c.data("scaleOrigin"),j=b._toPixel(i,d,e);c.css({left:Math.round(j[0])+"px",top:Math.round(j[1])+"px",width:g.tileWidth*h,height:g.tileHeight*h})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&f&&(g.reloadTiles=!0),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i,j=d._getBbox(),k=d._pixelSize,l=this,m=g.serviceContainer,n="image"===d.options.axisLayout,o=n?1:-1,p=d.options.tilingScheme,q=p.tileWidth,r=p.tileHeight,s=Math.floor((j[0]-p.origin[0])/(k*q)),t=Math.max(Math.floor((n?j[1]-p.origin[1]:p.origin[1]-j[3])/(k*r)),0),u=Math.ceil((j[2]-p.origin[0])/(k*q)),v=Math.ceil((n?j[3]-p.origin[1]:p.origin[1]-j[1])/(k*r)),w=d._getBboxMax(),x=d._getPixelSize(0),y=x/k,z=Math.floor((w[0]-p.origin[0])/(x*q))*y,A=Math.floor((p.origin[1]+o*w[3])/(x*r))*y,B=p.origin[0]+z*q*k,C=p.origin[1]+o*(A*r)*k,D=Math.round((B-j[0])/k),E=Math.round((n?C-j[1]:j[3]-C)/k),F=m.children().show(),G=F.filter("[data-pixel-size='"+k+"']").appendTo(m),H=e.style.opacity,I=function(a){l._loadImage(this.img,a,k,d,g,H)},J=function(){delete this.img,g.loadCount--,d._requestComplete()};for(g.reloadTiles&&F.find("img").attr("data-dirty","true"),G.size()?(G.css({left:D%q+"px",top:E%r+"px"}).data("scaleOrigin",d._toMap([D%q,E%r])),G.children().each(function(){var b=a(this),c=b.attr("data-tile").split(",");b.css({left:Math.round(100*(parseInt(c[0],10)-z)+(D-D%q)/q*100)+"%",top:Math.round(100*(parseInt(c[1],10)-A)+(E-E%r)/r*100)+"%"}),1>H&&b.fadeTo(0,H)})):(m.append(b.toStaticHTML("
                    ")),G=m.children(":last").data("scaleOrigin",d._toMap([D%q,E%r]))),h=s;u>h;h++)for(i=t;v>i;i++){var K=""+h+","+i,L=G.children("[data-tile='"+K+"']").removeAttr("data-dirty");if(0===L.size()||g.reloadTiles){var M,N=[p.origin[0]+h*q*k,p.origin[1]+o*(i*r)*k],O=[p.origin[0]+((h+1)*q-1)*k,p.origin[1]+o*((i+1)*r-1)*k],P=[N[0],N[1],O[0],O[1]],Q={bbox:P,width:q,height:r,zoom:d._getZoom(),tile:{row:i,column:h},index:Math.abs(i+h)},R=a.isFunction(e.src);if(R?M=e.src(Q):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),M=a.render[this._tmplGeoSrcId](Q)):M=e.src,g.loadCount++,d._requestQueued(),g.reloadTiles&&L.size()>0)L.attr("src",M);else{var S="",G.append(b.toStaticHTML(S)),L=G.children(":last")}"string"==typeof M?l._loadImage(L,M,k,d,g,H):M&&a.isFunction(M.promise)?(a.extend(M.promise(),{img:L}),M.done(I).fail(J)):L.remove()}}F.find("[data-dirty]").remove(),g.reloadTiles=!1}},resize:function(){},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--, -b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){1>g?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).error(function(b){a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).attr("src",c)}}}()}(jQuery,window),function(a,b,c){a.geo._serviceTypes.shingled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0};var g='
                    ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b._getContentBounds(),h=g.width,i=g.height;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),g=f/e;if(f>0){g=Math.round(1e3*g)/1e3;var j=c.data("origin"),k=b._toPixel(j,d,e);c.css({left:Math.round(k[0]),top:Math.round(k[1]),width:h*g,height:i*g})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i=d._getBbox(),j=d._pixelSize,k=this,l=g.serviceContainer,m=d._getContentBounds(),n=m.width,o=m.height,p=l.children('[data-pixel-size="'+j+'"]'),q=e.style.opacity;1>q||f||1===e.shinglesMax?l.find("img").attr("data-keep-alive","0"):e.shinglesMax>1&&l.find("img").slice(0,-(e.shinglesMax-1)).attr("data-keep-alive","0"),p.size()||(l.append(b.toStaticHTML('
                    ')),p=l.children(":last"));var r,s={bbox:i,width:n,height:o,zoom:d._getZoom(),tile:null,index:0},t=a.isFunction(e.src),u=p.position();u.left=-u.left,u.top=-u.top,t?r=e.src(s):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),r=a.render[this._tmplGeoSrcId](s)):r=e.src,g.loadCount++,d._requestQueued(),p.append(b.toStaticHTML('')),h=p.children(":last").data("center",d._center),"string"==typeof r?k._loadImage(h,r,j,d,g,q):r&&r.done(function(a){k._loadImage(h,a,j,d,g,q)}).fail(function(){h.remove(),g.loadCount--,d._requestComplete()})}},resize:function(b,c){var d=a.data(c,"geoServiceState");if(d&&c&&"visible"===c.style.visibility){this._cancelUnloaded(b,c);var e=d.serviceContainer,f=b._getContentBounds(),g=f.width,h=f.height,i=e.children();i.attr("data-pixel-size","0"),i.each(function(){var b=a(this),c=b.position();b.css({left:c.left+(g-b.width())/2,top:c.top+(h-b.height())/2})})}},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--,b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(1>g?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(':not([data-pixel-size="'+d+'"])').remove(),h.find("img[data-keep-alive]").remove(),f.loadCount=0))}).error(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0))}).attr("src",c)}}}()}(jQuery,window); \ No newline at end of file diff --git a/dist/jquery.geo-1.0.0-rc1.js b/dist/jquery.geo-1.0.0-rc1.js deleted file mode 100644 index e3a238b..0000000 --- a/dist/jquery.geo-1.0.0-rc1.js +++ /dev/null @@ -1,7522 +0,0 @@ -/*! jQuery Geo - v1.0.0-rc1 - 2016-06-05 -* http://jquerygeo.com -* Copyright (c) 2016 Ryan Morrison-Westphal; Licensed MIT */ -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -// Known Issues: -// -// * Patterns only support repeat. -// * Radial gradient are not implemented. The VML version of these look very -// different from the canvas one. -// * Clipping paths are not implemented. -// * Coordsize. The width and height attribute have higher priority than the -// width and height style values which isn't correct. -// * Painting mode isn't implemented. -// * Canvas width/height should is using content-box by default. IE in -// Quirks mode will draw the canvas using border-box. Either change your -// doctype to HTML5 -// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) -// or use Box Sizing Behavior from WebFX -// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) -// * Non uniform scaling does not correctly scale strokes. -// * Optimize. There is always room for speed improvements. - -// Only add this code if we do not already have a canvas implementation -if (!document.createElement('canvas').getContext) { - - (function () { - - // alias some functions to make (compiled) code shorter - var m = Math; - var mr = m.round; - var ms = m.sin; - var mc = m.cos; - var abs = m.abs; - var sqrt = m.sqrt; - - // this is used for sub pixel precision - var Z = 10; - var Z2 = Z / 2; - - var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; - - /** - * This funtion is assigned to the elements as element.getContext(). - * @this {HTMLElement} - * @return {CanvasRenderingContext2D_} - */ - function getContext() { - return this.context_ || - (this.context_ = new CanvasRenderingContext2D_(this)); - } - - var slice = Array.prototype.slice; - - /** - * Binds a function to an object. The returned function will always use the - * passed in {@code obj} as {@code this}. - * - * Example: - * - * g = bind(f, obj, a, b) - * g(c, d) // will do f.call(obj, a, b, c, d) - * - * @param {Function} f The function to bind the object to - * @param {Object} obj The object that should act as this when the function - * is called - * @param {*} var_args Rest arguments that will be used as the initial - * arguments when the function is called - * @return {Function} A new function that has bound this - */ - function bind(f, obj, var_args) { - var a = slice.call(arguments, 2); - return function () { - return f.apply(obj, a.concat(slice.call(arguments))); - }; - } - - function encodeHtmlAttribute(s) { - return String(s).replace(/&/g, '&').replace(/"/g, '"'); - } - - function addNamespace(doc, prefix, urn) { - if (!doc.namespaces[prefix]) { - doc.namespaces.add(prefix, urn, '#default#VML'); - } - } - - function addNamespacesAndStylesheet(doc) { - addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); - addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); - - // Setup default CSS. Only add one style sheet per document - if (!doc.styleSheets['ex_canvas_']) { - var ss = doc.createStyleSheet(); - ss.owningElement.id = 'ex_canvas_'; - ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + - // default size is 300x150 in Gecko and Opera - 'text-align:left;width:300px;height:150px}'; - } - } - - // Add namespaces and stylesheet at startup. - addNamespacesAndStylesheet(document); - - var G_vmlCanvasManager_ = { - init: function (opt_doc) { - var doc = opt_doc || document; - // Create a dummy element so that IE will allow canvas elements to be - // recognized. - doc.createElement('canvas'); - doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); - }, - - init_: function (doc) { - // find all canvas elements - var els = doc.getElementsByTagName('canvas'); - for (var i = 0; i < els.length; i++) { - this.initElement(els[i]); - } - }, - - /** - * Public initializes a canvas element so that it can be used as canvas - * element from now on. This is called automatically before the page is - * loaded but if you are creating elements using createElement you need to - * make sure this is called on the element. - * @param {HTMLElement} el The canvas element to initialize. - * @return {HTMLElement} the element that was created. - */ - initElement: function (el) { - if (!el.getContext) { - el.getContext = getContext; - - // Add namespaces and stylesheet to document of the element. - addNamespacesAndStylesheet(el.ownerDocument); - - // Remove fallback content. There is no way to hide text nodes so we - // just remove all childNodes. We could hide all elements and remove - // text nodes but who really cares about the fallback content. - el.innerHTML = ''; - - // do not use inline function because that will leak memory - el.attachEvent('onpropertychange', onPropertyChange); - el.attachEvent('onresize', onResize); - - var attrs = el.attributes; - if (attrs.width && attrs.width.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setWidth_(attrs.width.nodeValue); - el.style.width = attrs.width.nodeValue + 'px'; - } else { - el.width = el.clientWidth; - } - if (attrs.height && attrs.height.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setHeight_(attrs.height.nodeValue); - el.style.height = attrs.height.nodeValue + 'px'; - } else { - el.height = el.clientHeight; - } - //el.getContext().setCoordsize_() - } - return el; - } - }; - - function onPropertyChange(e) { - var el = e.srcElement; - - switch (e.propertyName) { - case 'width': - el.getContext().clearRect(); - el.style.width = el.attributes.width.nodeValue + 'px'; - // In IE8 this does not trigger onresize. - el.firstChild.style.width = el.clientWidth + 'px'; - break; - case 'height': - el.getContext().clearRect(); - el.style.height = el.attributes.height.nodeValue + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - break; - } - } - - function onResize(e) { - var el = e.srcElement; - if (el.firstChild) { - el.firstChild.style.width = el.clientWidth + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - } - } - - G_vmlCanvasManager_.init(); - - // precompute "00" to "FF" - var decToHex = []; - for (var i = 0; i < 16; i++) { - for (var j = 0; j < 16; j++) { - decToHex[i * 16 + j] = i.toString(16) + j.toString(16); - } - } - - function createMatrixIdentity() { - return [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1] - ]; - } - - function matrixMultiply(m1, m2) { - var result = createMatrixIdentity(); - - for (var x = 0; x < 3; x++) { - for (var y = 0; y < 3; y++) { - var sum = 0; - - for (var z = 0; z < 3; z++) { - sum += m1[x][z] * m2[z][y]; - } - - result[x][y] = sum; - } - } - return result; - } - - function copyState(o1, o2) { - o2.fillStyle = o1.fillStyle; - o2.lineCap = o1.lineCap; - o2.lineJoin = o1.lineJoin; - o2.lineWidth = o1.lineWidth; - o2.miterLimit = o1.miterLimit; - o2.shadowBlur = o1.shadowBlur; - o2.shadowColor = o1.shadowColor; - o2.shadowOffsetX = o1.shadowOffsetX; - o2.shadowOffsetY = o1.shadowOffsetY; - o2.strokeStyle = o1.strokeStyle; - o2.globalAlpha = o1.globalAlpha; - o2.font = o1.font; - o2.textAlign = o1.textAlign; - o2.textBaseline = o1.textBaseline; - o2.arcScaleX_ = o1.arcScaleX_; - o2.arcScaleY_ = o1.arcScaleY_; - o2.lineScale_ = o1.lineScale_; - } - - // var colorData = { - // aliceblue: '#F0F8FF', - // antiquewhite: '#FAEBD7', - // aquamarine: '#7FFFD4', - // azure: '#F0FFFF', - // beige: '#F5F5DC', - // bisque: '#FFE4C4', - // black: '#000000', - // blanchedalmond: '#FFEBCD', - // blueviolet: '#8A2BE2', - // brown: '#A52A2A', - // burlywood: '#DEB887', - // cadetblue: '#5F9EA0', - // chartreuse: '#7FFF00', - // chocolate: '#D2691E', - // coral: '#FF7F50', - // cornflowerblue: '#6495ED', - // cornsilk: '#FFF8DC', - // crimson: '#DC143C', - // cyan: '#00FFFF', - // darkblue: '#00008B', - // darkcyan: '#008B8B', - // darkgoldenrod: '#B8860B', - // darkgray: '#A9A9A9', - // darkgreen: '#006400', - // darkgrey: '#A9A9A9', - // darkkhaki: '#BDB76B', - // darkmagenta: '#8B008B', - // darkolivegreen: '#556B2F', - // darkorange: '#FF8C00', - // darkorchid: '#9932CC', - // darkred: '#8B0000', - // darksalmon: '#E9967A', - // darkseagreen: '#8FBC8F', - // darkslateblue: '#483D8B', - // darkslategray: '#2F4F4F', - // darkslategrey: '#2F4F4F', - // darkturquoise: '#00CED1', - // darkviolet: '#9400D3', - // deeppink: '#FF1493', - // deepskyblue: '#00BFFF', - // dimgray: '#696969', - // dimgrey: '#696969', - // dodgerblue: '#1E90FF', - // firebrick: '#B22222', - // floralwhite: '#FFFAF0', - // forestgreen: '#228B22', - // gainsboro: '#DCDCDC', - // ghostwhite: '#F8F8FF', - // gold: '#FFD700', - // goldenrod: '#DAA520', - // grey: '#808080', - // greenyellow: '#ADFF2F', - // honeydew: '#F0FFF0', - // hotpink: '#FF69B4', - // indianred: '#CD5C5C', - // indigo: '#4B0082', - // ivory: '#FFFFF0', - // khaki: '#F0E68C', - // lavender: '#E6E6FA', - // lavenderblush: '#FFF0F5', - // lawngreen: '#7CFC00', - // lemonchiffon: '#FFFACD', - // lightblue: '#ADD8E6', - // lightcoral: '#F08080', - // lightcyan: '#E0FFFF', - // lightgoldenrodyellow: '#FAFAD2', - // lightgreen: '#90EE90', - // lightgrey: '#D3D3D3', - // lightpink: '#FFB6C1', - // lightsalmon: '#FFA07A', - // lightseagreen: '#20B2AA', - // lightskyblue: '#87CEFA', - // lightslategray: '#778899', - // lightslategrey: '#778899', - // lightsteelblue: '#B0C4DE', - // lightyellow: '#FFFFE0', - // limegreen: '#32CD32', - // linen: '#FAF0E6', - // magenta: '#FF00FF', - // mediumaquamarine: '#66CDAA', - // mediumblue: '#0000CD', - // mediumorchid: '#BA55D3', - // mediumpurple: '#9370DB', - // mediumseagreen: '#3CB371', - // mediumslateblue: '#7B68EE', - // mediumspringgreen: '#00FA9A', - // mediumturquoise: '#48D1CC', - // mediumvioletred: '#C71585', - // midnightblue: '#191970', - // mintcream: '#F5FFFA', - // mistyrose: '#FFE4E1', - // moccasin: '#FFE4B5', - // navajowhite: '#FFDEAD', - // oldlace: '#FDF5E6', - // olivedrab: '#6B8E23', - // orange: '#FFA500', - // orangered: '#FF4500', - // orchid: '#DA70D6', - // palegoldenrod: '#EEE8AA', - // palegreen: '#98FB98', - // paleturquoise: '#AFEEEE', - // palevioletred: '#DB7093', - // papayawhip: '#FFEFD5', - // peachpuff: '#FFDAB9', - // peru: '#CD853F', - // pink: '#FFC0CB', - // plum: '#DDA0DD', - // powderblue: '#B0E0E6', - // rosybrown: '#BC8F8F', - // royalblue: '#4169E1', - // saddlebrown: '#8B4513', - // salmon: '#FA8072', - // sandybrown: '#F4A460', - // seagreen: '#2E8B57', - // seashell: '#FFF5EE', - // sienna: '#A0522D', - // skyblue: '#87CEEB', - // slateblue: '#6A5ACD', - // slategray: '#708090', - // slategrey: '#708090', - // snow: '#FFFAFA', - // springgreen: '#00FF7F', - // steelblue: '#4682B4', - // tan: '#D2B48C', - // thistle: '#D8BFD8', - // tomato: '#FF6347', - // turquoise: '#40E0D0', - // violet: '#EE82EE', - // wheat: '#F5DEB3', - // whitesmoke: '#F5F5F5', - // yellowgreen: '#9ACD32' - // }; - - - function getRgbHslContent(styleString) { - var start = styleString.indexOf('(', 3); - var end = styleString.indexOf(')', start + 1); - var parts = styleString.substring(start + 1, end).split(','); - // add alpha if needed - if (parts.length != 4 || styleString.charAt(3) != 'a') { - parts[3] = 1; - } - return parts; - } - - function percent(s) { - return parseFloat(s) / 100; - } - - function clamp(v, min, max) { - return Math.min(max, Math.max(min, v)); - } - - function hslToRgb(parts) { - var r, g, b, h, s, l; - h = parseFloat(parts[0]) / 360 % 360; - if (h < 0) - h++; - s = clamp(percent(parts[1]), 0, 1); - l = clamp(percent(parts[2]), 0, 1); - if (s == 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1 / 3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1 / 3); - } - - return '#' + decToHex[Math.floor(r * 255)] + - decToHex[Math.floor(g * 255)] + - decToHex[Math.floor(b * 255)]; - } - - function hueToRgb(m1, m2, h) { - if (h < 0) - h++; - if (h > 1) - h--; - - if (6 * h < 1) - return m1 + (m2 - m1) * 6 * h; - else if (2 * h < 1) - return m2; - else if (3 * h < 2) - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - else - return m1; - } - - var processStyleCache = {}; - - function processStyle(styleString) { - if (styleString in processStyleCache) { - return processStyleCache[styleString]; - } - - var str, alpha = 1; - - styleString = String(styleString); - if (styleString.charAt(0) == '#') { - str = styleString; - } else if (/^rgb/.test(styleString)) { - var parts = getRgbHslContent(styleString); - var str = '#', n; - for (var i = 0; i < 3; i++) { - if (parts[i].indexOf('%') != -1) { - n = Math.floor(percent(parts[i]) * 255); - } else { - n = +parts[i]; - } - str += decToHex[clamp(n, 0, 255)]; - } - alpha = +parts[3]; - } else if (/^hsl/.test(styleString)) { - var parts = getRgbHslContent(styleString); - str = hslToRgb(parts); - alpha = parts[3]; - } else { - str = /*colorData[styleString] ||*/styleString; - } - return processStyleCache[styleString] = { color: str, alpha: alpha }; - } - - var DEFAULT_STYLE = { - style: 'normal', - variant: 'normal', - weight: 'normal', - size: 10, - family: 'sans-serif' - }; - - // Internal text style cache - // var fontStyleCache = {}; - - // function processFontStyle(styleString) { - // if (fontStyleCache[styleString]) { - // return fontStyleCache[styleString]; - // } - - // var el = document.createElement('div'); - // var style = el.style; - // try { - // style.font = styleString; - // } catch (ex) { - // // Ignore failures to set to invalid font. - // } - - // return fontStyleCache[styleString] = { - // style: style.fontStyle || DEFAULT_STYLE.style, - // variant: style.fontVariant || DEFAULT_STYLE.variant, - // weight: style.fontWeight || DEFAULT_STYLE.weight, - // size: style.fontSize || DEFAULT_STYLE.size, - // family: style.fontFamily || DEFAULT_STYLE.family - // }; - // } - - // function getComputedStyle(style, element) { - // var computedStyle = {}; - - // for (var p in style) { - // computedStyle[p] = style[p]; - // } - - // // Compute the size - // var canvasFontSize = parseFloat(element.currentStyle.fontSize), - // fontSize = parseFloat(style.size); - - // if (typeof style.size == 'number') { - // computedStyle.size = style.size; - // } else if (style.size.indexOf('px') != -1) { - // computedStyle.size = fontSize; - // } else if (style.size.indexOf('em') != -1) { - // computedStyle.size = canvasFontSize * fontSize; - // } else if(style.size.indexOf('%') != -1) { - // computedStyle.size = (canvasFontSize / 100) * fontSize; - // } else if (style.size.indexOf('pt') != -1) { - // computedStyle.size = fontSize / .75; - // } else { - // computedStyle.size = canvasFontSize; - // } - - // // Different scaling between normal text and VML text. This was found using - // // trial and error to get the same size as non VML text. - // computedStyle.size *= 0.981; - - // return computedStyle; - // } - - // function buildStyle(style) { - // return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + - // style.size + 'px ' + style.family; - // } - - var lineCapMap = { - 'butt': 'flat', - 'round': 'round' - }; - - function processLineCap(lineCap) { - return lineCapMap[lineCap] || 'square'; - } - - /** - * This class implements CanvasRenderingContext2D interface as described by - * the WHATWG. - * @param {HTMLElement} canvasElement The element that the 2D context should - * be associated with - */ - function CanvasRenderingContext2D_(canvasElement) { - this.m_ = createMatrixIdentity(); - - this.mStack_ = []; - this.aStack_ = []; - this.currentPath_ = []; - - // Canvas context properties - this.strokeStyle = '#000'; - this.fillStyle = '#000'; - - this.lineWidth = 1; - this.lineJoin = 'miter'; - this.lineCap = 'butt'; - this.miterLimit = Z * 1; - this.globalAlpha = 1; - //this.font = '10px sans-serif'; - //this.textAlign = 'left'; - //this.textBaseline = 'alphabetic'; - this.canvas = canvasElement; - - var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + - canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; - var el = canvasElement.ownerDocument.createElement('div'); - el.style.cssText = cssText; - canvasElement.appendChild(el); - - var overlayEl = el.cloneNode(false); - // Use a non transparent background. - overlayEl.style.backgroundColor = 'red'; - overlayEl.style.filter = 'alpha(opacity=0)'; - canvasElement.appendChild(overlayEl); - - this.element_ = el; - this.arcScaleX_ = 1; - this.arcScaleY_ = 1; - this.lineScale_ = 1; - } - - var contextPrototype = CanvasRenderingContext2D_.prototype; - contextPrototype.clearRect = function () { - if (this.textMeasureEl_) { - this.textMeasureEl_.removeNode(true); - this.textMeasureEl_ = null; - } - this.element_.innerHTML = ''; - }; - - contextPrototype.beginPath = function () { - // TODO: Branch current matrix so that save/restore has no effect - // as per safari docs. - this.currentPath_ = []; - }; - - contextPrototype.moveTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'moveTo', x: p.x, y: p.y }); - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.lineTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'lineTo', x: p.x, y: p.y }); - - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY) { - var p = getCoords(this, aX, aY); - var cp1 = getCoords(this, aCP1x, aCP1y); - var cp2 = getCoords(this, aCP2x, aCP2y); - bezierCurveTo(this, cp1, cp2, p); - }; - - // Helper function that takes the already fixed cordinates. - function bezierCurveTo(self, cp1, cp2, p) { - self.currentPath_.push({ - type: 'bezierCurveTo', - cp1x: cp1.x, - cp1y: cp1.y, - cp2x: cp2.x, - cp2y: cp2.y, - x: p.x, - y: p.y - }); - self.currentX_ = p.x; - self.currentY_ = p.y; - } - - contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { - // the following is lifted almost directly from - // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes - - var cp = getCoords(this, aCPx, aCPy); - var p = getCoords(this, aX, aY); - - var cp1 = { - x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), - y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) - }; - var cp2 = { - x: cp1.x + (p.x - this.currentX_) / 3.0, - y: cp1.y + (p.y - this.currentY_) / 3.0 - }; - - bezierCurveTo(this, cp1, cp2, p); - }; - - contextPrototype.arc = function (aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise) { - aRadius *= Z; - var arcType = aClockwise ? 'at' : 'wa'; - - var xStart = aX + mc(aStartAngle) * aRadius - Z2; - var yStart = aY + ms(aStartAngle) * aRadius - Z2; - - var xEnd = aX + mc(aEndAngle) * aRadius - Z2; - var yEnd = aY + ms(aEndAngle) * aRadius - Z2; - - // IE won't render arches drawn counter clockwise if xStart == xEnd. - if (xStart == xEnd && !aClockwise) { - xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something - // that can be represented in binary - } - - var p = getCoords(this, aX, aY); - var pStart = getCoords(this, xStart, yStart); - var pEnd = getCoords(this, xEnd, yEnd); - - this.currentPath_.push({ type: arcType, - x: p.x, - y: p.y, - radius: aRadius, - xStart: pStart.x, - yStart: pStart.y, - xEnd: pEnd.x, - yEnd: pEnd.y - }); - - }; - - // contextPrototype.rect = function(aX, aY, aWidth, aHeight) { - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // }; - - // contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.stroke(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.fill(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { - // var gradient = new CanvasGradient_('gradient'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // return gradient; - // }; - - // contextPrototype.createRadialGradient = function(aX0, aY0, aR0, - // aX1, aY1, aR1) { - // var gradient = new CanvasGradient_('gradientradial'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.r0_ = aR0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // gradient.r1_ = aR1; - // return gradient; - // }; - - // contextPrototype.drawImage = function(image, var_args) { - // var dx, dy, dw, dh, sx, sy, sw, sh; - - // // to find the original width we overide the width and height - // var oldRuntimeWidth = image.runtimeStyle.width; - // var oldRuntimeHeight = image.runtimeStyle.height; - // image.runtimeStyle.width = 'auto'; - // image.runtimeStyle.height = 'auto'; - - // // get the original size - // var w = image.width; - // var h = image.height; - - // // and remove overides - // image.runtimeStyle.width = oldRuntimeWidth; - // image.runtimeStyle.height = oldRuntimeHeight; - - // if (arguments.length == 3) { - // dx = arguments[1]; - // dy = arguments[2]; - // sx = sy = 0; - // sw = dw = w; - // sh = dh = h; - // } else if (arguments.length == 5) { - // dx = arguments[1]; - // dy = arguments[2]; - // dw = arguments[3]; - // dh = arguments[4]; - // sx = sy = 0; - // sw = w; - // sh = h; - // } else if (arguments.length == 9) { - // sx = arguments[1]; - // sy = arguments[2]; - // sw = arguments[3]; - // sh = arguments[4]; - // dx = arguments[5]; - // dy = arguments[6]; - // dw = arguments[7]; - // dh = arguments[8]; - // } else { - // throw Error('Invalid number of arguments'); - // } - - // var d = getCoords(this, dx, dy); - - // var w2 = sw / 2; - // var h2 = sh / 2; - - // var vmlStr = []; - - // var W = 10; - // var H = 10; - - // // For some reason that I've now forgotten, using divs didn't work - // vmlStr.push(' ' , - // '', - // ''); - - // this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); - // }; - - contextPrototype.stroke = function (aFill) { - var lineStr = []; - var lineOpen = false; - - var W = 10; - var H = 10; - - lineStr.push(''); - - if (!aFill) { - appendStroke(this, lineStr); - } else { - appendFill(this, lineStr, min, max); - } - - lineStr.push(''); - - this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - }; - - function appendStroke(ctx, lineStr) { - var a = processStyle(ctx.strokeStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - var lineWidth = ctx.lineScale_ * ctx.lineWidth; - - // VML cannot correctly render a line if the width is less than 1px. - // In that case, we dilute the color to make the line look thinner. - if (lineWidth < 1) { - opacity *= lineWidth; - } - - lineStr.push( - '' - ); - } - - function appendFill(ctx, lineStr, min, max) { - var fillStyle = ctx.fillStyle; - var arcScaleX = ctx.arcScaleX_; - var arcScaleY = ctx.arcScaleY_; - var width = max.x - min.x; - var height = max.y - min.y; - // if (fillStyle instanceof CanvasGradient_) { - // // TODO: Gradients transformed with the transformation matrix. - // var angle = 0; - // var focus = {x: 0, y: 0}; - - // // additional offset - // var shift = 0; - // // scale factor for offset - // var expansion = 1; - - // if (fillStyle.type_ == 'gradient') { - // var x0 = fillStyle.x0_ / arcScaleX; - // var y0 = fillStyle.y0_ / arcScaleY; - // var x1 = fillStyle.x1_ / arcScaleX; - // var y1 = fillStyle.y1_ / arcScaleY; - // var p0 = getCoords(ctx, x0, y0); - // var p1 = getCoords(ctx, x1, y1); - // var dx = p1.x - p0.x; - // var dy = p1.y - p0.y; - // angle = Math.atan2(dx, dy) * 180 / Math.PI; - - // // The angle should be a non-negative number. - // if (angle < 0) { - // angle += 360; - // } - - // // Very small angles produce an unexpected result because they are - // // converted to a scientific notation string. - // if (angle < 1e-6) { - // angle = 0; - // } - // } else { - // var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); - // focus = { - // x: (p0.x - min.x) / width, - // y: (p0.y - min.y) / height - // }; - - // width /= arcScaleX * Z; - // height /= arcScaleY * Z; - // var dimension = m.max(width, height); - // shift = 2 * fillStyle.r0_ / dimension; - // expansion = 2 * fillStyle.r1_ / dimension - shift; - // } - - // // We need to sort the color stops in ascending order by offset, - // // otherwise IE won't interpret it correctly. - // var stops = fillStyle.colors_; - // stops.sort(function(cs1, cs2) { - // return cs1.offset - cs2.offset; - // }); - - // var length = stops.length; - // var color1 = stops[0].color; - // var color2 = stops[length - 1].color; - // var opacity1 = stops[0].alpha * ctx.globalAlpha; - // var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; - - // var colors = []; - // for (var i = 0; i < length; i++) { - // var stop = stops[i]; - // colors.push(stop.offset * expansion + shift + ' ' + stop.color); - // } - - // // When colors attribute is used, the meanings of opacity and o:opacity2 - // // are reversed. - // lineStr.push(''); - // } else if (fillStyle instanceof CanvasPattern_) { - // if (width && height) { - // var deltaLeft = -min.x; - // var deltaTop = -min.y; - // lineStr.push(''); - // } - // } else { - var a = processStyle(ctx.fillStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - lineStr.push(''); - // } - } - - contextPrototype.fill = function () { - this.stroke(true); - }; - - contextPrototype.closePath = function () { - this.currentPath_.push({ type: 'close' }); - }; - - function getCoords(ctx, aX, aY) { - var m = ctx.m_; - return { - x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, - y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 - }; - }; - - contextPrototype.save = function () { - var o = {}; - copyState(this, o); - this.aStack_.push(o); - this.mStack_.push(this.m_); - this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); - }; - - contextPrototype.restore = function () { - if (this.aStack_.length) { - copyState(this.aStack_.pop(), this); - this.m_ = this.mStack_.pop(); - } - }; - - function matrixIsFinite(m) { - return isFinite(m[0][0]) && isFinite(m[0][1]) && - isFinite(m[1][0]) && isFinite(m[1][1]) && - isFinite(m[2][0]) && isFinite(m[2][1]); - } - - function setM(ctx, m, updateLineScale) { - if (!matrixIsFinite(m)) { - return; - } - ctx.m_ = m; - - if (updateLineScale) { - // Get the line scale. - // Determinant of this.m_ means how much the area is enlarged by the - // transformation. So its square root can be used as a scale factor - // for width. - var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; - ctx.lineScale_ = sqrt(abs(det)); - } - } - - contextPrototype.translate = function (aX, aY) { - var m1 = [ - [1, 0, 0], - [0, 1, 0], - [aX, aY, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), false); - }; - - // contextPrototype.rotate = function(aRot) { - // var c = mc(aRot); - // var s = ms(aRot); - - // var m1 = [ - // [c, s, 0], - // [-s, c, 0], - // [0, 0, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), false); - // }; - - contextPrototype.scale = function (aX, aY) { - this.arcScaleX_ *= aX; - this.arcScaleY_ *= aY; - var m1 = [ - [aX, 0, 0], - [0, aY, 0], - [0, 0, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), true); - }; - - // contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { - // var m1 = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), true); - // }; - - // contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { - // var m = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, m, true); - // }; - - /** - * The text drawing function. - * The maxWidth argument isn't taken in account, since no browser supports - * it yet. - */ - // contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { - // var m = this.m_, - // delta = 1000, - // left = 0, - // right = delta, - // offset = {x: 0, y: 0}, - // lineStr = []; - - // var fontStyle = getComputedStyle(processFontStyle(this.font), - // this.element_); - - // var fontStyleString = buildStyle(fontStyle); - - // var elementStyle = this.element_.currentStyle; - // var textAlign = this.textAlign.toLowerCase(); - // switch (textAlign) { - // case 'left': - // case 'center': - // case 'right': - // break; - // case 'end': - // textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; - // break; - // case 'start': - // textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; - // break; - // default: - // textAlign = 'left'; - // } - - // // 1.75 is an arbitrary number, as there is no info about the text baseline - // switch (this.textBaseline) { - // case 'hanging': - // case 'top': - // offset.y = fontStyle.size / 1.75; - // break; - // case 'middle': - // break; - // default: - // case null: - // case 'alphabetic': - // case 'ideographic': - // case 'bottom': - // offset.y = -fontStyle.size / 2.25; - // break; - // } - - // switch(textAlign) { - // case 'right': - // left = delta; - // right = 0.05; - // break; - // case 'center': - // left = right = delta / 2; - // break; - // } - - // var d = getCoords(this, x + offset.x, y + offset.y); - - // lineStr.push(''); - - // if (stroke) { - // appendStroke(this, lineStr); - // } else { - // // TODO: Fix the min and max params. - // appendFill(this, lineStr, {x: -left, y: 0}, - // {x: right, y: fontStyle.size}); - // } - - // var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + - // m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; - - // var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); - - // lineStr.push('', - // '', - // ''); - - // this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - // }; - - // contextPrototype.fillText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, false); - // }; - - // contextPrototype.strokeText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, true); - // }; - - // contextPrototype.measureText = function(text) { - // if (!this.textMeasureEl_) { - // var s = ''; - // this.element_.insertAdjacentHTML('beforeEnd', s); - // this.textMeasureEl_ = this.element_.lastChild; - // } - // var doc = this.element_.ownerDocument; - // this.textMeasureEl_.innerHTML = ''; - // this.textMeasureEl_.style.font = this.font; - // // Don't use innerHTML or innerText because they allow markup/whitespace. - // this.textMeasureEl_.appendChild(doc.createTextNode(text)); - // return {width: this.textMeasureEl_.offsetWidth}; - // }; - - /******** STUBS ********/ - // contextPrototype.clip = function() { - // // TODO: Implement - // }; - - // contextPrototype.arcTo = function() { - // // TODO: Implement - // }; - - // contextPrototype.createPattern = function(image, repetition) { - // return new CanvasPattern_(image, repetition); - // }; - - // // Gradient / Pattern Stubs - // function CanvasGradient_(aType) { - // this.type_ = aType; - // this.x0_ = 0; - // this.y0_ = 0; - // this.r0_ = 0; - // this.x1_ = 0; - // this.y1_ = 0; - // this.r1_ = 0; - // this.colors_ = []; - // } - - // CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { - // aColor = processStyle(aColor); - // this.colors_.push({offset: aOffset, - // color: aColor.color, - // alpha: aColor.alpha}); - // }; - - // function CanvasPattern_(image, repetition) { - // assertImageIsValid(image); - // switch (repetition) { - // case 'repeat': - // case null: - // case '': - // this.repetition_ = 'repeat'; - // break - // case 'repeat-x': - // case 'repeat-y': - // case 'no-repeat': - // this.repetition_ = repetition; - // break; - // default: - // throwException('SYNTAX_ERR'); - // } - - // this.src_ = image.src; - // this.width_ = image.width; - // this.height_ = image.height; - // } - - function throwException(s) { - throw new DOMException_(s); - } - - // function assertImageIsValid(img) { - // if (!img || img.nodeType != 1 || img.tagName != 'IMG') { - // throwException('TYPE_MISMATCH_ERR'); - // } - // if (img.readyState != 'complete') { - // throwException('INVALID_STATE_ERR'); - // } - // } - - function DOMException_(s) { - this.code = this[s]; - this.message = s + ': DOM Exception ' + this.code; - } - var p = DOMException_.prototype = new Error; - p.INDEX_SIZE_ERR = 1; - p.DOMSTRING_SIZE_ERR = 2; - p.HIERARCHY_REQUEST_ERR = 3; - p.WRONG_DOCUMENT_ERR = 4; - p.INVALID_CHARACTER_ERR = 5; - p.NO_DATA_ALLOWED_ERR = 6; - p.NO_MODIFICATION_ALLOWED_ERR = 7; - p.NOT_FOUND_ERR = 8; - p.NOT_SUPPORTED_ERR = 9; - p.INUSE_ATTRIBUTE_ERR = 10; - p.INVALID_STATE_ERR = 11; - p.SYNTAX_ERR = 12; - p.INVALID_MODIFICATION_ERR = 13; - p.NAMESPACE_ERR = 14; - p.INVALID_ACCESS_ERR = 15; - p.VALIDATION_ERR = 16; - p.TYPE_MISMATCH_ERR = 17; - - // set up externs - G_vmlCanvasManager = G_vmlCanvasManager_; - CanvasRenderingContext2D = CanvasRenderingContext2D_; - //CanvasGradient = CanvasGradient_; - //CanvasPattern = CanvasPattern_; - DOMException = DOMException_; - })(); - -} // if - -/*! JsRender v1.0pre: http://github.com/BorisMoore/jsrender */ -/* - * Optimized version of jQuery Templates, for rendering to string. - * Does not require jQuery, or HTML DOM - * Integrates with JsViews (http://github.com/BorisMoore/jsviews) - * Copyright 2012, Boris Moore - * Released under the MIT License. - */ -// informal pre beta commit counter: 3 - -this.jsviews || this.jQuery && jQuery.views || (function( window, undefined ) { - -//========================== Top-level vars ========================== - -var versionNumber = "v1.0pre", - - $, rTag, rTmplString, extend, - sub = {}, - FALSE = false, TRUE = true, - jQuery = window.jQuery, - - rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // nil object helper view viewProperty pathTokens leafToken string - - rParams = /(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - - rNewLine = /\r?\n/g, - rUnescapeQuotes = /\\(['"])/g, - rEscapeQuotes = /\\?(['"])/g, - rBuildHash = /\x08(~)?([^\x08]+)\x08/g, - - autoViewKey = 0, - autoTmplName = 0, - escapeMapForHtml = { - "&": "&", - "<": "<", - ">": ">" - }, - tmplAttr = "data-jsv-tmpl", - fnDeclStr = "var j=j||" + (jQuery ? "jQuery." : "js") + "views,", - htmlSpecialChar = /[\x00"&'<>]/g, - slice = Array.prototype.slice, - - render = {}, - - // jsviews object ($.views if jQuery is loaded) - jsv = { - jsviews: versionNumber, - sub: sub, // subscription, e.g. JsViews integration - debugMode: TRUE, - err: function( e ) { - return jsv.debugMode ? ("
                    Error: " + (e.message || e) + ". ") : '""'; - }, - tmplFn: tmplFn, - render: render, - templates: templates, - tags: tags, - helpers: helpers, - converters: converters, - View: View, - convert: convert, - delimiters: setDelimiters, - tag: renderTag - }; - -//========================== Top-level functions ========================== - -//=================== -// jsviews.delimiters -//=================== - -function setDelimiters( openChars, closeChars ) { - // Set the tag opening and closing delimiters. Default is "{{" and "}}" - // openChar, closeChars: opening and closing strings, each with two characters - var firstOpenChar = "\\" + openChars.charAt( 0 ), // Escape the characters - since they could be regex special characters - secondOpenChar = "\\" + openChars.charAt( 1 ), - firstCloseChar = "\\" + closeChars.charAt( 0 ), - secondCloseChar = "\\" + closeChars.charAt( 1 ); - // Build regex with new delimiters - jsv.rTag = rTag // make rTag available to JsViews (or other components) for parsing binding expressions - = secondOpenChar - // tag (followed by / space or }) or colon or html or code - + "(?:(?:(\\w+(?=[\\/\\s" + firstCloseChar + "]))|(?:(\\w+)?(:)|(>)|(\\*)))" - // params - + "\\s*((?:[^" + firstCloseChar + "]|" + firstCloseChar + "(?!" + secondCloseChar + "))*?)" - // slash or closeBlock - + "(\\/)?|(?:\\/(\\w+)))" - // }} - + firstCloseChar; - - // Default rTag: tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/\s\}]))|(?:(\w+)?(:)|(>)|(\*)))\s*((?:[^}]|}(?!\}))*?)(\/)?|(?:\/(\w+)))}} - - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - rTag = new RegExp( firstOpenChar + rTag + secondCloseChar, "g" ); - rTmplString = new RegExp( "<.*>|" + openChars + ".*" + closeChars ); - return this; -} - -//================= -// View.hlp -//================= - -function getHelper( helper ) { - // Helper method called as view.hlp() from compiled template, for helper functions or template parameters ~foo - var view = this, - tmplHelpers = view.tmpl.helpers || {}; - helper = (view.ctx[ helper ] !== undefined ? view.ctx : tmplHelpers[ helper ] !== undefined ? tmplHelpers : helpers[ helper ] !== undefined ? helpers : {})[ helper ]; - return typeof helper !== "function" ? helper : function() { - return helper.apply(view, arguments); - }; -} - -//================= -// jsviews.convert -//================= - -function convert( converter, view, text ) { - var tmplConverters = view.tmpl.converters; - converter = tmplConverters && tmplConverters[ converter ] || converters[ converter ]; - return converter ? converter.call( view, text ) : text; -} - -//================= -// jsviews.tag -//================= - -function renderTag( tag, parentView, converter, content, tagObject ) { - // Called from within compiled template function, to render a nested tag - // Returns the rendered tag - tagObject.props = tagObject.props || {}; - var ret, - tmpl = tagObject.props.tmpl, - tmplTags = parentView.tmpl.tags, - nestedTemplates = parentView.tmpl.templates, - args = arguments, - tagFn = tmplTags && tmplTags[ tag ] || tags[ tag ]; - - if ( !tagFn ) { - return ""; - } - // Set the tmpl property to the content of the block tag, unless set as an override property on the tag - content = content && parentView.tmpl.tmpls[ content - 1 ]; - tmpl = tmpl || content || undefined; - tagObject.tmpl = - "" + tmpl === tmpl // if a string - ? nestedTemplates && nestedTemplates[ tmpl ] || templates[ tmpl ] || templates( tmpl ) - : tmpl; - - tagObject.isTag = TRUE; - tagObject.converter = converter; - tagObject.view = parentView; - tagObject.renderContent = renderContent; - if ( parentView.ctx ) { - extend( tagObject.ctx, parentView.ctx); - } - - ret = tagFn.apply( tagObject, args.length > 5 ? slice.call( args, 5 ) : [] ); - return ret || ( ret == undefined ? "" : ret.toString()); // (If ret is the value 0 or false, will render to string) -} - -//================= -// View constructor -//================= - -function View( context, path, parentView, data, template, index ) { - // Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded) - var views = parentView.views, -// TODO: add this, as part of smart re-linking on existing content ($.link method), or remove completely -// self = parentView.views[ index ]; -// if ( !self ) { ... } - self = { - tmpl: template, - path: path, - parent: parentView, - data: data, - ctx: context, - views: $.isArray( data ) ? [] : {}, - hlp: getHelper - }; - - if ( $.isArray( views )) { - views.splice( - self.index = index !== undefined - ? index - : views.length, 0, self - ); - } else { - views[ self.index = "_" + autoViewKey++ ] = self; - } - return self; -} - -//================= -// Registration -//================= - -function addToStore( self, store, name, item, process ) { - // Add item to named store such as templates, helpers, converters... - var key, onStore; - if ( name && typeof name === "object" && !name.nodeType ) { - // If name is a map, iterate over map and call store for key - for ( key in name ) { - store( key, name[ key ]); - } - return self; - } - if ( !name || item === undefined ) { - if ( process ) { - item = process( undefined, item || name ); - } - } else if ( "" + name === name ) { // name must be a string - if ( item === null ) { - // If item is null, delete this entry - delete store[name]; - } else if ( item = process ? process( name, item ) : item ) { - store[ name ] = item; - } - } - if ( onStore = sub.onStoreItem ) { - // e.g. JsViews integration - onStore( store, name, item, process ); - } - return item; -} - -function templates( name, tmpl ) { - // Register templates - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, templates, name, tmpl, compile ); -} - -function tags( name, tagFn ) { - // Register template tags - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, tags, name, tagFn ); -} - -function helpers( name, helperFn ) { - // Register helper functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.helpers( name, helperFn ) or $.view.helpers({ name: helperFn, ... }) to add additional helpers to the registered helpers collection. - // Getter: Use var helperFn = $.views.helpers( name ) or $.views.helpers[name] or $.views.helpers.name to return the function. - // Remove: Use $.view.helpers( name, null ) to remove a registered helper function from $.view.helpers. - // Within a template, access the helper using the syntax: {{... ~myHelper(...) ...}}. - return addToStore( this, helpers, name, helperFn ); -} - -function converters( name, converterFn ) { - // Register converter functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.converters( name, converterFn ) or $.view.converters({ name: converterFn, ... }) to add additional converters to the registered converters collection. - // Getter: Use var converterFn = $.views.converters( name ) or $.views.converters[name] or $.views.converters.name to return the converter function. - // Remove: Use $.view.converters( name, null ) to remove a registered converter from $.view.converters. - // Within a template, access the converter using the syntax: {{myConverter:...}}. - return addToStore( this, converters, name, converterFn ); -} - -//================= -// renderContent -//================= - -function renderContent( data, context, parentView, path, index ) { - // Render template against data as a tree of subviews (nested template), or as a string (top-level template). - // tagName parameter for internal use only. Used for rendering templates registered as tags (which may have associated presenter objects) - var i, l, dataItem, newView, itemWrap, itemsWrap, itemResult, parentContext, tmpl, layout, - props = {}, - swapContent = index === TRUE, - self = this, - result = ""; - - if ( self.isTag ) { - // This is a call from renderTag - tmpl = self.tmpl; - context = context || self.ctx; - parentView = parentView || self.view; - path = path || self.path; - index = index || self.index; - props = self.props; - } else { - tmpl = self.jquery && self[0] // This is a call $.fn.render - || self; // This is a call from tmpl.render - } - parentView = parentView || jsv.topView; - parentContext = parentView.ctx; - layout = tmpl.layout; - if ( data === parentView ) { - // Inherit the data from the parent view. - // This may be the contents of an {{if}} block - data = parentView.data; - layout = TRUE; - } - - // Set additional context on views created here, (as modified context inherited from the parent, and be inherited by child views) - // Note: If no jQuery, extend does not support chained copies - so limit extend() to two parameters - context = (context && context === parentContext) - ? parentContext - : (parentContext - // if parentContext, make copy - ? ((parentContext = extend( {}, parentContext ), context) - // If context, merge context with copied parentContext - ? extend( parentContext, context ) - : parentContext) - // if no parentContext, use context, or default to {} - : context || {}); - - if ( props.link === FALSE ) { - // Override inherited value of link by an explicit setting in props: link=false - // The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect. - context.link = FALSE; - } - if ( !tmpl.fn ) { - tmpl = templates[ tmpl ] || templates( tmpl ); - } - itemWrap = context.link && sub.onRenderItem; - itemsWrap = context.link && sub.onRenderItems; - - if ( tmpl ) { - if ( $.isArray( data ) && !layout ) { - // Create a view for the array, whose child views correspond to each data item. - // (Note: if index and parentView are passed in along with parent view, treat as - // insert -e.g. from view.addViews - so parentView is already the view item for array) - newView = swapContent ? parentView : (index !== undefined && parentView) || View( context, path, parentView, data, tmpl, index ); - - for ( i = 0, l = data.length; i < l; i++ ) { - // Create a view for each data item. - dataItem = data[ i ]; - itemResult = tmpl.fn( dataItem, View( context, path, newView, dataItem, tmpl, (index||0) + i ), jsv ); - result += itemWrap ? itemWrap( itemResult, props ) : itemResult; - } - } else { - // Create a view for singleton data object. - newView = swapContent ? parentView : View( context, path, parentView, data, tmpl, index ); - result += (data || layout) ? tmpl.fn( data, newView, jsv ) : ""; - } - parentView.topKey = newView.index; - return itemsWrap ? itemsWrap( result, path, newView.index, tmpl, props ) : result; - } - return ""; // No tmpl. Could throw... -} - -//=========================== -// Build and compile template -//=========================== - -// Generate a reusable function that will serve to render a template against data -// (Compile AST then build template function) - -function syntaxError() { - throw "Syntax error"; -} - -function tmplFn( markup, tmpl, bind ) { - // Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes - // Used for compiling templates, and also by JsViews to build functions for data link expressions - var newNode, node, i, l, code, hasTag, hasEncoder, getsValue, hasConverter, hasViewPath, tag, converter, params, hash, nestedTmpl, allowCode, - tmplOptions = tmpl ? { - allowCode: allowCode = tmpl.allowCode, - debug: tmpl.debug - } : {}, - nested = tmpl && tmpl.tmpls, - astTop = [], - loc = 0, - stack = [], - content = astTop, - current = [,,,astTop], - nestedIndex = 0; - - //==== nested functions ==== - function pushPreceedingContent( shift ) { - shift -= loc; - if ( shift ) { - content.push( markup.substr( loc, shift ).replace( rNewLine, "\\n" )); - } - } - - function parseTag( all, tagName, converter, colon, html, code, params, slash, closeBlock, index ) { - // tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(?:(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - // Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, contentMarkup ] - if ( html ) { - colon = ":"; - converter = "html"; - } - var hash = "", - passedCtx = "", - block = !slash && !colon; // Block tag if not self-closing and not {{:}} or {{>}} (special case) - - //==== nested helper function ==== - - tagName = tagName || colon; - pushPreceedingContent( index ); - loc = index + all.length; // location marker - parsed up to here - if ( code ) { - if ( allowCode ) { - content.push([ "*", params.replace( rUnescapeQuotes, "$1" ) ]); - } - } else if ( tagName ) { - if ( tagName === "else" ) { - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - content = current[ 3 ]; - block = TRUE; - } - params = (params - ? parseParams( params, bind ) - .replace( rBuildHash, function( all, isCtx, keyValue ) { - if ( isCtx ) { - passedCtx += keyValue + ","; - } else { - hash += keyValue + ","; - } - return ""; - }) - : ""); - hash = hash.slice( 0, -1 ); - params = params.slice( 0, -1 ); - newNode = [ - tagName, - converter || "", - params, - block && [], - "{" + (hash ? ("props:{" + hash + "},"): "") + "path:'" + params + "'" + (passedCtx ? ",ctx:{" + passedCtx.slice( 0, -1 ) + "}" : "") + "}" - ]; - if ( block ) { - stack.push( current ); - current = newNode; - current[ 5 ] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag - } - content.push( newNode ); - } else if ( closeBlock ) { - //if ( closeBlock !== current[ 0 ]) { - // throw "unmatched close tag: /" + closeBlock + ". Expected /" + current[ 0 ]; - //} - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - } - if ( !current ) { - throw "Expected block tag"; - } - content = current[ 3 ]; - } - //==== /end of nested functions ==== - - markup = markup.replace( rEscapeQuotes, "\\$1" ); - - // Build the AST (abstract syntax tree) under astTop - markup.replace( rTag, parseTag ); - - pushPreceedingContent( markup.length ); - - // Use the AST (astTop) to build the template function - l = astTop.length; - code = (l ? "" : '"";'); - - for ( i = 0; i < l; i++ ) { - // AST nodes: [ tagName, converter, params, content, hash, contentMarkup ] - node = astTop[ i ]; - if ( node[ 0 ] === "*" ) { - code = code.slice( 0, i ? -1 : -3 ) + ";" + node[ 1 ] + (i + 1 < l ? "ret+=" : ""); - } else if ( "" + node === node ) { // type string - code += '"' + node + '"+'; - } else { - tag = node[ 0 ]; - converter = node[ 1 ]; - params = node[ 2 ]; - content = node[ 3 ]; - hash = node[ 4 ]; - markup = node[ 5 ]; - if ( content ) { - // Create template object for nested template - nestedTmpl = TmplObject( markup, tmplOptions, tmpl, nestedIndex++ ); - // Compile to AST and then to compiled function - tmplFn( markup, nestedTmpl); - nested.push( nestedTmpl ); - } - hasViewPath = hasViewPath || hash.indexOf( "view" ) > -1; - code += (tag === ":" - ? (converter === "html" - ? (hasEncoder = TRUE, "e(" + params) - : converter - ? (hasConverter = TRUE, 'c("' + converter + '",view,' + params) - : (getsValue = TRUE, "((v=" + params + ')!=u?v:""') - ) - : (hasTag = TRUE, 't("' + tag + '",view,"' + (converter || "") + '",' - + (content ? nested.length : '""') // For block tags, pass in the key (nested.length) to the nested content template - + "," + hash + (params ? "," : "") + params)) - + ")+"; - } - } - code = new Function( "data, view, j, b, u", fnDeclStr - + (getsValue ? "v," : "") - + (hasTag ? "t=j.tag," : "") - + (hasConverter ? "c=j.convert," : "") - + (hasEncoder ? "e=j.converters.html," : "") - + "ret; try{\n\n" - + (tmplOptions.debug ? "debugger;" : "") - + (allowCode ? 'ret=' : 'return ') - + code.slice( 0, -1 ) + ";\n\n" - + (allowCode ? "return ret;" : "") - + "}catch(e){return j.err(e);}" - ); - - // Include only the var references that are needed in the code - if ( tmpl ) { - tmpl.fn = code; - tmpl.useVw = hasConverter || hasViewPath || hasTag; - } - return code; -} - -function parseParams( params, bind ) { - var named, - fnCall = {}, - parenDepth = 0, - quoted = FALSE, // boolean for string content in double quotes - aposed = FALSE; // or in single quotes - - function parseTokens( all, lftPrn0, lftPrn, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, prn2, space ) { - // rParams = /(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn path operator err eq path2 prn comma lftPrn3 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - operator = operator || ""; - lftPrn = lftPrn || lftPrn0 || lftPrn2; - path = path || path2; - prn = prn || prn2 || ""; - operator = operator || ""; - - function parsePath( all, object, helper, view, viewProperty, pathTokens, leafToken ) { - // rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // object helper view viewProperty pathTokens leafToken string - if ( object ) { - var ret = (helper - ? 'view.hlp("' + helper + '")' - : view - ? "view" - : "data") - + (leafToken - ? (viewProperty - ? "." + viewProperty - : helper - ? "" - : (view ? "" : "." + object) - ) + (pathTokens || "") - : (leafToken = helper ? "" : view ? viewProperty || "" : object, "")); - - if ( bind && prn !== "(" ) { - ret = "b(" + ret + ',"' + leafToken + '")'; - } - return ret + (leafToken ? "." + leafToken : ""); - } - return all; - } - - if ( err ) { - syntaxError(); - } else { - return (aposed - // within single-quoted string - ? (aposed = !apos, (aposed ? all : '"')) - : quoted - // within double-quoted string - ? (quoted = !quot, (quoted ? all : '"')) - : - ( - (lftPrn - ? (parenDepth++, lftPrn) - : "") - + (space - ? (parenDepth - ? "" - : named - ? (named = FALSE, "\b") - : "," - ) - : eq - // named param - ? (parenDepth && syntaxError(), named = TRUE, '\b' + path + ':') - : path - // path - ? (path.replace( rPath, parsePath ) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : operator) - ) - : operator - ? all - : rtPrn - // function - ? ((fnCall[ parenDepth-- ] = FALSE, rtPrn) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : "") - ) - : comma - ? (fnCall[ parenDepth ] || syntaxError(), ",") // We don't allow top-level literal arrays or objects - : lftPrn0 - ? "" - : (aposed = apos, quoted = quot, '"') - )) - ); - } - } - params = (params + " " ).replace( rParams, parseTokens ); - return params; -} - -function compile( name, tmpl, parent, options ) { - // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object - // options is the set of template properties, c - var tmplOrMarkup, elem, key, nested, nestedItem; - - //==== nested functions ==== - function tmplOrMarkupFromStr( value ) { - // If value is of type string - treat as selector, or name of compiled template - // Return the template object, if already compiled, or the markup string - - if ( ("" + value === value) || value.nodeType > 0 ) { - // If selector is valid and returns at least one element, get first element - elem = value.nodeType > 0 ? value : !rTmplString.test( value ) && jQuery && jQuery( value )[0]; - if ( elem && elem.type ) { - // It is a script element - // Create a name for data linking if none provided - value = templates[ elem.getAttribute( tmplAttr )]; - if ( !value ) { - // Not already compiled and cached, so compile and cache the name - name = name || "_" + autoTmplName++; - elem.setAttribute( tmplAttr, name ); - value = compile( name, elem.innerHTML, parent, options ); // Use tmpl as options - templates[ name ] = value; - } - } - return value; - } - // If value is not a string or dom element, return undefined - } - - //==== Compile the template ==== - tmplOrMarkup = tmplOrMarkupFromStr( tmpl ); - - // If tmpl is a template object, use it for options - options = options || (tmpl.markup ? tmpl : {}); - options.name = name; - nested = options.templates; - - // If tmpl is not a markup string or a selector string, then it must be a template object - // In that case, get it from the markup property of the object - if ( !tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr( tmpl.markup ))) { - if ( tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode )) { - // if the string references a compiled template object, but the debug or allowCode props are different, need to recompile - tmplOrMarkup = tmplOrMarkup.markup; - } - } - if ( tmplOrMarkup !== undefined ) { - if ( name && !parent ) { - render[ name ] = function() { - return tmpl.render.apply( tmpl, arguments ); - }; - } - if ( tmplOrMarkup.fn || tmpl.fn ) { - // tmpl is already compiled, so use it, or if different name is provided, clone it - if ( tmplOrMarkup.fn ) { - if ( name && name !== tmplOrMarkup.name ) { - tmpl = extend( extend( {}, tmplOrMarkup ), options); - } else { - tmpl = tmplOrMarkup; - } - } - } else { - // tmplOrMarkup is a markup string, not a compiled template - // Create template object - tmpl = TmplObject( tmplOrMarkup, options, parent, 0 ); - // Compile to AST and then to compiled function - tmplFn( tmplOrMarkup, tmpl ); - } - for ( key in nested ) { - // compile nested template declarations - nestedItem = nested[ key ]; - if ( nestedItem.name !== key ) { - nested[ key ] = compile( key, nestedItem, tmpl ); - } - } - return tmpl; - } -} -//==== /end of function compile ==== - -function TmplObject( markup, options, parent, index ) { - // Template object constructor - - // nested helper function - function extendStore( storeName ) { - if ( parent[ storeName ]) { - // Include parent items except if overridden by item of same name in options - tmpl[ storeName ] = extend( extend( {}, parent[ storeName ] ), options[ storeName ] ); - } - } - - options = options || {}; - var tmpl = { - markup: markup, - tmpls: [], - links: [], - render: renderContent - }; - if ( parent ) { - if ( parent.templates ) { - tmpl.templates = extend( extend( {}, parent.templates ), options.templates ); - } - tmpl.parent = parent; - tmpl.name = parent.name + "[" + index + "]"; - tmpl.index = index; - } - - extend( tmpl, options ); - if ( parent ) { - extendStore( "templates" ); - extendStore( "tags" ); - extendStore( "helpers" ); - extendStore( "converters" ); - } - return tmpl; -} - -//========================== Initialize ========================== - -if ( jQuery ) { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is loaded, so make $ the jQuery object - $ = jQuery; - $.templates = templates; - $.render = render; - $.views = jsv; - $.fn.render = renderContent; - -} else { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is not loaded. - - $ = window.jsviews = jsv; - $.extend = function( target, source ) { - var name; - target = target || {}; - for ( name in source ) { - target[ name ] = source[ name ]; - } - return target; - }; - - $.isArray = Array && Array.isArray || function( obj ) { - return Object.prototype.toString.call( obj ) === "[object Array]"; - }; -} - -extend = $.extend; - -jsv.topView = { views: {}, tmpl: {}, hlp: getHelper, ctx: jsv.helpers }; - -function replacerForHtml( ch ) { - // Original code from Mike Samuel - return escapeMapForHtml[ ch ] - // Intentional assignment that caches the result of encoding ch. - || (escapeMapForHtml[ ch ] = "&#" + ch.charCodeAt( 0 ) + ";"); -} - -//========================== Register tags ========================== - -tags({ - "if": function() { - var ifTag = this, - view = ifTag.view; - - view.onElse = function( tagObject, args ) { - var i = 0, - l = args.length; - - while ( l && !args[ i++ ]) { - // Only render content if args.length === 0 (i.e. this is an else with no condition) or if a condition argument is truey - if ( i === l ) { - return ""; - } - } - view.onElse = undefined; // If condition satisfied, so won't run 'else'. - tagObject.path = ""; - return tagObject.renderContent( view ); - // Test is satisfied, so render content, while remaining in current data context - // By passing the view, we inherit data context from the parent view, and the content is treated as a layout template - // (so if the data is an array, it will not iterate over the data - }; - return view.onElse( this, arguments ); - }, - "else": function() { - var view = this.view; - return view.onElse ? view.onElse( this, arguments ) : ""; - }, - "for": function() { - var i, - self = this, - result = "", - args = arguments, - l = args.length; - if ( self.props.layout ) { - self.tmpl.layout = TRUE; - } - for ( i = 0; i < l; i++ ) { - result += self.renderContent( args[ i ]); - } - return result; - }, - "=": function( value ) { - return value; - }, - "*": function( value ) { - return value; - } -}); - -//========================== Register global helpers ========================== - -// helpers({ // Global helper functions -// // TODO add any useful built-in helper functions -// }); - -//========================== Register converters ========================== - -converters({ - html: function( text ) { - // HTML encoding helper: Replace < > & and ' and " by corresponding entities. - // inspired by Mike Samuel - return text != undefined ? String( text ).replace( htmlSpecialChar, replacerForHtml ) : ""; - } -}); - -//========================== Define default delimiters ========================== -setDelimiters( "{{", "}}" ); - -})( this ); - -/*! - * jQuery Mousewheel 3.1.13 - * - * Copyright jQuery Foundation and other contributors - * Released under the MIT license - * http://jquery.org/license - */ - -(function (factory) { - if ( typeof define === 'function' && define.amd ) { - // AMD. Register as an anonymous module. - define(['jquery'], factory); - } else if (typeof exports === 'object') { - // Node/CommonJS style for Browserify - module.exports = factory; - } else { - // Browser globals - factory(jQuery); - } -}(function ($) { - - var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], - toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? - ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], - slice = Array.prototype.slice, - nullLowestDeltaTimeout, lowestDelta; - - if ( $.event.fixHooks ) { - for ( var i = toFix.length; i; ) { - $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; - } - } - - var special = $.event.special.mousewheel = { - version: '3.1.12', - - setup: function() { - if ( this.addEventListener ) { - for ( var i = toBind.length; i; ) { - this.addEventListener( toBind[--i], handler, false ); - } - } else { - this.onmousewheel = handler; - } - // Store the line height and page height for this particular element - $.data(this, 'mousewheel-line-height', special.getLineHeight(this)); - $.data(this, 'mousewheel-page-height', special.getPageHeight(this)); - }, - - teardown: function() { - if ( this.removeEventListener ) { - for ( var i = toBind.length; i; ) { - this.removeEventListener( toBind[--i], handler, false ); - } - } else { - this.onmousewheel = null; - } - // Clean up the data we added to the element - $.removeData(this, 'mousewheel-line-height'); - $.removeData(this, 'mousewheel-page-height'); - }, - - getLineHeight: function(elem) { - var $elem = $(elem), - $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent'](); - if (!$parent.length) { - $parent = $('body'); - } - return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16; - }, - - getPageHeight: function(elem) { - return $(elem).height(); - }, - - settings: { - adjustOldDeltas: true, // see shouldAdjustOldDeltas() below - normalizeOffset: true // calls getBoundingClientRect for each event - } - }; - - $.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); - }, - - unmousewheel: function(fn) { - return this.unbind('mousewheel', fn); - } - }); - - - function handler(event) { - var orgEvent = event || window.event, - args = slice.call(arguments, 1), - delta = 0, - deltaX = 0, - deltaY = 0, - absDelta = 0, - offsetX = 0, - offsetY = 0; - event = $.event.fix(orgEvent); - event.type = 'mousewheel'; - - // Old school scrollwheel delta - if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } - if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } - if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } - if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } - - // Firefox < 17 horizontal scrolling related to DOMMouseScroll event - if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { - deltaX = deltaY * -1; - deltaY = 0; - } - - // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy - delta = deltaY === 0 ? deltaX : deltaY; - - // New school wheel delta (wheel event) - if ( 'deltaY' in orgEvent ) { - deltaY = orgEvent.deltaY * -1; - delta = deltaY; - } - if ( 'deltaX' in orgEvent ) { - deltaX = orgEvent.deltaX; - if ( deltaY === 0 ) { delta = deltaX * -1; } - } - - // No change actually happened, no reason to go any further - if ( deltaY === 0 && deltaX === 0 ) { return; } - - // Need to convert lines and pages to pixels if we aren't already in pixels - // There are three delta modes: - // * deltaMode 0 is by pixels, nothing to do - // * deltaMode 1 is by lines - // * deltaMode 2 is by pages - if ( orgEvent.deltaMode === 1 ) { - var lineHeight = $.data(this, 'mousewheel-line-height'); - delta *= lineHeight; - deltaY *= lineHeight; - deltaX *= lineHeight; - } else if ( orgEvent.deltaMode === 2 ) { - var pageHeight = $.data(this, 'mousewheel-page-height'); - delta *= pageHeight; - deltaY *= pageHeight; - deltaX *= pageHeight; - } - - // Store lowest absolute delta to normalize the delta values - absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) ); - - if ( !lowestDelta || absDelta < lowestDelta ) { - lowestDelta = absDelta; - - // Adjust older deltas if necessary - if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { - lowestDelta /= 40; - } - } - - // Adjust older deltas if necessary - if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { - // Divide all the things by 40! - delta /= 40; - deltaX /= 40; - deltaY /= 40; - } - - // Get a whole, normalized value for the deltas - delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); - deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); - deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); - - // Normalise offsetX and offsetY properties - if ( special.settings.normalizeOffset && this.getBoundingClientRect ) { - var boundingRect = this.getBoundingClientRect(); - offsetX = event.clientX - boundingRect.left; - offsetY = event.clientY - boundingRect.top; - } - - // Add information to the event object - event.deltaX = deltaX; - event.deltaY = deltaY; - event.deltaFactor = lowestDelta; - event.offsetX = offsetX; - event.offsetY = offsetY; - // Go ahead and set deltaMode to 0 since we converted to pixels - // Although this is a little odd since we overwrite the deltaX/Y - // properties with normalized deltas. - event.deltaMode = 0; - - // Add event and delta to the front of the arguments - args.unshift(event, delta, deltaX, deltaY); - - // Clearout lowestDelta after sometime to better - // handle multiple device types that give different - // a different lowestDelta - // Ex: trackpad = 3 and mouse wheel = 120 - if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } - nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); - - return ($.event.dispatch || $.event.handle).apply(this, args); - } - - function nullLowestDelta() { - lowestDelta = null; - } - - function shouldAdjustOldDeltas(orgEvent, absDelta) { - // If this is an older event and the delta is divisable by 120, - // then we are assuming that the browser is treating this as an - // older mouse wheel event and that we should divide the deltas - // by 40 to try and get a more usable deltaFactor. - // Side note, this actually impacts the reported scroll distance - // in older browsers and can cause scrolling to be slower than native. - // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. - return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; - } - -})); - -/*! - * jQuery UI Widget 1.8.18 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ - -if ( ! $.widget ) { - -(function( $, undefined ) { - -// jQuery 1.4+ -if ( $.cleanData ) { - var _cleanData = $.cleanData; - $.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); - }; -} else { - var _remove = $.fn.remove; - $.fn.remove = function( selector, keepData ) { - return this.each(function() { - if ( !keepData ) { - if ( !selector || $.filter( selector, [ this ] ).length ) { - $( "*", this ).add( [ this ] ).each(function() { - try { - $( this ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - }); - } - } - return _remove.call( $(this), selector, keepData ); - }); - }; -} - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from -// $.each( basePrototype, function( key, val ) { -// if ( $.isPlainObject(val) ) { -// basePrototype[ key ] = $.extend( {}, val ); -// } -// }); - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = Array.prototype.slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - // prevent calls to internal methods - if ( isMethodCall && options.charAt( 0 ) === "_" ) { - return returnValue; - } - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ), - methodValue = instance && $.isFunction( instance[options] ) ? - instance[ options ].apply( instance, args ) : - instance; - // TODO: add this back in 1.9 and use $.error() (see #5972) -// if ( !instance ) { -// throw "cannot call methods on " + name + " prior to initialization; " + -// "attempted to call method '" + options + "'"; -// } -// if ( !$.isFunction( instance[options] ) ) { -// throw "no such method '" + options + "' for " + name + " widget instance"; -// } -// var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, name, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - // $.widget.bridge stores the plugin instance, but we do it anyway - // so that it's stored even before the _create function runs - $.data( element, this.widgetName, this ); - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - var self = this; - this.element.bind( "remove." + this.widgetName, function() { - self.destroy(); - }); - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: function() {}, - _init: function() {}, - - destroy: function() { - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - }, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - [ value ? "addClass" : "removeClass"]( - this.widgetBaseClass + "-disabled" + " " + - "ui-state-disabled" ) - .attr( "aria-disabled", value ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - - return !( $.isFunction(callback) && - callback.call( this.element[0], event, data ) === false || - event.isDefaultPrevented() ); - } -}; - -})( jQuery ); - -}; - - -(function ($, window, undefined) { - window.toStaticHTML = window.toStaticHTML || function ( x ) { return x; }; - - var pos_oo = Number.POSITIVE_INFINITY, - neg_oo = Number.NEGATIVE_INFINITY; - - $.geo = { - // - // utility functions - // - - _allCoordinates: function (geom) { - // return array of all positions in all geometries of geom - // not in JTS - var geometries = this._flatten(geom), - curGeom = 0, - result = []; - - for (; curGeom < geometries.length; curGeom++) { - var coordinates = geometries[curGeom].coordinates, - isArray = coordinates && $.isArray(coordinates[0]), - isDblArray = isArray && $.isArray(coordinates[0][0]), - isTriArray = isDblArray && $.isArray(coordinates[0][0][0]), - i, j, k; - - if (!isTriArray) { - if (!isDblArray) { - if (!isArray) { - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - for (k = 0; k < coordinates[i][j].length; k++) { - result.push(coordinates[i][j][k]); - } - } - } - } - return result; - }, - - _isGeodetic: function( coords ) { - // returns true if the first coordinate it can find is geodetic - - while ( $.isArray( coords ) ) { - if ( coords.length > 1 && ! $.isArray( coords[ 0 ] ) ) { - return ( coords[ 0 ] >= -180.001 && coords[ 0 ] <= 180.001 && coords[ 1 ] >= -90.001 && coords[ 1 ] <= 90.001 ); - } else { - coords = coords[ 0 ]; - } - } - - return false; - }, - - // - // bbox functions - // - - center: function (bbox, _ignoreGeo /* Internal Use Only */) { - // Envelope.centre in JTS - // bbox only, use centroid for geom - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return wasGeodetic ? $.geo.proj.toGeodetic(center) : center; - }, - - expandBy: function (bbox, dx, dy, _ignoreGeo /* Internal Use Only */) { - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - bbox = [bbox[0] - dx, bbox[1] - dy, bbox[2] + dx, bbox[3] + dy]; - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - height: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[3] - bbox[1]; - }, - - _in: function(bbox1, bbox2) { - return bbox1[0] <= bbox2[0] && - bbox1[1] <= bbox2[1] && - bbox1[2] >= bbox2[2] && - bbox1[3] >= bbox2[3]; - }, - - _bboxDisjoint: function( bbox1, bbox2 ) { - return bbox2[ 0 ] > bbox1[ 2 ] || - bbox2[ 2 ] < bbox1[ 0 ] || - bbox2[ 1 ] > bbox1[ 3 ] || - bbox2[ 3 ] < bbox1[ 1 ]; - }, - - include: function( bbox, value, _ignoreGeo /* Internal Use Only */ ) { - // similar to Envelope.expandToInclude in JTS - if ( !value || !$.isArray( value ) ) { - return bbox; - } - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox || value ) ) { - wasGeodetic = true; - } - - if ( !bbox ) { - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - } else if ( wasGeodetic ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - - if ( value.length === 2 ) { - value = [ value[ 0 ], value[ 1 ], value[ 0 ], value[ 1 ] ]; - } - - if ( $.geo.proj ) { - value = $.geo.proj.fromGeodetic( value ); - } - - bbox[0] = Math.min( value[ 0 ], bbox[ 0 ] ); - bbox[1] = Math.min( value[ 1 ], bbox[ 1 ] ); - bbox[2] = Math.max( value[ 2 ], bbox[ 2 ] ); - bbox[3] = Math.max( value[ 3 ], bbox[ 3 ] ); - - return wasGeodetic ? $.geo.proj.toGeodetic( bbox ) : bbox; - }, - - polygonize: function( bbox, _ignoreGeo /* Internal Use Only */ ) { - // adaptation of Polygonizer class in JTS for use with bboxes - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var polygon = { - type: "Polygon", - coordinates: [ [ - [ bbox[ 0 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 1 ] ] - ] ] - }; - - if ( wasGeodetic ) { - polygon.coordinates = $.geo.proj.toGeodetic( polygon.coordinates ); - } - - return polygon; - }, - - reaspect: function (bbox, ratio, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var width = this.width(bbox, true), - height = this.height(bbox, true), - center = this.center(bbox, true), - dx, dy; - - if (width !== 0 && height !== 0 && ratio > 0) { - if (width / height > ratio) { - dx = width / 2; - dy = dx / ratio; - } else { - dy = height / 2; - dx = dy * ratio; - } - - bbox = [center[0] - dx, center[1] - dy, center[0] + dx, center[1] + dy]; - } - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - recenter: function( bbox, center, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj ) { - if ( this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - if ( this._isGeodetic( center ) ) { - center = $.geo.proj.fromGeodetic(center); - } - } - - var halfWidth = ( bbox[ 2 ] - bbox[ 0 ] ) / 2, - halfHeight = ( bbox[ 3 ] - bbox[ 1 ] ) / 2; - - bbox = [ - center[ 0 ] - halfWidth, - center[ 1 ] - halfHeight, - center[ 0 ] + halfWidth, - center[ 1 ] + halfHeight - ]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - scaleBy: function ( bbox, scale, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var c = this.center(bbox, true), - dx = (bbox[2] - bbox[0]) * scale / 2, - dy = (bbox[3] - bbox[1]) * scale / 2; - - bbox = [c[0] - dx, c[1] - dy, c[0] + dx, c[1] + dy]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - width: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[2] - bbox[0]; - }, - - // - // geometry functions - // - - // bbox (Geometry.getEnvelope in JTS) - - bbox: function ( geom, _ignoreGeo /* Internal Use Only */ ) { - var result, wasGeodetic = false; - if ( !geom ) { - return undefined; - } else if ( geom.bbox ) { - result = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.bbox ) ) ? $.geo.proj.fromGeodetic( geom.bbox ) : geom.bbox; - } else { - result = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var coordinates = this._allCoordinates( geom ), - curCoord = 0; - - if ( coordinates.length === 0 ) { - return undefined; - } - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coordinates ) ) { - wasGeodetic = true; - coordinates = $.geo.proj.fromGeodetic( coordinates ); - } - - for ( ; curCoord < coordinates.length; curCoord++ ) { - result[0] = Math.min(coordinates[curCoord][0], result[0]); - result[1] = Math.min(coordinates[curCoord][1], result[1]); - result[2] = Math.max(coordinates[curCoord][0], result[2]); - result[3] = Math.max(coordinates[curCoord][1], result[3]); - } - } - - return wasGeodetic ? $.geo.proj.toGeodetic(result) : result; - }, - - // centroid - - centroid: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var c; //< temp storage for any coordinate during centroid op - - switch (geom.type) { - case "Point": - return $.extend({}, geom); - - case "LineString": - case "Polygon": - var a = 0, - coords = $.merge( [ ], geom.type === "Polygon" ? geom.coordinates[0] : geom.coordinates ), - i = 1, j, n, - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - c = [ 0, 0 ]; - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coords ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic(coords); - } - - //if (coords[0][0] != coords[coords.length - 1][0] || coords[0][1] != coords[coords.length - 1][1]) { - // coords.push(coords[0]); - //} - - for (; i <= coords.length; i++) { - j = i % coords.length; - - bbox[0] = Math.min(coords[j][0], bbox[0]); - bbox[1] = Math.min(coords[j][1], bbox[1]); - bbox[2] = Math.max(coords[j][0], bbox[2]); - bbox[3] = Math.max(coords[j][1], bbox[3]); - - n = (coords[i - 1][0] * coords[j][1]) - (coords[j][0] * coords[i - 1][1]); - a += n; - c[0] += (coords[i - 1][0] + coords[j][0]) * n; - c[1] += (coords[i - 1][1] + coords[j][1]) * n; - } - - if (a === 0) { - if (coords.length > 0) { - c[0] = Math.min( Math.max( coords[0][0], bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( coords[0][1], bbox[ 1 ] ), bbox[ 3 ] ); - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } else { - return undefined; - } - } - - a *= 3; - //c[0] /= a; - //c[1] /= a; - - c[0] = Math.min( Math.max( c[0] / a, bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( c[1] / a, bbox[ 1 ] ), bbox[ 3 ] ); - - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - - case "MultiPoint": - // should return center of mass for point cluster but just return first point for now - if ( geom.coordinates.length > 0 ) { - c = geom.coordinates[ 0 ]; - return { - type: "Point", - coordinates: [ c[ 0 ], c[ 1 ] ] - }; - } - break; - - case "MultiLineString": - case "MultiPolygon": - if ( geom.coordinates.length > 0 ) { - return this.centroid( { - type: geom.type.substr( 5 ), - coordinates: geom.coordinates[ 0 ] - }, _ignoreGeo ); - } - break; - - } - return undefined; - }, - - // contains - - contains: function (geom1, geom2) { - if (geom1.type !== "Polygon") { - return false; - } - - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1.coordinates, geom2.coordinates); - - case "LineString": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates); - - case "Polygon": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates[0]); - - default: - return false; - } - }, - - _containsPolygonPoint: function (polygonCoordinates, pointCoordinate) { - if (polygonCoordinates.length === 0 || polygonCoordinates[0].length < 4) { - return false; - } - - var rayCross = 0, - a = polygonCoordinates[0][0], - i = 1, - b, - x; - - for (; i < polygonCoordinates[0].length; i++) { - b = polygonCoordinates[0][i]; - - if ((a[1] <= pointCoordinate[1] && pointCoordinate[1] < b[1]) || (b[1] <= pointCoordinate[1] && pointCoordinate[1] < a[1]) && (pointCoordinate[0] < a[0] || pointCoordinate[0] < b[0])) { - x = a[0] + (b[0] - a[0]) * (pointCoordinate[1] - a[1]) / (b[1] - a[1]); - - if (x > pointCoordinate[0]) { - rayCross++; - } - } - - a = b; - } - - return rayCross % 2 === 1; - }, - - _containsPolygonLineString: function (polygonCoordinates, lineStringCoordinates) { - for (var i = 0; i < lineStringCoordinates.length; i++) { - if (!this._containsPolygonPoint(polygonCoordinates, lineStringCoordinates[i])) { - return false; - } - } - return true; - }, - - // distance - - distance: function ( geom1, geom2, _ignoreGeo /* Internal Use Only */ ) { - var geom1CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom1.coordinates ) ) ? $.geo.proj.fromGeodetic(geom1.coordinates) : geom1.coordinates, - geom2CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom2.coordinates ) ) ? $.geo.proj.fromGeodetic(geom2.coordinates) : geom2.coordinates; - - switch (geom1.type) { - case "Point": - switch (geom2.type) { - case "Point": - return this._distancePointPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "LineString": - return this._distanceLineStringPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "Polygon": - return this._containsPolygonPoint(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "LineString": - switch (geom2.type) { - case "Point": - return this._distanceLineStringPoint(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "LineString": - return this._distanceLineStringLineString(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "Polygon": - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "LineString": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected[0]) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected[0]); - default: - return undefined; - } - break; - } - }, - - _distancePointPoint: function (coordinate1, coordinate2) { - var dx = coordinate2[0] - coordinate1[0], - dy = coordinate2[1] - coordinate1[1]; - return Math.sqrt((dx * dx) + (dy * dy)); - }, - - _distanceLineStringPoint: function (lineStringCoordinates, pointCoordinate) { - var minDist = pos_oo; - - if (lineStringCoordinates.length > 0) { - var a = lineStringCoordinates[0], - - apx = pointCoordinate[0] - a[0], - apy = pointCoordinate[1] - a[1]; - - if (lineStringCoordinates.length === 1) { - return Math.sqrt(apx * apx + apy * apy); - } else { - for (var i = 1; i < lineStringCoordinates.length; i++) { - var b = lineStringCoordinates[i], - - abx = b[0] - a[0], - aby = b[1] - a[1], - bpx = pointCoordinate[0] - b[0], - bpy = pointCoordinate[1] - b[1], - - d = this._distanceSegmentPoint(abx, aby, apx, apy, bpx, bpy); - - if (d === 0) { - return 0; - } - - if (d < minDist) { - minDist = d; - } - - a = b; - apx = bpx; - apy = bpy; - } - } - } - - return Math.sqrt(minDist); - }, - - _distanceSegmentPoint: function (abx, aby, apx, apy, bpx, bpy) { - var dot1 = abx * apx + aby * apy; - - if (dot1 <= 0) { - return apx * apx + apy * apy; - } - - var dot2 = abx * abx + aby * aby; - - if (dot1 >= dot2) { - return bpx * bpx + bpy * bpy; - } - - return apx * apx + apy * apy - dot1 * dot1 / dot2; - }, - - _distanceLineStringLineString: function (lineStringCoordinates1, lineStringCoordinates2) { - var minDist = pos_oo; - for (var i = 0; i < lineStringCoordinates2.length; i++) { - minDist = Math.min(minDist, this._distanceLineStringPoint(lineStringCoordinates1, lineStringCoordinates2[i])); - } - return minDist; - }, - - // buffer - - _buffer: function( geom, distance, _ignoreGeo /* Internal Use Only */ ) { - var wasGeodetic = false, - coords = geom.coordinates; - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.coordinates ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic( geom.coordinates ); - } - - if ( geom.type === "Point" ) { - var resultCoords = [], - slices = 180, - i = 0, - a; - - for ( ; i <= slices; i++ ) { - a = ( i * 360 / slices ) * ( Math.PI / 180 ); - resultCoords.push( [ - coords[ 0 ] + Math.cos( a ) * distance, - coords[ 1 ] + Math.sin( a ) * distance - ] ); - } - - return { - type: "Polygon", - coordinates: [ ( wasGeodetic ? $.geo.proj.toGeodetic( resultCoords ) : resultCoords ) ] - }; - } else { - return undefined; - } - }, - - - // - // feature - // - - _basic: function( geom ) { - // return an array of all basic geometries - // e.g., MultiPolygons become multiple Polygons - // coordinate arrays are kept as references for speed & should not be altered - // not in JTS - var geometries = [ ]; - var multiType; - var i = 0; - var j; - - var flat = this._flatten( geom ); - - for ( ; i < flat.length; i++ ) { - if ( flat[ i ].type.substring( 0, 5 ) === "Multi" ) { - multiType = flat[ i ].type.substring( 5 ); - - for ( j = 0; j < flat[ i ].coordinates.length; j++ ) { - geometries.push( { - type: multiType, - coordinates: flat[ i ].coordinates[ j ] - } ); - } - } else { - geometries.push( flat[ i ] ); - } - } - - return geometries; - }, - - _flatten: function (geom) { - // return an array of only geometries - // will extract geometries from Feature, FeatureCollection, & GeometryCollection - // not in JTS - var geometries = [], - curGeom = 0; - switch (geom.type) { - case "Feature": - $.merge(geometries, this._flatten(geom.geometry)); - break; - - case "FeatureCollection": - for (; curGeom < geom.features.length; curGeom++) { - $.merge(geometries, this._flatten(geom.features[curGeom].geometry)); - } - break; - - case "GeometryCollection": - for (; curGeom < geom.geometries.length; curGeom++) { - $.merge(geometries, this._flatten(geom.geometries[curGeom])); - } - break; - - default: - geometries[0] = geom; - break; - } - return geometries; - }, - - length: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - lineStringCoordinates, - i = 1, dx, dy; - - switch ( geom.type ) { - case "Point": - return 0; - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][0] - lineStringCoordinates[ i - 1 ][0]; - dy = lineStringCoordinates[ i ][1] - lineStringCoordinates[ i - 1 ][1]; - sum += Math.sqrt((dx * dx) + (dy * dy)); - } - - return sum; - } - - // return undefined; - }, - - area: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - polygonCoordinates, - i = 1, j; - - switch ( geom.type ) { - case "Point": - case "LineString": - return 0; - - case "Polygon": - polygonCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( polygonCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( polygonCoordinates ) ) { - polygonCoordinates = $.geo.proj.fromGeodetic( polygonCoordinates ); - } - - for ( ; i <= polygonCoordinates.length; i++) { - j = i % polygonCoordinates.length; - sum += ( polygonCoordinates[ i - 1 ][ 0 ] - polygonCoordinates[ j ][ 0 ] ) * ( polygonCoordinates[ i - 1 ][ 1 ] + polygonCoordinates[ j ][ 1 ] ) / 2; - } - - return Math.abs( sum ); - } - }, - - pointAlong: function( geom, percentage, _ignoreGeo /* Internal Use Only */ ) { - var totalLength = 0, - previousPercentageSum = 0, - percentageSum = 0, - remainderPercentageSum, - len, - lineStringCoordinates, - segmentLengths = [], - i = 1, dx, dy, - c, c0, c1, - wasGeodetic = false; - - switch ( geom.type ) { - case "Point": - return $.extend( { }, geom ); - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( percentage === 0 ) { - return { - type: "Point", - coordinates: [ lineStringCoordinates[ 0 ][ 0 ], lineStringCoordinates[ 0 ][ 1 ] ] - }; - } else if ( percentage === 1 ) { - i = lineStringCoordinates.length - 1; - return { - type: "Point", - coordinates: [ lineStringCoordinates[ i ][ 0 ], lineStringCoordinates[ i ][ 1 ] ] - }; - } else { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - wasGeodetic = true; - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][ 0 ] - lineStringCoordinates[ i - 1 ][ 0 ]; - dy = lineStringCoordinates[ i ][ 1 ] - lineStringCoordinates[ i - 1 ][ 1 ]; - len = Math.sqrt((dx * dx) + (dy * dy)); - segmentLengths.push( len ); - totalLength += len; - } - - for ( i = 0; i < segmentLengths.length && percentageSum < percentage; i++ ) { - previousPercentageSum = percentageSum; - percentageSum += ( segmentLengths[ i ] / totalLength ); - } - - remainderPercentageSum = percentage - previousPercentageSum; - - c0 = lineStringCoordinates[ i - 1 ]; - c1 = lineStringCoordinates[ i ]; - - c = [ - c0[ 0 ] + ( remainderPercentageSum * ( c1[ 0 ] - c0[ 0 ] ) ), - c0[ 1 ] + ( remainderPercentageSum * ( c1[ 1 ] - c0[ 1 ] ) ) - ]; - - return { - type: "Point", - coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c - }; - } - } - }, - - // - // WKT functions - // - - WKT: (function () { - function pointToString(value) { - return "POINT " + pointToUntaggedString(value.coordinates); - } - - function pointToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - return "(" + coordinates.join(" ") + ")"; - } - } - - function lineStringToString(value) { - return "LINESTRING " + lineStringToUntaggedString(value.coordinates); - } - - function lineStringToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var points = []; - - for (var i = 0; i < coordinates.length; i++) { - points.push(coordinates[i].join(" ")); - } - - return "(" + points + ")"; - } - } - - function polygonToString(value) { - return "POLYGON " + polygonToUntaggedString(value.coordinates); - } - - function polygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMTPY"; - } else { - var lineStrings = []; - - for (var i = 0; i < coordinates.length; i++) { - lineStrings.push(lineStringToUntaggedString(coordinates[i])); - } - - return "(" + lineStrings + ")"; - } - } - - function multiPointToString(value) { - return "MULTIPOINT " + lineStringToUntaggedString(value.coordinates); - } - - function multiLineStringToString(value) { - return "MULTILINSTRING " + polygonToUntaggedString(value.coordinates); - } - - function multiPolygonToString(value) { - return "MULTIPOLYGON " + multiPolygonToUntaggedString(value.coordinates); - } - - function multiPolygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var polygons = []; - for (var i = 0; i < coordinates.length; i++) { - polygons.push(polygonToUntaggedString(coordinates[i])); - } - return "(" + polygons + ")"; - } - } - - function geometryCollectionToString(value) { - return "GEOMETRYCOLLECTION " + geometryCollectionToUntaggedString(value.geometries); - } - - function geometryCollectionToUntaggedString(geometries) { - if (!(geometries && geometries.length)) { - return "EMPTY"; - } else { - var geometryText = []; - for (var i = 0; i < geometries.length; i++) { - geometryText.push(stringify(geometries[i])); - } - return "(" + geometries + ")"; - } - } - - function stringify(value) { - if (!(value && value.type)) { - return ""; - } else { - switch (value.type) { - case "Point": - return pointToString(value); - - case "LineString": - return lineStringToString(value); - - case "Polygon": - return polygonToString(value); - - case "MultiPoint": - return multiPointToString(value); - - case "MultiLineString": - return multiLineStringToString(value); - - case "MultiPolygon": - return multiPolygonToString(value); - - case "GeometryCollection": - return geometryCollectionToString(value); - - default: - return ""; - } - } - } - - function pointParseUntagged(wkt) { - var pointString = wkt.match( /\(\s*([\d\.\-]+)\s+([\d\.\-]+)\s*\)/ ); - return pointString && pointString.length > 2 ? { - type: "Point", - coordinates: [ - parseFloat(pointString[1]), - parseFloat(pointString[2]) - ] - } : null; - } - - function lineStringParseUntagged(wkt) { - var lineString = wkt.match( /\s*\((.*)\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( lineString && lineString.length > 1 ) { - pointStrings = lineString[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "LineString", - coordinates: coords - }; - } else { - return null; - } - } - - function polygonParseUntagged(wkt) { - var polygon = wkt.match( /\s*\(\s*\((.*)\)\s*\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( polygon && polygon.length > 1 ) { - pointStrings = polygon[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "Polygon", - coordinates: [ coords ] - }; - } else { - return null; - } - } - - function multiPointParseUntagged(wkt) { - var multiSomething; - - if ( wkt.indexOf( "((" ) === -1 ) { - multiSomething = lineStringParseUntagged( wkt ); - } else { - multiSomething = multiLineStringParseUntagged( wkt ); - multiSomething.coordinates = $.geo._allCoordinates( multiSomething ); - } - - multiSomething.type = "MultiPoint"; - - return multiSomething; - } - - function multiLineStringParseUntagged(wkt) { - var lineStringsWkt = wkt.substr( 2, wkt.length - 4 ), - lineString, - lineStrings = lineStringsWkt.split( /\),\s*\(/ ), - i = 0, - multiLineString = { - type: "MultiLineString", - coordinates: [ ] - }; - - for ( ; i < lineStrings.length; i++ ) { - lineString = lineStringParseUntagged( "(" + lineStrings[ i ] + ")" ); - if ( lineString ) { - multiLineString.coordinates.push( lineString.coordinates ); - } - } - - return multiLineString; - } - - function multiPolygonParseUntagged(wkt) { - var polygonsWkt = wkt.substr( 1, wkt.length - 2 ), - polygon, - polygons = polygonsWkt.split( /\),\s*\(/ ), - i = 0, - multiPolygon = { - type: "MultiPolygon", - coordinates: [ ] - }; - - for ( ; i < polygons.length; i++ ) { - polygon = polygonParseUntagged( "(" + polygons[ i ] + ")" ); - if ( polygon ) { - multiPolygon.coordinates.push( polygon.coordinates ); - } - } - - return multiPolygon; - } - - function geometryCollectionParseUntagged( wkt ) { - var geometriesWkt = wkt.substr( 1, wkt.length - 2 ), - geometries = geometriesWkt.match( /\),[a-zA-Z]/g ), - geometryCollection = { - type: "GeometryCollection", - geometries: [ ] - }, - curGeom, - i = 0, curStart = 0, curLen; - - if ( geometries && geometries.length > 0 ) { - for ( ; i < geometries.length; i++ ) { - curLen = geometriesWkt.indexOf( geometries[ i ], curStart ) - curStart + 1; - curGeom = parse( geometriesWkt.substr( curStart, curLen ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - curStart += curLen + 1; - } - - // one more - curGeom = parse( geometriesWkt.substr( curStart ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - - return geometryCollection; - } else { - return null; - } - } - - function parse(wkt) { - wkt = $.trim(wkt); - - var typeIndex = wkt.indexOf( "(" ), - untagged = wkt.substr( typeIndex ); - - switch ($.trim(wkt.substr(0, typeIndex)).toUpperCase()) { - case "POINT": - return pointParseUntagged( untagged ); - - case "LINESTRING": - return lineStringParseUntagged( untagged ); - - case "POLYGON": - return polygonParseUntagged( untagged ); - - case "MULTIPOINT": - return multiPointParseUntagged( untagged ); - - case "MULTILINESTRING": - return multiLineStringParseUntagged( untagged ); - - case "MULTIPOLYGON": - return multiPolygonParseUntagged( untagged ); - - case "GEOMETRYCOLLECTION": - return geometryCollectionParseUntagged( untagged ); - - default: - return null; - } - } - - return { - stringify: stringify, - - parse: parse - }; - }()), - - // - // projection functions - // - - proj: (function () { - var halfPi = 1.5707963267948966192, - quarterPi = 0.7853981633974483096, - radiansPerDegree = 0.0174532925199432958, - degreesPerRadian = 57.295779513082320877, - semiMajorAxis = 6378137; - - return { - fromGeodeticPos: function (coordinate) { - return [ - semiMajorAxis * coordinate[ 0 ] * radiansPerDegree, - semiMajorAxis * Math.log(Math.tan(quarterPi + coordinate[ 1 ] * radiansPerDegree / 2)) - ]; - }, - - fromGeodetic: function ( coordinates ) { - if ( ! $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - fromGeodeticPos = this.fromGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length === 4) { - // bbox - var min = fromGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = fromGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = fromGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - }, - - toGeodeticPos: function (coordinate) { - return [ - (coordinate[ 0 ] / semiMajorAxis) * degreesPerRadian, - (halfPi - 2 * Math.atan(1 / Math.exp(coordinate[ 1 ] / semiMajorAxis))) * degreesPerRadian - ]; - }, - - toGeodetic: function (coordinates) { - if ( $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - toGeodeticPos = this.toGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length === 4) { - // bbox - var min = toGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = toGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = toGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - } - }; - }()), - - // - // service types (defined in other files) - // - - _serviceTypes: {} - }; -}(jQuery, this)); - -(function ($, window, undefined) { - var _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ); - - $.widget("geo.geographics", { - _$elem: undefined, - _options: {}, - _trueCanvas: true, - _trueDoubleBuffer: true, - - _width: 0, - _height: 0, - - _$canvas: undefined, - _context: undefined, - - _$canvasSceneFront: undefined, //< if _trueCanvas, where canvas images get written (front buffer) - _$canvasSceneBack: undefined, //< if _trueCanvas, where canvas images get written (back buffer) - _$canvasSceneStale: undefined, //< if _trueCanvas, scene to hide next - _$canvasSceneDrawn: undefined, //< if _trueCanvas, scene to show next - _timeoutEnd: null, - _requireFlip: false, - - _blitcanvas: undefined, - _blitcontext: undefined, - - _$labelsContainerFront: undefined, - _$labelsContainerBack: undefined, - _labelsHtml: "", - - options: { - style: { - borderRadius: "8px", - color: "#7f0000", - //fill: undefined, - fillOpacity: 0.2, - height: "8px", - opacity: 1, - //stroke: undefined, - strokeOpacity: 1, - strokeWidth: "2px", - visibility: "visible", - width: "8px" - }, - - doubleBuffer: true - }, - - _create: function () { - this._$elem = this.element; - this._options = this.options; - - this._$elem.css( { - webkitTransform: "translateZ(0)", - display: "inline-block", - overflow: "hidden", - textAlign: "left" - } ); - - if (this._$elem.css("position") === "static") { - this._$elem.css("position", "relative"); - } - - this._$elem.addClass( "geo-graphics" ); - - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - var posCss = 'position:absolute;left:0;top:0;margin:0;padding:0;', - sizeCss = 'width:' + this._width + 'px;height:' + this._height + 'px;', - sizeAttr = 'width="' + this._width + '" height="' + this._height + '"'; - - this._blitcanvas = document.createElement( "canvas" ); - - if ( this._blitcanvas.getContext ) { - this._$canvas = $( window.toStaticHTML( '' ) ); - - // test _trueDoubleBuffer - this._blitcanvas.width = 1; - this._blitcanvas.height = 1; - this._trueDoubleBuffer = this._blitcanvas.toDataURL().length > 6; - - if ( !(this._options.doubleBuffer && this._trueDoubleBuffer) ) { - this._$elem.append( this._$canvas ); - } - - this._context = this._$canvas[0].getContext("2d"); - - this._blitcanvas.width = this._width; - this._blitcanvas.height = this._height; - this._blitcontext = this._blitcanvas.getContext("2d"); - - // create our front & back buffers - // though, at any time either one can be in front - this._$canvasSceneFront = $( window.toStaticHTML( '' ) ).on( 'load', $.proxy( this._canvasImgLoad, this ) ); - this._$canvasSceneBack = $( window.toStaticHTML( '' ) ).on( 'load', $.proxy( this._canvasImgLoad, this ) ); - - } else if (_ieVersion <= 8) { - this._trueCanvas = false; - this._$elem.append( '
                    '); - this._$canvas = this._$elem.children(':last'); - - G_vmlCanvasManager.initElement(this._$canvas[0]); - this._context = this._$canvas[0].getContext("2d"); - this._$canvas.children().css({ backgroundColor: "transparent", width: this._width, height: this._height }); - } - - // create our front & back label containers - this._$labelsContainerFront = $( window.toStaticHTML( '
                    ' ) ); - this._$labelsContainerBack = $( window.toStaticHTML( '
                    ' ) ); - }, - - _setOption: function (key, value) { - if (key === "style") { - value = $.extend({}, this._options.style, value); - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - destroy: function () { - $.Widget.prototype.destroy.apply(this, arguments); - this._$elem.html(""); - this._$elem.removeClass( "geo-graphics" ); - }, - - clear: function () { - this._context.clearRect(0, 0, this._width, this._height); - this._labelsHtml = ""; - this._end( ); - }, - - drawArc: function (coordinates, startAngle, sweepAngle, style) { - style = this._getGraphicStyle(style); - - if (style.visibility !== "hidden" && style.opacity > 0 && style.widthValue > 0 && style.heightValue > 0) { - var r = Math.min(style.widthValue, style.heightValue) / 2; - - startAngle = (startAngle * Math.PI / 180); - sweepAngle = (sweepAngle * Math.PI / 180); - - this._context.save(); - this._context.translate(coordinates[0], coordinates[1]); - if (style.widthValue > style.heightValue) { - this._context.scale(style.widthValue / style.heightValue, 1); - } else { - this._context.scale(1, style.heightValue / style.widthValue); - } - - this._context.beginPath(); - this._context.arc(0, 0, r, startAngle, sweepAngle, false); - - if (this._trueCanvas) { - this._context.restore(); - } - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - if (!this._trueCanvas) { - this._context.restore(); - } - } - - this._end( ); - }, - - drawPoint: function (coordinates, style) { - style = this._getGraphicStyle(style); - if (style.widthValue === style.heightValue && style.heightValue === style.borderRadiusValue) { - this.drawArc(coordinates, 0, 360, style); - } else if (style.visibility !== "hidden" && style.opacity > 0) { - style.borderRadiusValue = Math.min(Math.min(style.widthValue, style.heightValue) / 2, style.borderRadiusValue); - coordinates[0] -= style.widthValue / 2; - coordinates[1] -= style.heightValue / 2; - this._context.beginPath(); - this._context.moveTo(coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.lineTo(coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1]); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1], coordinates[0] + style.widthValue, coordinates[1] + style.borderRadiusValue); - this._context.lineTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue, coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.lineTo(coordinates[0] + style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1] + style.heightValue, coordinates[0], coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.lineTo(coordinates[0], coordinates[1] + style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1], coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.closePath(); - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - - this._context.stroke(); - } - - this._end( ); - } - }, - - drawLineString: function (coordinates, style) { - this._drawLines([coordinates], false, style); - }, - - drawPolygon: function (coordinates, style) { - if ( !this._trueCanvas || coordinates.length === 1 ) { - // either we don't have fancy rendering or there's no need for it (no holes) - this._drawLines( coordinates, true, style ); - } else { - if ( !coordinates || !coordinates.length || coordinates[ 0 ].length < 3 ) { - // this is not a Polygon or it doesn't have a proper outer ring - return; - } - - style = this._getGraphicStyle(style); - this._blitcontext.globalCompositeOperation = "copy"; - - var pixelBbox, i, j; - - if ( style.visibility !== "hidden" && style.opacity > 0 ) { - this._blitcontext.clearRect(0, 0, this._width, this._height); - - if ( style.doFill ) { - if ( coordinates.length > 1 ) { - // stencil inner rings - this._blitcontext.globalCompositeOperation = "source-out"; - this._blitcontext.globalAlpha = 1; - - this._blitcontext.beginPath(); - - for ( i = 1; i < coordinates.length; i++ ) { - // start drawing inner rings, i - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - - for ( j = 0; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - } - - this._blitcontext.closePath(); - - this._blitcontext.fill( ); - } - } - - // path outer ring - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ 0 ][ 0 ][ 0 ], coordinates[ 0 ][ 0 ][ 1 ] ); - - pixelBbox = [ coordinates[ 0 ][ 0 ][ 0 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 0 ] + style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] + style.strokeWidthValue ]; - - for ( i = 1; i < coordinates[ 0 ].length - 1; i++ ) { - this._blitcontext.lineTo( coordinates[ 0 ][ i ][ 0 ], coordinates[ 0 ][ i ][ 1 ] ); - - pixelBbox[ 0 ] = Math.min( coordinates[ 0 ][ i ][ 0 ] - style.strokeWidthValue, pixelBbox[ 0 ] ); - pixelBbox[ 1 ] = Math.min( coordinates[ 0 ][ i ][ 1 ] - style.strokeWidthValue, pixelBbox[ 1 ] ); - pixelBbox[ 2 ] = Math.max( coordinates[ 0 ][ i ][ 0 ] + style.strokeWidthValue, pixelBbox[ 2 ] ); - pixelBbox[ 3 ] = Math.max( coordinates[ 0 ][ i ][ 1 ] + style.strokeWidthValue, pixelBbox[ 3 ] ); - } - - this._blitcontext.closePath(); - - if ( style.doFill ) { - // fill outer ring - this._blitcontext.fillStyle = style.fill; - this._blitcontext.globalAlpha = style.opacity * style.fillOpacity; - this._blitcontext.fill( ); - } - - this._blitcontext.globalCompositeOperation = "source-over"; - if ( style.doStroke ) { - // stroke outer ring - this._blitcontext.lineCap = this._blitcontext.lineJoin = "round"; - this._blitcontext.lineWidth = style.strokeWidthValue; - this._blitcontext.strokeStyle = style.stroke; - - this._blitcontext.globalAlpha = style.opacity * style.strokeOpacity; - this._blitcontext.stroke( ); - - if ( coordinates.length > 1 ) { - // stroke inner rings - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.stroke( ); - } - } - } - - // blit - pixelBbox[ 0 ] = Math.min( Math.max( pixelBbox[ 0 ], 0), this._width ); - pixelBbox[ 1 ] = Math.min( Math.max( pixelBbox[ 1 ], 0), this._height ); - pixelBbox[ 2 ] = Math.min( Math.max( pixelBbox[ 2 ], 0), this._width ); - pixelBbox[ 3 ] = Math.min( Math.max( pixelBbox[ 3 ], 0), this._height ); - - if ( pixelBbox[ 0 ] !== pixelBbox[ 2 ] && pixelBbox[ 1 ] !== pixelBbox[ 3 ] ) { - this._context.drawImage(this._blitcanvas, pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ], pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ] ); - - this._end( ); - } - } - } - }, - - drawBbox: function (bbox, style) { - this._drawLines([[ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ]], true, style); - }, - - drawLabel: function( coordinates, label ) { - this._labelsHtml += '
                    ' + label + '
                    '; - }, - - resize: function( dx, dy ) { - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - if ( this._trueCanvas ) { - this._$canvas[0].width = this._width; - this._$canvas[0].height = this._height; - - this._$canvasSceneFront.css( { - left: dx, - top: dy - } ); - - this._$canvasSceneBack.css( { - width: this._width, - height: this._height - } ); - } else { - this._$canvas.css( { - width: this._width, - height: this._height - } ); - } - - var labelPositionFront = this._$labelsContainerFront.position(); - - this._$labelsContainerFront.css( { - left: labelPositionFront.left + dx, - top: labelPositionFront.top + dy, - width: this._width, - height: this._height - } ); - - this._$labelsContainerBack.css( { - width: this._width, - height: this._height - } ); - }, - - interactiveTransform: function( origin, scale ) { - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - if ( this._trueCanvas && this._options.doubleBuffer && this._trueDoubleBuffer ) { - this._canvasSceneLoad( ); - - // transform a finished scene, can assume no drawing during these calls - this._$canvasSceneFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - - // transform labels - this._$labelsContainerFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - }, - - _canvasImgLoad: function( ) { - var geographics = this; - geographics._$canvasSceneFront = geographics._$canvasSceneDrawn.prependTo( geographics._$elem ); - geographics._$canvasSceneBack = geographics._$canvasSceneStale; - geographics._$canvasSceneBack.detach(); - }, - - _canvasSceneLoad: function() { - var geographics = this; - if ( geographics._requireFlip ) { - geographics._requireFlip = false; - geographics._$canvasSceneStale = geographics._$canvasSceneFront; - - geographics._$canvasSceneDrawn = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ); - } - }, - - _endCallback: function() { - var geographics = this; - - if ( !geographics._timeoutEnd ) { - // something has canceled the draw - return; - } - - if ( geographics._trueCanvas && geographics._options.doubleBuffer && geographics._trueDoubleBuffer ) { - this._canvasSceneLoad( ); - } - - geographics._$labelsContainerBack.html( window.toStaticHTML( geographics._labelsHtml ) ).find("a").css({ - position: "relative", - zIndex: 1, - display: "inline-block", - webkitTransform: "translateZ(0)" - }); - - var oldLabelsContainer = geographics._$labelsContainerFront; - - geographics._$labelsContainerFront = geographics._$labelsContainerBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).appendTo( geographics._$elem ); - - geographics._$labelsContainerBack = oldLabelsContainer.detach(); - - geographics._timeoutEnd = null; - }, - - _end: function( ) { - // end/finalize a scene - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - this._requireFlip = true; - - this._timeoutEnd = setTimeout( $.proxy(this._endCallback, this), 20 ); - }, - - _getGraphicStyle: function (style) { - function safeParse(value) { - value = parseInt(value, 10); - return (+value + '') === value ? +value : value; - } - - style = $.extend({}, this._options.style, style); - style.borderRadiusValue = safeParse(style.borderRadius); - style.fill = style.fill || style.color; - style.doFill = style.fill && style.fillOpacity > 0; - style.stroke = style.stroke || style.color; - style.strokeWidthValue = safeParse(style.strokeWidth); - style.doStroke = style.stroke && style.strokeOpacity > 0 && style.strokeWidthValue > 0; - style.widthValue = safeParse(style.width); - style.heightValue = safeParse(style.height); - return style; - }, - - _drawLines: function (coordinates, close, style) { - if (!coordinates || !coordinates.length || coordinates[0].length < 2) { - return; - } - - var i, j; - style = this._getGraphicStyle(style); - - if (style.visibility !== "hidden" && style.opacity > 0) { - this._context.beginPath(); - - for (i = 0; i < coordinates.length; i++) { - this._context.moveTo(coordinates[i][0][0], coordinates[i][0][1]); - for (j = 1; j < coordinates[i].length; j++) { - this._context.lineTo(coordinates[i][j][0], coordinates[i][j][1]); - } - } - - if (close) { - this._context.closePath(); - } - - if (close && style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineCap = this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - this._end( ); - } - } - }); -}(jQuery, window)); - - -(function ($, window, undefined) { - var _widgetIdSeed = 0, - _ieVersion = ( function() { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ), - - _gecko = ( function() { - return ( navigator.userAgent.match( /gecko\/*\d/i ) || [] ).length > 0; - }() ), - - _defaultOptions = { - bbox: [-180, -85, 180, 85], - bboxMax: [-180, -85, 180, 85], - center: [0, 0], - cursors: { - "static": "default", - pan: "url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move", - click: "crosshair", - zoom: "crosshair", - dragBox: "crosshair", - dragCircle: "crosshair", - drawPoint: "crosshair", - drawLineString: "crosshair", - drawPolygon: "crosshair", - measureLength: "crosshair", - measureArea: "crosshair" - }, - measureLabels: { - length: "{{:length.toFixed( 2 )}} m", - area: "{{:area.toFixed( 2 )}} sq m" - }, - drawStyle: {}, - shapeStyle: {}, - mode: "pan", - pannable: true, - scroll: "default", - shift: "default", - services: [ - { - "class": "osm", - type: "tiled", - src: function (view) { - return "//otile" + ((view.index % 4) + 1) + ((location.protocol === 'https:') ? "-s" : "") + ".mqcdn.com/tiles/1.0.0/osm/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; - }, - attr: 'Tiles Courtesy of MapQuest ' - } - ], - tilingScheme: { - tileWidth: 256, - tileHeight: 256, - levels: 18, - basePixelSize: 156543.03392799936, - origin: [-20037508.342787, 20037508.342787] - }, - axisLayout: "map", - zoom: 0, - zoomMin: 0, - zoomMax: Number.POSITIVE_INFINITY, - zoomFactor: 2, //< determines what a zoom level means - pixelSize: 0 - }; - - $.widget("geo.geomap", { - // private widget members - _$elem: undefined, //< map div for maps, service div for services - _map: undefined, //< only defined in services - _created: false, - _createdGraphics: false, - _widgetId: 0, - _tmplLengthId: "", - _tmplAreaId: "", - - _contentBounds: {}, - - _$resizeContainer: undefined, //< all elements that should match _contentBounds' size - - _$eventTarget: undefined, - _$contentFrame: undefined, - _$existingChildren: undefined, - _$attrList: undefined, - _$servicesContainer: undefined, - _$shapesContainers: undefined, //< all shapesContainer divs (map only) - - _$panContainer: undefined, //< all non-service elements that move while panning - _$shapesContainer: undefined, //< just "our" shapesContainer div (map & service) - _$drawContainer: undefined, - _$measureContainer: undefined, - _$measureLabel: undefined, - - _dpi: 96, - - _currentServices: [], //< internal copy - - _center: undefined, - _pixelSize: undefined, - _centerMax: undefined, - _pixelSizeMax: undefined, - _pixelSizeMin: undefined, - - _userGeodetic: true, - - _centerInteractive: undefined, - _pixelSizeInteractive: undefined, - _timeoutInteractive: null, - _timeoutWheel: null, - _triggerInteractive: false, - - _timeoutRefreshShapes: null, - - _loadCount: 0, - - _wheelLevel: 0, - - _fullZoomFactor: 2, //< interactiveScale factor needed to zoom a whole level - _partialZoomFactor: 1.18920711500273, //< interactiveScale factor needed to zoom a fraction of a level (the fourth root of 2) - - _mouseDown: undefined, - _inOp: undefined, - _toolPan: undefined, - _shiftDown: undefined, - _anchor: undefined, - _current: undefined, - _downDate: undefined, - _moveDate: undefined, - _clickDate: undefined, - _lastMove: undefined, - _lastDrag: undefined, - - _windowHandler: null, - _resizeTimeout: null, - - _panning: undefined, - _velocity: undefined, - _friction: undefined, - - _pointerEvents: undefined, - _supportTouch: undefined, - _softDblClick: undefined, - _isTap: undefined, - _isDbltap: undefined, - - _isMultiTouch: undefined, - _multiTouchAnchor: [], //< TouchList - _multiTouchAnchorBbox: undefined, //< bbox - _multiTouchCurrentBbox: undefined, //< bbox - - _drawTimeout: null, //< used in drawPoint mode so we don't send two shape events on dbltap - _drawPixels: [], //< an array of coordinate arrays for drawing lines & polygons, in pixel coordinates - _drawCoords: [], - - _graphicShapes: [], //< an array of objects containing style object refs & GeoJSON object refs - - _initOptions: {}, - - _options: {}, - - options: $.extend({}, _defaultOptions), - - _createWidget: function (options, element) { - this._$elem = $(element); - - if (this._$elem.is(".geo-service")) { - this._graphicShapes = []; - $.Widget.prototype._createWidget.apply(this, arguments); - return; - } - - this._widgetId = _widgetIdSeed++; - this._serviceIdSeed = 0; - this._tmplLengthId = "geoMeasureLength" + this._widgetId; - this._tmplAreaId = "geoMeasureArea" + this._widgetId; - - this._$elem.addClass("geo-map").css( { - webkitTransform: "translateZ(0)", - touchAction: 'none' - } ); - - this._initOptions = options || {}; - - this._forcePosition(this._$elem); - - this._$elem.css("text-align", "left"); - - var size = this._findMapSize(); - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._createChildren(); - - this._center = [ 0, 0 ]; - this._centerMax = [ 0, 0 ]; - this._centerInteractive = [ 0, 0 ]; - - this.options["pixelSize"] = this._pixelSize = this._pixelSizeMax = 156543.03392799936; - this._pixelSizeMin = this._pixelSizeMax / Math.pow( 2, 17 ); - - this._mouseDown = - this._inOp = - this._toolPan = - this._shiftDown = - this._panning = - this._isTap = - this._isDbltap = - this._isMultiTouch = false; - - this._anchor = [ 0, 0 ]; /* mouse down */ - this._current = [ 0, 0 ]; /* mouse move no matter what */ - this._lastMove = [ 0, 0 ]; - this._lastDrag = [ 0, 0 ]; - this._velocity = [ 0, 0 ]; - - this._friction = [0.8, 0.8]; - - this._downDate = - this._moveDate = - this._clickDate = 0; - - this._drawPixels = []; - this._drawCoords = []; - this._graphicShapes = []; - - - $.Widget.prototype._createWidget.apply(this, arguments); - }, - - _create: function () { - this._options = this.options; - - if (this._$elem.is(".geo-service")) { - this._map = this._$elem.data( "geoMap" ); - this._$elem.data( "geoService", this ); - return; - } - - this._map = this; - - this._pointerEvents = window.PointerEvent; - this._supportTouch = ("ontouchend" in document); - this._softDblClick = this._pointerEvents || this._supportTouch || _ieVersion === 7; - - var geomap = this, - touchStartEvent = this._pointerEvents ? 'pointerdown' : ( this._supportTouch ? "touchstart mousedown" : "mousedown" ), - touchStopEvent = this._pointerEvents ? 'pointerup pointercancel' : ( this._supportTouch ? "touchend touchcancel mouseup" : "mouseup" ), - touchMoveEvent = this._pointerEvents ? 'pointermove' : ( this._supportTouch ? "touchmove mousemove" : "mousemove" ); - - $(document).keydown($.proxy(this._document_keydown, this)); - - if ( this._softDblClick ) { - this._$eventTarget.on( 'softdblclick', $.proxy(this._eventTarget_dblclick, this)); - } else { - this._$eventTarget.dblclick($.proxy(this._eventTarget_dblclick, this)); - } - - this._$eventTarget.bind(touchStartEvent, $.proxy(this._eventTarget_touchstart, this)); - - var dragTarget = (this._$eventTarget[0].setCapture || this._pointerEvents) ? this._$eventTarget : $(document); - dragTarget.bind(touchMoveEvent, $.proxy(this._dragTarget_touchmove, this)); - dragTarget.bind(touchStopEvent, $.proxy(this._dragTarget_touchstop, this)); - - this._$eventTarget.mousewheel($.proxy(this._eventTarget_mousewheel, this)); - - this._windowHandler = function () { - if (geomap._resizeTimeout) { - clearTimeout(geomap._resizeTimeout); - } - geomap._resizeTimeout = setTimeout(function () { - if (geomap._created) { - geomap._$elem.geomap( "resize", true ); - } - }, 500); - }; - - $(window).resize(this._windowHandler); - - this._$drawContainer.geographics({ style: this._initOptions.drawStyle || {}, doubleBuffer: false }); - this._options["drawStyle"] = this._$drawContainer.geographics("option", "style"); - - this._$shapesContainer.geographics( { style: this._initOptions.shapeStyle || { }, doubleBuffer: !_gecko } ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - - if (this._initOptions) { - // always init tilingScheme right away, even if it's null - if ( this._initOptions.tilingScheme !== undefined ) { - this._setOption("tilingScheme", this._initOptions.tilingScheme || null, false); - } - - if ( this._initOptions.services ) { - // jQuery UI Widget Factory merges user services with our default, we want to clobber the default - this._options[ "services" ] = $.merge( [ ], this._initOptions.services ); - } - if (this._initOptions.bboxMax) { - this._setOption("bboxMax", this._initOptions.bboxMax, false); - this._setOption("bbox", this._initOptions.bboxMax, false); - } - if (this._initOptions.zoomMin !== undefined) { - this._setOption("zoomMin", this._initOptions.zoomMin, false); - } - if (this._initOptions.zoomMax !== undefined) { - this._setOption("zoomMax", this._initOptions.zoomMax, false); - } - if (this._initOptions.zoomFactor !== undefined) { - this._setOption("zoomFactor", this._initOptions.zoomFactor, false); - this._fullZoomFactor = this._initOptions.zoomFactor; - this._partialZoomFactor = Math.pow(4, 1 / this._fullZoomFactor); // 4th root of full - } - if (this._initOptions.bbox) { - this._setOption("bbox", this._initOptions.bbox, false); - } - if (this._initOptions.center) { - this._setOption("center", this._initOptions.center, false); - } - if (this._initOptions.zoom !== undefined) { - this._setOption("zoom", this._initOptions.zoom, false); - } - } - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._createServices(); - this._refresh(); - - this._created = true; - }, - - _setOption: function (key, value, refresh) { - if ( key === "pixelSize" ) { - return; - } - - refresh = (refresh === undefined || refresh); - - if ( this._$elem.is( ".geo-map" ) ) { - this._panFinalize(); - } - - var center, pixelSize, bbox, zoom; - - switch (key) { - case "bbox": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2]; - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height); - - // clamp to zoom - zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( center, pixelSize ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( center, pixelSize, false, refresh ); - } - - value = this._getBbox( center, pixelSize ); - break; - - case "bboxMax": - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - break; - - case "center": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( value, this._pixelSizeInteractive ); - this._interactiveTransform( ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( value, this._pixelSize, false, refresh ); - } - break; - - case "measureLabels": - value = $.extend( this._options[ "measureLabels" ], value ); - - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - break; - - case "drawStyle": - if (this._$drawContainer) { - this._$drawContainer.geographics("option", "style", value); - value = this._$drawContainer.geographics("option", "style"); - } - break; - - case "shapeStyle": - if ( this._$elem.is( ".geo-service" ) && !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("option", "style", value); - value = this._$shapesContainer.geographics("option", "style"); - } - break; - - case "mode": - this._resetDrawing( ); - this._$eventTarget.css("cursor", this._options["cursors"][value]); - break; - - case "zoom": - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj; - if ( this._created ) { - this._setZoom(value, false, refresh); - } else { - value = Math.max( value, 0 ); - this._setCenterAndSize( this._center, this._getPixelSize( value ), false, refresh ); - } - break; - } - - $.Widget.prototype._setOption.apply(this, arguments); - - switch ( key ) { - case "bbox": - case "center": - if ( this._userGeodetic ) { - this._options[ "bbox" ] = $.geo.proj.toGeodetic( this._options[ "bbox" ] ); - this._options[ "center" ] = $.geo.proj.toGeodetic( this._center ); - } - break; - - case "tilingScheme": - if ( value !== null ) { - this._pixelSizeMax = this._getPixelSize( 0 ); - this._pixelSizeMin = this._getPixelSize( value.pixelSizes ? value.pixelSizes.length - 1 : value.levels - 1 ); - this._centerMax = [ - value.origin[ 0 ] + this._pixelSizeMax * value.tileWidth / 2, - value.origin[ 1 ] + this._pixelSizeMax * value.tileHeight / 2 - ]; - } - break; - - case "bboxMax": - if ( this._userGeodetic ) { - bbox = $.geo.proj.fromGeodetic( value ); - } else { - bbox = value; - } - - this._centerMax = $.geo.center( bbox ); - this._pixelSizeMax = Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - break; - - case "services": - this._createServices(); - if (refresh) { - this._refresh(); - this._refreshAllShapes(); - } - break; - - case "shapeStyle": - if ( refresh && this._createdGraphics ) { - this._$shapesContainer.geographics("clear"); - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - break; - } - }, - - destroy: function () { - if ( this._$elem.is(".geo-service") ) { - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - } - } else { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - - this._created = false; - - $(window).unbind("resize", this._windowHandler); - - for ( var i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - - this._$drawContainer.geographics("destroy"); - this._$drawContainer = undefined; - - this._$existingChildren.detach(); - this._$elem.html(""); - this._$elem.append(this._$existingChildren); - this._$elem.removeClass("geo-map"); - } - - $.Widget.prototype.destroy.apply(this, arguments); - }, - - toMap: function (p) { - p = this._toMap(p); - return this._userGeodetic ? $.geo.proj.toGeodetic(p) : p; - }, - - toPixel: function ( p, _center /* Internal Use Only */, _pixelSize /* Internal Use Only */ ) { - return this._toPixel( $.geo.proj ? $.geo.proj.fromGeodetic( p ) : p, _center, _pixelSize ); - }, - - opacity: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "opacity", value, this._$elem ); - } else { - if ( value >= 0 || value <= 1 ) { - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - service.style.opacity = value; - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - $.geo[ "_serviceTypes" ][ service.type ].opacity( this, service ); - } - } - } - } - }, - - toggle: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "toggle", value, this._$elem ); - } else { - - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - if ( value === undefined ) { - // toggle visibility - value = ( service.style.visibility !== "visible" ); - } - - service.style.visibility = ( value ? "visible" : "hidden" ); - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - service.serviceContainer.toggle( value ); - - if ( value ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service ); - } - } - } - } - }, - - zoom: function (numberOfLevels) { - if (numberOfLevels !== null) { - this._setZoom(this._options["zoom"] + numberOfLevels, false, true); - } - }, - - refresh: function ( force, _serviceContainer ) { - if ( !this._panning ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "refresh", force, this._$elem ); - } else { - this._refresh( force, _serviceContainer ); - this._refreshAllShapes( _serviceContainer ); - } - } - }, - - resize: function ( _trigger /* Internal Use Only */ ) { - var size = this._findMapSize(), - dx = size["width"]/2 - this._contentBounds.width/2, - dy = size["height"]/2 - this._contentBounds.height/2, - i; - - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._$resizeContainer.css( { - width: size["width"], - height: size["height"] - } ); - - for (i = 0; i < this._currentServices.length; i++) { - $.geo["_serviceTypes"][this._currentServices[i].type].resize(this, this._currentServices[i], dx, dy); - } - - this._$elem.find( ".geo-graphics" ).css( { - width: size["width"], - height: size["height"] - }).geographics( "resize", dx, dy ); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._setCenterAndSize(this._center, this._pixelSize, _trigger, true); - }, - - append: function ( shape /* , style, label, refresh */ ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - if ( !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - var shapes, arg, i, realStyle, realLabel, realRefresh; - - if ( $.isArray( shape ) ) { - shapes = shape; - } else if ( shape.type === "FeatureCollection" ) { - shapes = shape.features; - } else { - shapes = [ shape ]; - } - - for ( i = 1; i < arguments.length; i++ ) { - arg = arguments[ i ]; - - if ( arg !== null ) { - if ( typeof arg === "object" ) { - realStyle = arg; - } else if ( typeof arg === "number" || typeof arg === "string" ) { - realLabel = arg; - } else if ( typeof arg === "boolean" ) { - realRefresh = arg; - } - } - } - - for ( i = 0; i < shapes.length; i++ ) { - if ( !$.data( shapes[ i ], "geoBbox" ) ) { - var bbox = $.geo.bbox( shapes[ i ] ); - if ( $.geo.proj && $.geo._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - $.data( shapes[ i ], "geoBbox", bbox ); - } - - this._graphicShapes.push( { - shape: shapes[ i ], - style: realStyle, - label: realLabel - } ); - } - - if ( realRefresh === undefined || realRefresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - empty: function ( refresh ) { - this._graphicShapes = []; - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - }, - - find: function ( selector, pixelTolerance ) { - if ( this._timeoutInteractive ) { - return []; - } - - var isPoint = $.isPlainObject( selector ), - //searchPixel = isPoint ? this._map.toPixel( selector.coordinates ) : undefined, - mapTol = this._map._pixelSize * pixelTolerance, - result = [], - graphicShape, - geometries, - curGeom, - i; - - if ( this._$elem.is( ".geo-map" ) ) { - $( this._$elem.find( ".geo-service" ).get().reverse() ).each( function( ) { - result = $.merge( result, $( this ).geomap( "find", selector, pixelTolerance ) ); - } ); - } - - for ( i = this._graphicShapes.length - 1; i >= 0; i-- ) { - graphicShape = this._graphicShapes[ i ]; - - if ( isPoint ) { - if ( graphicShape.shape.type === "Point" ) { - if ( $.geo.distance( graphicShape.shape, selector ) <= mapTol ) { - result.push( graphicShape.shape ); - } - } else { - var bbox = $.data( graphicShape.shape, "geoBbox" ), - bboxPolygon = { - type: "Polygon", - coordinates: [ [ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ] ] - }, - projectedPoint = { - type: "Point", - coordinates: $.geo.proj && $.geo._isGeodetic( selector.coordinates ) ? $.geo.proj.fromGeodetic( selector.coordinates ) : selector.coordinates - }; - - if ( $.geo.distance( bboxPolygon, projectedPoint, true ) <= mapTol ) { - geometries = $.geo._basic( graphicShape.shape ); - for ( curGeom = 0; curGeom < geometries.length; curGeom++ ) { - if ( $.geo.distance( geometries[ curGeom ], selector ) <= mapTol ) { - result.push( graphicShape.shape ); - break; - } - } - } - } - } else { - result.push( graphicShape.shape ); - } - } - - return result; - }, - - remove: function ( shape, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - var shapes = $.isArray( shape ) ? shape : [ shape ], - rest; - - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - if ( $.inArray( this._graphicShapes[ i ].shape, shapes ) >= 0 ) { - rest = this._graphicShapes.slice( i + 1 ); - this._graphicShapes.length = i; - this._graphicShapes.push.apply( this._graphicShapes, rest ); - i--; - } - } - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - _getBbox: function (center, pixelSize) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - // calculate the internal bbox - var halfWidth = this._contentBounds[ "width" ] / 2 * pixelSize, - halfHeight = this._contentBounds[ "height" ] / 2 * pixelSize; - return [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - }, - - _setBbox: function (value /* , trigger, refresh */ ) { - var center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2], - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height), - zoom = this._getZoom( center, pixelSize ); - - // clamp to zoom - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._setInteractiveCenterAndSize( center, pixelSize ); - this._interactiveTransform( ); - }, - - _getBboxMax: function () { - // calculate the internal bboxMax - var halfWidth = this._contentBounds["width"] / 2 * this._pixelSizeMax, - halfHeight = this._contentBounds["height"] / 2 * this._pixelSizeMax; - return [this._centerMax[0] - halfWidth, this._centerMax[1] - halfHeight, this._centerMax[0] + halfWidth, this._centerMax[1] + halfHeight]; - }, - - _getCenter: function () { - return this._center; - }, - - _getContentBounds: function () { - return this._contentBounds; - }, - - _getServicesContainer: function () { - return this._$servicesContainer; - }, - - _getZoom: function ( center, pixelSize ) { - // calculate the internal zoom level, vs. public zoom property - // this does not take zoomMin or zoomMax into account - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var tilingScheme = this._options["tilingScheme"]; - if ( tilingScheme ) { - if ( tilingScheme.pixelSizes ) { - var roundedPixelSize = Math.floor(pixelSize * 1000), - levels = tilingScheme.pixelSizes.length, - i = levels - 1; - - for ( ; i >= 0; i-- ) { - if ( Math.floor( tilingScheme.pixelSizes[ i ] * 1000 ) >= roundedPixelSize ) { - return i; - } - } - - return 0; - } else { - return Math.round( Math.log( tilingScheme.basePixelSize / pixelSize) / Math.log( 2 ) ); - } - } else { - var ratio = this._contentBounds["width"] / this._contentBounds["height"], - bbox = $.geo.reaspect( this._getBbox( center, pixelSize ), ratio, true ), - bboxMax = $.geo.reaspect(this._getBboxMax(), ratio, true); - - return Math.round( Math.log($.geo.width(bboxMax, true) / $.geo.width(bbox, true)) / Math.log(this._fullZoomFactor) ); - } - }, - - _setZoom: function ( value, trigger /* , refresh */ ) { - // set the map widget's zoom, taking zoomMin and zoomMax into account - this._clearInteractiveTimeout( ); - - value = Math.min( Math.max( value, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ); - - this._setInteractiveCenterAndSize( this._centerInteractive, this._getPixelSize( value ) ); - this._interactiveTransform( ); - this._setInteractiveTimeout( trigger ); - }, - - _createChildren: function () { - this._$existingChildren = this._$elem.children(); - - this._forcePosition(this._$existingChildren); - - this._$existingChildren.detach().css( { - mozUserSelect: "none" - } ); - - - var contentSizeCss = "width:" + this._contentBounds["width"] + "px; height:" + this._contentBounds["height"] + "px; margin:0; padding:0;", - contentPosCss = "position:absolute; left:0; top:0;"; - - this._$elem.prepend( window.toStaticHTML( '
                    ' ) ); - this._$eventTarget = this._$contentFrame = this._$elem.children(':first'); - - this._$contentFrame.append('
                    '); - this._$servicesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append( '
                      ' ); - this._$attrList = this._$contentFrame.children( ":last" ); - - this._$contentFrame.append('
                      '); - this._$drawContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                      '); - this._$measureContainer = this._$contentFrame.children(':last'); - this._$measureLabel = this._$measureContainer.children(); - - this._$contentFrame.append('
                      '); - this._$shapesContainer = this._$contentFrame.children(':last'); - - this._$panContainer = $( [ this._$shapesContainer[ 0 ], this._$drawContainer[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$resizeContainer = $( [ this._$contentFrame[ 0 ], this._$servicesContainer[ 0 ], this._$eventTarget[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$contentFrame.append(this._$existingChildren); - - if ( ! $("#geo-measure-style").length ) { - $("head").prepend( window.toStaticHTML( '' ) ); - } - }, - - _createServices: function () { - var service, i; - - for ( i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap( "destroy" ); - $.geo[ "_serviceTypes" ][ this._currentServices[ i ].type ].destroy( this, this._$servicesContainer, this._currentServices[ i ] ); - } - - this._currentServices = [ ]; - this._$servicesContainer.html( "" ); - this._$attrList.html( "" ); - - for ( i = 0; i < this._options[ "services" ].length; i++ ) { - service = this._currentServices[ i ] = $.extend( { }, this._options[ "services" ][ i ] ); - - // keep a reference to the original - service.serviceObject = this._options[ "services" ][ i ]; - - // default the service style property on our copy - service.style = $.extend( { - visibility: "visible", - opacity: 1 - }, service.style ); - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = 'class="geo-service ' + ( service["class"] ? service["class"] : '' ) + '"', - scHtml = '
                      ', - serviceContainer; - - this._$servicesContainer.append( window.toStaticHTML( scHtml ) ); - serviceContainer = this._$servicesContainer.children( ":last" ); - service.serviceContainer = serviceContainer; - - $.geo[ "_serviceTypes" ][ service.type ].create( this, serviceContainer, service, i ); - - serviceContainer.data( "geoMap", this ).geomap(); - - if ( service.attr ) { - this._$attrList.append( '
                    • ' + service.attr + '
                    • ' ); - } - } - - // start with our map-level shapesContainer - this._$shapesContainers = this._$shapesContainer; - - this._$attrList.find( "a" ).css( { - position: "relative", - zIndex: 1, - display: "inline-block", - webkitTransform: "translateZ(0)" - } ); - }, - - _createServiceGraphics: function( ) { - // only called in the context of a service-level geomap - var $contentFrame = this._$elem.closest( ".geo-content-frame" ); - this._$elem.append('
                      '); - this._$shapesContainer = this._$elem.children(':last'); - - this._map._$shapesContainers = this._map._$shapesContainers.add( this._$shapesContainer ); - - this._$shapesContainer.geographics( { doubleBuffer: !_gecko }); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - }, - - _refreshDrawing: function ( ) { - this._$drawContainer.geographics("clear"); - - if ( this._drawPixels.length > 0 ) { - var mode = this._options[ "mode" ], - pixels = this._drawPixels, - coords = this._drawCoords, - label, - labelShape, - labelPixel, - widthOver, - heightOver; - - switch ( mode ) { - case "measureLength": - mode = "drawLineString"; - labelShape = { - type: "LineString", - coordinates: coords - }; - label = $.render[ this._tmplLengthId ]( { length: $.geo.length( labelShape, true ) } ); - labelPixel = $.merge( [], pixels[ pixels.length - 1 ] ); - break; - - case "measureArea": - mode = "drawPolygon"; - - labelShape = { - type: "Polygon", - coordinates: [ $.merge( [ ], coords ) ] - }; - labelShape.coordinates[ 0 ].push( coords[ 0 ] ); - - label = $.render[ this._tmplAreaId ]( { area: $.geo.area( labelShape, true ) } ); - labelPixel = this._toPixel( $.geo.centroid( labelShape ).coordinates ); - pixels = [ pixels ]; - break; - - case "drawPolygon": - pixels = [ pixels ]; - break; - } - - this._$drawContainer.geographics( mode, pixels ); - - if ( label ) { - this._$measureLabel.html( label ); - - widthOver = this._contentBounds.width - ( this._$measureLabel.outerWidth( true ) + labelPixel[ 0 ] ); - heightOver = this._contentBounds.height - ( this._$measureLabel.outerHeight( true ) + labelPixel[ 1 ] ); - - if ( widthOver < 0 ) { - labelPixel[ 0 ] += widthOver; - } - - if ( heightOver < 0 ) { - labelPixel[ 1 ] += heightOver; - } - - this._$measureLabel.css( { - left: Math.max( labelPixel[ 0 ], 0 ), - top: Math.max( labelPixel[ 1 ], 0 ) - } ).show(); - } - } - }, - - _resetDrawing: function () { - this._drawPixels = []; - this._drawCoords = []; - this._$drawContainer.geographics("clear"); - this._$measureLabel.hide(); - }, - - _refreshAllShapes: function ( _serviceContainer ) { - this._timeoutRefreshShapes = null; - - var service, - geoService, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - geoService = service.serviceContainer.data( "geoService" ); - - if ( geoService._createdGraphics ) { - geoService._$shapesContainer.geographics( "clear" ); - if ( geoService._graphicShapes.length > 0 ) { - geoService._refreshShapes( geoService._$shapesContainer, geoService._graphicShapes, geoService._graphicShapes, geoService._graphicShapes ); - } - } - } - } - - if ( this._createdGraphics && !_serviceContainer ) { - this._$shapesContainer.geographics( "clear" ); - if ( this._graphicShapes.length > 0 ) { - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - } - }, - - - _refreshShapes: function (geographics, shapes, styles, labels, center, pixelSize) { - var i, mgi, - shape, - shapeBbox, - style, - label, - hasLabel, - labelPixel, - centroid, - bbox = this._map._getBbox(center, pixelSize); - - for (i = 0; i < shapes.length; i++) { - shape = shapes[i].shape || shapes[i]; - shape = shape.geometry || shape; - shapeBbox = $.data(shape, "geoBbox"); - - if ( shapeBbox && $.geo._bboxDisjoint( bbox, shapeBbox ) ) { - continue; - } - - style = $.isArray(styles) ? styles[i].style : styles; - label = $.isArray(labels) ? labels[i].label : labels; - hasLabel = ( label !== undefined ); - labelPixel = undefined; - centroid = $.geo.centroid( shape ); - - switch (shape.type) { - case "Point": - labelPixel = this._map.toPixel( shape.coordinates, center, pixelSize ); - this._$shapesContainer.geographics("drawPoint", labelPixel, style); - break; - case "LineString": - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.pointAlong( shape, 0.5 ).coordinates, center, pixelSize ); - } - break; - case "Polygon": - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiPoint": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPoint", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiLineString": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiPolygon": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - - case "GeometryCollection": - this._refreshShapes(geographics, shape.geometries, style, label, center, pixelSize); - break; - } - - if ( hasLabel && labelPixel ) { - this._$shapesContainer.geographics( "drawLabel", labelPixel, label ); - } - } - }, - - _findMapSize: function () { - // really, really attempt to find a size for this thing - // even if it's hidden (look at parents) - var size = { width: 0, height: 0 }, - sizeContainer = this._$elem; - - while (sizeContainer.size() && !(size["width"] > 0 && size["height"] > 0)) { - size = { width: sizeContainer.width(), height: sizeContainer.height() }; - if (size["width"] <= 0 || size["height"] <= 0) { - size = { width: parseInt(sizeContainer.css("width"), 10), height: parseInt(sizeContainer.css("height"), 10) }; - } - sizeContainer = sizeContainer.parent(); - } - return size; - }, - - _forcePosition: function (elem) { - var cssPosition = elem.css("position"); - if (cssPosition !== "relative" && cssPosition !== "absolute" && cssPosition !== "fixed") { - elem.css("position", "relative"); - } - }, - - _getPixelSize: function ( zoom ) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme !== null) { - if (zoom === 0) { - return tilingScheme.pixelSizes ? tilingScheme.pixelSizes[0] : tilingScheme.basePixelSize; - } - - zoom = Math.round(zoom); - zoom = Math.max(zoom, 0); - var levels = tilingScheme.pixelSizes ? tilingScheme.pixelSizes.length : tilingScheme.levels; - zoom = Math.min(zoom, levels - 1); - - if ( tilingScheme.pixelSizes ) { - return tilingScheme.pixelSizes[zoom]; - } else { - return tilingScheme.basePixelSize / Math.pow(2, zoom); - } - } else { - var bbox = $.geo.scaleBy( this._getBboxMax(), 1 / Math.pow( this._fullZoomFactor, zoom ), true ); - return Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - } - }, - - _getZoomCenterAndSize: function ( anchor, zoomDelta, full ) { - var zoomFactor = ( full ? this._fullZoomFactor : this._partialZoomFactor ), - scale = Math.pow( zoomFactor, -zoomDelta ), - pixelSize = this._pixelSizeInteractive * scale; - - if ( this._options[ "tilingScheme" ] ) { - // clamp to min/max pixelSize - pixelSize = Math.min( Math.max( pixelSize, this._pixelSizeMin ), this._pixelSizeMax ); - } - - var zoom = this._getZoom(this._centerInteractive, pixelSize); - - // clamp to zoom - if ( full && this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoomDelta < 0 && zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._pixelSizeInteractive; - } else if ( zoomDelta > 0 && zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._pixelSizeInteractive; - } - } - - var ratio = pixelSize / this._pixelSizeInteractive, - anchorMapCoord = this._toMap( anchor, this._centerInteractive, this._pixelSizeInteractive ), - centerDelta = [(this._centerInteractive[0] - anchorMapCoord[0]) * ratio, (this._centerInteractive[1] - anchorMapCoord[1]) * ratio], - scaleCenter = [anchorMapCoord[0] + centerDelta[0], anchorMapCoord[1] + centerDelta[1]]; - - return { pixelSize: pixelSize, center: scaleCenter }; - }, - - _panFinalize: function () { - if (this._panning) { - this._velocity = [0, 0]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._inOp = false; - this._anchor = this._current; - this._mouseDown = this._toolPan = this._panning = false; - } - }, - - _panMove: function () { - if ( ! this._options[ "pannable" ] ) { - return; - } - - var dx = this._current[0] - this._lastDrag[0], - dy = this._current[1] - this._lastDrag[1]; - - if (this._toolPan || dx > 3 || dx < -3 || dy > 3 || dy < -3) { - if (!this._toolPan) { - this._toolPan = true; - this._$eventTarget.css("cursor", this._options["cursors"]["pan"]); - } - - if (this._mouseDown) { - this._velocity = [dx, dy]; - } - - if (dx !== 0 || dy !== 0) { - this._panning = true; - this._lastDrag = this._current; - - this._centerInteractive[ 0 ] -= ( dx * this._pixelSizeInteractive ); - this._centerInteractive[ 1 ] += ( ( this._options[ "axisLayout" ] === "image" ? -1 : 1 ) * dy * this._pixelSizeInteractive ); - this._setInteractiveCenterAndSize( this._centerInteractive, this._pixelSizeInteractive ); - this._interactiveTransform( ); - } - } - }, - - _clearInteractiveTimeout: function() { - if ( this._timeoutRefreshShapes ) { - clearTimeout( this._timeoutRefreshShapes ); - this._timeoutRefreshShapes = null; - } - - if ( this._timeoutInteractive ) { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - return true; - } else { - this._centerInteractive[ 0 ] = this._center[ 0 ]; - this._centerInteractive[ 1 ] = this._center[ 1 ]; - this._pixelSizeInteractive = this._pixelSize; - return false; - } - }, - - _interactiveTransform: function( ) { - var service, - - scalePixelSize = this._pixelSize, - scaleRatio = scalePixelSize / this._pixelSizeInteractive; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = this._toMap( [ 0, 0 ] ), - newPixelPoint = this._toPixel( oldMapOrigin, this._centerInteractive, this._pixelSizeInteractive ); - - - this._$shapesContainers.geographics("interactiveTransform", newPixelPoint, scaleRatio); - } - - for ( var i = 0; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo[ "_serviceTypes" ][ service.type ].interactiveTransform( this, service, this._centerInteractive, this._pixelSizeInteractive ); - } - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel( this._drawCoords, this._centerInteractive, this._pixelSizeInteractive ); - this._refreshDrawing(); - } - }, - - _interactiveTimeout: function( ) { - if ( this._isMultiTouch ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - } else if ( this._created && this._timeoutInteractive ) { - this._setCenterAndSize( this._centerInteractive, this._pixelSizeInteractive, this._triggerInteractive, true ); - this._timeoutInteractive = null; - this._triggerInteractive = false; - - this._timeoutRefreshShapes = setTimeout( $.proxy( this._refreshAllShapes, this ), 128 ); - } - }, - - _setInteractiveTimeout: function( trigger ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - this._triggerInteractive |= trigger; - }, - - _refresh: function ( force, _serviceContainer ) { - var service, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service, force ); - } - } - }, - - _setInteractiveCenterAndSize: function ( center, pixelSize ) { - // set the temporary (interactive) center & size - // also, update the public-facing options - // this does not take zoomMin or zoomMax into account - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - this._pixelSizeInteractive = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox( center, pixelSize ) ); - this._options["center"] = $.geo.proj.toGeodetic( center ); - } else { - this._options["bbox"] = this._getBbox( center, pixelSize ); - this._options["center"][ 0 ] = center[ 0 ]; - this._options["center"][ 1 ] = center[ 1 ]; - } - - this._options["pixelSize"] = pixelSize; - this._options["zoom"] = this._getZoom( center, pixelSize ); - }, - - _setCenterAndSize: function (center, pixelSize, trigger, refresh) { - if ( ! $.isArray( center ) || center.length !== 2 || typeof center[ 0 ] !== "number" || typeof center[ 1 ] !== "number" ) { - return; - } - - // the final call during any extent change - // only called by timeoutInteractive & resize - // clamp to zoom - var zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - - if ( this._created ) { - // one last interactiveTransform to put pinched map into place - this._interactiveTransform( ); - } - - this._options["pixelSize"] = this._pixelSize = pixelSize; - - this._center[ 0 ] = center[ 0 ]; - this._center[ 1 ] = center[ 1 ]; - - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox() ); - this._options["center"] = $.geo.proj.toGeodetic( this._center ); - } else { - this._options["bbox"] = this._getBbox(); - this._options["center"] = $.merge( [ ], center ); - } - - this._options["zoom"] = zoom; - - if (trigger) { - this._trigger("bboxchange", window.event, { bbox: $.merge( [ ], this._options["bbox"] ) }); - } - - if (refresh) { - this._refresh(); - this._refreshAllShapes( ); - this._refreshDrawing(); - } - }, - - _requestQueued: function ( ) { - if ( this._loadCount === 0 ) { - this._trigger( "loadstart", window.event ); - } - this._loadCount++; - }, - - _requestComplete: function ( ) { - this._loadCount--; - if ( this._loadCount <= 0 ) { - this._loadCount = 0; - this._trigger( "loadend", window.event ); - } - }, - - _toMap: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - xRatio = $.geo.width(bbox, true) / width, - yRatio = $.geo.height(bbox, true) / height, - yOffset, - image = this._options[ "axisLayout" ] === "image", - result = [], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - yOffset = (p[ i ][ j ][ k ][1] * yRatio); - result[ i ][ j ][ k ] = [ - bbox[ 0 ] + ( p[ i ][ j ][ k ][ 0 ] * xRatio ), - image ? bbox[ 1 ] + yOffset : bbox[ 3 ] - yOffset - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _toPixel: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - bboxWidth = $.geo.width(bbox, true), - bboxHeight = $.geo.height(bbox, true), - image = this._options[ "axisLayout" ] === "image", - xRatio = width / bboxWidth, - yRatio = height / bboxHeight, - result = [ ], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = [ - Math.round( ( p[ i ][ j ][ k ][ 0 ] - bbox[ 0 ] ) * xRatio ), - Math.round( ( image ? p[ i ][ j ][ k ][ 1 ] - bbox[ 1 ] : bbox[ 3 ] - p[ i ][ j ][ k ][ 1 ] ) * yRatio ) - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _document_keydown: function (e) { - var len = this._drawCoords.length; - if (len > 0 && e.which === 27) { - if (len <= 2) { - this._resetDrawing(); - this._inOp = false; - } else { - this._drawCoords[len - 2] = $.merge( [], this._drawCoords[ len - 1 ] ); - this._drawPixels[len - 2] = $.merge( [], this._drawPixels[ len - 1 ] ); - - this._drawCoords.length--; - this._drawPixels.length--; - - this._refreshDrawing(); - } - } - }, - - _eventTarget_dblclick_zoom: function(e) { - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - this._trigger("dblclick", e, { type: "Point", coordinates: this._toMap(this._current, this._centerInteractive, this._pixelSizeInteractive ) }); - - if (!e.isDefaultPrevented()) { - var centerAndSize = this._getZoomCenterAndSize(this._current, 1, true ); - - this._setInteractiveCenterAndSize( centerAndSize.center, centerAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - }, - - _eventTarget_dblclick: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - switch (this._options["mode"]) { - case "drawLineString": - case "measureLength": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] === this._drawCoords[1][0] && - this._drawCoords[0][1] === this._drawCoords[1][1] ) ) { - this._drawCoords.length--; - this._trigger( "shape", e, { - type: "LineString", - coordinates: this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords - } ); - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "drawPolygon": - case "measureArea": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] === this._drawCoords[1][0] && - this._drawCoords[0][1] === this._drawCoords[1][1] ) ) { - var endIndex = this._drawCoords.length - 1; - if (endIndex > 2) { - this._drawCoords[endIndex] = $.merge( [], this._drawCoords[0] ); - this._trigger( "shape", e, { - type: "Polygon", - coordinates: [ this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords ] - } ); - } - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - default: - this._eventTarget_dblclick_zoom(e); - break; - } - - this._inOp = false; - }, - - _eventTarget_touchstart: function (e) { - if ( typeof( document.elementFromPoint ) !== "undefined" ) { - var elFromPt = document.elementFromPoint( e.pageX, e.pageY ); - if ( elFromPt && elFromPt.nodeName === "A" ) { - return; - } - } - - var mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ); - - if ( mode === "static" ) { - return; - } - - if ( !this._pointerEvents && !this._supportTouch && e.which !== 1 ) { - return; - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var offset = $(e.currentTarget).offset(), - touches = e.originalEvent.changedTouches; - - if ( this._pointerEvents ) { - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 ) { - // switch to multitouch - e.currentTarget.setPointerCapture( e.originalEvent.pointerId ); - - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( e.originalEvent ); - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._anchor = $.geo.center( this._multiTouchCurrentBbox, true ); - this._current = $.merge( [], this._anchor ); - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - } else if ( this._multiTouchAnchor.length < 2 ) { - e.currentTarget.setPointerCapture( e.originalEvent.pointerId ); - - this._multiTouchAnchor.push( e.originalEvent ); - - this._multiTouchCurrentBbox = [ - this._multiTouchAnchor[0].pageX - offset.left, - this._multiTouchAnchor[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ this._multiTouchAnchor[0].pageX - offset.left, this._multiTouchAnchor[0].pageY - offset.top ]; - } - } else if ( this._supportTouch && touches ) { - this._multiTouchAnchor = $.merge( [ ], touches ); - - this._isMultiTouch = this._multiTouchAnchor.length > 1; - - if ( this._isMultiTouch ) { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - touches[1].pageX - offset.left, - touches[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ touches[0].pageX - offset.left, touches[0].pageY - offset.top ]; - } - } else { - this._current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - var downDate = $.now(); - if (downDate - this._downDate < 750) { - if (this._isTap) { - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance > 8) { - this._isTap = false; - } else { - this._current = $.merge( [ ], this._anchor ); - } - } - - if (this._isDbltap) { - this._isDbltap = false; - } else { - this._isDbltap = this._isTap; - } - } else { - this._isDbltap = false; - } - this._isTap = true; - this._downDate = downDate; - } - - this._mouseDown = true; - this._anchor = $.merge( [ ], this._current ); - - if (!this._inOp && e.shiftKey && shift !== "off") { - this._shiftDown = true; - this._$eventTarget.css( "cursor", this._options[ "cursors" ][ shift === "default" ? defaultShift : shift ] ); - } else if ( !this._isMultiTouch && ( this._options[ "pannable" ] || mode === "dragBox" || mode === "dragCircle" ) ) { - this._inOp = true; - - if ( mode !== "zoom" && mode !== "dragBox" && mode !== "dragCircle" ) { - this._lastDrag = this._current; - - if (e.currentTarget.setCapture) { - e.currentTarget.setCapture(); - } - } - } - - e.preventDefault(); - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - }, - - _dragTarget_touchmove: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - var doInteractiveTimeout = false; - if ( this._mouseDown ) { - doInteractiveTimeout = this._clearInteractiveTimeout( ); - } - - var offset = this._$eventTarget.offset(), - drawCoordsLen = this._drawCoords.length, - touches = e.originalEvent.changedTouches, - current = null, - anchorDistance, - currentDistance, - wheelLevel, - delta, - pinchCenterAndSize, - i; - - if ( this._pointerEvents ) { - if ( this._isMultiTouch ) { - if ( e.originalEvent.pointerId === this._multiTouchAnchor[ 0 ].pointerId ) { - this._multiTouchCurrentBbox[ 0 ] = e.originalEvent.pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = e.originalEvent.pageY - offset.top; - } else if ( e.originalEvent.pointerId === this._multiTouchAnchor[ 1 ].pointerId ) { - this._multiTouchCurrentBbox[ 2 ] = e.originalEvent.pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = e.originalEvent.pageY - offset.top; - } else { - // untracked pointer - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ); - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - } else { - this._multiTouchAnchor[ 0 ] = e.originalEvent; - - this._multiTouchCurrentBbox = [ - this._multiTouchAnchor[0].pageX - offset.left, - this._multiTouchAnchor[0].pageY - offset.top, - NaN, - NaN - ]; - - current = [e.originalEvent.pageX - offset.left, e.originalEvent.pageY - offset.top]; - } - } else if ( this._supportTouch && touches ) { - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 && touches[ 0 ].identifier !== this._multiTouchAnchor[ 0 ].identifier ) { - // switch to multitouch - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( touches[ 0 ] ); - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._anchor = this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - if ( this._isMultiTouch ) { - - for ( i = 0; i < touches.length; i++ ) { - if ( touches[ i ].identifier === this._multiTouchAnchor[ 0 ].identifier ) { - this._multiTouchCurrentBbox[ 0 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = touches[ i ].pageY - offset.top; - } else if ( touches[ i ].identifier === this._multiTouchAnchor[ 1 ].identifier ) { - this._multiTouchCurrentBbox[ 2 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = touches[ i ].pageY - offset.top; - } - } - - anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ); - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if ( current === null ) { - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - if (current[0] === this._lastMove[0] && current[1] === this._lastMove[1]) { - if ( this._inOp ) { - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } else { - // fixes: [bug] highlight pop - return false; - } - } - - if ( _ieVersion === 7 ) { - this._isDbltap = this._isTap = false; - } - - if (this._mouseDown) { - this._current = current; - this._moveDate = $.now(); - } - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - var mode = this._options["mode"], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - dx, dy, circleSize; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - switch (mode) { - case "zoom": - case "dragBox": - if ( this._mouseDown ) { - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawBbox", [ - this._anchor[ 0 ], - this._anchor[ 1 ], - current[ 0 ], - current[ 1 ] - ] ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "dragCircle": - if ( this._mouseDown ) { - dx = current[ 0 ] - this._anchor[ 0 ]; - dy = current[ 1 ] - this._anchor[ 1 ]; - circleSize = Math.sqrt( ( dx * dx) + ( dy * dy ) ) * 2; - //circleSize = Math.max( Math.abs( current[ 0 ] - this._anchor[ 0 ] ), Math.abs( current[ 1 ] - this._anchor[ 1 ] ) ) * 2; - - // not part of _refreshDrawing - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawArc", this._anchor, 0, 360, { - width: circleSize, - height: circleSize - } ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - if (drawCoordsLen > 0) { - this._drawCoords[drawCoordsLen - 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[drawCoordsLen - 1] = current; - - this._refreshDrawing(); - } - - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - default: - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - } - - this._lastMove = current; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchstop: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if ( !this._mouseDown ) { - if ( _ieVersion === 7 ) { - // ie7 doesn't appear to trigger dblclick on this._$eventTarget, - // we fake regular click here to cause soft dblclick - this._eventTarget_touchstart(e); - } else { - // Chrome & Firefox trigger a rogue mouseup event when doing a dblclick maximize in Windows(/Linux?) - // ignore it - return; - } - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var mouseWasDown = this._mouseDown, - wasToolPan = this._toolPan, - offset = this._$eventTarget.offset(), - mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - current = null, i, clickDate, - dx, dy, - coordBuffer, - triggerShape; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - if ( this._pointerEvents ) { - if ( e.originalEvent.pointerId === this._multiTouchAnchor[ 0 ].pointerId || e.originalEvent.pointerId === this._multiTouchAnchor[ 1 ].pointerId ) { - e.currentTarget.releasePointerCapture( e.originalEvent.pointerId ); - - current = [e.originalEvent.pageX - offset.left, e.originalEvent.pageY - offset.top]; - - this._multiTouchAnchor = []; - this._inOp = false; - } else { - // untracked pointer - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return; - } - - } else if (this._supportTouch && e.originalEvent.changedTouches) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - this._multiTouchAnchor = []; - this._inOp = false; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - if (this._isTap) { - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - if (Math.sqrt((dx * dx) + (dy * dy)) <= 8) { - current = $.merge( [ ], this._anchor ); - } - } - } - - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._shiftDown = this._mouseDown = this._toolPan = false; - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isMultiTouch = false; - - this._wheelLevel = 0; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return; - } - - if (document.releaseCapture) { - document.releaseCapture(); - } - - if (mouseWasDown) { - clickDate = $.now(); - this._current = current; - - switch ( mode ) { - case "zoom": - case "dragBox": - if ( dx !== 0 || dy !== 0 ) { - var minSize = this._pixelSize * 6, - bboxCoords = this._toMap( [ this._anchor, current ] ), - bbox = [ - Math.min( bboxCoords[0][0], bboxCoords[1][0] ), - Math.min( bboxCoords[0][1], bboxCoords[1][1] ), - Math.max( bboxCoords[0][0], bboxCoords[1][0] ), - Math.max( bboxCoords[0][1], bboxCoords[1][1] ) - ]; - - if ( mode === "zoom" ) { - if ( ( bbox[2] - bbox[0] ) < minSize && ( bbox[3] - bbox[1] ) < minSize ) { - bbox = $.geo.scaleBy( this._getBbox( $.geo.center( bbox, true ) ), 0.5, true ); - } - - this._setBbox(bbox, true, true); - doInteractiveTimeout = true; - } else { - triggerShape = $.geo.polygonize( bbox, true ); - triggerShape.bbox = bbox; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - this._trigger( "shape", e, triggerShape ); - } - } else { - if ( mode === "dragBox" ) { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - } - - this._resetDrawing(); - break; - - case "dragCircle": - if ( dx !== 0 || dy !== 0 ) { - var image = this._options[ "axisLayout" ] === "image", - d = Math.sqrt( ( dx * dx) + ( dy * dy ) ), - n = 180, - a; - - this._drawPixels.length = n + 1; - - for ( i = 0; i < n; i++ ) { - a = ( i * 360 / n ) * ( Math.PI / 180 ); - this._drawPixels[ i ] = [ - this._anchor[ 0 ] + Math.cos( a ) * d, - this._anchor[ 1 ] + Math.sin( a ) * d - ]; - } - - this._drawPixels[ n ] = [ - this._drawPixels[ 0 ][ 0 ], - this._drawPixels[ 0 ][ 1 ] - ]; - - // using coordBuffer for bbox coords - coordBuffer = this._toMap( [ - [ this._anchor[ 0 ] - d, this._anchor[ 1 ] + ( image ? -d : d ) ], - [ this._anchor[ 0 ] + d, this._anchor[ 1 ] + ( image ? d : -d ) ] - ] ); - - triggerShape = { - type: "Polygon", - coordinates: [ this._toMap( this._drawPixels ) ], - bbox: [ coordBuffer[ 0 ][ 0 ], coordBuffer[ 0 ][ 1 ], coordBuffer[ 1 ][ 0 ], coordBuffer[ 1 ][ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - - this._resetDrawing(); - } else { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - break; - - case "drawPoint": - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - var geomap = this; - this._drawTimeout = setTimeout(function () { - if (geomap._drawTimeout) { - geomap._trigger("shape", e, { type: "Point", coordinates: geomap.toMap(current) }); - geomap._inOp = false; - geomap._drawTimeout = null; - } - }, 250); - } - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (wasToolPan) { - this._panFinalize(); - } else { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - - if (!e.isDefaultPrevented()) { - i = (this._drawCoords.length === 0 ? 0 : this._drawCoords.length - 1); - - this._drawCoords[i] = this._toMap(current); - this._drawPixels[i] = current; - - if (i < 2 || !(this._drawCoords[i][0] === this._drawCoords[i-1][0] && - this._drawCoords[i][1] === this._drawCoords[i-1][1])) { - this._drawCoords[i + 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[i + 1] = current; - } - - this._refreshDrawing(); - } - } - break; - - default: - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - this._inOp = false; - } - } - break; - } - - this._clickDate = clickDate; - - if (this._softDblClick && this._isDbltap) { - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - this._$eventTarget.trigger("softdblclick", e); - return false; - } - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _eventTarget_mousewheel: function ( e ) { - if ( this._options[ "mode" ] === "static" || this._options[ "scroll" ] === "off" ) { - return; - } - - e.preventDefault(); - - if ( this._mouseDown ) { - return false; - } - - if ( e.deltaY !== 0 ) { - if ( this._timeoutWheel ) { - clearTimeout( this._timeoutWheel ); - this._timeoutWheel = null; - } - - var geomap = this; - var currentTarget = e.currentTarget; - var deltaY = e.deltaY; - var pageX = e.pageX; - var pageY = e.pageY; - - this._timeoutWheel = setTimeout( function () { - geomap._clearInteractiveTimeout( ); - - var delta = deltaY > 0 ? 1 : -1; - - var offset = $(currentTarget).offset(); - geomap._anchor = [pageX - offset.left, pageY - offset.top]; - - var wheelCenterAndSize = geomap._getZoomCenterAndSize( geomap._anchor, delta, geomap._options[ "tilingScheme" ] !== null ); - - geomap._setInteractiveCenterAndSize( wheelCenterAndSize.center, wheelCenterAndSize.pixelSize ); - geomap._interactiveTransform( ); - - geomap._setInteractiveTimeout( true ); - }, 30 ); - - } - - return false; - } - } - ); -}(jQuery, window)); - - -(function ($, window, undefined) { - $.geo._serviceTypes.tiled = (function () { - var rTmplString = new RegExp( "<.*>|{{.*}}" ); - - return { - _serviceId: 0, - _tmplGeoSrcId: "", - - - create: function (map, serviceContainer, service /* , index */) { - this._serviceId = map._serviceIdSeed++; - this._tmplGeoSrcId = "geoSrc" + this._serviceId; - - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0, - reloadTiles: false - }; - - var scHtml = '
                      '; - - serviceContainer.append( window.toStaticHTML( scHtml ) ); - - serviceState.serviceContainer = serviceContainer.children( ":last" ); - - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - //console.log( "tiled.interactiveTransform( " + center.join( ", " ) + ", " + pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ), - tilingScheme = map.options[ "tilingScheme" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data("pixelSize"), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapCoord = $scaleContainer.data("scaleOrigin"), - newPixelPoint = map._toPixel(oldMapCoord, center, pixelSize); - - $scaleContainer.css( { - left: Math.round(newPixelPoint[0]) + "px", - top: Math.round(newPixelPoint[1]) + "px", - width: tilingScheme.tileWidth * scaleRatio, - height: tilingScheme.tileHeight * scaleRatio - } ); - - /* - if ( $("body")[0].filters !== undefined ) { - $scaleContainer.children().each( function ( i ) { - $( this ).css( "filter", "progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11=" + scaleRatio + ",M22=" + scaleRatio + ",sizingmethod='auto expand')" ); - } ); - } - */ - } - }); - } - }, - - refresh: function (map, service, force) { - //console.log( "tiled.refresh( " + map._center.join( ", " ) + ", " + map._pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ); - - this._cancelUnloaded(map, service); - - if ( serviceState && force ) { - // if hidden atm, we want to make sure we reload this service after it becomes visible - serviceState.reloadTiles = true; - } - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - $serviceContainer = serviceState.serviceContainer, - - image = map.options[ "axisLayout" ] === "image", - ySign = image ? +1 : -1, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - - tileX = Math.floor((bbox[0] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.max( Math.floor( ( image ? bbox[1] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 3 ] ) / (pixelSize * tileHeight) ), 0 ), - tileX2 = Math.ceil((bbox[2] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil( ( image ? bbox[3] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 1 ] ) / (pixelSize * tileHeight) ), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] + ySign * bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMinOrMaxY = tilingScheme.origin[1] + ySign * (fullYAtScale * tileHeight) * pixelSize, - - serviceLeft = Math.round((fullXMinX - bbox[0]) / pixelSize), - serviceTop = Math.round( ( image ? fullYMinOrMaxY - bbox[1] : bbox[3] - fullYMinOrMaxY ) / pixelSize), - - scaleContainers = $serviceContainer.children().show(), - scaleContainer = scaleContainers.filter("[data-pixel-size='" + pixelSize + "']").appendTo($serviceContainer), - - opacity = service.style.opacity, - - x, y, - - loadImageDeferredDone = function( url ) { - // when a Deferred call is done, add the image to the map - // a reference to the correct img element is on the Deferred object itself - serviceObj._loadImage( this.img, url, pixelSize, map, serviceState, opacity ); - }, - - loadImageDeferredFail = function( ) { - delete this.img; - serviceState.loadCount--; - map._requestComplete(); - }; - - if (serviceState.reloadTiles) { - scaleContainers.find("img").attr("data-dirty", "true"); - } - - if (!scaleContainer.size()) { - $serviceContainer.append( window.toStaticHTML( "
                      " ) ); - scaleContainer = $serviceContainer.children(":last").data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - } else { - scaleContainer.css({ - left: (serviceLeft % tileWidth) + "px", - top: (serviceTop % tileHeight) + "px" - }).data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - - scaleContainer.children().each( function () { - var $img = $(this), - tile = $img.attr("data-tile").split(","); - - $img.css({ - left: Math.round(((parseInt(tile[0], 10) - fullXAtScale) * 100) + (serviceLeft - (serviceLeft % tileWidth)) / tileWidth * 100) + "%", - top: Math.round(((parseInt(tile[1], 10) - fullYAtScale) * 100) + (serviceTop - (serviceTop % tileHeight)) / tileHeight * 100) + "%" - }); - - if (opacity < 1) { - $img.fadeTo(0, opacity); - } - } ); - } - - for (x = tileX; x < tileX2; x++) { - for (y = tileY; y < tileY2; y++) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ($img.size() === 0 || serviceState.reloadTiles) { - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] + ySign * (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] + ySign * ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - urlArgs = { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }, - isFunc = $.isFunction( service[ 'src' ] ), - imageUrl; - - if ( isFunc ) { - imageUrl = service[ 'src' ]( urlArgs ); - } else { - if ( rTmplString.test( service[ 'src' ] ) ) { - $.templates( this._tmplGeoSrcId, service[ 'src' ] ); - imageUrl = $.render[ this._tmplGeoSrcId ]( urlArgs ); - } else { - imageUrl = service[ 'src' ]; - } - } - - serviceState.loadCount++; - map._requestQueued(); - - if (serviceState.reloadTiles && $img.size() > 0) { - $img.attr("src", imageUrl); - } else { - var imgMarkup = ""; - - scaleContainer.append( window.toStaticHTML( imgMarkup ) ); - $img = scaleContainer.children(":last"); - } - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl && $.isFunction( imageUrl.promise ) ) { - // assume Deferred - $.extend( imageUrl.promise( ), { img: $img } ); - imageUrl.done( loadImageDeferredDone ).fail( loadImageDeferredFail ); - } else { - $img.remove( ); - } - } - } - } - - scaleContainers.find("[data-dirty]").remove(); - serviceState.reloadTiles = false; - } - }, - - resize: function ( /* map, service, dx, dy */ ) { - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.css( "display", service.style.visibility === "visible" ? "block" : "none" ); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if (serviceState && serviceState.loadCount > 0) { - /* - * #193 - disabled until we can do this without canceling all AJAX requests - * - if ( window.stop !== undefined ) { - window.stop(); - } else if( document.execCommand !== undefined ) { - document.execCommand("Stop", false); - } - */ - - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery, window)); - -(function ($, window, undefined) { - $.geo._serviceTypes.shingled = (function () { - var rTmplString = new RegExp( "<.*>|{{.*}}" ); - - return { - _serviceId: 0, - _tmplGeoSrcId: "", - - create: function ( map, serviceContainer, service /* , index */ ) { - this._serviceId = map._serviceIdSeed++; - this._tmplGeoSrcId = "geoSrc" + this._serviceId; - - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0 - }; - - var scHtml = '
                      '; - - serviceContainer.append( window.toStaticHTML( scHtml ) ); - - serviceState.serviceContainer = serviceContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - var serviceState = $.data( service, "geoServiceState" ), - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds[ "width" ], - mapHeight = contentBounds[ "height" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data( "pixelSize" ), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin, center, pixelSize ); - - $scaleContainer.css( { - left: Math.round( newPixelPoint[ 0 ] ), - top: Math.round( newPixelPoint[ 1 ] ), - width: mapWidth * scaleRatio, - height: mapHeight * scaleRatio - } ); - } - }); - } - }, - - refresh: function (map, service, force) { - var serviceState = $.data(service, "geoServiceState"); - - this._cancelUnloaded(map, service); - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainer = serviceContainer.children('[data-pixel-size="' + pixelSize + '"]'), - - opacity = service.style.opacity, - - $img; - - if (opacity < 1 || force || service.shinglesMax === 1) { - serviceContainer.find("img").attr("data-keep-alive", "0"); - } else if ( service.shinglesMax > 1 ) { - serviceContainer.find("img").slice( 0, -( service.shinglesMax - 1 ) ).attr("data-keep-alive", "0"); - } - - if ( !scaleContainer.size() ) { - serviceContainer.append( window.toStaticHTML( '
                      ' ) ); - scaleContainer = serviceContainer.children(":last"); - } - - var urlArgs = { - bbox: bbox, - width: mapWidth, - height: mapHeight, - zoom: map._getZoom(), - tile: null, - index: 0 - }, - isFunc = $.isFunction( service[ 'src' ] ), - imageUrl, - imagePos = scaleContainer.position( ); - - imagePos.left = - ( imagePos.left ); - imagePos.top = - ( imagePos.top ); - - if ( isFunc ) { - imageUrl = service[ 'src' ]( urlArgs ); - } else { - if ( rTmplString.test( service[ 'src' ] ) ) { - $.templates( this._tmplGeoSrcId, service[ 'src' ] ); - imageUrl = $.render[ this._tmplGeoSrcId ]( urlArgs ); - } else { - imageUrl = service[ 'src' ]; - } - } - - serviceState.loadCount++; - map._requestQueued(); - - scaleContainer.append( window.toStaticHTML( '' ) ); - $img = scaleContainer.children(":last").data("center", map._center); - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl ) { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, map, serviceState, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - map._requestComplete(); - } ); - } - - } - }, - - resize: function ( map, service /* , dx, dy */ ) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState && service && service.style.visibility === "visible" ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainers = serviceContainer.children(); - - scaleContainers.attr("data-pixel-size", "0"); - - scaleContainers.each( function ( ) { - var $scaleContainer = $(this), - position = $scaleContainer.position( ); - - $scaleContainer.css( { - left: position.left + ( mapWidth - $scaleContainer.width( ) ) / 2, - top: position.top + ( mapHeight - $scaleContainer.height( ) ) / 2 - } ); - - } ); - } - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.css("display", service.style.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - // #newpanzoom - serviceContainer.children(':not([data-pixel-size="' + pixelSize + '"])').remove(); - - serviceContainer.find( "img[data-keep-alive]" ).remove( ); - - serviceState.loadCount = 0; - } - }).error(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery, window)); diff --git a/dist/jquery.geo-1.0.0-rc1.min.js b/dist/jquery.geo-1.0.0-rc1.min.js deleted file mode 100644 index 7966039..0000000 --- a/dist/jquery.geo-1.0.0-rc1.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! jQuery Geo - v1.0.0-rc1 - 2016-06-05 -* http://jquerygeo.com -* Copyright (c) 2016 Ryan Morrison-Westphal; Licensed MIT */ -document.createElement("canvas").getContext||!function(){function a(){return this.context_||(this.context_=new q(this))}function b(a,b,c){var d=G.call(arguments,2);return function(){return a.apply(b,d.concat(G.call(arguments)))}}function c(a,b,c){a.namespaces[b]||a.namespaces.add(b,c,"#default#VML")}function d(a){if(c(a,"g_vml_","urn:schemas-microsoft-com:vml"),c(a,"g_o_","urn:schemas-microsoft-com:office:office"),!a.styleSheets.ex_canvas_){var b=a.createStyleSheet();b.owningElement.id="ex_canvas_",b.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function e(a){var b=a.srcElement;switch(a.propertyName){case"width":b.getContext().clearRect(),b.style.width=b.attributes.width.nodeValue+"px",b.firstChild.style.width=b.clientWidth+"px";break;case"height":b.getContext().clearRect(),b.style.height=b.attributes.height.nodeValue+"px",b.firstChild.style.height=b.clientHeight+"px"}}function f(a){var b=a.srcElement;b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px",b.firstChild.style.height=b.clientHeight+"px")}function g(){return[[1,0,0],[0,1,0],[0,0,1]]}function h(a,b){for(var c=g(),d=0;3>d;d++)for(var e=0;3>e;e++){for(var f=0,h=0;3>h;h++)f+=a[d][h]*b[h][e];c[d][e]=f}return c}function i(a,b){b.fillStyle=a.fillStyle,b.lineCap=a.lineCap,b.lineJoin=a.lineJoin,b.lineWidth=a.lineWidth,b.miterLimit=a.miterLimit,b.shadowBlur=a.shadowBlur,b.shadowColor=a.shadowColor,b.shadowOffsetX=a.shadowOffsetX,b.shadowOffsetY=a.shadowOffsetY,b.strokeStyle=a.strokeStyle,b.globalAlpha=a.globalAlpha,b.font=a.font,b.textAlign=a.textAlign,b.textBaseline=a.textBaseline,b.arcScaleX_=a.arcScaleX_,b.arcScaleY_=a.arcScaleY_,b.lineScale_=a.lineScale_}function j(a){var b=a.indexOf("(",3),c=a.indexOf(")",b+1),d=a.substring(b+1,c).split(",");return(4!=d.length||"a"!=a.charAt(3))&&(d[3]=1),d}function k(a){return parseFloat(a)/100}function l(a,b,c){return Math.min(c,Math.max(b,a))}function m(a){var b,c,d,e,f,g;if(e=parseFloat(a[0])/360%360,0>e&&e++,f=l(k(a[1]),0,1),g=l(k(a[2]),0,1),0==f)b=c=d=g;else{var h=.5>g?g*(1+f):g+f-g*f,i=2*g-h;b=n(i,h,e+1/3),c=n(i,h,e),d=n(i,h,e-1/3)}return"#"+I[Math.floor(255*b)]+I[Math.floor(255*c)]+I[Math.floor(255*d)]}function n(a,b,c){return 0>c&&c++,c>1&&c--,1>6*c?a+6*(b-a)*c:1>2*c?b:2>3*c?a+(b-a)*(2/3-c)*6:a}function o(a){if(a in L)return L[a];var b,c=1;if(a=String(a),"#"==a.charAt(0))b=a;else if(/^rgb/.test(a)){for(var d,e=j(a),b="#",f=0;3>f;f++)d=-1!=e[f].indexOf("%")?Math.floor(255*k(e[f])):+e[f],b+=I[l(d,0,255)];c=+e[3]}else if(/^hsl/.test(a)){var e=j(a);b=m(e),c=e[3]}else b=a;return L[a]={color:b,alpha:c}}function p(a){return M[a]||"square"}function q(a){this.m_=g(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.strokeStyle="#000",this.fillStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=1*E,this.globalAlpha=1,this.canvas=a;var b="width:"+a.clientWidth+"px;height:"+a.clientHeight+"px;overflow:hidden;position:absolute",c=a.ownerDocument.createElement("div");c.style.cssText=b,a.appendChild(c);var d=c.cloneNode(!1);d.style.backgroundColor="red",d.style.filter="alpha(opacity=0)",a.appendChild(d),this.element_=c,this.arcScaleX_=1,this.arcScaleY_=1,this.lineScale_=1}function r(a,b,c,d){a.currentPath_.push({type:"bezierCurveTo",cp1x:b.x,cp1y:b.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y}),a.currentX_=d.x,a.currentY_=d.y}function s(a,b){var c=o(a.strokeStyle),d=c.color,e=c.alpha*a.globalAlpha,f=a.lineScale_*a.lineWidth;1>f&&(e*=f),b.push("')}function t(a,b,c,d){var e=(a.fillStyle,a.arcScaleX_,a.arcScaleY_,d.x-c.x,d.y-c.y,o(a.fillStyle)),f=e.color,g=e.alpha*a.globalAlpha;b.push('')}function u(a,b,c){var d=a.m_;return{x:E*(b*d[0][0]+c*d[1][0]+d[2][0])-F,y:E*(b*d[0][1]+c*d[1][1]+d[2][1])-F}}function v(a){return isFinite(a[0][0])&&isFinite(a[0][1])&&isFinite(a[1][0])&&isFinite(a[1][1])&&isFinite(a[2][0])&&isFinite(a[2][1])}function w(a,b,c){if(v(b)&&(a.m_=b,c)){var d=b[0][0]*b[1][1]-b[0][1]*b[1][0];a.lineScale_=D(C(d))}}function x(a){this.code=this[a],this.message=a+": DOM Exception "+this.code}var y=Math,z=y.round,A=y.sin,B=y.cos,C=y.abs,D=y.sqrt,E=10,F=E/2,G=(+navigator.userAgent.match(/MSIE ([\d.]+)?/)[1],Array.prototype.slice);d(document);var H={init:function(a){var c=a||document;c.createElement("canvas"),c.attachEvent("onreadystatechange",b(this.init_,this,c))},init_:function(a){for(var b=a.getElementsByTagName("canvas"),c=0;cJ;J++)for(var K=0;16>K;K++)I[16*J+K]=J.toString(16)+K.toString(16);var L={},M={butt:"flat",round:"round"},N=q.prototype;N.clearRect=function(){this.textMeasureEl_&&(this.textMeasureEl_.removeNode(!0),this.textMeasureEl_=null),this.element_.innerHTML=""},N.beginPath=function(){this.currentPath_=[]},N.moveTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"moveTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.lineTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"lineTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.bezierCurveTo=function(a,b,c,d,e,f){var g=u(this,e,f),h=u(this,a,b),i=u(this,c,d);r(this,h,i,g)},N.quadraticCurveTo=function(a,b,c,d){var e=u(this,a,b),f=u(this,c,d),g={x:this.currentX_+2/3*(e.x-this.currentX_),y:this.currentY_+2/3*(e.y-this.currentY_)},h={x:g.x+(f.x-this.currentX_)/3,y:g.y+(f.y-this.currentY_)/3};r(this,g,h,f)},N.arc=function(a,b,c,d,e,f){c*=E;var g=f?"at":"wa",h=a+B(d)*c-F,i=b+A(d)*c-F,j=a+B(e)*c-F,k=b+A(e)*c-F;h!=j||f||(h+=.125);var l=u(this,a,b),m=u(this,h,i),n=u(this,j,k);this.currentPath_.push({type:g,x:l.x,y:l.y,radius:c,xStart:m.x,yStart:m.y,xEnd:n.x,yEnd:n.y})},N.stroke=function(a){var b=[],c=10,d=10;b.push("f.x)&&(f.x=i.x),(null==e.y||i.yf.y)&&(f.y=i.y))}b.push(' ">'),a?t(this,b,e,f):s(this,b),b.push(""),this.element_.insertAdjacentHTML("beforeEnd",b.join(""))},N.fill=function(){this.stroke(!0)},N.closePath=function(){this.currentPath_.push({type:"close"})},N.save=function(){var a={};i(this,a),this.aStack_.push(a),this.mStack_.push(this.m_),this.m_=h(g(),this.m_)},N.restore=function(){this.aStack_.length&&(i(this.aStack_.pop(),this),this.m_=this.mStack_.pop())},N.translate=function(a,b){var c=[[1,0,0],[0,1,0],[a,b,1]];w(this,h(c,this.m_),!1)},N.scale=function(a,b){this.arcScaleX_*=a,this.arcScaleY_*=b;var c=[[a,0,0],[0,b,0],[0,0,1]];w(this,h(c,this.m_),!0)};var O=x.prototype=new Error;O.INDEX_SIZE_ERR=1,O.DOMSTRING_SIZE_ERR=2,O.HIERARCHY_REQUEST_ERR=3,O.WRONG_DOCUMENT_ERR=4,O.INVALID_CHARACTER_ERR=5,O.NO_DATA_ALLOWED_ERR=6,O.NO_MODIFICATION_ALLOWED_ERR=7,O.NOT_FOUND_ERR=8,O.NOT_SUPPORTED_ERR=9,O.INUSE_ATTRIBUTE_ERR=10,O.INVALID_STATE_ERR=11,O.SYNTAX_ERR=12,O.INVALID_MODIFICATION_ERR=13,O.NAMESPACE_ERR=14,O.INVALID_ACCESS_ERR=15,O.VALIDATION_ERR=16,O.TYPE_MISMATCH_ERR=17,G_vmlCanvasManager=H,CanvasRenderingContext2D=q,DOMException=x}(),this.jsviews||this.jQuery&&jQuery.views||function(a,b){function c(a,b){var c="\\"+a.charAt(0),d="\\"+a.charAt(1),e="\\"+b.charAt(0),f="\\"+b.charAt(1);return Q.rTag=u=d+"(?:(?:(\\w+(?=[\\/\\s"+e+"]))|(?:(\\w+)?(:)|(>)|(\\*)))\\s*((?:[^"+e+"]|"+e+"(?!"+f+"))*?)(\\/)?|(?:\\/(\\w+)))"+e,u=new RegExp(c+u+f,"g"),v=new RegExp("<.*>|"+a+".*"+b),this}function d(a){var c=this,d=c.tmpl.helpers||{};return a=(c.ctx[a]!==b?c.ctx:d[a]!==b?d:k[a]!==b?k:{})[a],"function"!=typeof a?a:function(){return a.apply(c,arguments)}}function e(a,b,c){var d=b.tmpl.converters;return a=d&&d[a]||l[a],a?a.call(b,c):c}function f(a,c,d,e,f){f.props=f.props||{};var g,h=f.props.tmpl,k=c.tmpl.tags,l=c.tmpl.templates,n=arguments,o=k&&k[a]||j[a];return o?(e=e&&c.tmpl.tmpls[e-1],h=h||e||b,f.tmpl=""+h===h?l&&l[h]||i[h]||i(h):h,f.isTag=A,f.converter=d,f.view=c,f.renderContent=m,c.ctx&&w(f.ctx,c.ctx),g=o.apply(f,n.length>5?O.call(n,5):[]),g||(g==b?"":g.toString())):""}function g(a,c,e,f,g,h){var i=e.views,j={tmpl:g,path:c,parent:e,data:f,ctx:a,views:t.isArray(f)?[]:{},hlp:d};return t.isArray(i)?i.splice(j.index=h!==b?h:i.length,0,j):i[j.index="_"+I++]=j,j}function h(a,c,d,e,f){var g,h;if(d&&"object"==typeof d&&!d.nodeType){for(g in d)c(g,d[g]);return a}return d&&e!==b?""+d===d&&(null===e?delete c[d]:(e=f?f(d,e):e)&&(c[d]=e)):f&&(e=f(b,e||d)),(h=y.onStoreItem)&&h(c,d,e,f),e}function i(a,b){return h(this,i,a,b,q)}function j(a,b){return h(this,j,a,b)}function k(a,b){return h(this,k,a,b)}function l(a,b){return h(this,l,a,b)}function m(a,c,d,e,f){var h,j,k,l,m,n,o,p,q,r,s={},u=f===A,v=this,x="";if(v.isTag?(q=v.tmpl,c=c||v.ctx,d=d||v.view,e=e||v.path,f=f||v.index,s=v.props):q=v.jquery&&v[0]||v,d=d||Q.topView,p=d.ctx,r=q.layout,a===d&&(a=d.data,r=A),c=c&&c===p?p:p?(p=w({},p),c?w(p,c):p):c||{},s.link===z&&(c.link=z),q.fn||(q=i[q]||i(q)),m=c.link&&y.onRenderItem,n=c.link&&y.onRenderItems,q){if(t.isArray(a)&&!r)for(l=u?d:f!==b&&d||g(c,e,d,a,q,f),h=0,j=a.length;j>h;h++)k=a[h],o=q.fn(k,g(c,e,l,k,q,(f||0)+h),Q),x+=m?m(o,s):o;else l=u?d:g(c,e,d,a,q,f),x+=a||r?q.fn(a,l,Q):"";return d.topKey=l.index,n?n(x,e,l.index,q,s):x}return""}function n(){throw"Syntax error"}function o(a,b,c){function d(b){b-=D,b&&J.push(a.substr(D,b).replace(E,"\\n"))}function e(b,e,g,h,i,j,k,l,m,n){i&&(h=":",g="html");var o="",q="",r=!l&&!h;if(e=e||h,d(n),D=n+b.length,j?y&&J.push(["*",k.replace(F,"$1")]):e?("else"===e&&(K[5]=a.substring(K[5],n),K=I.pop(),J=K[3],r=A),k=k?p(k,c).replace(H,function(a,b,c){return b?q+=c+",":o+=c+",",""}):"",o=o.slice(0,-1),k=k.slice(0,-1),f=[e,g||"",k,r&&[],"{"+(o?"props:{"+o+"},":"")+"path:'"+k+"'"+(q?",ctx:{"+q.slice(0,-1)+"}":"")+"}"],r&&(I.push(K),K=f,K[5]=D),J.push(f)):m&&(K[5]=a.substring(K[5],n),K=I.pop()),!K)throw"Expected block tag";J=K[3]}var f,g,h,i,j,k,l,m,n,q,s,t,v,w,x,y,z=b?{allowCode:y=b.allowCode,debug:b.debug}:{},B=b&&b.tmpls,C=[],D=0,I=[],J=C,K=[,,,C],L=0;for(a=a.replace(G,"\\$1"),a.replace(u,e),d(a.length),i=C.length,j=i?"":'"";',h=0;i>h;h++)g=C[h],"*"===g[0]?j=j.slice(0,h?-1:-3)+";"+g[1]+(i>h+1?"ret+=":""):""+g===g?j+='"'+g+'"+':(s=g[0],t=g[1],v=g[2],J=g[3],w=g[4],a=g[5],J&&(x=r(a,z,b,L++),o(a,x),B.push(x)),q=q||w.indexOf("view")>-1,j+=(":"===s?"html"===t?(l=A,"e("+v):t?(n=A,'c("'+t+'",view,'+v):(m=A,"((v="+v+')!=u?v:""'):(k=A,'t("'+s+'",view,"'+(t||"")+'",'+(J?B.length:'""')+","+w+(v?",":"")+v))+")+");return j=new Function("data, view, j, b, u",M+(m?"v,":"")+(k?"t=j.tag,":"")+(n?"c=j.convert,":"")+(l?"e=j.converters.html,":"")+"ret; try{\n\n"+(z.debug?"debugger;":"")+(y?"ret=":"return ")+j.slice(0,-1)+";\n\n"+(y?"return ret;":"")+"}catch(e){return j.err(e);}"),b&&(b.fn=j,b.useVw=n||q||k),j}function p(a,b){function c(a,c,i,j,k,l,m,o,p,q,r,s,t,u,v,w){function x(a,c,d,e,f,g,h){if(c){var i=(d?'view.hlp("'+d+'")':e?"view":"data")+(h?(f?"."+f:d?"":e?"":"."+c)+(g||""):(h=d?"":e?f||"":c,""));return b&&"("!==p&&(i="b("+i+',"'+h+'")'),i+(h?"."+h:"")}return a}return k=k||"",i=i||c||r,j=j||o,p=p||v||"",k=k||"",l?void n():h?(h=!s,h?a:'"'):g?(g=!t,g?a:'"'):(i?(f++,i):"")+(w?f?"":d?(d=z,"\b"):",":m?(f&&n(),d=A,"\b"+j+":"):j?j.replace(C,x)+(p?(e[++f]=A,p):k):k?a:u?(e[f--]=z,u+(p?(e[++f]=A,p):"")):q?(e[f]||n(),","):c?"":(h=s,g=t,'"'))}var d,e={},f=0,g=z,h=z;return a=(a+" ").replace(D,c)}function q(a,c,d,e){function f(b){return""+b===b||b.nodeType>0?(h=b.nodeType>0?b:!v.test(b)&&B&&B(b)[0],h&&h.type&&(b=i[h.getAttribute(L)],b||(a=a||"_"+J++,h.setAttribute(L,a),b=q(a,h.innerHTML,d,e),i[a]=b)),b):void 0}var g,h,j,k,l;if(g=f(c),e=e||(c.markup?c:{}),e.name=a,k=e.templates,!g&&c.markup&&(g=f(c.markup))&&(!g.fn||g.debug===c.debug&&g.allowCode===c.allowCode||(g=g.markup)),g!==b){a&&!d&&(P[a]=function(){return c.render.apply(c,arguments)}),g.fn||c.fn?g.fn&&(c=a&&a!==g.name?w(w({},g),e):g):(c=r(g,e,d,0),o(g,c));for(j in k)l=k[j],l.name!==j&&(k[j]=q(j,l,c));return c}}function r(a,b,c,d){function e(a){c[a]&&(f[a]=w(w({},c[a]),b[a]))}b=b||{};var f={markup:a,tmpls:[],links:[],render:m};return c&&(c.templates&&(f.templates=w(w({},c.templates),b.templates)),f.parent=c,f.name=c.name+"["+d+"]",f.index=d),w(f,b),c&&(e("templates"),e("tags"),e("helpers"),e("converters")),f}function s(a){return K[a]||(K[a]="&#"+a.charCodeAt(0)+";")}var t,u,v,w,x="v1.0pre",y={},z=!1,A=!0,B=a.jQuery,C=/^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g,D=/(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,E=/\r?\n/g,F=/\\(['"])/g,G=/\\?(['"])/g,H=/\x08(~)?([^\x08]+)\x08/g,I=0,J=0,K={"&":"&","<":"<",">":">"},L="data-jsv-tmpl",M="var j=j||"+(B?"jQuery.":"js")+"views,",N=/[\x00"&'<>]/g,O=Array.prototype.slice,P={},Q={jsviews:x,sub:y,debugMode:A,err:function(a){return Q.debugMode?"
                      Error: "+(a.message||a)+". ":'""'},tmplFn:o,render:P,templates:i,tags:j,helpers:k,converters:l,View:g,convert:e,delimiters:c,tag:f};B?(t=B,t.templates=i,t.render=P,t.views=Q,t.fn.render=m):(t=a.jsviews=Q,t.extend=function(a,b){var c;a=a||{};for(c in b)a[c]=b[c];return a},t.isArray=Array&&Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)}),w=t.extend,Q.topView={views:{},tmpl:{},hlp:d,ctx:Q.helpers},j({"if":function(){var a=this,c=a.view;return c.onElse=function(a,d){for(var e=0,f=d.length;f&&!d[e++];)if(e===f)return"";return c.onElse=b,a.path="",a.renderContent(c)},c.onElse(this,arguments)},"else":function(){var a=this.view;return a.onElse?a.onElse(this,arguments):""},"for":function(){var a,b=this,c="",d=arguments,e=d.length;for(b.props.layout&&(b.tmpl.layout=A),a=0;e>a;a++)c+=b.renderContent(d[a]);return c},"=":function(a){return a},"*":function(a){return a}}),l({html:function(a){return a!=b?String(a).replace(N,s):""}}),c("{{","}}")}(this),function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})}),$.widget||!function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d,e=0;null!=(d=b[e]);e++)try{a(d).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){return c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}}),d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e,f=b.split(".")[0];b=b.split(".")[1],e=f+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][e]=function(c){return!!a.data(c,b)},a[f]=a[f]||{},a[f][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[f][b].prototype=a.extend(!0,g,{namespace:f,widgetName:b,widgetEventPrefix:a[f][b].prototype.widgetEventPrefix||b,widgetBaseClass:e},d),a.widget.bridge(b,a[f][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f="string"==typeof e,g=Array.prototype.slice.call(arguments,1),h=this;return e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e,f&&"_"===e.charAt(0)?h:(f?this.each(function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;return f!==d&&f!==b?(h=f,!1):void 0}):this.each(function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))}),h)}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(0===arguments.length)return a.extend({},this.options);if("string"==typeof c){if(d===b)return this.options[c];e={},e[c]=d}return this._setOptions(e),this},_setOptions:function(b){var c=this;return a.each(b,function(a,b){c._setOption(a,b)}),this},_setOption:function(a,b){return this.options[a]=b,"disabled"===a&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",b),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];if(d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}}(jQuery),function(a,b,c){b.toStaticHTML=b.toStaticHTML||function(a){return a};var d=Number.POSITIVE_INFINITY,e=Number.NEGATIVE_INFINITY;a.geo={_allCoordinates:function(b){for(var c=this._flatten(b),d=0,e=[];d1&&!a.isArray(b[0]))return b[0]>=-180.001&&b[0]<=180.001&&b[1]>=-90.001&&b[1]<=90.001;b=b[0]}return!1},center:function(b,c){var d=!1;!c&&a.geo.proj&&this._isGeodetic(b)&&(d=!0,b=a.geo.proj.fromGeodetic(b));var e=[(b[0]+b[2])/2,(b[1]+b[3])/2];return d?a.geo.proj.toGeodetic(e):e},expandBy:function(b,c,d,e){var f=!1;return!e&&a.geo.proj&&this._isGeodetic(b)&&(f=!0,b=a.geo.proj.fromGeodetic(b)),b=[b[0]-c,b[1]-d,b[2]+c,b[3]+d],f?a.geo.proj.toGeodetic(b):b},height:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[3]-b[1]},_in:function(a,b){return a[0]<=b[0]&&a[1]<=b[1]&&a[2]>=b[2]&&a[3]>=b[3]},_bboxDisjoint:function(a,b){return b[0]>a[2]||b[2]a[3]||b[3]0&&(h/i>c?(f=h/2,g=f/c):(g=i/2,f=g*c),b=[j[0]-f,j[1]-g,j[0]+f,j[1]+g]),e?a.geo.proj.toGeodetic(b):b},recenter:function(b,c,d){var e=!1;!d&&a.geo.proj&&(this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b)),this._isGeodetic(c)&&(c=a.geo.proj.fromGeodetic(c)));var f=(b[2]-b[0])/2,g=(b[3]-b[1])/2;return b=[c[0]-f,c[1]-g,c[0]+f,c[1]+g],e?a.geo.proj.toGeodetic(b):b},scaleBy:function(b,c,d){var e=!1;!d&&a.geo.proj&&this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b));var f=this.center(b,!0),g=(b[2]-b[0])*c/2,h=(b[3]-b[1])*c/2;return b=[f[0]-g,f[1]-h,f[0]+g,f[1]+h],e?a.geo.proj.toGeodetic(b):b},width:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[2]-b[0]},bbox:function(b,f){var g,h=!1;if(!b)return c;if(b.bbox)g=!f&&a.geo.proj&&this._isGeodetic(b.bbox)?a.geo.proj.fromGeodetic(b.bbox):b.bbox;else{g=[d,d,e,e];var i=this._allCoordinates(b),j=0;if(0===i.length)return c;for(!f&&a.geo.proj&&this._isGeodetic(i)&&(h=!0,i=a.geo.proj.fromGeodetic(i));j0?(g[0]=Math.min(Math.max(k[0][0],m[0]),m[2]),g[1]=Math.min(Math.max(k[0][1],m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g}):c:(j*=3,g[0]=Math.min(Math.max(g[0]/j,m[0]),m[2]),g[1]=Math.min(Math.max(g[1]/j,m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g});case"MultiPoint":if(b.coordinates.length>0)return g=b.coordinates[0],{type:"Point",coordinates:[g[0],g[1]]};break;case"MultiLineString":case"MultiPolygon":if(b.coordinates.length>0)return this.centroid({type:b.type.substr(5),coordinates:b.coordinates[0]},f)}return c},contains:function(a,b){if("Polygon"!==a.type)return!1;switch(b.type){case"Point":return this._containsPolygonPoint(a.coordinates,b.coordinates);case"LineString":return this._containsPolygonLineString(a.coordinates,b.coordinates);case"Polygon":return this._containsPolygonLineString(a.coordinates,b.coordinates[0]);default:return!1}},_containsPolygonPoint:function(a,b){if(0===a.length||a[0].length<4)return!1;for(var c,d,e=0,f=a[0][0],g=1;gb[0]&&e++),f=c;return e%2===1},_containsPolygonLineString:function(a,b){for(var c=0;c0){var e=a[0],f=b[0]-e[0],g=b[1]-e[1];if(1===a.length)return Math.sqrt(f*f+g*g);for(var h=1;hn&&(c=n),e=i,f=l,g=m}}return Math.sqrt(c)},_distanceSegmentPoint:function(a,b,c,d,e,f){var g=a*c+b*d;if(0>=g)return c*c+d*d;var h=a*a+b*b;return g>=h?e*e+f*f:c*c+d*d-g*g/h},_distanceLineStringLineString:function(a,b){for(var c=d,e=0;e=k;k++)h=360*k/j*(Math.PI/180),i.push([g[0]+Math.cos(h)*d,g[1]+Math.sin(h)*d]);return{type:"Polygon",coordinates:[f?a.geo.proj.toGeodetic(i):i]}}return c},_basic:function(a){for(var b,c,d=[],e=0,f=this._flatten(a);eo;q++)n=o,o+=p[q]/m;return e=c-n,k=g[q-1],l=g[q],j=[k[0]+e*(l[0]-k[0]),k[1]+e*(l[1]-k[1])],{type:"Point",coordinates:r?a.geo.proj.toGeodetic(j):j}}},WKT:function(){function b(a){return"POINT "+c(a.coordinates)}function c(a){return a&&a.length?"("+a.join(" ")+")":"EMPTY"}function d(a){return"LINESTRING "+e(a.coordinates)}function e(a){if(a&&a.length){for(var b=[],c=0;c2?{type:"Point",coordinates:[parseFloat(b[1]),parseFloat(b[2])]}:null}function p(a){var b,c,d=a.match(/\s*\((.*)\)/),e=[],f=0;if(d&&d.length>1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f0){for(;g
                      ";while(c[0]);return a>6?a:!a}();a.widget("geo.geographics",{_$elem:c,_options:{},_trueCanvas:!0,_trueDoubleBuffer:!0,_width:0,_height:0,_$canvas:c,_context:c,_$canvasSceneFront:c,_$canvasSceneBack:c,_$canvasSceneStale:c,_$canvasSceneDrawn:c,_timeoutEnd:null,_requireFlip:!1,_blitcanvas:c,_blitcontext:c,_$labelsContainerFront:c,_$labelsContainerBack:c,_labelsHtml:"",options:{style:{borderRadius:"8px",color:"#7f0000",fillOpacity:.2,height:"8px",opacity:1,strokeOpacity:1,strokeWidth:"2px",visibility:"visible",width:"8px"},doubleBuffer:!0},_create:function(){this._$elem=this.element,this._options=this.options,this._$elem.css({webkitTransform:"translateZ(0)",display:"inline-block",overflow:"hidden",textAlign:"left"}),"static"===this._$elem.css("position")&&this._$elem.css("position","relative"),this._$elem.addClass("geo-graphics"),this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10));var c="position:absolute;left:0;top:0;margin:0;padding:0;",e="width:"+this._width+"px;height:"+this._height+"px;",f='width="'+this._width+'" height="'+this._height+'"';this._blitcanvas=document.createElement("canvas"),this._blitcanvas.getContext?(this._$canvas=a(b.toStaticHTML("')),this._blitcanvas.width=1,this._blitcanvas.height=1,this._trueDoubleBuffer=this._blitcanvas.toDataURL().length>6,this._options.doubleBuffer&&this._trueDoubleBuffer||this._$elem.append(this._$canvas),this._context=this._$canvas[0].getContext("2d"),this._blitcanvas.width=this._width,this._blitcanvas.height=this._height,this._blitcontext=this._blitcanvas.getContext("2d"),this._$canvasSceneFront=a(b.toStaticHTML('')).on("load",a.proxy(this._canvasImgLoad,this)),this._$canvasSceneBack=a(b.toStaticHTML('')).on("load",a.proxy(this._canvasImgLoad,this))):8>=d&&(this._trueCanvas=!1,this._$elem.append("
                      '),this._$canvas=this._$elem.children(":last"),G_vmlCanvasManager.initElement(this._$canvas[0]),this._context=this._$canvas[0].getContext("2d"),this._$canvas.children().css({backgroundColor:"transparent",width:this._width,height:this._height})),this._$labelsContainerFront=a(b.toStaticHTML('
                      ')),this._$labelsContainerBack=a(b.toStaticHTML('
                      '))},_setOption:function(b,c){"style"===b&&(c=a.extend({},this._options.style,c)),a.Widget.prototype._setOption.apply(this,arguments)},destroy:function(){a.Widget.prototype.destroy.apply(this,arguments),this._$elem.html(""),this._$elem.removeClass("geo-graphics")},clear:function(){this._context.clearRect(0,0,this._width,this._height),this._labelsHtml="",this._end()},drawArc:function(a,b,c,d){if(d=this._getGraphicStyle(d),"hidden"!==d.visibility&&d.opacity>0&&d.widthValue>0&&d.heightValue>0){var e=Math.min(d.widthValue,d.heightValue)/2;b=b*Math.PI/180,c=c*Math.PI/180,this._context.save(),this._context.translate(a[0],a[1]),d.widthValue>d.heightValue?this._context.scale(d.widthValue/d.heightValue,1):this._context.scale(1,d.heightValue/d.widthValue),this._context.beginPath(),this._context.arc(0,0,e,b,c,!1),this._trueCanvas&&this._context.restore(),d.doFill&&(this._context.fillStyle=d.fill,this._context.globalAlpha=d.opacity*d.fillOpacity,this._context.fill()),d.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=d.strokeWidthValue,this._context.strokeStyle=d.stroke,this._context.globalAlpha=d.opacity*d.strokeOpacity,this._context.stroke()),this._trueCanvas||this._context.restore()}this._end()},drawPoint:function(a,b){b=this._getGraphicStyle(b),b.widthValue===b.heightValue&&b.heightValue===b.borderRadiusValue?this.drawArc(a,0,360,b):"hidden"!==b.visibility&&b.opacity>0&&(b.borderRadiusValue=Math.min(Math.min(b.widthValue,b.heightValue)/2,b.borderRadiusValue),a[0]-=b.widthValue/2,a[1]-=b.heightValue/2,this._context.beginPath(),this._context.moveTo(a[0]+b.borderRadiusValue,a[1]),this._context.lineTo(a[0]+b.widthValue-b.borderRadiusValue,a[1]),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1],a[0]+b.widthValue,a[1]+b.borderRadiusValue),this._context.lineTo(a[0]+b.widthValue,a[1]+b.heightValue-b.borderRadiusValue),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1]+b.heightValue,a[0]+b.widthValue-b.borderRadiusValue,a[1]+b.heightValue),this._context.lineTo(a[0]+b.borderRadiusValue,a[1]+b.heightValue),this._context.quadraticCurveTo(a[0],a[1]+b.heightValue,a[0],a[1]+b.heightValue-b.borderRadiusValue),this._context.lineTo(a[0],a[1]+b.borderRadiusValue),this._context.quadraticCurveTo(a[0],a[1],a[0]+b.borderRadiusValue,a[1]),this._context.closePath(),b.doFill&&(this._context.fillStyle=b.fill,this._context.globalAlpha=b.opacity*b.fillOpacity,this._context.fill()),b.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=b.strokeWidthValue,this._context.strokeStyle=b.stroke,this._context.globalAlpha=b.opacity*b.strokeOpacity,this._context.stroke()),this._end())},drawLineString:function(a,b){this._drawLines([a],!1,b)},drawPolygon:function(a,b){if(this._trueCanvas&&1!==a.length){if(!a||!a.length||a[0].length<3)return;b=this._getGraphicStyle(b),this._blitcontext.globalCompositeOperation="copy";var c,d,e;if("hidden"!==b.visibility&&b.opacity>0){if(this._blitcontext.clearRect(0,0,this._width,this._height),b.doFill&&a.length>1){for(this._blitcontext.globalCompositeOperation="source-out",this._blitcontext.globalAlpha=1,this._blitcontext.beginPath(),d=1;d1))for(d=1;d'+b+""},resize:function(a,b){this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10)),this._trueCanvas?(this._$canvas[0].width=this._width,this._$canvas[0].height=this._height,this._$canvasSceneFront.css({left:a,top:b}),this._$canvasSceneBack.css({width:this._width,height:this._height})):this._$canvas.css({width:this._width,height:this._height});var c=this._$labelsContainerFront.position();this._$labelsContainerFront.css({left:c.left+a,top:c.top+b,width:this._width,height:this._height}),this._$labelsContainerBack.css({width:this._width,height:this._height})},interactiveTransform:function(a,b){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._trueCanvas&&this._options.doubleBuffer&&this._trueDoubleBuffer?(this._canvasSceneLoad(),this._$canvasSceneFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})):this._context.clearRect(0,0,this._width,this._height),this._$labelsContainerFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})},_canvasImgLoad:function(){var a=this;a._$canvasSceneFront=a._$canvasSceneDrawn.prependTo(a._$elem),a._$canvasSceneBack=a._$canvasSceneStale,a._$canvasSceneBack.detach()},_canvasSceneLoad:function(){var a=this;a._requireFlip&&(a._requireFlip=!1,a._$canvasSceneStale=a._$canvasSceneFront,a._$canvasSceneDrawn=a._$canvasSceneBack.css({left:0,top:0,width:a._width,height:a._height}).prop("src",a._$canvas[0].toDataURL()))},_endCallback:function(){var a=this;if(a._timeoutEnd){a._trueCanvas&&a._options.doubleBuffer&&a._trueDoubleBuffer&&this._canvasSceneLoad(),a._$labelsContainerBack.html(b.toStaticHTML(a._labelsHtml)).find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"});var c=a._$labelsContainerFront;a._$labelsContainerFront=a._$labelsContainerBack.css({left:0,top:0,width:a._width,height:a._height}).appendTo(a._$elem),a._$labelsContainerBack=c.detach(),a._timeoutEnd=null}},_end:function(){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._requireFlip=!0,this._timeoutEnd=setTimeout(a.proxy(this._endCallback,this),20)},_getGraphicStyle:function(b){function c(a){return a=parseInt(a,10),+a+""===a?+a:a}return b=a.extend({},this._options.style,b),b.borderRadiusValue=c(b.borderRadius),b.fill=b.fill||b.color,b.doFill=b.fill&&b.fillOpacity>0,b.stroke=b.stroke||b.color,b.strokeWidthValue=c(b.strokeWidth),b.doStroke=b.stroke&&b.strokeOpacity>0&&b.strokeWidthValue>0,b.widthValue=c(b.width),b.heightValue=c(b.height),b},_drawLines:function(a,b,c){if(a&&a.length&&!(a[0].length<2)){var d,e;if(c=this._getGraphicStyle(c),"hidden"!==c.visibility&&c.opacity>0){for(this._context.beginPath(),d=0;d
                      ";while(c[0]);return a>6?a:!a}(),f=function(){return(navigator.userAgent.match(/gecko\/*\d/i)||[]).length>0}(),g={bbox:[-180,-85,180,85],bboxMax:[-180,-85,180,85],center:[0,0],cursors:{"static":"default",pan:"url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move",click:"crosshair",zoom:"crosshair",dragBox:"crosshair",dragCircle:"crosshair",drawPoint:"crosshair",drawLineString:"crosshair",drawPolygon:"crosshair",measureLength:"crosshair",measureArea:"crosshair"},measureLabels:{length:"{{:length.toFixed( 2 )}} m",area:"{{:area.toFixed( 2 )}} sq m"},drawStyle:{},shapeStyle:{},mode:"pan",pannable:!0,scroll:"default",shift:"default",services:[{"class":"osm",type:"tiled",src:function(a){return"//otile"+(a.index%4+1)+("https:"===location.protocol?"-s":"")+".mqcdn.com/tiles/1.0.0/osm/"+a.zoom+"/"+a.tile.column+"/"+a.tile.row+".png"},attr:'Tiles Courtesy of MapQuest '}],tilingScheme:{tileWidth:256,tileHeight:256,levels:18,basePixelSize:156543.03392799935,origin:[-20037508.342787,20037508.342787]},axisLayout:"map",zoom:0,zoomMin:0,zoomMax:Number.POSITIVE_INFINITY,zoomFactor:2,pixelSize:0};a.widget("geo.geomap",{_$elem:c,_map:c,_created:!1,_createdGraphics:!1,_widgetId:0,_tmplLengthId:"",_tmplAreaId:"",_contentBounds:{},_$resizeContainer:c,_$eventTarget:c,_$contentFrame:c,_$existingChildren:c,_$attrList:c,_$servicesContainer:c,_$shapesContainers:c,_$panContainer:c,_$shapesContainer:c,_$drawContainer:c,_$measureContainer:c,_$measureLabel:c,_dpi:96,_currentServices:[],_center:c,_pixelSize:c,_centerMax:c,_pixelSizeMax:c,_pixelSizeMin:c,_userGeodetic:!0,_centerInteractive:c,_pixelSizeInteractive:c,_timeoutInteractive:null,_timeoutWheel:null,_triggerInteractive:!1,_timeoutRefreshShapes:null,_loadCount:0,_wheelLevel:0,_fullZoomFactor:2,_partialZoomFactor:1.18920711500273,_mouseDown:c,_inOp:c,_toolPan:c,_shiftDown:c,_anchor:c,_current:c,_downDate:c,_moveDate:c,_clickDate:c,_lastMove:c,_lastDrag:c,_windowHandler:null,_resizeTimeout:null,_panning:c,_velocity:c,_friction:c,_pointerEvents:c,_supportTouch:c,_softDblClick:c,_isTap:c,_isDbltap:c,_isMultiTouch:c,_multiTouchAnchor:[],_multiTouchAnchorBbox:c,_multiTouchCurrentBbox:c,_drawTimeout:null,_drawPixels:[],_drawCoords:[],_graphicShapes:[],_initOptions:{},_options:{},options:a.extend({},g),_createWidget:function(b,c){if(this._$elem=a(c),this._$elem.is(".geo-service"))return this._graphicShapes=[],void a.Widget.prototype._createWidget.apply(this,arguments);this._widgetId=d++,this._serviceIdSeed=0,this._tmplLengthId="geoMeasureLength"+this._widgetId,this._tmplAreaId="geoMeasureArea"+this._widgetId,this._$elem.addClass("geo-map").css({webkitTransform:"translateZ(0)",touchAction:"none"}),this._initOptions=b||{},this._forcePosition(this._$elem),this._$elem.css("text-align","left");var e=this._findMapSize();this._contentBounds={x:parseInt(this._$elem.css("padding-left"),10),y:parseInt(this._$elem.css("padding-top"),10),width:e.width,height:e.height},this._createChildren(),this._center=[0,0],this._centerMax=[0,0],this._centerInteractive=[0,0],this.options.pixelSize=this._pixelSize=this._pixelSizeMax=156543.03392799935,this._pixelSizeMin=this._pixelSizeMax/Math.pow(2,17),this._mouseDown=this._inOp=this._toolPan=this._shiftDown=this._panning=this._isTap=this._isDbltap=this._isMultiTouch=!1,this._anchor=[0,0],this._current=[0,0],this._lastMove=[0,0],this._lastDrag=[0,0],this._velocity=[0,0],this._friction=[.8,.8],this._downDate=this._moveDate=this._clickDate=0,this._drawPixels=[],this._drawCoords=[],this._graphicShapes=[],a.Widget.prototype._createWidget.apply(this,arguments)},_create:function(){if(this._options=this.options,this._$elem.is(".geo-service"))return this._map=this._$elem.data("geoMap"),void this._$elem.data("geoService",this);this._map=this,this._pointerEvents=b.PointerEvent,this._supportTouch="ontouchend"in document,this._softDblClick=this._pointerEvents||this._supportTouch||7===e;var d=this,g=this._pointerEvents?"pointerdown":this._supportTouch?"touchstart mousedown":"mousedown",h=this._pointerEvents?"pointerup pointercancel":this._supportTouch?"touchend touchcancel mouseup":"mouseup",i=this._pointerEvents?"pointermove":this._supportTouch?"touchmove mousemove":"mousemove";a(document).keydown(a.proxy(this._document_keydown,this)),this._softDblClick?this._$eventTarget.on("softdblclick",a.proxy(this._eventTarget_dblclick,this)):this._$eventTarget.dblclick(a.proxy(this._eventTarget_dblclick,this)),this._$eventTarget.bind(g,a.proxy(this._eventTarget_touchstart,this));var j=this._$eventTarget[0].setCapture||this._pointerEvents?this._$eventTarget:a(document);j.bind(i,a.proxy(this._dragTarget_touchmove,this)),j.bind(h,a.proxy(this._dragTarget_touchstop,this)),this._$eventTarget.mousewheel(a.proxy(this._eventTarget_mousewheel,this)),this._windowHandler=function(){d._resizeTimeout&&clearTimeout(d._resizeTimeout),d._resizeTimeout=setTimeout(function(){d._created&&d._$elem.geomap("resize",!0)},500)},a(b).resize(this._windowHandler),this._$drawContainer.geographics({style:this._initOptions.drawStyle||{},doubleBuffer:!1}),this._options.drawStyle=this._$drawContainer.geographics("option","style"),this._$shapesContainer.geographics({style:this._initOptions.shapeStyle||{},doubleBuffer:!f}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style"),this._initOptions&&(this._initOptions.tilingScheme!==c&&this._setOption("tilingScheme",this._initOptions.tilingScheme||null,!1),this._initOptions.services&&(this._options.services=a.merge([],this._initOptions.services)),this._initOptions.bboxMax&&(this._setOption("bboxMax",this._initOptions.bboxMax,!1),this._setOption("bbox",this._initOptions.bboxMax,!1)),this._initOptions.zoomMin!==c&&this._setOption("zoomMin",this._initOptions.zoomMin,!1),this._initOptions.zoomMax!==c&&this._setOption("zoomMax",this._initOptions.zoomMax,!1),this._initOptions.zoomFactor!==c&&(this._setOption("zoomFactor",this._initOptions.zoomFactor,!1),this._fullZoomFactor=this._initOptions.zoomFactor,this._partialZoomFactor=Math.pow(4,1/this._fullZoomFactor)),this._initOptions.bbox&&this._setOption("bbox",this._initOptions.bbox,!1),this._initOptions.center&&this._setOption("center",this._initOptions.center,!1),this._initOptions.zoom!==c&&this._setOption("zoom",this._initOptions.zoom,!1)),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area),this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._createServices(),this._refresh(),this._created=!0},_setOption:function(b,d,e){if("pixelSize"!==b){e=e===c||e,this._$elem.is(".geo-map")&&this._panFinalize();var f,g,h,i;switch(b){case"bbox":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),f=[d[0]+(d[2]-d[0])/2,d[1]+(d[3]-d[1])/2],g=Math.max(a.geo.width(d,!0)/this._contentBounds.width,a.geo.height(d,!0)/this._contentBounds.height),i=this._getZoom(f,g),this._options.tilingScheme?g=this._getPixelSize(Math.min(Math.max(i,this._options.zoomMin),this._options.zoomMax)):ithis._options.zoomMax&&(g=this._getPixelSize(this._options.zoomMax)),this._created?(this._setInteractiveCenterAndSize(f,g),this._setInteractiveTimeout(!1)):this._setCenterAndSize(f,g,!1,e),d=this._getBbox(f,g);break;case"bboxMax":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d);break;case"center":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),this._created?(this._setInteractiveCenterAndSize(d,this._pixelSizeInteractive),this._interactiveTransform(),this._setInteractiveTimeout(!1)):this._setCenterAndSize(d,this._pixelSize,!1,e);break;case"measureLabels":d=a.extend(this._options.measureLabels,d),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area);break;case"drawStyle":this._$drawContainer&&(this._$drawContainer.geographics("option","style",d),d=this._$drawContainer.geographics("option","style"));break;case"shapeStyle":this._$elem.is(".geo-service")&&!this._createdGraphics&&this._createServiceGraphics(),this._createdGraphics&&(this._$shapesContainer.geographics("option","style",d),d=this._$shapesContainer.geographics("option","style"));break;case"mode":this._resetDrawing(),this._$eventTarget.css("cursor",this._options.cursors[d]);break;case"zoom":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj,this._created?this._setZoom(d,!1,e):(d=Math.max(d,0),this._setCenterAndSize(this._center,this._getPixelSize(d),!1,e))}switch(a.Widget.prototype._setOption.apply(this,arguments),b){case"bbox":case"center":this._userGeodetic&&(this._options.bbox=a.geo.proj.toGeodetic(this._options.bbox),this._options.center=a.geo.proj.toGeodetic(this._center));break;case"tilingScheme":null!==d&&(this._pixelSizeMax=this._getPixelSize(0),this._pixelSizeMin=this._getPixelSize(d.pixelSizes?d.pixelSizes.length-1:d.levels-1),this._centerMax=[d.origin[0]+this._pixelSizeMax*d.tileWidth/2,d.origin[1]+this._pixelSizeMax*d.tileHeight/2]);break;case"bboxMax":h=this._userGeodetic?a.geo.proj.fromGeodetic(d):d,this._centerMax=a.geo.center(h),this._pixelSizeMax=Math.max(a.geo.width(h,!0)/this._contentBounds.width,a.geo.height(h,!0)/this._contentBounds.height);break;case"services":this._createServices(),e&&(this._refresh(),this._refreshAllShapes());break;case"shapeStyle":e&&this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))}}},destroy:function(){if(this._$elem.is(".geo-service"))this._createdGraphics&&(this._$shapesContainer.geographics("destroy"),this._$shapesContainer=c,this._createdGraphics=!1);else{clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,this._created=!1,a(b).unbind("resize",this._windowHandler);for(var d=0;d=0||1>=b)for(var d=0;d0)){this._createdGraphics||this._createServiceGraphics();var d,e,f,g,h,i;for(d=a.isArray(b)?b:"FeatureCollection"===b.type?b.features:[b],f=1;f=0;g--)if(d=this._graphicShapes[g],h)if("Point"===d.shape.type)a.geo.distance(d.shape,b)<=i&&j.push(d.shape);else{var k=a.data(d.shape,"geoBbox"),l={type:"Polygon",coordinates:[[[k[0],k[1]],[k[0],k[3]],[k[2],k[3]],[k[2],k[1]],[k[0],k[1]]]]},m={type:"Point",coordinates:a.geo.proj&&a.geo._isGeodetic(b.coordinates)?a.geo.proj.fromGeodetic(b.coordinates):b.coordinates};if(a.geo.distance(l,m,!0)<=i)for(e=a.geo._basic(d.shape),f=0;f0)){for(var e,f=a.isArray(b)?b:[b],g=0;g=0&&(e=this._graphicShapes.slice(g+1),this._graphicShapes.length=g,this._graphicShapes.push.apply(this._graphicShapes,e),g--);(d===c||d)&&(this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh(),this._refreshAllShapes())}},_getBbox:function(a,b){a=a||this._center,b=b||this._pixelSize;var c=this._contentBounds.width/2*b,d=this._contentBounds.height/2*b;return[a[0]-c,a[1]-d,a[0]+c,a[1]+d]},_setBbox:function(b){var c=[b[0]+(b[2]-b[0])/2,b[1]+(b[3]-b[1])/2],d=Math.max(a.geo.width(b,!0)/this._contentBounds.width,a.geo.height(b,!0)/this._contentBounds.height),e=this._getZoom(c,d);this._options.tilingScheme?d=this._getPixelSize(Math.min(Math.max(e,this._options.zoomMin),this._options.zoomMax)):ethis._options.zoomMax&&(d=this._getPixelSize(this._options.zoomMax)),this._setInteractiveCenterAndSize(c,d),this._interactiveTransform()},_getBboxMax:function(){var a=this._contentBounds.width/2*this._pixelSizeMax,b=this._contentBounds.height/2*this._pixelSizeMax;return[this._centerMax[0]-a,this._centerMax[1]-b,this._centerMax[0]+a,this._centerMax[1]+b]},_getCenter:function(){return this._center},_getContentBounds:function(){return this._contentBounds},_getServicesContainer:function(){return this._$servicesContainer},_getZoom:function(b,c){b=b||this._center,c=c||this._pixelSize;var d=this._options.tilingScheme;if(d){if(d.pixelSizes){for(var e=Math.floor(1e3*c),f=d.pixelSizes.length,g=f-1;g>=0;g--)if(Math.floor(1e3*d.pixelSizes[g])>=e)return g;return 0}return Math.round(Math.log(d.basePixelSize/c)/Math.log(2))}var h=this._contentBounds.width/this._contentBounds.height,i=a.geo.reaspect(this._getBbox(b,c),h,!0),j=a.geo.reaspect(this._getBboxMax(),h,!0);return Math.round(Math.log(a.geo.width(j,!0)/a.geo.width(i,!0))/Math.log(this._fullZoomFactor))},_setZoom:function(a,b){this._clearInteractiveTimeout(),a=Math.min(Math.max(a,this._options.zoomMin),this._options.zoomMax),this._setInteractiveCenterAndSize(this._centerInteractive,this._getPixelSize(a)),this._interactiveTransform(),this._setInteractiveTimeout(b)},_createChildren:function(){this._$existingChildren=this._$elem.children(),this._forcePosition(this._$existingChildren),this._$existingChildren.detach().css({mozUserSelect:"none"});var c="width:"+this._contentBounds.width+"px; height:"+this._contentBounds.height+"px; margin:0; padding:0;",d="position:absolute; left:0; top:0;";this._$elem.prepend(b.toStaticHTML('
                      ')),this._$eventTarget=this._$contentFrame=this._$elem.children(":first"),this._$contentFrame.append('
                      '),this._$servicesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                        '),this._$attrList=this._$contentFrame.children(":last"),this._$contentFrame.append('
                        '),this._$drawContainer=this._$contentFrame.children(":last"), -this._$contentFrame.append('
                        '),this._$measureContainer=this._$contentFrame.children(":last"),this._$measureLabel=this._$measureContainer.children(),this._$contentFrame.append('
                        '),this._$shapesContainer=this._$contentFrame.children(":last"),this._$panContainer=a([this._$shapesContainer[0],this._$drawContainer[0],this._$measureContainer[0]]),this._$resizeContainer=a([this._$contentFrame[0],this._$servicesContainer[0],this._$eventTarget[0],this._$measureContainer[0]]),this._$contentFrame.append(this._$existingChildren),a("#geo-measure-style").length||a("head").prepend(b.toStaticHTML('"))},_createServices:function(){var c,d;for(d=0;d';this._$servicesContainer.append(b.toStaticHTML(h)),e=this._$servicesContainer.children(":last"),c.serviceContainer=e,a.geo._serviceTypes[c.type].create(this,e,c,d),e.data("geoMap",this).geomap(),c.attr&&this._$attrList.append("
                      • "+c.attr+"
                      • ")}this._$shapesContainers=this._$shapesContainer,this._$attrList.find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"})},_createServiceGraphics:function(){var a=this._$elem.closest(".geo-content-frame");this._$elem.append('
                        '),this._$shapesContainer=this._$elem.children(":last"),this._map._$shapesContainers=this._map._$shapesContainers.add(this._$shapesContainer),this._$shapesContainer.geographics({doubleBuffer:!f}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style")},_refreshDrawing:function(){if(this._$drawContainer.geographics("clear"),this._drawPixels.length>0){var b,c,d,e,f,g=this._options.mode,h=this._drawPixels,i=this._drawCoords;switch(g){case"measureLength":g="drawLineString",c={type:"LineString",coordinates:i},b=a.render[this._tmplLengthId]({length:a.geo.length(c,!0)}),d=a.merge([],h[h.length-1]);break;case"measureArea":g="drawPolygon",c={type:"Polygon",coordinates:[a.merge([],i)]},c.coordinates[0].push(i[0]),b=a.render[this._tmplAreaId]({area:a.geo.area(c,!0)}),d=this._toPixel(a.geo.centroid(c).coordinates),h=[h];break;case"drawPolygon":h=[h]}this._$drawContainer.geographics(g,h),b&&(this._$measureLabel.html(b),e=this._contentBounds.width-(this._$measureLabel.outerWidth(!0)+d[0]),f=this._contentBounds.height-(this._$measureLabel.outerHeight(!0)+d[1]),0>e&&(d[0]+=e),0>f&&(d[1]+=f),this._$measureLabel.css({left:Math.max(d[0],0),top:Math.max(d[1],0)}).show())}},_resetDrawing:function(){this._drawPixels=[],this._drawCoords=[],this._$drawContainer.geographics("clear"),this._$measureLabel.hide()},_refreshAllShapes:function(a){this._timeoutRefreshShapes=null;for(var b,c,d=0;d0&&c._refreshShapes(c._$shapesContainer,c._graphicShapes,c._graphicShapes,c._graphicShapes)));this._createdGraphics&&!a&&(this._$shapesContainer.geographics("clear"),this._graphicShapes.length>0&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))},_refreshShapes:function(b,d,e,f,g,h){var i,j,k,l,m,n,o,p,q,r=this._map._getBbox(g,h);for(i=0;i0&&a.height>0);)a={width:b.width(),height:b.height()},(a.width<=0||a.height<=0)&&(a={width:parseInt(b.css("width"),10),height:parseInt(b.css("height"),10)}),b=b.parent();return a},_forcePosition:function(a){var b=a.css("position");"relative"!==b&&"absolute"!==b&&"fixed"!==b&&a.css("position","relative")},_getPixelSize:function(b){var c=this._options.tilingScheme;if(null!==c){if(0===b)return c.pixelSizes?c.pixelSizes[0]:c.basePixelSize;b=Math.round(b),b=Math.max(b,0);var d=c.pixelSizes?c.pixelSizes.length:c.levels;return b=Math.min(b,d-1),c.pixelSizes?c.pixelSizes[b]:c.basePixelSize/Math.pow(2,b)}var e=a.geo.scaleBy(this._getBboxMax(),1/Math.pow(this._fullZoomFactor,b),!0);return Math.max(a.geo.width(e,!0)/this._contentBounds.width,a.geo.height(e,!0)/this._contentBounds.height)},_getZoomCenterAndSize:function(a,b,c){var d=c?this._fullZoomFactor:this._partialZoomFactor,e=Math.pow(d,-b),f=this._pixelSizeInteractive*e;this._options.tilingScheme&&(f=Math.min(Math.max(f,this._pixelSizeMin),this._pixelSizeMax));var g=this._getZoom(this._centerInteractive,f);c&&this._options.tilingScheme?f=this._getPixelSize(Math.min(Math.max(g,this._options.zoomMin),this._options.zoomMax)):0>b&&g0&&g>this._options.zoomMax&&(f=this._pixelSizeInteractive);var h=f/this._pixelSizeInteractive,i=this._toMap(a,this._centerInteractive,this._pixelSizeInteractive),j=[(this._centerInteractive[0]-i[0])*h,(this._centerInteractive[1]-i[1])*h],k=[i[0]+j[0],i[1]+j[1]];return{pixelSize:f,center:k}},_panFinalize:function(){this._panning&&(this._velocity=[0,0],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._inOp=!1,this._anchor=this._current,this._mouseDown=this._toolPan=this._panning=!1)},_panMove:function(){if(this._options.pannable){var a=this._current[0]-this._lastDrag[0],b=this._current[1]-this._lastDrag[1];(this._toolPan||a>3||-3>a||b>3||-3>b)&&(this._toolPan||(this._toolPan=!0,this._$eventTarget.css("cursor",this._options.cursors.pan)),this._mouseDown&&(this._velocity=[a,b]),(0!==a||0!==b)&&(this._panning=!0,this._lastDrag=this._current,this._centerInteractive[0]-=a*this._pixelSizeInteractive,this._centerInteractive[1]+=("image"===this._options.axisLayout?-1:1)*b*this._pixelSizeInteractive,this._setInteractiveCenterAndSize(this._centerInteractive,this._pixelSizeInteractive),this._interactiveTransform()))}},_clearInteractiveTimeout:function(){return this._timeoutRefreshShapes&&(clearTimeout(this._timeoutRefreshShapes),this._timeoutRefreshShapes=null),this._timeoutInteractive?(clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,!0):(this._centerInteractive[0]=this._center[0],this._centerInteractive[1]=this._center[1],this._pixelSizeInteractive=this._pixelSize,!1)},_interactiveTransform:function(){var b,c=this._pixelSize,d=c/this._pixelSizeInteractive;if(c>0){d=Math.round(1e3*d)/1e3;var e=this._toMap([0,0]),f=this._toPixel(e,this._centerInteractive,this._pixelSizeInteractive);this._$shapesContainers.geographics("interactiveTransform",f,d)}for(var g=0;g0&&(this._drawPixels=this._toPixel(this._drawCoords,this._centerInteractive,this._pixelSizeInteractive),this._refreshDrawing())},_interactiveTimeout:function(){this._isMultiTouch?this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128):this._created&&this._timeoutInteractive&&(this._setCenterAndSize(this._centerInteractive,this._pixelSizeInteractive,this._triggerInteractive,!0),this._timeoutInteractive=null,this._triggerInteractive=!1,this._timeoutRefreshShapes=setTimeout(a.proxy(this._refreshAllShapes,this),128))},_setInteractiveTimeout:function(b){this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128),this._triggerInteractive|=b},_refresh:function(b,c){for(var d,e=0;ethis._options.zoomMax&&(this._pixelSizeInteractive=d=this._getPixelSize(this._options.zoomMax)),this._centerInteractive[0]=c[0],this._centerInteractive[1]=c[1],this._created&&this._interactiveTransform(),this._options.pixelSize=this._pixelSize=d,this._center[0]=c[0],this._center[1]=c[1],this._userGeodetic?(this._options.bbox=a.geo.proj.toGeodetic(this._getBbox()),this._options.center=a.geo.proj.toGeodetic(this._center)):(this._options.bbox=this._getBbox(),this._options.center=a.merge([],c)),this._options.zoom=g,e&&this._trigger("bboxchange",b.event,{bbox:a.merge([],this._options.bbox)}),f&&(this._refresh(),this._refreshAllShapes(),this._refreshDrawing())}},_requestQueued:function(){0===this._loadCount&&this._trigger("loadstart",b.event),this._loadCount++},_requestComplete:function(){this._loadCount--,this._loadCount<=0&&(this._loadCount=0,this._trigger("loadend",b.event))},_toMap:function(b,c,d){c=c||this._center,d=d||this._pixelSize;var e,f,g,h,i=a.isArray(b[0]),j=i&&a.isArray(b[0][0]),k=j&&a.isArray(b[0][0][0]),l=this._contentBounds.width,m=this._contentBounds.height,n=l/2*d,o=m/2*d,p=[c[0]-n,c[1]-o,c[0]+n,c[1]+o],q=a.geo.width(p,!0)/l,r=a.geo.height(p,!0)/m,s="image"===this._options.axisLayout,t=[];for(k||(j||(i||(b=[b]),b=[b]),b=[b]),f=0;f0&&27===b.which&&(2>=c?(this._resetDrawing(),this._inOp=!1):(this._drawCoords[c-2]=a.merge([],this._drawCoords[c-1]),this._drawPixels[c-2]=a.merge([],this._drawPixels[c-1]),this._drawCoords.length--,this._drawPixels.length--,this._refreshDrawing()))},_eventTarget_dblclick_zoom:function(a){var b=this._clearInteractiveTimeout();if(this._trigger("dblclick",a,{type:"Point",coordinates:this._toMap(this._current,this._centerInteractive,this._pixelSizeInteractive)}),!a.isDefaultPrevented()){var c=this._getZoomCenterAndSize(this._current,1,!0);this._setInteractiveCenterAndSize(c.center,c.pixelSize),this._interactiveTransform(),b=!0}b&&this._setInteractiveTimeout(!0)},_eventTarget_dblclick:function(c){if("static"!==this._options.mode){switch(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),this._options.mode){case"drawLineString":case"measureLength":this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])?(this._drawCoords.length--,this._trigger("shape",c,{type:"LineString",coordinates:this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords})):this._eventTarget_dblclick_zoom(c),this._resetDrawing();break;case"drawPolygon":case"measureArea":if(this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])){var d=this._drawCoords.length-1;d>2&&(this._drawCoords[d]=a.merge([],this._drawCoords[0]),this._trigger("shape",c,{type:"Polygon",coordinates:[this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords]}))}else this._eventTarget_dblclick_zoom(c);this._resetDrawing();break;default:this._eventTarget_dblclick_zoom(c)}this._inOp=!1}},_eventTarget_touchstart:function(b){if("undefined"!=typeof document.elementFromPoint){var c=document.elementFromPoint(b.pageX,b.pageY);if(c&&"A"===c.nodeName)return}var d=this._options.mode,e=this._options.shift,f="dragBox"===d?"dragBox":"zoom";if("static"!==d&&(this._pointerEvents||this._supportTouch||1===b.which)){var g=this._clearInteractiveTimeout(),h=a(b.currentTarget).offset(),i=b.originalEvent.changedTouches;if(this._pointerEvents){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0)return b.currentTarget.setPointerCapture(b.originalEvent.pointerId),this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-h.left,this._multiTouchAnchor[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=a.geo.center(this._multiTouchCurrentBbox,!0),this._current=a.merge([],this._anchor),g&&this._setInteractiveTimeout(!0),!1;this._multiTouchAnchor.length<2&&(b.currentTarget.setPointerCapture(b.originalEvent.pointerId),this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top,NaN,NaN],this._current=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top])}else this._supportTouch&&i?(this._multiTouchAnchor=a.merge([],i),this._isMultiTouch=this._multiTouchAnchor.length>1,this._isMultiTouch?(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,i[1].pageX-h.left,i[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._current=a.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,NaN,NaN],this._current=[i[0].pageX-h.left,i[0].pageY-h.top])):this._current=[b.pageX-h.left,b.pageY-h.top];if(this._softDblClick){var j=a.now();if(j-this._downDate<750){if(this._isTap){var k=this._current[0]-this._anchor[0],l=this._current[1]-this._anchor[1],m=Math.sqrt(k*k+l*l);m>8?this._isTap=!1:this._current=a.merge([],this._anchor)}this._isDbltap?this._isDbltap=!1:this._isDbltap=this._isTap}else this._isDbltap=!1;this._isTap=!0,this._downDate=j}return this._mouseDown=!0,this._anchor=a.merge([],this._current),!this._inOp&&b.shiftKey&&"off"!==e?(this._shiftDown=!0,this._$eventTarget.css("cursor",this._options.cursors["default"===e?f:e])):this._isMultiTouch||!this._options.pannable&&"dragBox"!==d&&"dragCircle"!==d||(this._inOp=!0,"zoom"!==d&&"dragBox"!==d&&"dragCircle"!==d&&(this._lastDrag=this._current,b.currentTarget.setCapture&&b.currentTarget.setCapture())),b.preventDefault(),g&&this._setInteractiveTimeout(!0),!1}},_dragTarget_touchmove:function(b){if("static"!==this._options.mode){var c=!1;this._mouseDown&&(c=this._clearInteractiveTimeout());var d,f,g,h,i,j,k=this._$eventTarget.offset(),l=this._drawCoords.length,m=b.originalEvent.changedTouches,n=null;if(this._pointerEvents)if(this._isMultiTouch){if(b.originalEvent.pointerId===this._multiTouchAnchor[0].pointerId)this._multiTouchCurrentBbox[0]=b.originalEvent.pageX-k.left,this._multiTouchCurrentBbox[1]=b.originalEvent.pageY-k.top;else{if(b.originalEvent.pointerId!==this._multiTouchAnchor[1].pointerId)return b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1;this._multiTouchCurrentBbox[2]=b.originalEvent.pageX-k.left,this._multiTouchCurrentBbox[3]=b.originalEvent.pageY-k.top}d=a.geo._distancePointPoint([this._multiTouchAnchorBbox[0],this._multiTouchAnchorBbox[1]],[this._multiTouchAnchorBbox[2],this._multiTouchAnchorBbox[3]]),f=a.geo._distancePointPoint([this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1]],[this._multiTouchCurrentBbox[2],this._multiTouchCurrentBbox[3]]),g=(f-d)/d,g*=g>0?5:10,h=g-this._wheelLevel,this._wheelLevel=g,i=this._getZoomCenterAndSize(this._anchor,h,!1),this._setInteractiveCenterAndSize(i.center,i.pixelSize),this._interactiveTransform(),c=!0,n=a.geo.center(this._multiTouchCurrentBbox,!0)}else this._multiTouchAnchor[0]=b.originalEvent,this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-k.left,this._multiTouchAnchor[0].pageY-k.top,NaN,NaN],n=[b.originalEvent.pageX-k.left,b.originalEvent.pageY-k.top];else if(this._supportTouch&&m){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&m[0].identifier!==this._multiTouchAnchor[0].identifier)return this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(m[0]),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-k.left,this._multiTouchAnchor[1].pageY-k.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=this._current=a.geo.center(this._multiTouchCurrentBbox,!0),c&&this._setInteractiveTimeout(!0),!1;if(this._isMultiTouch){for(j=0;j0?5:10,h=g-this._wheelLevel,this._wheelLevel=g,i=this._getZoomCenterAndSize(this._anchor,h,!1),this._setInteractiveCenterAndSize(i.center,i.pixelSize),this._interactiveTransform(),c=!0,n=a.geo.center(this._multiTouchCurrentBbox,!0)}else n=[b.originalEvent.changedTouches[0].pageX-k.left,b.originalEvent.changedTouches[0].pageY-k.top]}else n=[b.pageX-k.left,b.pageY-k.top];if(null===n)return b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1;if(n[0]===this._lastMove[0]&&n[1]===this._lastMove[1])return this._inOp?(b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1):!1;if(7===e&&(this._isDbltap=this._isTap=!1),this._mouseDown&&(this._current=n,this._moveDate=a.now()),this._isMultiTouch)return b.preventDefault(),this._isDbltap=this._isTap=!1,c&&this._setInteractiveTimeout(!0),!1;var o,p,q,r=this._options.mode,s=this._options.shift,t="dragBox"===r?"dragBox":"zoom";switch(this._shiftDown&&(r="default"===s?t:s),r){case"zoom":case"dragBox":this._mouseDown?(this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawBbox",[this._anchor[0],this._anchor[1],n[0],n[1]])):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)});break;case"dragCircle":this._mouseDown?(o=n[0]-this._anchor[0],p=n[1]-this._anchor[1],q=2*Math.sqrt(o*o+p*p),this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawArc",this._anchor,0,360,{width:q,height:q})):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)});break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":this._mouseDown||this._toolPan?(this._panMove(),c=!0):(l>0&&(this._drawCoords[l-1]=this._toMap(n,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[l-1]=n,this._refreshDrawing()),this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)}));break;default:this._mouseDown||this._toolPan?(this._panMove(),c=!0):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)})}return this._lastMove=n,c&&this._setInteractiveTimeout(!0),this._inOp?(b.preventDefault(),!1):void 0}},_dragTarget_touchstop:function(c){if("static"!==this._options.mode){if(!this._mouseDown){if(7!==e)return;this._eventTarget_touchstart(c)}var d,f,g,h,i,j,k=this._clearInteractiveTimeout(),l=this._mouseDown,m=this._toolPan,n=this._$eventTarget.offset(),o=this._options.mode,p=this._options.shift,q="dragBox"===o?"dragBox":"zoom",r=null;if(this._shiftDown&&(o="default"===p?q:p),this._pointerEvents){if(c.originalEvent.pointerId!==this._multiTouchAnchor[0].pointerId&&c.originalEvent.pointerId!==this._multiTouchAnchor[1].pointerId)return c.preventDefault(),void(k&&this._setInteractiveTimeout(!0));c.currentTarget.releasePointerCapture(c.originalEvent.pointerId),r=[c.originalEvent.pageX-n.left,c.originalEvent.pageY-n.top],this._multiTouchAnchor=[],this._inOp=!1}else this._supportTouch&&c.originalEvent.changedTouches?(r=[c.originalEvent.changedTouches[0].pageX-n.left,c.originalEvent.changedTouches[0].pageY-n.top],this._multiTouchAnchor=[],this._inOp=!1):r=[c.pageX-n.left,c.pageY-n.top];if(this._softDblClick&&this._isTap&&(g=r[0]-this._anchor[0],h=r[1]-this._anchor[1],Math.sqrt(g*g+h*h)<=8&&(r=a.merge([],this._anchor))),g=r[0]-this._anchor[0],h=r[1]-this._anchor[1],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._shiftDown=this._mouseDown=this._toolPan=!1,this._isMultiTouch)return c.preventDefault(),this._isMultiTouch=!1,this._wheelLevel=0,void(k&&this._setInteractiveTimeout(!0));if(document.releaseCapture&&document.releaseCapture(),l){switch(f=a.now(),this._current=r,o){case"zoom":case"dragBox":if(0!==g||0!==h){var s=6*this._pixelSize,t=this._toMap([this._anchor,r]),u=[Math.min(t[0][0],t[1][0]),Math.min(t[0][1],t[1][1]),Math.max(t[0][0],t[1][0]),Math.max(t[0][1],t[1][1])];"zoom"===o?(u[2]-u[0]d;d++)v=360*d/y*(Math.PI/180),this._drawPixels[d]=[this._anchor[0]+Math.cos(v)*x,this._anchor[1]+Math.sin(v)*x];this._drawPixels[y]=[this._drawPixels[0][0],this._drawPixels[0][1]],i=this._toMap([[this._anchor[0]-x,this._anchor[1]+(w?-x:x)],[this._anchor[0]+x,this._anchor[1]+(w?x:-x)]]),j={type:"Polygon",coordinates:[this._toMap(this._drawPixels)],bbox:[i[0][0],i[0][1],i[1][0],i[1][1]]},this._userGeodetic&&(j.coordinates=a.geo.proj.toGeodetic(j.coordinates),j.bbox=a.geo.proj.toGeodetic(j.bbox)),this._trigger("shape",c,j),this._resetDrawing()}else i=this._toMap(r),j={type:"Point",coordinates:[i[0],i[1]],bbox:[i[0],i[1],i[0],i[1]]},this._userGeodetic&&(j.coordinates=a.geo.proj.toGeodetic(j.coordinates),j.bbox=a.geo.proj.toGeodetic(j.bbox)),this._trigger("shape",c,j);break;case"drawPoint":if(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),m)this._panFinalize();else if(f-this._clickDate>100){var z=this;this._drawTimeout=setTimeout(function(){z._drawTimeout&&(z._trigger("shape",c,{type:"Point",coordinates:z.toMap(r)}),z._inOp=!1,z._drawTimeout=null)},250)}break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":m?this._panFinalize():(this._trigger("click",c,{type:"Point",coordinates:this.toMap(r)}),c.isDefaultPrevented()||(d=0===this._drawCoords.length?0:this._drawCoords.length-1,this._drawCoords[d]=this._toMap(r),this._drawPixels[d]=r,(2>d||this._drawCoords[d][0]!==this._drawCoords[d-1][0]||this._drawCoords[d][1]!==this._drawCoords[d-1][1])&&(this._drawCoords[d+1]=this._toMap(r,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[d+1]=r),this._refreshDrawing()));break;default:m?this._panFinalize():f-this._clickDate>100&&(this._trigger("click",c,{type:"Point",coordinates:this.toMap(r)}),this._inOp=!1)}if(this._clickDate=f,this._softDblClick&&this._isDbltap)return this._isDbltap=this._isTap=!1,k&&this._setInteractiveTimeout(!0),this._$eventTarget.trigger("softdblclick",c),!1}return k&&this._setInteractiveTimeout(!0),this._inOp?(c.preventDefault(),!1):void 0}},_eventTarget_mousewheel:function(b){if("static"!==this._options.mode&&"off"!==this._options.scroll){if(b.preventDefault(),this._mouseDown)return!1;if(0!==b.deltaY){this._timeoutWheel&&(clearTimeout(this._timeoutWheel),this._timeoutWheel=null);var c=this,d=b.currentTarget,e=b.deltaY,f=b.pageX,g=b.pageY;this._timeoutWheel=setTimeout(function(){c._clearInteractiveTimeout();var b=e>0?1:-1,h=a(d).offset();c._anchor=[f-h.left,g-h.top];var i=c._getZoomCenterAndSize(c._anchor,b,null!==c._options.tilingScheme);c._setInteractiveCenterAndSize(i.center,i.pixelSize),c._interactiveTransform(),c._setInteractiveTimeout(!0)},30)}return!1}}})}(jQuery,window),function(a,b,c){a.geo._serviceTypes.tiled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0,reloadTiles:!1};var g='
                        ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b.options.tilingScheme;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),h=f/e;if(f>0){h=Math.round(1e3*h)/1e3;var i=c.data("scaleOrigin"),j=b._toPixel(i,d,e);c.css({left:Math.round(j[0])+"px",top:Math.round(j[1])+"px",width:g.tileWidth*h,height:g.tileHeight*h})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&f&&(g.reloadTiles=!0),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i,j=d._getBbox(),k=d._pixelSize,l=this,m=g.serviceContainer,n="image"===d.options.axisLayout,o=n?1:-1,p=d.options.tilingScheme,q=p.tileWidth,r=p.tileHeight,s=Math.floor((j[0]-p.origin[0])/(k*q)),t=Math.max(Math.floor((n?j[1]-p.origin[1]:p.origin[1]-j[3])/(k*r)),0),u=Math.ceil((j[2]-p.origin[0])/(k*q)),v=Math.ceil((n?j[3]-p.origin[1]:p.origin[1]-j[1])/(k*r)),w=d._getBboxMax(),x=d._getPixelSize(0),y=x/k,z=Math.floor((w[0]-p.origin[0])/(x*q))*y,A=Math.floor((p.origin[1]+o*w[3])/(x*r))*y,B=p.origin[0]+z*q*k,C=p.origin[1]+o*(A*r)*k,D=Math.round((B-j[0])/k),E=Math.round((n?C-j[1]:j[3]-C)/k),F=m.children().show(),G=F.filter("[data-pixel-size='"+k+"']").appendTo(m),H=e.style.opacity,I=function(a){l._loadImage(this.img,a,k,d,g,H)},J=function(){delete this.img,g.loadCount--,d._requestComplete()};for(g.reloadTiles&&F.find("img").attr("data-dirty","true"),G.size()?(G.css({left:D%q+"px",top:E%r+"px"}).data("scaleOrigin",d._toMap([D%q,E%r])),G.children().each(function(){var b=a(this),c=b.attr("data-tile").split(",");b.css({left:Math.round(100*(parseInt(c[0],10)-z)+(D-D%q)/q*100)+"%",top:Math.round(100*(parseInt(c[1],10)-A)+(E-E%r)/r*100)+"%"}),1>H&&b.fadeTo(0,H)})):(m.append(b.toStaticHTML("
                        ")),G=m.children(":last").data("scaleOrigin",d._toMap([D%q,E%r]))),h=s;u>h;h++)for(i=t;v>i;i++){var K=""+h+","+i,L=G.children("[data-tile='"+K+"']").removeAttr("data-dirty");if(0===L.size()||g.reloadTiles){var M,N=[p.origin[0]+h*q*k,p.origin[1]+o*(i*r)*k],O=[p.origin[0]+((h+1)*q-1)*k,p.origin[1]+o*((i+1)*r-1)*k],P=[N[0],N[1],O[0],O[1]],Q={bbox:P,width:q,height:r,zoom:d._getZoom(),tile:{row:i,column:h},index:Math.abs(i+h)},R=a.isFunction(e.src);if(R?M=e.src(Q):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),M=a.render[this._tmplGeoSrcId](Q)):M=e.src,g.loadCount++,d._requestQueued(),g.reloadTiles&&L.size()>0)L.attr("src",M);else{var S="",G.append(b.toStaticHTML(S)),L=G.children(":last")}"string"==typeof M?l._loadImage(L,M,k,d,g,H):M&&a.isFunction(M.promise)?(a.extend(M.promise(),{img:L}),M.done(I).fail(J)):L.remove()}}F.find("[data-dirty]").remove(),g.reloadTiles=!1}},resize:function(){},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--, -b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){1>g?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).error(function(b){a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).attr("src",c)}}}()}(jQuery,window),function(a,b,c){a.geo._serviceTypes.shingled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0};var g='
                        ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b._getContentBounds(),h=g.width,i=g.height;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),g=f/e;if(f>0){g=Math.round(1e3*g)/1e3;var j=c.data("origin"),k=b._toPixel(j,d,e);c.css({left:Math.round(k[0]),top:Math.round(k[1]),width:h*g,height:i*g})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i=d._getBbox(),j=d._pixelSize,k=this,l=g.serviceContainer,m=d._getContentBounds(),n=m.width,o=m.height,p=l.children('[data-pixel-size="'+j+'"]'),q=e.style.opacity;1>q||f||1===e.shinglesMax?l.find("img").attr("data-keep-alive","0"):e.shinglesMax>1&&l.find("img").slice(0,-(e.shinglesMax-1)).attr("data-keep-alive","0"),p.size()||(l.append(b.toStaticHTML('
                        ')),p=l.children(":last"));var r,s={bbox:i,width:n,height:o,zoom:d._getZoom(),tile:null,index:0},t=a.isFunction(e.src),u=p.position();u.left=-u.left,u.top=-u.top,t?r=e.src(s):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),r=a.render[this._tmplGeoSrcId](s)):r=e.src,g.loadCount++,d._requestQueued(),p.append(b.toStaticHTML('')),h=p.children(":last").data("center",d._center),"string"==typeof r?k._loadImage(h,r,j,d,g,q):r&&r.done(function(a){k._loadImage(h,a,j,d,g,q)}).fail(function(){h.remove(),g.loadCount--,d._requestComplete()})}},resize:function(b,c){var d=a.data(c,"geoServiceState");if(d&&c&&"visible"===c.style.visibility){this._cancelUnloaded(b,c);var e=d.serviceContainer,f=b._getContentBounds(),g=f.width,h=f.height,i=e.children();i.attr("data-pixel-size","0"),i.each(function(){var b=a(this),c=b.position();b.css({left:c.left+(g-b.width())/2,top:c.top+(h-b.height())/2})})}},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--,b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(1>g?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(':not([data-pixel-size="'+d+'"])').remove(),h.find("img[data-keep-alive]").remove(),f.loadCount=0))}).error(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0))}).attr("src",c)}}}()}(jQuery,window); \ No newline at end of file diff --git a/dist/jquery.geo-1.0.0-test.js b/dist/jquery.geo-1.0.0-test.js deleted file mode 100644 index a5da020..0000000 --- a/dist/jquery.geo-1.0.0-test.js +++ /dev/null @@ -1,7522 +0,0 @@ -/*! jQuery Geo - v1.0.0-test - 2016-06-05 -* http://jquerygeo.com -* Copyright (c) 2016 Ryan Morrison-Westphal; Licensed MIT */ -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -// Known Issues: -// -// * Patterns only support repeat. -// * Radial gradient are not implemented. The VML version of these look very -// different from the canvas one. -// * Clipping paths are not implemented. -// * Coordsize. The width and height attribute have higher priority than the -// width and height style values which isn't correct. -// * Painting mode isn't implemented. -// * Canvas width/height should is using content-box by default. IE in -// Quirks mode will draw the canvas using border-box. Either change your -// doctype to HTML5 -// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) -// or use Box Sizing Behavior from WebFX -// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) -// * Non uniform scaling does not correctly scale strokes. -// * Optimize. There is always room for speed improvements. - -// Only add this code if we do not already have a canvas implementation -if (!document.createElement('canvas').getContext) { - - (function () { - - // alias some functions to make (compiled) code shorter - var m = Math; - var mr = m.round; - var ms = m.sin; - var mc = m.cos; - var abs = m.abs; - var sqrt = m.sqrt; - - // this is used for sub pixel precision - var Z = 10; - var Z2 = Z / 2; - - var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; - - /** - * This funtion is assigned to the elements as element.getContext(). - * @this {HTMLElement} - * @return {CanvasRenderingContext2D_} - */ - function getContext() { - return this.context_ || - (this.context_ = new CanvasRenderingContext2D_(this)); - } - - var slice = Array.prototype.slice; - - /** - * Binds a function to an object. The returned function will always use the - * passed in {@code obj} as {@code this}. - * - * Example: - * - * g = bind(f, obj, a, b) - * g(c, d) // will do f.call(obj, a, b, c, d) - * - * @param {Function} f The function to bind the object to - * @param {Object} obj The object that should act as this when the function - * is called - * @param {*} var_args Rest arguments that will be used as the initial - * arguments when the function is called - * @return {Function} A new function that has bound this - */ - function bind(f, obj, var_args) { - var a = slice.call(arguments, 2); - return function () { - return f.apply(obj, a.concat(slice.call(arguments))); - }; - } - - function encodeHtmlAttribute(s) { - return String(s).replace(/&/g, '&').replace(/"/g, '"'); - } - - function addNamespace(doc, prefix, urn) { - if (!doc.namespaces[prefix]) { - doc.namespaces.add(prefix, urn, '#default#VML'); - } - } - - function addNamespacesAndStylesheet(doc) { - addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); - addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); - - // Setup default CSS. Only add one style sheet per document - if (!doc.styleSheets['ex_canvas_']) { - var ss = doc.createStyleSheet(); - ss.owningElement.id = 'ex_canvas_'; - ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + - // default size is 300x150 in Gecko and Opera - 'text-align:left;width:300px;height:150px}'; - } - } - - // Add namespaces and stylesheet at startup. - addNamespacesAndStylesheet(document); - - var G_vmlCanvasManager_ = { - init: function (opt_doc) { - var doc = opt_doc || document; - // Create a dummy element so that IE will allow canvas elements to be - // recognized. - doc.createElement('canvas'); - doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); - }, - - init_: function (doc) { - // find all canvas elements - var els = doc.getElementsByTagName('canvas'); - for (var i = 0; i < els.length; i++) { - this.initElement(els[i]); - } - }, - - /** - * Public initializes a canvas element so that it can be used as canvas - * element from now on. This is called automatically before the page is - * loaded but if you are creating elements using createElement you need to - * make sure this is called on the element. - * @param {HTMLElement} el The canvas element to initialize. - * @return {HTMLElement} the element that was created. - */ - initElement: function (el) { - if (!el.getContext) { - el.getContext = getContext; - - // Add namespaces and stylesheet to document of the element. - addNamespacesAndStylesheet(el.ownerDocument); - - // Remove fallback content. There is no way to hide text nodes so we - // just remove all childNodes. We could hide all elements and remove - // text nodes but who really cares about the fallback content. - el.innerHTML = ''; - - // do not use inline function because that will leak memory - el.attachEvent('onpropertychange', onPropertyChange); - el.attachEvent('onresize', onResize); - - var attrs = el.attributes; - if (attrs.width && attrs.width.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setWidth_(attrs.width.nodeValue); - el.style.width = attrs.width.nodeValue + 'px'; - } else { - el.width = el.clientWidth; - } - if (attrs.height && attrs.height.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setHeight_(attrs.height.nodeValue); - el.style.height = attrs.height.nodeValue + 'px'; - } else { - el.height = el.clientHeight; - } - //el.getContext().setCoordsize_() - } - return el; - } - }; - - function onPropertyChange(e) { - var el = e.srcElement; - - switch (e.propertyName) { - case 'width': - el.getContext().clearRect(); - el.style.width = el.attributes.width.nodeValue + 'px'; - // In IE8 this does not trigger onresize. - el.firstChild.style.width = el.clientWidth + 'px'; - break; - case 'height': - el.getContext().clearRect(); - el.style.height = el.attributes.height.nodeValue + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - break; - } - } - - function onResize(e) { - var el = e.srcElement; - if (el.firstChild) { - el.firstChild.style.width = el.clientWidth + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - } - } - - G_vmlCanvasManager_.init(); - - // precompute "00" to "FF" - var decToHex = []; - for (var i = 0; i < 16; i++) { - for (var j = 0; j < 16; j++) { - decToHex[i * 16 + j] = i.toString(16) + j.toString(16); - } - } - - function createMatrixIdentity() { - return [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1] - ]; - } - - function matrixMultiply(m1, m2) { - var result = createMatrixIdentity(); - - for (var x = 0; x < 3; x++) { - for (var y = 0; y < 3; y++) { - var sum = 0; - - for (var z = 0; z < 3; z++) { - sum += m1[x][z] * m2[z][y]; - } - - result[x][y] = sum; - } - } - return result; - } - - function copyState(o1, o2) { - o2.fillStyle = o1.fillStyle; - o2.lineCap = o1.lineCap; - o2.lineJoin = o1.lineJoin; - o2.lineWidth = o1.lineWidth; - o2.miterLimit = o1.miterLimit; - o2.shadowBlur = o1.shadowBlur; - o2.shadowColor = o1.shadowColor; - o2.shadowOffsetX = o1.shadowOffsetX; - o2.shadowOffsetY = o1.shadowOffsetY; - o2.strokeStyle = o1.strokeStyle; - o2.globalAlpha = o1.globalAlpha; - o2.font = o1.font; - o2.textAlign = o1.textAlign; - o2.textBaseline = o1.textBaseline; - o2.arcScaleX_ = o1.arcScaleX_; - o2.arcScaleY_ = o1.arcScaleY_; - o2.lineScale_ = o1.lineScale_; - } - - // var colorData = { - // aliceblue: '#F0F8FF', - // antiquewhite: '#FAEBD7', - // aquamarine: '#7FFFD4', - // azure: '#F0FFFF', - // beige: '#F5F5DC', - // bisque: '#FFE4C4', - // black: '#000000', - // blanchedalmond: '#FFEBCD', - // blueviolet: '#8A2BE2', - // brown: '#A52A2A', - // burlywood: '#DEB887', - // cadetblue: '#5F9EA0', - // chartreuse: '#7FFF00', - // chocolate: '#D2691E', - // coral: '#FF7F50', - // cornflowerblue: '#6495ED', - // cornsilk: '#FFF8DC', - // crimson: '#DC143C', - // cyan: '#00FFFF', - // darkblue: '#00008B', - // darkcyan: '#008B8B', - // darkgoldenrod: '#B8860B', - // darkgray: '#A9A9A9', - // darkgreen: '#006400', - // darkgrey: '#A9A9A9', - // darkkhaki: '#BDB76B', - // darkmagenta: '#8B008B', - // darkolivegreen: '#556B2F', - // darkorange: '#FF8C00', - // darkorchid: '#9932CC', - // darkred: '#8B0000', - // darksalmon: '#E9967A', - // darkseagreen: '#8FBC8F', - // darkslateblue: '#483D8B', - // darkslategray: '#2F4F4F', - // darkslategrey: '#2F4F4F', - // darkturquoise: '#00CED1', - // darkviolet: '#9400D3', - // deeppink: '#FF1493', - // deepskyblue: '#00BFFF', - // dimgray: '#696969', - // dimgrey: '#696969', - // dodgerblue: '#1E90FF', - // firebrick: '#B22222', - // floralwhite: '#FFFAF0', - // forestgreen: '#228B22', - // gainsboro: '#DCDCDC', - // ghostwhite: '#F8F8FF', - // gold: '#FFD700', - // goldenrod: '#DAA520', - // grey: '#808080', - // greenyellow: '#ADFF2F', - // honeydew: '#F0FFF0', - // hotpink: '#FF69B4', - // indianred: '#CD5C5C', - // indigo: '#4B0082', - // ivory: '#FFFFF0', - // khaki: '#F0E68C', - // lavender: '#E6E6FA', - // lavenderblush: '#FFF0F5', - // lawngreen: '#7CFC00', - // lemonchiffon: '#FFFACD', - // lightblue: '#ADD8E6', - // lightcoral: '#F08080', - // lightcyan: '#E0FFFF', - // lightgoldenrodyellow: '#FAFAD2', - // lightgreen: '#90EE90', - // lightgrey: '#D3D3D3', - // lightpink: '#FFB6C1', - // lightsalmon: '#FFA07A', - // lightseagreen: '#20B2AA', - // lightskyblue: '#87CEFA', - // lightslategray: '#778899', - // lightslategrey: '#778899', - // lightsteelblue: '#B0C4DE', - // lightyellow: '#FFFFE0', - // limegreen: '#32CD32', - // linen: '#FAF0E6', - // magenta: '#FF00FF', - // mediumaquamarine: '#66CDAA', - // mediumblue: '#0000CD', - // mediumorchid: '#BA55D3', - // mediumpurple: '#9370DB', - // mediumseagreen: '#3CB371', - // mediumslateblue: '#7B68EE', - // mediumspringgreen: '#00FA9A', - // mediumturquoise: '#48D1CC', - // mediumvioletred: '#C71585', - // midnightblue: '#191970', - // mintcream: '#F5FFFA', - // mistyrose: '#FFE4E1', - // moccasin: '#FFE4B5', - // navajowhite: '#FFDEAD', - // oldlace: '#FDF5E6', - // olivedrab: '#6B8E23', - // orange: '#FFA500', - // orangered: '#FF4500', - // orchid: '#DA70D6', - // palegoldenrod: '#EEE8AA', - // palegreen: '#98FB98', - // paleturquoise: '#AFEEEE', - // palevioletred: '#DB7093', - // papayawhip: '#FFEFD5', - // peachpuff: '#FFDAB9', - // peru: '#CD853F', - // pink: '#FFC0CB', - // plum: '#DDA0DD', - // powderblue: '#B0E0E6', - // rosybrown: '#BC8F8F', - // royalblue: '#4169E1', - // saddlebrown: '#8B4513', - // salmon: '#FA8072', - // sandybrown: '#F4A460', - // seagreen: '#2E8B57', - // seashell: '#FFF5EE', - // sienna: '#A0522D', - // skyblue: '#87CEEB', - // slateblue: '#6A5ACD', - // slategray: '#708090', - // slategrey: '#708090', - // snow: '#FFFAFA', - // springgreen: '#00FF7F', - // steelblue: '#4682B4', - // tan: '#D2B48C', - // thistle: '#D8BFD8', - // tomato: '#FF6347', - // turquoise: '#40E0D0', - // violet: '#EE82EE', - // wheat: '#F5DEB3', - // whitesmoke: '#F5F5F5', - // yellowgreen: '#9ACD32' - // }; - - - function getRgbHslContent(styleString) { - var start = styleString.indexOf('(', 3); - var end = styleString.indexOf(')', start + 1); - var parts = styleString.substring(start + 1, end).split(','); - // add alpha if needed - if (parts.length != 4 || styleString.charAt(3) != 'a') { - parts[3] = 1; - } - return parts; - } - - function percent(s) { - return parseFloat(s) / 100; - } - - function clamp(v, min, max) { - return Math.min(max, Math.max(min, v)); - } - - function hslToRgb(parts) { - var r, g, b, h, s, l; - h = parseFloat(parts[0]) / 360 % 360; - if (h < 0) - h++; - s = clamp(percent(parts[1]), 0, 1); - l = clamp(percent(parts[2]), 0, 1); - if (s == 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1 / 3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1 / 3); - } - - return '#' + decToHex[Math.floor(r * 255)] + - decToHex[Math.floor(g * 255)] + - decToHex[Math.floor(b * 255)]; - } - - function hueToRgb(m1, m2, h) { - if (h < 0) - h++; - if (h > 1) - h--; - - if (6 * h < 1) - return m1 + (m2 - m1) * 6 * h; - else if (2 * h < 1) - return m2; - else if (3 * h < 2) - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - else - return m1; - } - - var processStyleCache = {}; - - function processStyle(styleString) { - if (styleString in processStyleCache) { - return processStyleCache[styleString]; - } - - var str, alpha = 1; - - styleString = String(styleString); - if (styleString.charAt(0) == '#') { - str = styleString; - } else if (/^rgb/.test(styleString)) { - var parts = getRgbHslContent(styleString); - var str = '#', n; - for (var i = 0; i < 3; i++) { - if (parts[i].indexOf('%') != -1) { - n = Math.floor(percent(parts[i]) * 255); - } else { - n = +parts[i]; - } - str += decToHex[clamp(n, 0, 255)]; - } - alpha = +parts[3]; - } else if (/^hsl/.test(styleString)) { - var parts = getRgbHslContent(styleString); - str = hslToRgb(parts); - alpha = parts[3]; - } else { - str = /*colorData[styleString] ||*/styleString; - } - return processStyleCache[styleString] = { color: str, alpha: alpha }; - } - - var DEFAULT_STYLE = { - style: 'normal', - variant: 'normal', - weight: 'normal', - size: 10, - family: 'sans-serif' - }; - - // Internal text style cache - // var fontStyleCache = {}; - - // function processFontStyle(styleString) { - // if (fontStyleCache[styleString]) { - // return fontStyleCache[styleString]; - // } - - // var el = document.createElement('div'); - // var style = el.style; - // try { - // style.font = styleString; - // } catch (ex) { - // // Ignore failures to set to invalid font. - // } - - // return fontStyleCache[styleString] = { - // style: style.fontStyle || DEFAULT_STYLE.style, - // variant: style.fontVariant || DEFAULT_STYLE.variant, - // weight: style.fontWeight || DEFAULT_STYLE.weight, - // size: style.fontSize || DEFAULT_STYLE.size, - // family: style.fontFamily || DEFAULT_STYLE.family - // }; - // } - - // function getComputedStyle(style, element) { - // var computedStyle = {}; - - // for (var p in style) { - // computedStyle[p] = style[p]; - // } - - // // Compute the size - // var canvasFontSize = parseFloat(element.currentStyle.fontSize), - // fontSize = parseFloat(style.size); - - // if (typeof style.size == 'number') { - // computedStyle.size = style.size; - // } else if (style.size.indexOf('px') != -1) { - // computedStyle.size = fontSize; - // } else if (style.size.indexOf('em') != -1) { - // computedStyle.size = canvasFontSize * fontSize; - // } else if(style.size.indexOf('%') != -1) { - // computedStyle.size = (canvasFontSize / 100) * fontSize; - // } else if (style.size.indexOf('pt') != -1) { - // computedStyle.size = fontSize / .75; - // } else { - // computedStyle.size = canvasFontSize; - // } - - // // Different scaling between normal text and VML text. This was found using - // // trial and error to get the same size as non VML text. - // computedStyle.size *= 0.981; - - // return computedStyle; - // } - - // function buildStyle(style) { - // return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + - // style.size + 'px ' + style.family; - // } - - var lineCapMap = { - 'butt': 'flat', - 'round': 'round' - }; - - function processLineCap(lineCap) { - return lineCapMap[lineCap] || 'square'; - } - - /** - * This class implements CanvasRenderingContext2D interface as described by - * the WHATWG. - * @param {HTMLElement} canvasElement The element that the 2D context should - * be associated with - */ - function CanvasRenderingContext2D_(canvasElement) { - this.m_ = createMatrixIdentity(); - - this.mStack_ = []; - this.aStack_ = []; - this.currentPath_ = []; - - // Canvas context properties - this.strokeStyle = '#000'; - this.fillStyle = '#000'; - - this.lineWidth = 1; - this.lineJoin = 'miter'; - this.lineCap = 'butt'; - this.miterLimit = Z * 1; - this.globalAlpha = 1; - //this.font = '10px sans-serif'; - //this.textAlign = 'left'; - //this.textBaseline = 'alphabetic'; - this.canvas = canvasElement; - - var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + - canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; - var el = canvasElement.ownerDocument.createElement('div'); - el.style.cssText = cssText; - canvasElement.appendChild(el); - - var overlayEl = el.cloneNode(false); - // Use a non transparent background. - overlayEl.style.backgroundColor = 'red'; - overlayEl.style.filter = 'alpha(opacity=0)'; - canvasElement.appendChild(overlayEl); - - this.element_ = el; - this.arcScaleX_ = 1; - this.arcScaleY_ = 1; - this.lineScale_ = 1; - } - - var contextPrototype = CanvasRenderingContext2D_.prototype; - contextPrototype.clearRect = function () { - if (this.textMeasureEl_) { - this.textMeasureEl_.removeNode(true); - this.textMeasureEl_ = null; - } - this.element_.innerHTML = ''; - }; - - contextPrototype.beginPath = function () { - // TODO: Branch current matrix so that save/restore has no effect - // as per safari docs. - this.currentPath_ = []; - }; - - contextPrototype.moveTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'moveTo', x: p.x, y: p.y }); - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.lineTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'lineTo', x: p.x, y: p.y }); - - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY) { - var p = getCoords(this, aX, aY); - var cp1 = getCoords(this, aCP1x, aCP1y); - var cp2 = getCoords(this, aCP2x, aCP2y); - bezierCurveTo(this, cp1, cp2, p); - }; - - // Helper function that takes the already fixed cordinates. - function bezierCurveTo(self, cp1, cp2, p) { - self.currentPath_.push({ - type: 'bezierCurveTo', - cp1x: cp1.x, - cp1y: cp1.y, - cp2x: cp2.x, - cp2y: cp2.y, - x: p.x, - y: p.y - }); - self.currentX_ = p.x; - self.currentY_ = p.y; - } - - contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { - // the following is lifted almost directly from - // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes - - var cp = getCoords(this, aCPx, aCPy); - var p = getCoords(this, aX, aY); - - var cp1 = { - x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), - y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) - }; - var cp2 = { - x: cp1.x + (p.x - this.currentX_) / 3.0, - y: cp1.y + (p.y - this.currentY_) / 3.0 - }; - - bezierCurveTo(this, cp1, cp2, p); - }; - - contextPrototype.arc = function (aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise) { - aRadius *= Z; - var arcType = aClockwise ? 'at' : 'wa'; - - var xStart = aX + mc(aStartAngle) * aRadius - Z2; - var yStart = aY + ms(aStartAngle) * aRadius - Z2; - - var xEnd = aX + mc(aEndAngle) * aRadius - Z2; - var yEnd = aY + ms(aEndAngle) * aRadius - Z2; - - // IE won't render arches drawn counter clockwise if xStart == xEnd. - if (xStart == xEnd && !aClockwise) { - xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something - // that can be represented in binary - } - - var p = getCoords(this, aX, aY); - var pStart = getCoords(this, xStart, yStart); - var pEnd = getCoords(this, xEnd, yEnd); - - this.currentPath_.push({ type: arcType, - x: p.x, - y: p.y, - radius: aRadius, - xStart: pStart.x, - yStart: pStart.y, - xEnd: pEnd.x, - yEnd: pEnd.y - }); - - }; - - // contextPrototype.rect = function(aX, aY, aWidth, aHeight) { - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // }; - - // contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.stroke(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.fill(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { - // var gradient = new CanvasGradient_('gradient'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // return gradient; - // }; - - // contextPrototype.createRadialGradient = function(aX0, aY0, aR0, - // aX1, aY1, aR1) { - // var gradient = new CanvasGradient_('gradientradial'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.r0_ = aR0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // gradient.r1_ = aR1; - // return gradient; - // }; - - // contextPrototype.drawImage = function(image, var_args) { - // var dx, dy, dw, dh, sx, sy, sw, sh; - - // // to find the original width we overide the width and height - // var oldRuntimeWidth = image.runtimeStyle.width; - // var oldRuntimeHeight = image.runtimeStyle.height; - // image.runtimeStyle.width = 'auto'; - // image.runtimeStyle.height = 'auto'; - - // // get the original size - // var w = image.width; - // var h = image.height; - - // // and remove overides - // image.runtimeStyle.width = oldRuntimeWidth; - // image.runtimeStyle.height = oldRuntimeHeight; - - // if (arguments.length == 3) { - // dx = arguments[1]; - // dy = arguments[2]; - // sx = sy = 0; - // sw = dw = w; - // sh = dh = h; - // } else if (arguments.length == 5) { - // dx = arguments[1]; - // dy = arguments[2]; - // dw = arguments[3]; - // dh = arguments[4]; - // sx = sy = 0; - // sw = w; - // sh = h; - // } else if (arguments.length == 9) { - // sx = arguments[1]; - // sy = arguments[2]; - // sw = arguments[3]; - // sh = arguments[4]; - // dx = arguments[5]; - // dy = arguments[6]; - // dw = arguments[7]; - // dh = arguments[8]; - // } else { - // throw Error('Invalid number of arguments'); - // } - - // var d = getCoords(this, dx, dy); - - // var w2 = sw / 2; - // var h2 = sh / 2; - - // var vmlStr = []; - - // var W = 10; - // var H = 10; - - // // For some reason that I've now forgotten, using divs didn't work - // vmlStr.push(' ' , - // '', - // ''); - - // this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); - // }; - - contextPrototype.stroke = function (aFill) { - var lineStr = []; - var lineOpen = false; - - var W = 10; - var H = 10; - - lineStr.push(''); - - if (!aFill) { - appendStroke(this, lineStr); - } else { - appendFill(this, lineStr, min, max); - } - - lineStr.push(''); - - this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - }; - - function appendStroke(ctx, lineStr) { - var a = processStyle(ctx.strokeStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - var lineWidth = ctx.lineScale_ * ctx.lineWidth; - - // VML cannot correctly render a line if the width is less than 1px. - // In that case, we dilute the color to make the line look thinner. - if (lineWidth < 1) { - opacity *= lineWidth; - } - - lineStr.push( - '' - ); - } - - function appendFill(ctx, lineStr, min, max) { - var fillStyle = ctx.fillStyle; - var arcScaleX = ctx.arcScaleX_; - var arcScaleY = ctx.arcScaleY_; - var width = max.x - min.x; - var height = max.y - min.y; - // if (fillStyle instanceof CanvasGradient_) { - // // TODO: Gradients transformed with the transformation matrix. - // var angle = 0; - // var focus = {x: 0, y: 0}; - - // // additional offset - // var shift = 0; - // // scale factor for offset - // var expansion = 1; - - // if (fillStyle.type_ == 'gradient') { - // var x0 = fillStyle.x0_ / arcScaleX; - // var y0 = fillStyle.y0_ / arcScaleY; - // var x1 = fillStyle.x1_ / arcScaleX; - // var y1 = fillStyle.y1_ / arcScaleY; - // var p0 = getCoords(ctx, x0, y0); - // var p1 = getCoords(ctx, x1, y1); - // var dx = p1.x - p0.x; - // var dy = p1.y - p0.y; - // angle = Math.atan2(dx, dy) * 180 / Math.PI; - - // // The angle should be a non-negative number. - // if (angle < 0) { - // angle += 360; - // } - - // // Very small angles produce an unexpected result because they are - // // converted to a scientific notation string. - // if (angle < 1e-6) { - // angle = 0; - // } - // } else { - // var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); - // focus = { - // x: (p0.x - min.x) / width, - // y: (p0.y - min.y) / height - // }; - - // width /= arcScaleX * Z; - // height /= arcScaleY * Z; - // var dimension = m.max(width, height); - // shift = 2 * fillStyle.r0_ / dimension; - // expansion = 2 * fillStyle.r1_ / dimension - shift; - // } - - // // We need to sort the color stops in ascending order by offset, - // // otherwise IE won't interpret it correctly. - // var stops = fillStyle.colors_; - // stops.sort(function(cs1, cs2) { - // return cs1.offset - cs2.offset; - // }); - - // var length = stops.length; - // var color1 = stops[0].color; - // var color2 = stops[length - 1].color; - // var opacity1 = stops[0].alpha * ctx.globalAlpha; - // var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; - - // var colors = []; - // for (var i = 0; i < length; i++) { - // var stop = stops[i]; - // colors.push(stop.offset * expansion + shift + ' ' + stop.color); - // } - - // // When colors attribute is used, the meanings of opacity and o:opacity2 - // // are reversed. - // lineStr.push(''); - // } else if (fillStyle instanceof CanvasPattern_) { - // if (width && height) { - // var deltaLeft = -min.x; - // var deltaTop = -min.y; - // lineStr.push(''); - // } - // } else { - var a = processStyle(ctx.fillStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - lineStr.push(''); - // } - } - - contextPrototype.fill = function () { - this.stroke(true); - }; - - contextPrototype.closePath = function () { - this.currentPath_.push({ type: 'close' }); - }; - - function getCoords(ctx, aX, aY) { - var m = ctx.m_; - return { - x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, - y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 - }; - }; - - contextPrototype.save = function () { - var o = {}; - copyState(this, o); - this.aStack_.push(o); - this.mStack_.push(this.m_); - this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); - }; - - contextPrototype.restore = function () { - if (this.aStack_.length) { - copyState(this.aStack_.pop(), this); - this.m_ = this.mStack_.pop(); - } - }; - - function matrixIsFinite(m) { - return isFinite(m[0][0]) && isFinite(m[0][1]) && - isFinite(m[1][0]) && isFinite(m[1][1]) && - isFinite(m[2][0]) && isFinite(m[2][1]); - } - - function setM(ctx, m, updateLineScale) { - if (!matrixIsFinite(m)) { - return; - } - ctx.m_ = m; - - if (updateLineScale) { - // Get the line scale. - // Determinant of this.m_ means how much the area is enlarged by the - // transformation. So its square root can be used as a scale factor - // for width. - var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; - ctx.lineScale_ = sqrt(abs(det)); - } - } - - contextPrototype.translate = function (aX, aY) { - var m1 = [ - [1, 0, 0], - [0, 1, 0], - [aX, aY, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), false); - }; - - // contextPrototype.rotate = function(aRot) { - // var c = mc(aRot); - // var s = ms(aRot); - - // var m1 = [ - // [c, s, 0], - // [-s, c, 0], - // [0, 0, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), false); - // }; - - contextPrototype.scale = function (aX, aY) { - this.arcScaleX_ *= aX; - this.arcScaleY_ *= aY; - var m1 = [ - [aX, 0, 0], - [0, aY, 0], - [0, 0, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), true); - }; - - // contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { - // var m1 = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), true); - // }; - - // contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { - // var m = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, m, true); - // }; - - /** - * The text drawing function. - * The maxWidth argument isn't taken in account, since no browser supports - * it yet. - */ - // contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { - // var m = this.m_, - // delta = 1000, - // left = 0, - // right = delta, - // offset = {x: 0, y: 0}, - // lineStr = []; - - // var fontStyle = getComputedStyle(processFontStyle(this.font), - // this.element_); - - // var fontStyleString = buildStyle(fontStyle); - - // var elementStyle = this.element_.currentStyle; - // var textAlign = this.textAlign.toLowerCase(); - // switch (textAlign) { - // case 'left': - // case 'center': - // case 'right': - // break; - // case 'end': - // textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; - // break; - // case 'start': - // textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; - // break; - // default: - // textAlign = 'left'; - // } - - // // 1.75 is an arbitrary number, as there is no info about the text baseline - // switch (this.textBaseline) { - // case 'hanging': - // case 'top': - // offset.y = fontStyle.size / 1.75; - // break; - // case 'middle': - // break; - // default: - // case null: - // case 'alphabetic': - // case 'ideographic': - // case 'bottom': - // offset.y = -fontStyle.size / 2.25; - // break; - // } - - // switch(textAlign) { - // case 'right': - // left = delta; - // right = 0.05; - // break; - // case 'center': - // left = right = delta / 2; - // break; - // } - - // var d = getCoords(this, x + offset.x, y + offset.y); - - // lineStr.push(''); - - // if (stroke) { - // appendStroke(this, lineStr); - // } else { - // // TODO: Fix the min and max params. - // appendFill(this, lineStr, {x: -left, y: 0}, - // {x: right, y: fontStyle.size}); - // } - - // var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + - // m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; - - // var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); - - // lineStr.push('', - // '', - // ''); - - // this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - // }; - - // contextPrototype.fillText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, false); - // }; - - // contextPrototype.strokeText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, true); - // }; - - // contextPrototype.measureText = function(text) { - // if (!this.textMeasureEl_) { - // var s = ''; - // this.element_.insertAdjacentHTML('beforeEnd', s); - // this.textMeasureEl_ = this.element_.lastChild; - // } - // var doc = this.element_.ownerDocument; - // this.textMeasureEl_.innerHTML = ''; - // this.textMeasureEl_.style.font = this.font; - // // Don't use innerHTML or innerText because they allow markup/whitespace. - // this.textMeasureEl_.appendChild(doc.createTextNode(text)); - // return {width: this.textMeasureEl_.offsetWidth}; - // }; - - /******** STUBS ********/ - // contextPrototype.clip = function() { - // // TODO: Implement - // }; - - // contextPrototype.arcTo = function() { - // // TODO: Implement - // }; - - // contextPrototype.createPattern = function(image, repetition) { - // return new CanvasPattern_(image, repetition); - // }; - - // // Gradient / Pattern Stubs - // function CanvasGradient_(aType) { - // this.type_ = aType; - // this.x0_ = 0; - // this.y0_ = 0; - // this.r0_ = 0; - // this.x1_ = 0; - // this.y1_ = 0; - // this.r1_ = 0; - // this.colors_ = []; - // } - - // CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { - // aColor = processStyle(aColor); - // this.colors_.push({offset: aOffset, - // color: aColor.color, - // alpha: aColor.alpha}); - // }; - - // function CanvasPattern_(image, repetition) { - // assertImageIsValid(image); - // switch (repetition) { - // case 'repeat': - // case null: - // case '': - // this.repetition_ = 'repeat'; - // break - // case 'repeat-x': - // case 'repeat-y': - // case 'no-repeat': - // this.repetition_ = repetition; - // break; - // default: - // throwException('SYNTAX_ERR'); - // } - - // this.src_ = image.src; - // this.width_ = image.width; - // this.height_ = image.height; - // } - - function throwException(s) { - throw new DOMException_(s); - } - - // function assertImageIsValid(img) { - // if (!img || img.nodeType != 1 || img.tagName != 'IMG') { - // throwException('TYPE_MISMATCH_ERR'); - // } - // if (img.readyState != 'complete') { - // throwException('INVALID_STATE_ERR'); - // } - // } - - function DOMException_(s) { - this.code = this[s]; - this.message = s + ': DOM Exception ' + this.code; - } - var p = DOMException_.prototype = new Error; - p.INDEX_SIZE_ERR = 1; - p.DOMSTRING_SIZE_ERR = 2; - p.HIERARCHY_REQUEST_ERR = 3; - p.WRONG_DOCUMENT_ERR = 4; - p.INVALID_CHARACTER_ERR = 5; - p.NO_DATA_ALLOWED_ERR = 6; - p.NO_MODIFICATION_ALLOWED_ERR = 7; - p.NOT_FOUND_ERR = 8; - p.NOT_SUPPORTED_ERR = 9; - p.INUSE_ATTRIBUTE_ERR = 10; - p.INVALID_STATE_ERR = 11; - p.SYNTAX_ERR = 12; - p.INVALID_MODIFICATION_ERR = 13; - p.NAMESPACE_ERR = 14; - p.INVALID_ACCESS_ERR = 15; - p.VALIDATION_ERR = 16; - p.TYPE_MISMATCH_ERR = 17; - - // set up externs - G_vmlCanvasManager = G_vmlCanvasManager_; - CanvasRenderingContext2D = CanvasRenderingContext2D_; - //CanvasGradient = CanvasGradient_; - //CanvasPattern = CanvasPattern_; - DOMException = DOMException_; - })(); - -} // if - -/*! JsRender v1.0pre: http://github.com/BorisMoore/jsrender */ -/* - * Optimized version of jQuery Templates, for rendering to string. - * Does not require jQuery, or HTML DOM - * Integrates with JsViews (http://github.com/BorisMoore/jsviews) - * Copyright 2012, Boris Moore - * Released under the MIT License. - */ -// informal pre beta commit counter: 3 - -this.jsviews || this.jQuery && jQuery.views || (function( window, undefined ) { - -//========================== Top-level vars ========================== - -var versionNumber = "v1.0pre", - - $, rTag, rTmplString, extend, - sub = {}, - FALSE = false, TRUE = true, - jQuery = window.jQuery, - - rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // nil object helper view viewProperty pathTokens leafToken string - - rParams = /(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - - rNewLine = /\r?\n/g, - rUnescapeQuotes = /\\(['"])/g, - rEscapeQuotes = /\\?(['"])/g, - rBuildHash = /\x08(~)?([^\x08]+)\x08/g, - - autoViewKey = 0, - autoTmplName = 0, - escapeMapForHtml = { - "&": "&", - "<": "<", - ">": ">" - }, - tmplAttr = "data-jsv-tmpl", - fnDeclStr = "var j=j||" + (jQuery ? "jQuery." : "js") + "views,", - htmlSpecialChar = /[\x00"&'<>]/g, - slice = Array.prototype.slice, - - render = {}, - - // jsviews object ($.views if jQuery is loaded) - jsv = { - jsviews: versionNumber, - sub: sub, // subscription, e.g. JsViews integration - debugMode: TRUE, - err: function( e ) { - return jsv.debugMode ? ("
                        Error: " + (e.message || e) + ". ") : '""'; - }, - tmplFn: tmplFn, - render: render, - templates: templates, - tags: tags, - helpers: helpers, - converters: converters, - View: View, - convert: convert, - delimiters: setDelimiters, - tag: renderTag - }; - -//========================== Top-level functions ========================== - -//=================== -// jsviews.delimiters -//=================== - -function setDelimiters( openChars, closeChars ) { - // Set the tag opening and closing delimiters. Default is "{{" and "}}" - // openChar, closeChars: opening and closing strings, each with two characters - var firstOpenChar = "\\" + openChars.charAt( 0 ), // Escape the characters - since they could be regex special characters - secondOpenChar = "\\" + openChars.charAt( 1 ), - firstCloseChar = "\\" + closeChars.charAt( 0 ), - secondCloseChar = "\\" + closeChars.charAt( 1 ); - // Build regex with new delimiters - jsv.rTag = rTag // make rTag available to JsViews (or other components) for parsing binding expressions - = secondOpenChar - // tag (followed by / space or }) or colon or html or code - + "(?:(?:(\\w+(?=[\\/\\s" + firstCloseChar + "]))|(?:(\\w+)?(:)|(>)|(\\*)))" - // params - + "\\s*((?:[^" + firstCloseChar + "]|" + firstCloseChar + "(?!" + secondCloseChar + "))*?)" - // slash or closeBlock - + "(\\/)?|(?:\\/(\\w+)))" - // }} - + firstCloseChar; - - // Default rTag: tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/\s\}]))|(?:(\w+)?(:)|(>)|(\*)))\s*((?:[^}]|}(?!\}))*?)(\/)?|(?:\/(\w+)))}} - - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - rTag = new RegExp( firstOpenChar + rTag + secondCloseChar, "g" ); - rTmplString = new RegExp( "<.*>|" + openChars + ".*" + closeChars ); - return this; -} - -//================= -// View.hlp -//================= - -function getHelper( helper ) { - // Helper method called as view.hlp() from compiled template, for helper functions or template parameters ~foo - var view = this, - tmplHelpers = view.tmpl.helpers || {}; - helper = (view.ctx[ helper ] !== undefined ? view.ctx : tmplHelpers[ helper ] !== undefined ? tmplHelpers : helpers[ helper ] !== undefined ? helpers : {})[ helper ]; - return typeof helper !== "function" ? helper : function() { - return helper.apply(view, arguments); - }; -} - -//================= -// jsviews.convert -//================= - -function convert( converter, view, text ) { - var tmplConverters = view.tmpl.converters; - converter = tmplConverters && tmplConverters[ converter ] || converters[ converter ]; - return converter ? converter.call( view, text ) : text; -} - -//================= -// jsviews.tag -//================= - -function renderTag( tag, parentView, converter, content, tagObject ) { - // Called from within compiled template function, to render a nested tag - // Returns the rendered tag - tagObject.props = tagObject.props || {}; - var ret, - tmpl = tagObject.props.tmpl, - tmplTags = parentView.tmpl.tags, - nestedTemplates = parentView.tmpl.templates, - args = arguments, - tagFn = tmplTags && tmplTags[ tag ] || tags[ tag ]; - - if ( !tagFn ) { - return ""; - } - // Set the tmpl property to the content of the block tag, unless set as an override property on the tag - content = content && parentView.tmpl.tmpls[ content - 1 ]; - tmpl = tmpl || content || undefined; - tagObject.tmpl = - "" + tmpl === tmpl // if a string - ? nestedTemplates && nestedTemplates[ tmpl ] || templates[ tmpl ] || templates( tmpl ) - : tmpl; - - tagObject.isTag = TRUE; - tagObject.converter = converter; - tagObject.view = parentView; - tagObject.renderContent = renderContent; - if ( parentView.ctx ) { - extend( tagObject.ctx, parentView.ctx); - } - - ret = tagFn.apply( tagObject, args.length > 5 ? slice.call( args, 5 ) : [] ); - return ret || ( ret == undefined ? "" : ret.toString()); // (If ret is the value 0 or false, will render to string) -} - -//================= -// View constructor -//================= - -function View( context, path, parentView, data, template, index ) { - // Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded) - var views = parentView.views, -// TODO: add this, as part of smart re-linking on existing content ($.link method), or remove completely -// self = parentView.views[ index ]; -// if ( !self ) { ... } - self = { - tmpl: template, - path: path, - parent: parentView, - data: data, - ctx: context, - views: $.isArray( data ) ? [] : {}, - hlp: getHelper - }; - - if ( $.isArray( views )) { - views.splice( - self.index = index !== undefined - ? index - : views.length, 0, self - ); - } else { - views[ self.index = "_" + autoViewKey++ ] = self; - } - return self; -} - -//================= -// Registration -//================= - -function addToStore( self, store, name, item, process ) { - // Add item to named store such as templates, helpers, converters... - var key, onStore; - if ( name && typeof name === "object" && !name.nodeType ) { - // If name is a map, iterate over map and call store for key - for ( key in name ) { - store( key, name[ key ]); - } - return self; - } - if ( !name || item === undefined ) { - if ( process ) { - item = process( undefined, item || name ); - } - } else if ( "" + name === name ) { // name must be a string - if ( item === null ) { - // If item is null, delete this entry - delete store[name]; - } else if ( item = process ? process( name, item ) : item ) { - store[ name ] = item; - } - } - if ( onStore = sub.onStoreItem ) { - // e.g. JsViews integration - onStore( store, name, item, process ); - } - return item; -} - -function templates( name, tmpl ) { - // Register templates - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, templates, name, tmpl, compile ); -} - -function tags( name, tagFn ) { - // Register template tags - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, tags, name, tagFn ); -} - -function helpers( name, helperFn ) { - // Register helper functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.helpers( name, helperFn ) or $.view.helpers({ name: helperFn, ... }) to add additional helpers to the registered helpers collection. - // Getter: Use var helperFn = $.views.helpers( name ) or $.views.helpers[name] or $.views.helpers.name to return the function. - // Remove: Use $.view.helpers( name, null ) to remove a registered helper function from $.view.helpers. - // Within a template, access the helper using the syntax: {{... ~myHelper(...) ...}}. - return addToStore( this, helpers, name, helperFn ); -} - -function converters( name, converterFn ) { - // Register converter functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.converters( name, converterFn ) or $.view.converters({ name: converterFn, ... }) to add additional converters to the registered converters collection. - // Getter: Use var converterFn = $.views.converters( name ) or $.views.converters[name] or $.views.converters.name to return the converter function. - // Remove: Use $.view.converters( name, null ) to remove a registered converter from $.view.converters. - // Within a template, access the converter using the syntax: {{myConverter:...}}. - return addToStore( this, converters, name, converterFn ); -} - -//================= -// renderContent -//================= - -function renderContent( data, context, parentView, path, index ) { - // Render template against data as a tree of subviews (nested template), or as a string (top-level template). - // tagName parameter for internal use only. Used for rendering templates registered as tags (which may have associated presenter objects) - var i, l, dataItem, newView, itemWrap, itemsWrap, itemResult, parentContext, tmpl, layout, - props = {}, - swapContent = index === TRUE, - self = this, - result = ""; - - if ( self.isTag ) { - // This is a call from renderTag - tmpl = self.tmpl; - context = context || self.ctx; - parentView = parentView || self.view; - path = path || self.path; - index = index || self.index; - props = self.props; - } else { - tmpl = self.jquery && self[0] // This is a call $.fn.render - || self; // This is a call from tmpl.render - } - parentView = parentView || jsv.topView; - parentContext = parentView.ctx; - layout = tmpl.layout; - if ( data === parentView ) { - // Inherit the data from the parent view. - // This may be the contents of an {{if}} block - data = parentView.data; - layout = TRUE; - } - - // Set additional context on views created here, (as modified context inherited from the parent, and be inherited by child views) - // Note: If no jQuery, extend does not support chained copies - so limit extend() to two parameters - context = (context && context === parentContext) - ? parentContext - : (parentContext - // if parentContext, make copy - ? ((parentContext = extend( {}, parentContext ), context) - // If context, merge context with copied parentContext - ? extend( parentContext, context ) - : parentContext) - // if no parentContext, use context, or default to {} - : context || {}); - - if ( props.link === FALSE ) { - // Override inherited value of link by an explicit setting in props: link=false - // The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect. - context.link = FALSE; - } - if ( !tmpl.fn ) { - tmpl = templates[ tmpl ] || templates( tmpl ); - } - itemWrap = context.link && sub.onRenderItem; - itemsWrap = context.link && sub.onRenderItems; - - if ( tmpl ) { - if ( $.isArray( data ) && !layout ) { - // Create a view for the array, whose child views correspond to each data item. - // (Note: if index and parentView are passed in along with parent view, treat as - // insert -e.g. from view.addViews - so parentView is already the view item for array) - newView = swapContent ? parentView : (index !== undefined && parentView) || View( context, path, parentView, data, tmpl, index ); - - for ( i = 0, l = data.length; i < l; i++ ) { - // Create a view for each data item. - dataItem = data[ i ]; - itemResult = tmpl.fn( dataItem, View( context, path, newView, dataItem, tmpl, (index||0) + i ), jsv ); - result += itemWrap ? itemWrap( itemResult, props ) : itemResult; - } - } else { - // Create a view for singleton data object. - newView = swapContent ? parentView : View( context, path, parentView, data, tmpl, index ); - result += (data || layout) ? tmpl.fn( data, newView, jsv ) : ""; - } - parentView.topKey = newView.index; - return itemsWrap ? itemsWrap( result, path, newView.index, tmpl, props ) : result; - } - return ""; // No tmpl. Could throw... -} - -//=========================== -// Build and compile template -//=========================== - -// Generate a reusable function that will serve to render a template against data -// (Compile AST then build template function) - -function syntaxError() { - throw "Syntax error"; -} - -function tmplFn( markup, tmpl, bind ) { - // Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes - // Used for compiling templates, and also by JsViews to build functions for data link expressions - var newNode, node, i, l, code, hasTag, hasEncoder, getsValue, hasConverter, hasViewPath, tag, converter, params, hash, nestedTmpl, allowCode, - tmplOptions = tmpl ? { - allowCode: allowCode = tmpl.allowCode, - debug: tmpl.debug - } : {}, - nested = tmpl && tmpl.tmpls, - astTop = [], - loc = 0, - stack = [], - content = astTop, - current = [,,,astTop], - nestedIndex = 0; - - //==== nested functions ==== - function pushPreceedingContent( shift ) { - shift -= loc; - if ( shift ) { - content.push( markup.substr( loc, shift ).replace( rNewLine, "\\n" )); - } - } - - function parseTag( all, tagName, converter, colon, html, code, params, slash, closeBlock, index ) { - // tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(?:(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - // Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, contentMarkup ] - if ( html ) { - colon = ":"; - converter = "html"; - } - var hash = "", - passedCtx = "", - block = !slash && !colon; // Block tag if not self-closing and not {{:}} or {{>}} (special case) - - //==== nested helper function ==== - - tagName = tagName || colon; - pushPreceedingContent( index ); - loc = index + all.length; // location marker - parsed up to here - if ( code ) { - if ( allowCode ) { - content.push([ "*", params.replace( rUnescapeQuotes, "$1" ) ]); - } - } else if ( tagName ) { - if ( tagName === "else" ) { - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - content = current[ 3 ]; - block = TRUE; - } - params = (params - ? parseParams( params, bind ) - .replace( rBuildHash, function( all, isCtx, keyValue ) { - if ( isCtx ) { - passedCtx += keyValue + ","; - } else { - hash += keyValue + ","; - } - return ""; - }) - : ""); - hash = hash.slice( 0, -1 ); - params = params.slice( 0, -1 ); - newNode = [ - tagName, - converter || "", - params, - block && [], - "{" + (hash ? ("props:{" + hash + "},"): "") + "path:'" + params + "'" + (passedCtx ? ",ctx:{" + passedCtx.slice( 0, -1 ) + "}" : "") + "}" - ]; - if ( block ) { - stack.push( current ); - current = newNode; - current[ 5 ] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag - } - content.push( newNode ); - } else if ( closeBlock ) { - //if ( closeBlock !== current[ 0 ]) { - // throw "unmatched close tag: /" + closeBlock + ". Expected /" + current[ 0 ]; - //} - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - } - if ( !current ) { - throw "Expected block tag"; - } - content = current[ 3 ]; - } - //==== /end of nested functions ==== - - markup = markup.replace( rEscapeQuotes, "\\$1" ); - - // Build the AST (abstract syntax tree) under astTop - markup.replace( rTag, parseTag ); - - pushPreceedingContent( markup.length ); - - // Use the AST (astTop) to build the template function - l = astTop.length; - code = (l ? "" : '"";'); - - for ( i = 0; i < l; i++ ) { - // AST nodes: [ tagName, converter, params, content, hash, contentMarkup ] - node = astTop[ i ]; - if ( node[ 0 ] === "*" ) { - code = code.slice( 0, i ? -1 : -3 ) + ";" + node[ 1 ] + (i + 1 < l ? "ret+=" : ""); - } else if ( "" + node === node ) { // type string - code += '"' + node + '"+'; - } else { - tag = node[ 0 ]; - converter = node[ 1 ]; - params = node[ 2 ]; - content = node[ 3 ]; - hash = node[ 4 ]; - markup = node[ 5 ]; - if ( content ) { - // Create template object for nested template - nestedTmpl = TmplObject( markup, tmplOptions, tmpl, nestedIndex++ ); - // Compile to AST and then to compiled function - tmplFn( markup, nestedTmpl); - nested.push( nestedTmpl ); - } - hasViewPath = hasViewPath || hash.indexOf( "view" ) > -1; - code += (tag === ":" - ? (converter === "html" - ? (hasEncoder = TRUE, "e(" + params) - : converter - ? (hasConverter = TRUE, 'c("' + converter + '",view,' + params) - : (getsValue = TRUE, "((v=" + params + ')!=u?v:""') - ) - : (hasTag = TRUE, 't("' + tag + '",view,"' + (converter || "") + '",' - + (content ? nested.length : '""') // For block tags, pass in the key (nested.length) to the nested content template - + "," + hash + (params ? "," : "") + params)) - + ")+"; - } - } - code = new Function( "data, view, j, b, u", fnDeclStr - + (getsValue ? "v," : "") - + (hasTag ? "t=j.tag," : "") - + (hasConverter ? "c=j.convert," : "") - + (hasEncoder ? "e=j.converters.html," : "") - + "ret; try{\n\n" - + (tmplOptions.debug ? "debugger;" : "") - + (allowCode ? 'ret=' : 'return ') - + code.slice( 0, -1 ) + ";\n\n" - + (allowCode ? "return ret;" : "") - + "}catch(e){return j.err(e);}" - ); - - // Include only the var references that are needed in the code - if ( tmpl ) { - tmpl.fn = code; - tmpl.useVw = hasConverter || hasViewPath || hasTag; - } - return code; -} - -function parseParams( params, bind ) { - var named, - fnCall = {}, - parenDepth = 0, - quoted = FALSE, // boolean for string content in double quotes - aposed = FALSE; // or in single quotes - - function parseTokens( all, lftPrn0, lftPrn, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, prn2, space ) { - // rParams = /(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn path operator err eq path2 prn comma lftPrn3 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - operator = operator || ""; - lftPrn = lftPrn || lftPrn0 || lftPrn2; - path = path || path2; - prn = prn || prn2 || ""; - operator = operator || ""; - - function parsePath( all, object, helper, view, viewProperty, pathTokens, leafToken ) { - // rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // object helper view viewProperty pathTokens leafToken string - if ( object ) { - var ret = (helper - ? 'view.hlp("' + helper + '")' - : view - ? "view" - : "data") - + (leafToken - ? (viewProperty - ? "." + viewProperty - : helper - ? "" - : (view ? "" : "." + object) - ) + (pathTokens || "") - : (leafToken = helper ? "" : view ? viewProperty || "" : object, "")); - - if ( bind && prn !== "(" ) { - ret = "b(" + ret + ',"' + leafToken + '")'; - } - return ret + (leafToken ? "." + leafToken : ""); - } - return all; - } - - if ( err ) { - syntaxError(); - } else { - return (aposed - // within single-quoted string - ? (aposed = !apos, (aposed ? all : '"')) - : quoted - // within double-quoted string - ? (quoted = !quot, (quoted ? all : '"')) - : - ( - (lftPrn - ? (parenDepth++, lftPrn) - : "") - + (space - ? (parenDepth - ? "" - : named - ? (named = FALSE, "\b") - : "," - ) - : eq - // named param - ? (parenDepth && syntaxError(), named = TRUE, '\b' + path + ':') - : path - // path - ? (path.replace( rPath, parsePath ) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : operator) - ) - : operator - ? all - : rtPrn - // function - ? ((fnCall[ parenDepth-- ] = FALSE, rtPrn) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : "") - ) - : comma - ? (fnCall[ parenDepth ] || syntaxError(), ",") // We don't allow top-level literal arrays or objects - : lftPrn0 - ? "" - : (aposed = apos, quoted = quot, '"') - )) - ); - } - } - params = (params + " " ).replace( rParams, parseTokens ); - return params; -} - -function compile( name, tmpl, parent, options ) { - // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object - // options is the set of template properties, c - var tmplOrMarkup, elem, key, nested, nestedItem; - - //==== nested functions ==== - function tmplOrMarkupFromStr( value ) { - // If value is of type string - treat as selector, or name of compiled template - // Return the template object, if already compiled, or the markup string - - if ( ("" + value === value) || value.nodeType > 0 ) { - // If selector is valid and returns at least one element, get first element - elem = value.nodeType > 0 ? value : !rTmplString.test( value ) && jQuery && jQuery( value )[0]; - if ( elem && elem.type ) { - // It is a script element - // Create a name for data linking if none provided - value = templates[ elem.getAttribute( tmplAttr )]; - if ( !value ) { - // Not already compiled and cached, so compile and cache the name - name = name || "_" + autoTmplName++; - elem.setAttribute( tmplAttr, name ); - value = compile( name, elem.innerHTML, parent, options ); // Use tmpl as options - templates[ name ] = value; - } - } - return value; - } - // If value is not a string or dom element, return undefined - } - - //==== Compile the template ==== - tmplOrMarkup = tmplOrMarkupFromStr( tmpl ); - - // If tmpl is a template object, use it for options - options = options || (tmpl.markup ? tmpl : {}); - options.name = name; - nested = options.templates; - - // If tmpl is not a markup string or a selector string, then it must be a template object - // In that case, get it from the markup property of the object - if ( !tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr( tmpl.markup ))) { - if ( tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode )) { - // if the string references a compiled template object, but the debug or allowCode props are different, need to recompile - tmplOrMarkup = tmplOrMarkup.markup; - } - } - if ( tmplOrMarkup !== undefined ) { - if ( name && !parent ) { - render[ name ] = function() { - return tmpl.render.apply( tmpl, arguments ); - }; - } - if ( tmplOrMarkup.fn || tmpl.fn ) { - // tmpl is already compiled, so use it, or if different name is provided, clone it - if ( tmplOrMarkup.fn ) { - if ( name && name !== tmplOrMarkup.name ) { - tmpl = extend( extend( {}, tmplOrMarkup ), options); - } else { - tmpl = tmplOrMarkup; - } - } - } else { - // tmplOrMarkup is a markup string, not a compiled template - // Create template object - tmpl = TmplObject( tmplOrMarkup, options, parent, 0 ); - // Compile to AST and then to compiled function - tmplFn( tmplOrMarkup, tmpl ); - } - for ( key in nested ) { - // compile nested template declarations - nestedItem = nested[ key ]; - if ( nestedItem.name !== key ) { - nested[ key ] = compile( key, nestedItem, tmpl ); - } - } - return tmpl; - } -} -//==== /end of function compile ==== - -function TmplObject( markup, options, parent, index ) { - // Template object constructor - - // nested helper function - function extendStore( storeName ) { - if ( parent[ storeName ]) { - // Include parent items except if overridden by item of same name in options - tmpl[ storeName ] = extend( extend( {}, parent[ storeName ] ), options[ storeName ] ); - } - } - - options = options || {}; - var tmpl = { - markup: markup, - tmpls: [], - links: [], - render: renderContent - }; - if ( parent ) { - if ( parent.templates ) { - tmpl.templates = extend( extend( {}, parent.templates ), options.templates ); - } - tmpl.parent = parent; - tmpl.name = parent.name + "[" + index + "]"; - tmpl.index = index; - } - - extend( tmpl, options ); - if ( parent ) { - extendStore( "templates" ); - extendStore( "tags" ); - extendStore( "helpers" ); - extendStore( "converters" ); - } - return tmpl; -} - -//========================== Initialize ========================== - -if ( jQuery ) { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is loaded, so make $ the jQuery object - $ = jQuery; - $.templates = templates; - $.render = render; - $.views = jsv; - $.fn.render = renderContent; - -} else { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is not loaded. - - $ = window.jsviews = jsv; - $.extend = function( target, source ) { - var name; - target = target || {}; - for ( name in source ) { - target[ name ] = source[ name ]; - } - return target; - }; - - $.isArray = Array && Array.isArray || function( obj ) { - return Object.prototype.toString.call( obj ) === "[object Array]"; - }; -} - -extend = $.extend; - -jsv.topView = { views: {}, tmpl: {}, hlp: getHelper, ctx: jsv.helpers }; - -function replacerForHtml( ch ) { - // Original code from Mike Samuel - return escapeMapForHtml[ ch ] - // Intentional assignment that caches the result of encoding ch. - || (escapeMapForHtml[ ch ] = "&#" + ch.charCodeAt( 0 ) + ";"); -} - -//========================== Register tags ========================== - -tags({ - "if": function() { - var ifTag = this, - view = ifTag.view; - - view.onElse = function( tagObject, args ) { - var i = 0, - l = args.length; - - while ( l && !args[ i++ ]) { - // Only render content if args.length === 0 (i.e. this is an else with no condition) or if a condition argument is truey - if ( i === l ) { - return ""; - } - } - view.onElse = undefined; // If condition satisfied, so won't run 'else'. - tagObject.path = ""; - return tagObject.renderContent( view ); - // Test is satisfied, so render content, while remaining in current data context - // By passing the view, we inherit data context from the parent view, and the content is treated as a layout template - // (so if the data is an array, it will not iterate over the data - }; - return view.onElse( this, arguments ); - }, - "else": function() { - var view = this.view; - return view.onElse ? view.onElse( this, arguments ) : ""; - }, - "for": function() { - var i, - self = this, - result = "", - args = arguments, - l = args.length; - if ( self.props.layout ) { - self.tmpl.layout = TRUE; - } - for ( i = 0; i < l; i++ ) { - result += self.renderContent( args[ i ]); - } - return result; - }, - "=": function( value ) { - return value; - }, - "*": function( value ) { - return value; - } -}); - -//========================== Register global helpers ========================== - -// helpers({ // Global helper functions -// // TODO add any useful built-in helper functions -// }); - -//========================== Register converters ========================== - -converters({ - html: function( text ) { - // HTML encoding helper: Replace < > & and ' and " by corresponding entities. - // inspired by Mike Samuel - return text != undefined ? String( text ).replace( htmlSpecialChar, replacerForHtml ) : ""; - } -}); - -//========================== Define default delimiters ========================== -setDelimiters( "{{", "}}" ); - -})( this ); - -/*! - * jQuery Mousewheel 3.1.13 - * - * Copyright jQuery Foundation and other contributors - * Released under the MIT license - * http://jquery.org/license - */ - -(function (factory) { - if ( typeof define === 'function' && define.amd ) { - // AMD. Register as an anonymous module. - define(['jquery'], factory); - } else if (typeof exports === 'object') { - // Node/CommonJS style for Browserify - module.exports = factory; - } else { - // Browser globals - factory(jQuery); - } -}(function ($) { - - var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], - toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? - ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], - slice = Array.prototype.slice, - nullLowestDeltaTimeout, lowestDelta; - - if ( $.event.fixHooks ) { - for ( var i = toFix.length; i; ) { - $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; - } - } - - var special = $.event.special.mousewheel = { - version: '3.1.12', - - setup: function() { - if ( this.addEventListener ) { - for ( var i = toBind.length; i; ) { - this.addEventListener( toBind[--i], handler, false ); - } - } else { - this.onmousewheel = handler; - } - // Store the line height and page height for this particular element - $.data(this, 'mousewheel-line-height', special.getLineHeight(this)); - $.data(this, 'mousewheel-page-height', special.getPageHeight(this)); - }, - - teardown: function() { - if ( this.removeEventListener ) { - for ( var i = toBind.length; i; ) { - this.removeEventListener( toBind[--i], handler, false ); - } - } else { - this.onmousewheel = null; - } - // Clean up the data we added to the element - $.removeData(this, 'mousewheel-line-height'); - $.removeData(this, 'mousewheel-page-height'); - }, - - getLineHeight: function(elem) { - var $elem = $(elem), - $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent'](); - if (!$parent.length) { - $parent = $('body'); - } - return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16; - }, - - getPageHeight: function(elem) { - return $(elem).height(); - }, - - settings: { - adjustOldDeltas: true, // see shouldAdjustOldDeltas() below - normalizeOffset: true // calls getBoundingClientRect for each event - } - }; - - $.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); - }, - - unmousewheel: function(fn) { - return this.unbind('mousewheel', fn); - } - }); - - - function handler(event) { - var orgEvent = event || window.event, - args = slice.call(arguments, 1), - delta = 0, - deltaX = 0, - deltaY = 0, - absDelta = 0, - offsetX = 0, - offsetY = 0; - event = $.event.fix(orgEvent); - event.type = 'mousewheel'; - - // Old school scrollwheel delta - if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } - if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } - if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } - if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } - - // Firefox < 17 horizontal scrolling related to DOMMouseScroll event - if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { - deltaX = deltaY * -1; - deltaY = 0; - } - - // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy - delta = deltaY === 0 ? deltaX : deltaY; - - // New school wheel delta (wheel event) - if ( 'deltaY' in orgEvent ) { - deltaY = orgEvent.deltaY * -1; - delta = deltaY; - } - if ( 'deltaX' in orgEvent ) { - deltaX = orgEvent.deltaX; - if ( deltaY === 0 ) { delta = deltaX * -1; } - } - - // No change actually happened, no reason to go any further - if ( deltaY === 0 && deltaX === 0 ) { return; } - - // Need to convert lines and pages to pixels if we aren't already in pixels - // There are three delta modes: - // * deltaMode 0 is by pixels, nothing to do - // * deltaMode 1 is by lines - // * deltaMode 2 is by pages - if ( orgEvent.deltaMode === 1 ) { - var lineHeight = $.data(this, 'mousewheel-line-height'); - delta *= lineHeight; - deltaY *= lineHeight; - deltaX *= lineHeight; - } else if ( orgEvent.deltaMode === 2 ) { - var pageHeight = $.data(this, 'mousewheel-page-height'); - delta *= pageHeight; - deltaY *= pageHeight; - deltaX *= pageHeight; - } - - // Store lowest absolute delta to normalize the delta values - absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) ); - - if ( !lowestDelta || absDelta < lowestDelta ) { - lowestDelta = absDelta; - - // Adjust older deltas if necessary - if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { - lowestDelta /= 40; - } - } - - // Adjust older deltas if necessary - if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { - // Divide all the things by 40! - delta /= 40; - deltaX /= 40; - deltaY /= 40; - } - - // Get a whole, normalized value for the deltas - delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); - deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); - deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); - - // Normalise offsetX and offsetY properties - if ( special.settings.normalizeOffset && this.getBoundingClientRect ) { - var boundingRect = this.getBoundingClientRect(); - offsetX = event.clientX - boundingRect.left; - offsetY = event.clientY - boundingRect.top; - } - - // Add information to the event object - event.deltaX = deltaX; - event.deltaY = deltaY; - event.deltaFactor = lowestDelta; - event.offsetX = offsetX; - event.offsetY = offsetY; - // Go ahead and set deltaMode to 0 since we converted to pixels - // Although this is a little odd since we overwrite the deltaX/Y - // properties with normalized deltas. - event.deltaMode = 0; - - // Add event and delta to the front of the arguments - args.unshift(event, delta, deltaX, deltaY); - - // Clearout lowestDelta after sometime to better - // handle multiple device types that give different - // a different lowestDelta - // Ex: trackpad = 3 and mouse wheel = 120 - if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } - nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); - - return ($.event.dispatch || $.event.handle).apply(this, args); - } - - function nullLowestDelta() { - lowestDelta = null; - } - - function shouldAdjustOldDeltas(orgEvent, absDelta) { - // If this is an older event and the delta is divisable by 120, - // then we are assuming that the browser is treating this as an - // older mouse wheel event and that we should divide the deltas - // by 40 to try and get a more usable deltaFactor. - // Side note, this actually impacts the reported scroll distance - // in older browsers and can cause scrolling to be slower than native. - // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. - return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; - } - -})); - -/*! - * jQuery UI Widget 1.8.18 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ - -if ( ! $.widget ) { - -(function( $, undefined ) { - -// jQuery 1.4+ -if ( $.cleanData ) { - var _cleanData = $.cleanData; - $.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); - }; -} else { - var _remove = $.fn.remove; - $.fn.remove = function( selector, keepData ) { - return this.each(function() { - if ( !keepData ) { - if ( !selector || $.filter( selector, [ this ] ).length ) { - $( "*", this ).add( [ this ] ).each(function() { - try { - $( this ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - }); - } - } - return _remove.call( $(this), selector, keepData ); - }); - }; -} - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from -// $.each( basePrototype, function( key, val ) { -// if ( $.isPlainObject(val) ) { -// basePrototype[ key ] = $.extend( {}, val ); -// } -// }); - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = Array.prototype.slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - // prevent calls to internal methods - if ( isMethodCall && options.charAt( 0 ) === "_" ) { - return returnValue; - } - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ), - methodValue = instance && $.isFunction( instance[options] ) ? - instance[ options ].apply( instance, args ) : - instance; - // TODO: add this back in 1.9 and use $.error() (see #5972) -// if ( !instance ) { -// throw "cannot call methods on " + name + " prior to initialization; " + -// "attempted to call method '" + options + "'"; -// } -// if ( !$.isFunction( instance[options] ) ) { -// throw "no such method '" + options + "' for " + name + " widget instance"; -// } -// var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, name, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - // $.widget.bridge stores the plugin instance, but we do it anyway - // so that it's stored even before the _create function runs - $.data( element, this.widgetName, this ); - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - var self = this; - this.element.bind( "remove." + this.widgetName, function() { - self.destroy(); - }); - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: function() {}, - _init: function() {}, - - destroy: function() { - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - }, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - [ value ? "addClass" : "removeClass"]( - this.widgetBaseClass + "-disabled" + " " + - "ui-state-disabled" ) - .attr( "aria-disabled", value ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - - return !( $.isFunction(callback) && - callback.call( this.element[0], event, data ) === false || - event.isDefaultPrevented() ); - } -}; - -})( jQuery ); - -}; - - -(function ($, window, undefined) { - window.toStaticHTML = window.toStaticHTML || function ( x ) { return x; }; - - var pos_oo = Number.POSITIVE_INFINITY, - neg_oo = Number.NEGATIVE_INFINITY; - - $.geo = { - // - // utility functions - // - - _allCoordinates: function (geom) { - // return array of all positions in all geometries of geom - // not in JTS - var geometries = this._flatten(geom), - curGeom = 0, - result = []; - - for (; curGeom < geometries.length; curGeom++) { - var coordinates = geometries[curGeom].coordinates, - isArray = coordinates && $.isArray(coordinates[0]), - isDblArray = isArray && $.isArray(coordinates[0][0]), - isTriArray = isDblArray && $.isArray(coordinates[0][0][0]), - i, j, k; - - if (!isTriArray) { - if (!isDblArray) { - if (!isArray) { - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - for (k = 0; k < coordinates[i][j].length; k++) { - result.push(coordinates[i][j][k]); - } - } - } - } - return result; - }, - - _isGeodetic: function( coords ) { - // returns true if the first coordinate it can find is geodetic - - while ( $.isArray( coords ) ) { - if ( coords.length > 1 && ! $.isArray( coords[ 0 ] ) ) { - return ( coords[ 0 ] >= -180.001 && coords[ 0 ] <= 180.001 && coords[ 1 ] >= -90.001 && coords[ 1 ] <= 90.001 ); - } else { - coords = coords[ 0 ]; - } - } - - return false; - }, - - // - // bbox functions - // - - center: function (bbox, _ignoreGeo /* Internal Use Only */) { - // Envelope.centre in JTS - // bbox only, use centroid for geom - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return wasGeodetic ? $.geo.proj.toGeodetic(center) : center; - }, - - expandBy: function (bbox, dx, dy, _ignoreGeo /* Internal Use Only */) { - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - bbox = [bbox[0] - dx, bbox[1] - dy, bbox[2] + dx, bbox[3] + dy]; - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - height: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[3] - bbox[1]; - }, - - _in: function(bbox1, bbox2) { - return bbox1[0] <= bbox2[0] && - bbox1[1] <= bbox2[1] && - bbox1[2] >= bbox2[2] && - bbox1[3] >= bbox2[3]; - }, - - _bboxDisjoint: function( bbox1, bbox2 ) { - return bbox2[ 0 ] > bbox1[ 2 ] || - bbox2[ 2 ] < bbox1[ 0 ] || - bbox2[ 1 ] > bbox1[ 3 ] || - bbox2[ 3 ] < bbox1[ 1 ]; - }, - - include: function( bbox, value, _ignoreGeo /* Internal Use Only */ ) { - // similar to Envelope.expandToInclude in JTS - if ( !value || !$.isArray( value ) ) { - return bbox; - } - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox || value ) ) { - wasGeodetic = true; - } - - if ( !bbox ) { - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - } else if ( wasGeodetic ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - - if ( value.length === 2 ) { - value = [ value[ 0 ], value[ 1 ], value[ 0 ], value[ 1 ] ]; - } - - if ( $.geo.proj ) { - value = $.geo.proj.fromGeodetic( value ); - } - - bbox[0] = Math.min( value[ 0 ], bbox[ 0 ] ); - bbox[1] = Math.min( value[ 1 ], bbox[ 1 ] ); - bbox[2] = Math.max( value[ 2 ], bbox[ 2 ] ); - bbox[3] = Math.max( value[ 3 ], bbox[ 3 ] ); - - return wasGeodetic ? $.geo.proj.toGeodetic( bbox ) : bbox; - }, - - polygonize: function( bbox, _ignoreGeo /* Internal Use Only */ ) { - // adaptation of Polygonizer class in JTS for use with bboxes - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var polygon = { - type: "Polygon", - coordinates: [ [ - [ bbox[ 0 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 1 ] ] - ] ] - }; - - if ( wasGeodetic ) { - polygon.coordinates = $.geo.proj.toGeodetic( polygon.coordinates ); - } - - return polygon; - }, - - reaspect: function (bbox, ratio, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var width = this.width(bbox, true), - height = this.height(bbox, true), - center = this.center(bbox, true), - dx, dy; - - if (width !== 0 && height !== 0 && ratio > 0) { - if (width / height > ratio) { - dx = width / 2; - dy = dx / ratio; - } else { - dy = height / 2; - dx = dy * ratio; - } - - bbox = [center[0] - dx, center[1] - dy, center[0] + dx, center[1] + dy]; - } - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - recenter: function( bbox, center, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj ) { - if ( this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - if ( this._isGeodetic( center ) ) { - center = $.geo.proj.fromGeodetic(center); - } - } - - var halfWidth = ( bbox[ 2 ] - bbox[ 0 ] ) / 2, - halfHeight = ( bbox[ 3 ] - bbox[ 1 ] ) / 2; - - bbox = [ - center[ 0 ] - halfWidth, - center[ 1 ] - halfHeight, - center[ 0 ] + halfWidth, - center[ 1 ] + halfHeight - ]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - scaleBy: function ( bbox, scale, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var c = this.center(bbox, true), - dx = (bbox[2] - bbox[0]) * scale / 2, - dy = (bbox[3] - bbox[1]) * scale / 2; - - bbox = [c[0] - dx, c[1] - dy, c[0] + dx, c[1] + dy]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - width: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[2] - bbox[0]; - }, - - // - // geometry functions - // - - // bbox (Geometry.getEnvelope in JTS) - - bbox: function ( geom, _ignoreGeo /* Internal Use Only */ ) { - var result, wasGeodetic = false; - if ( !geom ) { - return undefined; - } else if ( geom.bbox ) { - result = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.bbox ) ) ? $.geo.proj.fromGeodetic( geom.bbox ) : geom.bbox; - } else { - result = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var coordinates = this._allCoordinates( geom ), - curCoord = 0; - - if ( coordinates.length === 0 ) { - return undefined; - } - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coordinates ) ) { - wasGeodetic = true; - coordinates = $.geo.proj.fromGeodetic( coordinates ); - } - - for ( ; curCoord < coordinates.length; curCoord++ ) { - result[0] = Math.min(coordinates[curCoord][0], result[0]); - result[1] = Math.min(coordinates[curCoord][1], result[1]); - result[2] = Math.max(coordinates[curCoord][0], result[2]); - result[3] = Math.max(coordinates[curCoord][1], result[3]); - } - } - - return wasGeodetic ? $.geo.proj.toGeodetic(result) : result; - }, - - // centroid - - centroid: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var c; //< temp storage for any coordinate during centroid op - - switch (geom.type) { - case "Point": - return $.extend({}, geom); - - case "LineString": - case "Polygon": - var a = 0, - coords = $.merge( [ ], geom.type === "Polygon" ? geom.coordinates[0] : geom.coordinates ), - i = 1, j, n, - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - c = [ 0, 0 ]; - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coords ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic(coords); - } - - //if (coords[0][0] != coords[coords.length - 1][0] || coords[0][1] != coords[coords.length - 1][1]) { - // coords.push(coords[0]); - //} - - for (; i <= coords.length; i++) { - j = i % coords.length; - - bbox[0] = Math.min(coords[j][0], bbox[0]); - bbox[1] = Math.min(coords[j][1], bbox[1]); - bbox[2] = Math.max(coords[j][0], bbox[2]); - bbox[3] = Math.max(coords[j][1], bbox[3]); - - n = (coords[i - 1][0] * coords[j][1]) - (coords[j][0] * coords[i - 1][1]); - a += n; - c[0] += (coords[i - 1][0] + coords[j][0]) * n; - c[1] += (coords[i - 1][1] + coords[j][1]) * n; - } - - if (a === 0) { - if (coords.length > 0) { - c[0] = Math.min( Math.max( coords[0][0], bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( coords[0][1], bbox[ 1 ] ), bbox[ 3 ] ); - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } else { - return undefined; - } - } - - a *= 3; - //c[0] /= a; - //c[1] /= a; - - c[0] = Math.min( Math.max( c[0] / a, bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( c[1] / a, bbox[ 1 ] ), bbox[ 3 ] ); - - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - - case "MultiPoint": - // should return center of mass for point cluster but just return first point for now - if ( geom.coordinates.length > 0 ) { - c = geom.coordinates[ 0 ]; - return { - type: "Point", - coordinates: [ c[ 0 ], c[ 1 ] ] - }; - } - break; - - case "MultiLineString": - case "MultiPolygon": - if ( geom.coordinates.length > 0 ) { - return this.centroid( { - type: geom.type.substr( 5 ), - coordinates: geom.coordinates[ 0 ] - }, _ignoreGeo ); - } - break; - - } - return undefined; - }, - - // contains - - contains: function (geom1, geom2) { - if (geom1.type !== "Polygon") { - return false; - } - - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1.coordinates, geom2.coordinates); - - case "LineString": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates); - - case "Polygon": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates[0]); - - default: - return false; - } - }, - - _containsPolygonPoint: function (polygonCoordinates, pointCoordinate) { - if (polygonCoordinates.length === 0 || polygonCoordinates[0].length < 4) { - return false; - } - - var rayCross = 0, - a = polygonCoordinates[0][0], - i = 1, - b, - x; - - for (; i < polygonCoordinates[0].length; i++) { - b = polygonCoordinates[0][i]; - - if ((a[1] <= pointCoordinate[1] && pointCoordinate[1] < b[1]) || (b[1] <= pointCoordinate[1] && pointCoordinate[1] < a[1]) && (pointCoordinate[0] < a[0] || pointCoordinate[0] < b[0])) { - x = a[0] + (b[0] - a[0]) * (pointCoordinate[1] - a[1]) / (b[1] - a[1]); - - if (x > pointCoordinate[0]) { - rayCross++; - } - } - - a = b; - } - - return rayCross % 2 === 1; - }, - - _containsPolygonLineString: function (polygonCoordinates, lineStringCoordinates) { - for (var i = 0; i < lineStringCoordinates.length; i++) { - if (!this._containsPolygonPoint(polygonCoordinates, lineStringCoordinates[i])) { - return false; - } - } - return true; - }, - - // distance - - distance: function ( geom1, geom2, _ignoreGeo /* Internal Use Only */ ) { - var geom1CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom1.coordinates ) ) ? $.geo.proj.fromGeodetic(geom1.coordinates) : geom1.coordinates, - geom2CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom2.coordinates ) ) ? $.geo.proj.fromGeodetic(geom2.coordinates) : geom2.coordinates; - - switch (geom1.type) { - case "Point": - switch (geom2.type) { - case "Point": - return this._distancePointPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "LineString": - return this._distanceLineStringPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "Polygon": - return this._containsPolygonPoint(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "LineString": - switch (geom2.type) { - case "Point": - return this._distanceLineStringPoint(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "LineString": - return this._distanceLineStringLineString(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "Polygon": - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "LineString": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected[0]) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected[0]); - default: - return undefined; - } - break; - } - }, - - _distancePointPoint: function (coordinate1, coordinate2) { - var dx = coordinate2[0] - coordinate1[0], - dy = coordinate2[1] - coordinate1[1]; - return Math.sqrt((dx * dx) + (dy * dy)); - }, - - _distanceLineStringPoint: function (lineStringCoordinates, pointCoordinate) { - var minDist = pos_oo; - - if (lineStringCoordinates.length > 0) { - var a = lineStringCoordinates[0], - - apx = pointCoordinate[0] - a[0], - apy = pointCoordinate[1] - a[1]; - - if (lineStringCoordinates.length === 1) { - return Math.sqrt(apx * apx + apy * apy); - } else { - for (var i = 1; i < lineStringCoordinates.length; i++) { - var b = lineStringCoordinates[i], - - abx = b[0] - a[0], - aby = b[1] - a[1], - bpx = pointCoordinate[0] - b[0], - bpy = pointCoordinate[1] - b[1], - - d = this._distanceSegmentPoint(abx, aby, apx, apy, bpx, bpy); - - if (d === 0) { - return 0; - } - - if (d < minDist) { - minDist = d; - } - - a = b; - apx = bpx; - apy = bpy; - } - } - } - - return Math.sqrt(minDist); - }, - - _distanceSegmentPoint: function (abx, aby, apx, apy, bpx, bpy) { - var dot1 = abx * apx + aby * apy; - - if (dot1 <= 0) { - return apx * apx + apy * apy; - } - - var dot2 = abx * abx + aby * aby; - - if (dot1 >= dot2) { - return bpx * bpx + bpy * bpy; - } - - return apx * apx + apy * apy - dot1 * dot1 / dot2; - }, - - _distanceLineStringLineString: function (lineStringCoordinates1, lineStringCoordinates2) { - var minDist = pos_oo; - for (var i = 0; i < lineStringCoordinates2.length; i++) { - minDist = Math.min(minDist, this._distanceLineStringPoint(lineStringCoordinates1, lineStringCoordinates2[i])); - } - return minDist; - }, - - // buffer - - _buffer: function( geom, distance, _ignoreGeo /* Internal Use Only */ ) { - var wasGeodetic = false, - coords = geom.coordinates; - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.coordinates ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic( geom.coordinates ); - } - - if ( geom.type === "Point" ) { - var resultCoords = [], - slices = 180, - i = 0, - a; - - for ( ; i <= slices; i++ ) { - a = ( i * 360 / slices ) * ( Math.PI / 180 ); - resultCoords.push( [ - coords[ 0 ] + Math.cos( a ) * distance, - coords[ 1 ] + Math.sin( a ) * distance - ] ); - } - - return { - type: "Polygon", - coordinates: [ ( wasGeodetic ? $.geo.proj.toGeodetic( resultCoords ) : resultCoords ) ] - }; - } else { - return undefined; - } - }, - - - // - // feature - // - - _basic: function( geom ) { - // return an array of all basic geometries - // e.g., MultiPolygons become multiple Polygons - // coordinate arrays are kept as references for speed & should not be altered - // not in JTS - var geometries = [ ]; - var multiType; - var i = 0; - var j; - - var flat = this._flatten( geom ); - - for ( ; i < flat.length; i++ ) { - if ( flat[ i ].type.substring( 0, 5 ) === "Multi" ) { - multiType = flat[ i ].type.substring( 5 ); - - for ( j = 0; j < flat[ i ].coordinates.length; j++ ) { - geometries.push( { - type: multiType, - coordinates: flat[ i ].coordinates[ j ] - } ); - } - } else { - geometries.push( flat[ i ] ); - } - } - - return geometries; - }, - - _flatten: function (geom) { - // return an array of only geometries - // will extract geometries from Feature, FeatureCollection, & GeometryCollection - // not in JTS - var geometries = [], - curGeom = 0; - switch (geom.type) { - case "Feature": - $.merge(geometries, this._flatten(geom.geometry)); - break; - - case "FeatureCollection": - for (; curGeom < geom.features.length; curGeom++) { - $.merge(geometries, this._flatten(geom.features[curGeom].geometry)); - } - break; - - case "GeometryCollection": - for (; curGeom < geom.geometries.length; curGeom++) { - $.merge(geometries, this._flatten(geom.geometries[curGeom])); - } - break; - - default: - geometries[0] = geom; - break; - } - return geometries; - }, - - length: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - lineStringCoordinates, - i = 1, dx, dy; - - switch ( geom.type ) { - case "Point": - return 0; - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][0] - lineStringCoordinates[ i - 1 ][0]; - dy = lineStringCoordinates[ i ][1] - lineStringCoordinates[ i - 1 ][1]; - sum += Math.sqrt((dx * dx) + (dy * dy)); - } - - return sum; - } - - // return undefined; - }, - - area: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - polygonCoordinates, - i = 1, j; - - switch ( geom.type ) { - case "Point": - case "LineString": - return 0; - - case "Polygon": - polygonCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( polygonCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( polygonCoordinates ) ) { - polygonCoordinates = $.geo.proj.fromGeodetic( polygonCoordinates ); - } - - for ( ; i <= polygonCoordinates.length; i++) { - j = i % polygonCoordinates.length; - sum += ( polygonCoordinates[ i - 1 ][ 0 ] - polygonCoordinates[ j ][ 0 ] ) * ( polygonCoordinates[ i - 1 ][ 1 ] + polygonCoordinates[ j ][ 1 ] ) / 2; - } - - return Math.abs( sum ); - } - }, - - pointAlong: function( geom, percentage, _ignoreGeo /* Internal Use Only */ ) { - var totalLength = 0, - previousPercentageSum = 0, - percentageSum = 0, - remainderPercentageSum, - len, - lineStringCoordinates, - segmentLengths = [], - i = 1, dx, dy, - c, c0, c1, - wasGeodetic = false; - - switch ( geom.type ) { - case "Point": - return $.extend( { }, geom ); - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( percentage === 0 ) { - return { - type: "Point", - coordinates: [ lineStringCoordinates[ 0 ][ 0 ], lineStringCoordinates[ 0 ][ 1 ] ] - }; - } else if ( percentage === 1 ) { - i = lineStringCoordinates.length - 1; - return { - type: "Point", - coordinates: [ lineStringCoordinates[ i ][ 0 ], lineStringCoordinates[ i ][ 1 ] ] - }; - } else { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - wasGeodetic = true; - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][ 0 ] - lineStringCoordinates[ i - 1 ][ 0 ]; - dy = lineStringCoordinates[ i ][ 1 ] - lineStringCoordinates[ i - 1 ][ 1 ]; - len = Math.sqrt((dx * dx) + (dy * dy)); - segmentLengths.push( len ); - totalLength += len; - } - - for ( i = 0; i < segmentLengths.length && percentageSum < percentage; i++ ) { - previousPercentageSum = percentageSum; - percentageSum += ( segmentLengths[ i ] / totalLength ); - } - - remainderPercentageSum = percentage - previousPercentageSum; - - c0 = lineStringCoordinates[ i - 1 ]; - c1 = lineStringCoordinates[ i ]; - - c = [ - c0[ 0 ] + ( remainderPercentageSum * ( c1[ 0 ] - c0[ 0 ] ) ), - c0[ 1 ] + ( remainderPercentageSum * ( c1[ 1 ] - c0[ 1 ] ) ) - ]; - - return { - type: "Point", - coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c - }; - } - } - }, - - // - // WKT functions - // - - WKT: (function () { - function pointToString(value) { - return "POINT " + pointToUntaggedString(value.coordinates); - } - - function pointToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - return "(" + coordinates.join(" ") + ")"; - } - } - - function lineStringToString(value) { - return "LINESTRING " + lineStringToUntaggedString(value.coordinates); - } - - function lineStringToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var points = []; - - for (var i = 0; i < coordinates.length; i++) { - points.push(coordinates[i].join(" ")); - } - - return "(" + points + ")"; - } - } - - function polygonToString(value) { - return "POLYGON " + polygonToUntaggedString(value.coordinates); - } - - function polygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMTPY"; - } else { - var lineStrings = []; - - for (var i = 0; i < coordinates.length; i++) { - lineStrings.push(lineStringToUntaggedString(coordinates[i])); - } - - return "(" + lineStrings + ")"; - } - } - - function multiPointToString(value) { - return "MULTIPOINT " + lineStringToUntaggedString(value.coordinates); - } - - function multiLineStringToString(value) { - return "MULTILINSTRING " + polygonToUntaggedString(value.coordinates); - } - - function multiPolygonToString(value) { - return "MULTIPOLYGON " + multiPolygonToUntaggedString(value.coordinates); - } - - function multiPolygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var polygons = []; - for (var i = 0; i < coordinates.length; i++) { - polygons.push(polygonToUntaggedString(coordinates[i])); - } - return "(" + polygons + ")"; - } - } - - function geometryCollectionToString(value) { - return "GEOMETRYCOLLECTION " + geometryCollectionToUntaggedString(value.geometries); - } - - function geometryCollectionToUntaggedString(geometries) { - if (!(geometries && geometries.length)) { - return "EMPTY"; - } else { - var geometryText = []; - for (var i = 0; i < geometries.length; i++) { - geometryText.push(stringify(geometries[i])); - } - return "(" + geometries + ")"; - } - } - - function stringify(value) { - if (!(value && value.type)) { - return ""; - } else { - switch (value.type) { - case "Point": - return pointToString(value); - - case "LineString": - return lineStringToString(value); - - case "Polygon": - return polygonToString(value); - - case "MultiPoint": - return multiPointToString(value); - - case "MultiLineString": - return multiLineStringToString(value); - - case "MultiPolygon": - return multiPolygonToString(value); - - case "GeometryCollection": - return geometryCollectionToString(value); - - default: - return ""; - } - } - } - - function pointParseUntagged(wkt) { - var pointString = wkt.match( /\(\s*([\d\.\-]+)\s+([\d\.\-]+)\s*\)/ ); - return pointString && pointString.length > 2 ? { - type: "Point", - coordinates: [ - parseFloat(pointString[1]), - parseFloat(pointString[2]) - ] - } : null; - } - - function lineStringParseUntagged(wkt) { - var lineString = wkt.match( /\s*\((.*)\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( lineString && lineString.length > 1 ) { - pointStrings = lineString[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "LineString", - coordinates: coords - }; - } else { - return null; - } - } - - function polygonParseUntagged(wkt) { - var polygon = wkt.match( /\s*\(\s*\((.*)\)\s*\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( polygon && polygon.length > 1 ) { - pointStrings = polygon[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "Polygon", - coordinates: [ coords ] - }; - } else { - return null; - } - } - - function multiPointParseUntagged(wkt) { - var multiSomething; - - if ( wkt.indexOf( "((" ) === -1 ) { - multiSomething = lineStringParseUntagged( wkt ); - } else { - multiSomething = multiLineStringParseUntagged( wkt ); - multiSomething.coordinates = $.geo._allCoordinates( multiSomething ); - } - - multiSomething.type = "MultiPoint"; - - return multiSomething; - } - - function multiLineStringParseUntagged(wkt) { - var lineStringsWkt = wkt.substr( 2, wkt.length - 4 ), - lineString, - lineStrings = lineStringsWkt.split( /\),\s*\(/ ), - i = 0, - multiLineString = { - type: "MultiLineString", - coordinates: [ ] - }; - - for ( ; i < lineStrings.length; i++ ) { - lineString = lineStringParseUntagged( "(" + lineStrings[ i ] + ")" ); - if ( lineString ) { - multiLineString.coordinates.push( lineString.coordinates ); - } - } - - return multiLineString; - } - - function multiPolygonParseUntagged(wkt) { - var polygonsWkt = wkt.substr( 1, wkt.length - 2 ), - polygon, - polygons = polygonsWkt.split( /\),\s*\(/ ), - i = 0, - multiPolygon = { - type: "MultiPolygon", - coordinates: [ ] - }; - - for ( ; i < polygons.length; i++ ) { - polygon = polygonParseUntagged( "(" + polygons[ i ] + ")" ); - if ( polygon ) { - multiPolygon.coordinates.push( polygon.coordinates ); - } - } - - return multiPolygon; - } - - function geometryCollectionParseUntagged( wkt ) { - var geometriesWkt = wkt.substr( 1, wkt.length - 2 ), - geometries = geometriesWkt.match( /\),[a-zA-Z]/g ), - geometryCollection = { - type: "GeometryCollection", - geometries: [ ] - }, - curGeom, - i = 0, curStart = 0, curLen; - - if ( geometries && geometries.length > 0 ) { - for ( ; i < geometries.length; i++ ) { - curLen = geometriesWkt.indexOf( geometries[ i ], curStart ) - curStart + 1; - curGeom = parse( geometriesWkt.substr( curStart, curLen ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - curStart += curLen + 1; - } - - // one more - curGeom = parse( geometriesWkt.substr( curStart ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - - return geometryCollection; - } else { - return null; - } - } - - function parse(wkt) { - wkt = $.trim(wkt); - - var typeIndex = wkt.indexOf( "(" ), - untagged = wkt.substr( typeIndex ); - - switch ($.trim(wkt.substr(0, typeIndex)).toUpperCase()) { - case "POINT": - return pointParseUntagged( untagged ); - - case "LINESTRING": - return lineStringParseUntagged( untagged ); - - case "POLYGON": - return polygonParseUntagged( untagged ); - - case "MULTIPOINT": - return multiPointParseUntagged( untagged ); - - case "MULTILINESTRING": - return multiLineStringParseUntagged( untagged ); - - case "MULTIPOLYGON": - return multiPolygonParseUntagged( untagged ); - - case "GEOMETRYCOLLECTION": - return geometryCollectionParseUntagged( untagged ); - - default: - return null; - } - } - - return { - stringify: stringify, - - parse: parse - }; - }()), - - // - // projection functions - // - - proj: (function () { - var halfPi = 1.5707963267948966192, - quarterPi = 0.7853981633974483096, - radiansPerDegree = 0.0174532925199432958, - degreesPerRadian = 57.295779513082320877, - semiMajorAxis = 6378137; - - return { - fromGeodeticPos: function (coordinate) { - return [ - semiMajorAxis * coordinate[ 0 ] * radiansPerDegree, - semiMajorAxis * Math.log(Math.tan(quarterPi + coordinate[ 1 ] * radiansPerDegree / 2)) - ]; - }, - - fromGeodetic: function ( coordinates ) { - if ( ! $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - fromGeodeticPos = this.fromGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length === 4) { - // bbox - var min = fromGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = fromGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = fromGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - }, - - toGeodeticPos: function (coordinate) { - return [ - (coordinate[ 0 ] / semiMajorAxis) * degreesPerRadian, - (halfPi - 2 * Math.atan(1 / Math.exp(coordinate[ 1 ] / semiMajorAxis))) * degreesPerRadian - ]; - }, - - toGeodetic: function (coordinates) { - if ( $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - toGeodeticPos = this.toGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length === 4) { - // bbox - var min = toGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = toGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = toGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - } - }; - }()), - - // - // service types (defined in other files) - // - - _serviceTypes: {} - }; -}(jQuery, this)); - -(function ($, window, undefined) { - var _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ); - - $.widget("geo.geographics", { - _$elem: undefined, - _options: {}, - _trueCanvas: true, - _trueDoubleBuffer: true, - - _width: 0, - _height: 0, - - _$canvas: undefined, - _context: undefined, - - _$canvasSceneFront: undefined, //< if _trueCanvas, where canvas images get written (front buffer) - _$canvasSceneBack: undefined, //< if _trueCanvas, where canvas images get written (back buffer) - _$canvasSceneStale: undefined, //< if _trueCanvas, scene to hide next - _$canvasSceneDrawn: undefined, //< if _trueCanvas, scene to show next - _timeoutEnd: null, - _requireFlip: false, - - _blitcanvas: undefined, - _blitcontext: undefined, - - _$labelsContainerFront: undefined, - _$labelsContainerBack: undefined, - _labelsHtml: "", - - options: { - style: { - borderRadius: "8px", - color: "#7f0000", - //fill: undefined, - fillOpacity: 0.2, - height: "8px", - opacity: 1, - //stroke: undefined, - strokeOpacity: 1, - strokeWidth: "2px", - visibility: "visible", - width: "8px" - }, - - doubleBuffer: true - }, - - _create: function () { - this._$elem = this.element; - this._options = this.options; - - this._$elem.css( { - webkitTransform: "translateZ(0)", - display: "inline-block", - overflow: "hidden", - textAlign: "left" - } ); - - if (this._$elem.css("position") === "static") { - this._$elem.css("position", "relative"); - } - - this._$elem.addClass( "geo-graphics" ); - - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - var posCss = 'position:absolute;left:0;top:0;margin:0;padding:0;', - sizeCss = 'width:' + this._width + 'px;height:' + this._height + 'px;', - sizeAttr = 'width="' + this._width + '" height="' + this._height + '"'; - - this._blitcanvas = document.createElement( "canvas" ); - - if ( this._blitcanvas.getContext ) { - this._$canvas = $( window.toStaticHTML( '' ) ); - - // test _trueDoubleBuffer - this._blitcanvas.width = 1; - this._blitcanvas.height = 1; - this._trueDoubleBuffer = this._blitcanvas.toDataURL().length > 6; - - if ( !(this._options.doubleBuffer && this._trueDoubleBuffer) ) { - this._$elem.append( this._$canvas ); - } - - this._context = this._$canvas[0].getContext("2d"); - - this._blitcanvas.width = this._width; - this._blitcanvas.height = this._height; - this._blitcontext = this._blitcanvas.getContext("2d"); - - // create our front & back buffers - // though, at any time either one can be in front - this._$canvasSceneFront = $( window.toStaticHTML( '' ) ).on( 'load', $.proxy( this._canvasImgLoad, this ) ); - this._$canvasSceneBack = $( window.toStaticHTML( '' ) ).on( 'load', $.proxy( this._canvasImgLoad, this ) ); - - } else if (_ieVersion <= 8) { - this._trueCanvas = false; - this._$elem.append( '
                        '); - this._$canvas = this._$elem.children(':last'); - - G_vmlCanvasManager.initElement(this._$canvas[0]); - this._context = this._$canvas[0].getContext("2d"); - this._$canvas.children().css({ backgroundColor: "transparent", width: this._width, height: this._height }); - } - - // create our front & back label containers - this._$labelsContainerFront = $( window.toStaticHTML( '
                        ' ) ); - this._$labelsContainerBack = $( window.toStaticHTML( '
                        ' ) ); - }, - - _setOption: function (key, value) { - if (key === "style") { - value = $.extend({}, this._options.style, value); - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - destroy: function () { - $.Widget.prototype.destroy.apply(this, arguments); - this._$elem.html(""); - this._$elem.removeClass( "geo-graphics" ); - }, - - clear: function () { - this._context.clearRect(0, 0, this._width, this._height); - this._labelsHtml = ""; - this._end( ); - }, - - drawArc: function (coordinates, startAngle, sweepAngle, style) { - style = this._getGraphicStyle(style); - - if (style.visibility !== "hidden" && style.opacity > 0 && style.widthValue > 0 && style.heightValue > 0) { - var r = Math.min(style.widthValue, style.heightValue) / 2; - - startAngle = (startAngle * Math.PI / 180); - sweepAngle = (sweepAngle * Math.PI / 180); - - this._context.save(); - this._context.translate(coordinates[0], coordinates[1]); - if (style.widthValue > style.heightValue) { - this._context.scale(style.widthValue / style.heightValue, 1); - } else { - this._context.scale(1, style.heightValue / style.widthValue); - } - - this._context.beginPath(); - this._context.arc(0, 0, r, startAngle, sweepAngle, false); - - if (this._trueCanvas) { - this._context.restore(); - } - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - if (!this._trueCanvas) { - this._context.restore(); - } - } - - this._end( ); - }, - - drawPoint: function (coordinates, style) { - style = this._getGraphicStyle(style); - if (style.widthValue === style.heightValue && style.heightValue === style.borderRadiusValue) { - this.drawArc(coordinates, 0, 360, style); - } else if (style.visibility !== "hidden" && style.opacity > 0) { - style.borderRadiusValue = Math.min(Math.min(style.widthValue, style.heightValue) / 2, style.borderRadiusValue); - coordinates[0] -= style.widthValue / 2; - coordinates[1] -= style.heightValue / 2; - this._context.beginPath(); - this._context.moveTo(coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.lineTo(coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1]); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1], coordinates[0] + style.widthValue, coordinates[1] + style.borderRadiusValue); - this._context.lineTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue, coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.lineTo(coordinates[0] + style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1] + style.heightValue, coordinates[0], coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.lineTo(coordinates[0], coordinates[1] + style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1], coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.closePath(); - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - - this._context.stroke(); - } - - this._end( ); - } - }, - - drawLineString: function (coordinates, style) { - this._drawLines([coordinates], false, style); - }, - - drawPolygon: function (coordinates, style) { - if ( !this._trueCanvas || coordinates.length === 1 ) { - // either we don't have fancy rendering or there's no need for it (no holes) - this._drawLines( coordinates, true, style ); - } else { - if ( !coordinates || !coordinates.length || coordinates[ 0 ].length < 3 ) { - // this is not a Polygon or it doesn't have a proper outer ring - return; - } - - style = this._getGraphicStyle(style); - this._blitcontext.globalCompositeOperation = "copy"; - - var pixelBbox, i, j; - - if ( style.visibility !== "hidden" && style.opacity > 0 ) { - this._blitcontext.clearRect(0, 0, this._width, this._height); - - if ( style.doFill ) { - if ( coordinates.length > 1 ) { - // stencil inner rings - this._blitcontext.globalCompositeOperation = "source-out"; - this._blitcontext.globalAlpha = 1; - - this._blitcontext.beginPath(); - - for ( i = 1; i < coordinates.length; i++ ) { - // start drawing inner rings, i - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - - for ( j = 0; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - } - - this._blitcontext.closePath(); - - this._blitcontext.fill( ); - } - } - - // path outer ring - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ 0 ][ 0 ][ 0 ], coordinates[ 0 ][ 0 ][ 1 ] ); - - pixelBbox = [ coordinates[ 0 ][ 0 ][ 0 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 0 ] + style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] + style.strokeWidthValue ]; - - for ( i = 1; i < coordinates[ 0 ].length - 1; i++ ) { - this._blitcontext.lineTo( coordinates[ 0 ][ i ][ 0 ], coordinates[ 0 ][ i ][ 1 ] ); - - pixelBbox[ 0 ] = Math.min( coordinates[ 0 ][ i ][ 0 ] - style.strokeWidthValue, pixelBbox[ 0 ] ); - pixelBbox[ 1 ] = Math.min( coordinates[ 0 ][ i ][ 1 ] - style.strokeWidthValue, pixelBbox[ 1 ] ); - pixelBbox[ 2 ] = Math.max( coordinates[ 0 ][ i ][ 0 ] + style.strokeWidthValue, pixelBbox[ 2 ] ); - pixelBbox[ 3 ] = Math.max( coordinates[ 0 ][ i ][ 1 ] + style.strokeWidthValue, pixelBbox[ 3 ] ); - } - - this._blitcontext.closePath(); - - if ( style.doFill ) { - // fill outer ring - this._blitcontext.fillStyle = style.fill; - this._blitcontext.globalAlpha = style.opacity * style.fillOpacity; - this._blitcontext.fill( ); - } - - this._blitcontext.globalCompositeOperation = "source-over"; - if ( style.doStroke ) { - // stroke outer ring - this._blitcontext.lineCap = this._blitcontext.lineJoin = "round"; - this._blitcontext.lineWidth = style.strokeWidthValue; - this._blitcontext.strokeStyle = style.stroke; - - this._blitcontext.globalAlpha = style.opacity * style.strokeOpacity; - this._blitcontext.stroke( ); - - if ( coordinates.length > 1 ) { - // stroke inner rings - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.stroke( ); - } - } - } - - // blit - pixelBbox[ 0 ] = Math.min( Math.max( pixelBbox[ 0 ], 0), this._width ); - pixelBbox[ 1 ] = Math.min( Math.max( pixelBbox[ 1 ], 0), this._height ); - pixelBbox[ 2 ] = Math.min( Math.max( pixelBbox[ 2 ], 0), this._width ); - pixelBbox[ 3 ] = Math.min( Math.max( pixelBbox[ 3 ], 0), this._height ); - - if ( pixelBbox[ 0 ] !== pixelBbox[ 2 ] && pixelBbox[ 1 ] !== pixelBbox[ 3 ] ) { - this._context.drawImage(this._blitcanvas, pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ], pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ] ); - - this._end( ); - } - } - } - }, - - drawBbox: function (bbox, style) { - this._drawLines([[ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ]], true, style); - }, - - drawLabel: function( coordinates, label ) { - this._labelsHtml += '
                        ' + label + '
                        '; - }, - - resize: function( dx, dy ) { - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - if ( this._trueCanvas ) { - this._$canvas[0].width = this._width; - this._$canvas[0].height = this._height; - - this._$canvasSceneFront.css( { - left: dx, - top: dy - } ); - - this._$canvasSceneBack.css( { - width: this._width, - height: this._height - } ); - } else { - this._$canvas.css( { - width: this._width, - height: this._height - } ); - } - - var labelPositionFront = this._$labelsContainerFront.position(); - - this._$labelsContainerFront.css( { - left: labelPositionFront.left + dx, - top: labelPositionFront.top + dy, - width: this._width, - height: this._height - } ); - - this._$labelsContainerBack.css( { - width: this._width, - height: this._height - } ); - }, - - interactiveTransform: function( origin, scale ) { - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - if ( this._trueCanvas && this._options.doubleBuffer && this._trueDoubleBuffer ) { - this._canvasSceneLoad( ); - - // transform a finished scene, can assume no drawing during these calls - this._$canvasSceneFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - - // transform labels - this._$labelsContainerFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - }, - - _canvasImgLoad: function( ) { - var geographics = this; - geographics._$canvasSceneFront = geographics._$canvasSceneDrawn.prependTo( geographics._$elem ); - geographics._$canvasSceneBack = geographics._$canvasSceneStale; - geographics._$canvasSceneBack.detach(); - }, - - _canvasSceneLoad: function() { - var geographics = this; - if ( geographics._requireFlip ) { - geographics._requireFlip = false; - geographics._$canvasSceneStale = geographics._$canvasSceneFront; - - geographics._$canvasSceneDrawn = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ); - } - }, - - _endCallback: function() { - var geographics = this; - - if ( !geographics._timeoutEnd ) { - // something has canceled the draw - return; - } - - if ( geographics._trueCanvas && geographics._options.doubleBuffer && geographics._trueDoubleBuffer ) { - this._canvasSceneLoad( ); - } - - geographics._$labelsContainerBack.html( window.toStaticHTML( geographics._labelsHtml ) ).find("a").css({ - position: "relative", - zIndex: 1, - display: "inline-block", - webkitTransform: "translateZ(0)" - }); - - var oldLabelsContainer = geographics._$labelsContainerFront; - - geographics._$labelsContainerFront = geographics._$labelsContainerBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).appendTo( geographics._$elem ); - - geographics._$labelsContainerBack = oldLabelsContainer.detach(); - - geographics._timeoutEnd = null; - }, - - _end: function( ) { - // end/finalize a scene - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - this._requireFlip = true; - - this._timeoutEnd = setTimeout( $.proxy(this._endCallback, this), 20 ); - }, - - _getGraphicStyle: function (style) { - function safeParse(value) { - value = parseInt(value, 10); - return (+value + '') === value ? +value : value; - } - - style = $.extend({}, this._options.style, style); - style.borderRadiusValue = safeParse(style.borderRadius); - style.fill = style.fill || style.color; - style.doFill = style.fill && style.fillOpacity > 0; - style.stroke = style.stroke || style.color; - style.strokeWidthValue = safeParse(style.strokeWidth); - style.doStroke = style.stroke && style.strokeOpacity > 0 && style.strokeWidthValue > 0; - style.widthValue = safeParse(style.width); - style.heightValue = safeParse(style.height); - return style; - }, - - _drawLines: function (coordinates, close, style) { - if (!coordinates || !coordinates.length || coordinates[0].length < 2) { - return; - } - - var i, j; - style = this._getGraphicStyle(style); - - if (style.visibility !== "hidden" && style.opacity > 0) { - this._context.beginPath(); - - for (i = 0; i < coordinates.length; i++) { - this._context.moveTo(coordinates[i][0][0], coordinates[i][0][1]); - for (j = 1; j < coordinates[i].length; j++) { - this._context.lineTo(coordinates[i][j][0], coordinates[i][j][1]); - } - } - - if (close) { - this._context.closePath(); - } - - if (close && style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineCap = this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - this._end( ); - } - } - }); -}(jQuery, window)); - - -(function ($, window, undefined) { - var _widgetIdSeed = 0, - _ieVersion = ( function() { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ), - - _gecko = ( function() { - return ( navigator.userAgent.match( /gecko\/*\d/i ) || [] ).length > 0; - }() ), - - _defaultOptions = { - bbox: [-180, -85, 180, 85], - bboxMax: [-180, -85, 180, 85], - center: [0, 0], - cursors: { - "static": "default", - pan: "url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move", - click: "crosshair", - zoom: "crosshair", - dragBox: "crosshair", - dragCircle: "crosshair", - drawPoint: "crosshair", - drawLineString: "crosshair", - drawPolygon: "crosshair", - measureLength: "crosshair", - measureArea: "crosshair" - }, - measureLabels: { - length: "{{:length.toFixed( 2 )}} m", - area: "{{:area.toFixed( 2 )}} sq m" - }, - drawStyle: {}, - shapeStyle: {}, - mode: "pan", - pannable: true, - scroll: "default", - shift: "default", - services: [ - { - "class": "osm", - type: "tiled", - src: function (view) { - return "//otile" + ((view.index % 4) + 1) + ((location.protocol === 'https:') ? "-s" : "") + ".mqcdn.com/tiles/1.0.0/osm/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; - }, - attr: 'Tiles Courtesy of MapQuest ' - } - ], - tilingScheme: { - tileWidth: 256, - tileHeight: 256, - levels: 18, - basePixelSize: 156543.03392799936, - origin: [-20037508.342787, 20037508.342787] - }, - axisLayout: "map", - zoom: 0, - zoomMin: 0, - zoomMax: Number.POSITIVE_INFINITY, - zoomFactor: 2, //< determines what a zoom level means - pixelSize: 0 - }; - - $.widget("geo.geomap", { - // private widget members - _$elem: undefined, //< map div for maps, service div for services - _map: undefined, //< only defined in services - _created: false, - _createdGraphics: false, - _widgetId: 0, - _tmplLengthId: "", - _tmplAreaId: "", - - _contentBounds: {}, - - _$resizeContainer: undefined, //< all elements that should match _contentBounds' size - - _$eventTarget: undefined, - _$contentFrame: undefined, - _$existingChildren: undefined, - _$attrList: undefined, - _$servicesContainer: undefined, - _$shapesContainers: undefined, //< all shapesContainer divs (map only) - - _$panContainer: undefined, //< all non-service elements that move while panning - _$shapesContainer: undefined, //< just "our" shapesContainer div (map & service) - _$drawContainer: undefined, - _$measureContainer: undefined, - _$measureLabel: undefined, - - _dpi: 96, - - _currentServices: [], //< internal copy - - _center: undefined, - _pixelSize: undefined, - _centerMax: undefined, - _pixelSizeMax: undefined, - _pixelSizeMin: undefined, - - _userGeodetic: true, - - _centerInteractive: undefined, - _pixelSizeInteractive: undefined, - _timeoutInteractive: null, - _timeoutWheel: null, - _triggerInteractive: false, - - _timeoutRefreshShapes: null, - - _loadCount: 0, - - _wheelLevel: 0, - - _fullZoomFactor: 2, //< interactiveScale factor needed to zoom a whole level - _partialZoomFactor: 1.18920711500273, //< interactiveScale factor needed to zoom a fraction of a level (the fourth root of 2) - - _mouseDown: undefined, - _inOp: undefined, - _toolPan: undefined, - _shiftDown: undefined, - _anchor: undefined, - _current: undefined, - _downDate: undefined, - _moveDate: undefined, - _clickDate: undefined, - _lastMove: undefined, - _lastDrag: undefined, - - _windowHandler: null, - _resizeTimeout: null, - - _panning: undefined, - _velocity: undefined, - _friction: undefined, - - _pointerEvents: undefined, - _supportTouch: undefined, - _softDblClick: undefined, - _isTap: undefined, - _isDbltap: undefined, - - _isMultiTouch: undefined, - _multiTouchAnchor: [], //< TouchList - _multiTouchAnchorBbox: undefined, //< bbox - _multiTouchCurrentBbox: undefined, //< bbox - - _drawTimeout: null, //< used in drawPoint mode so we don't send two shape events on dbltap - _drawPixels: [], //< an array of coordinate arrays for drawing lines & polygons, in pixel coordinates - _drawCoords: [], - - _graphicShapes: [], //< an array of objects containing style object refs & GeoJSON object refs - - _initOptions: {}, - - _options: {}, - - options: $.extend({}, _defaultOptions), - - _createWidget: function (options, element) { - this._$elem = $(element); - - if (this._$elem.is(".geo-service")) { - this._graphicShapes = []; - $.Widget.prototype._createWidget.apply(this, arguments); - return; - } - - this._widgetId = _widgetIdSeed++; - this._serviceIdSeed = 0; - this._tmplLengthId = "geoMeasureLength" + this._widgetId; - this._tmplAreaId = "geoMeasureArea" + this._widgetId; - - this._$elem.addClass("geo-map").css( { - webkitTransform: "translateZ(0)", - touchAction: 'none' - } ); - - this._initOptions = options || {}; - - this._forcePosition(this._$elem); - - this._$elem.css("text-align", "left"); - - var size = this._findMapSize(); - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._createChildren(); - - this._center = [ 0, 0 ]; - this._centerMax = [ 0, 0 ]; - this._centerInteractive = [ 0, 0 ]; - - this.options["pixelSize"] = this._pixelSize = this._pixelSizeMax = 156543.03392799936; - this._pixelSizeMin = this._pixelSizeMax / Math.pow( 2, 17 ); - - this._mouseDown = - this._inOp = - this._toolPan = - this._shiftDown = - this._panning = - this._isTap = - this._isDbltap = - this._isMultiTouch = false; - - this._anchor = [ 0, 0 ]; /* mouse down */ - this._current = [ 0, 0 ]; /* mouse move no matter what */ - this._lastMove = [ 0, 0 ]; - this._lastDrag = [ 0, 0 ]; - this._velocity = [ 0, 0 ]; - - this._friction = [0.8, 0.8]; - - this._downDate = - this._moveDate = - this._clickDate = 0; - - this._drawPixels = []; - this._drawCoords = []; - this._graphicShapes = []; - - - $.Widget.prototype._createWidget.apply(this, arguments); - }, - - _create: function () { - this._options = this.options; - - if (this._$elem.is(".geo-service")) { - this._map = this._$elem.data( "geoMap" ); - this._$elem.data( "geoService", this ); - return; - } - - this._map = this; - - this._pointerEvents = window.PointerEvent; - this._supportTouch = ("ontouchend" in document); - this._softDblClick = this._pointerEvents || this._supportTouch || _ieVersion === 7; - - var geomap = this, - touchStartEvent = this._pointerEvents ? 'pointerdown' : ( this._supportTouch ? "touchstart mousedown" : "mousedown" ), - touchStopEvent = this._pointerEvents ? 'pointerup pointercancel' : ( this._supportTouch ? "touchend touchcancel mouseup" : "mouseup" ), - touchMoveEvent = this._pointerEvents ? 'pointermove' : ( this._supportTouch ? "touchmove mousemove" : "mousemove" ); - - $(document).keydown($.proxy(this._document_keydown, this)); - - if ( this._softDblClick ) { - this._$eventTarget.on( 'softdblclick', $.proxy(this._eventTarget_dblclick, this)); - } else { - this._$eventTarget.dblclick($.proxy(this._eventTarget_dblclick, this)); - } - - this._$eventTarget.bind(touchStartEvent, $.proxy(this._eventTarget_touchstart, this)); - - var dragTarget = (this._$eventTarget[0].setCapture || this._pointerEvents) ? this._$eventTarget : $(document); - dragTarget.bind(touchMoveEvent, $.proxy(this._dragTarget_touchmove, this)); - dragTarget.bind(touchStopEvent, $.proxy(this._dragTarget_touchstop, this)); - - this._$eventTarget.mousewheel($.proxy(this._eventTarget_mousewheel, this)); - - this._windowHandler = function () { - if (geomap._resizeTimeout) { - clearTimeout(geomap._resizeTimeout); - } - geomap._resizeTimeout = setTimeout(function () { - if (geomap._created) { - geomap._$elem.geomap( "resize", true ); - } - }, 500); - }; - - $(window).resize(this._windowHandler); - - this._$drawContainer.geographics({ style: this._initOptions.drawStyle || {}, doubleBuffer: false }); - this._options["drawStyle"] = this._$drawContainer.geographics("option", "style"); - - this._$shapesContainer.geographics( { style: this._initOptions.shapeStyle || { }, doubleBuffer: !_gecko } ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - - if (this._initOptions) { - // always init tilingScheme right away, even if it's null - if ( this._initOptions.tilingScheme !== undefined ) { - this._setOption("tilingScheme", this._initOptions.tilingScheme || null, false); - } - - if ( this._initOptions.services ) { - // jQuery UI Widget Factory merges user services with our default, we want to clobber the default - this._options[ "services" ] = $.merge( [ ], this._initOptions.services ); - } - if (this._initOptions.bboxMax) { - this._setOption("bboxMax", this._initOptions.bboxMax, false); - this._setOption("bbox", this._initOptions.bboxMax, false); - } - if (this._initOptions.zoomMin !== undefined) { - this._setOption("zoomMin", this._initOptions.zoomMin, false); - } - if (this._initOptions.zoomMax !== undefined) { - this._setOption("zoomMax", this._initOptions.zoomMax, false); - } - if (this._initOptions.zoomFactor !== undefined) { - this._setOption("zoomFactor", this._initOptions.zoomFactor, false); - this._fullZoomFactor = this._initOptions.zoomFactor; - this._partialZoomFactor = Math.pow(4, 1 / this._fullZoomFactor); // 4th root of full - } - if (this._initOptions.bbox) { - this._setOption("bbox", this._initOptions.bbox, false); - } - if (this._initOptions.center) { - this._setOption("center", this._initOptions.center, false); - } - if (this._initOptions.zoom !== undefined) { - this._setOption("zoom", this._initOptions.zoom, false); - } - } - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._createServices(); - this._refresh(); - - this._created = true; - }, - - _setOption: function (key, value, refresh) { - if ( key === "pixelSize" ) { - return; - } - - refresh = (refresh === undefined || refresh); - - if ( this._$elem.is( ".geo-map" ) ) { - this._panFinalize(); - } - - var center, pixelSize, bbox, zoom; - - switch (key) { - case "bbox": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2]; - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height); - - // clamp to zoom - zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( center, pixelSize ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( center, pixelSize, false, refresh ); - } - - value = this._getBbox( center, pixelSize ); - break; - - case "bboxMax": - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - break; - - case "center": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( value, this._pixelSizeInteractive ); - this._interactiveTransform( ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( value, this._pixelSize, false, refresh ); - } - break; - - case "measureLabels": - value = $.extend( this._options[ "measureLabels" ], value ); - - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - break; - - case "drawStyle": - if (this._$drawContainer) { - this._$drawContainer.geographics("option", "style", value); - value = this._$drawContainer.geographics("option", "style"); - } - break; - - case "shapeStyle": - if ( this._$elem.is( ".geo-service" ) && !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("option", "style", value); - value = this._$shapesContainer.geographics("option", "style"); - } - break; - - case "mode": - this._resetDrawing( ); - this._$eventTarget.css("cursor", this._options["cursors"][value]); - break; - - case "zoom": - this._userGeodetic = this._options["axisLayout"] === "map" && $.geo.proj; - if ( this._created ) { - this._setZoom(value, false, refresh); - } else { - value = Math.max( value, 0 ); - this._setCenterAndSize( this._center, this._getPixelSize( value ), false, refresh ); - } - break; - } - - $.Widget.prototype._setOption.apply(this, arguments); - - switch ( key ) { - case "bbox": - case "center": - if ( this._userGeodetic ) { - this._options[ "bbox" ] = $.geo.proj.toGeodetic( this._options[ "bbox" ] ); - this._options[ "center" ] = $.geo.proj.toGeodetic( this._center ); - } - break; - - case "tilingScheme": - if ( value !== null ) { - this._pixelSizeMax = this._getPixelSize( 0 ); - this._pixelSizeMin = this._getPixelSize( value.pixelSizes ? value.pixelSizes.length - 1 : value.levels - 1 ); - this._centerMax = [ - value.origin[ 0 ] + this._pixelSizeMax * value.tileWidth / 2, - value.origin[ 1 ] + this._pixelSizeMax * value.tileHeight / 2 - ]; - } - break; - - case "bboxMax": - if ( this._userGeodetic ) { - bbox = $.geo.proj.fromGeodetic( value ); - } else { - bbox = value; - } - - this._centerMax = $.geo.center( bbox ); - this._pixelSizeMax = Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - break; - - case "services": - this._createServices(); - if (refresh) { - this._refresh(); - this._refreshAllShapes(); - } - break; - - case "shapeStyle": - if ( refresh && this._createdGraphics ) { - this._$shapesContainer.geographics("clear"); - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - break; - } - }, - - destroy: function () { - if ( this._$elem.is(".geo-service") ) { - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - } - } else { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - - this._created = false; - - $(window).unbind("resize", this._windowHandler); - - for ( var i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - - this._$drawContainer.geographics("destroy"); - this._$drawContainer = undefined; - - this._$existingChildren.detach(); - this._$elem.html(""); - this._$elem.append(this._$existingChildren); - this._$elem.removeClass("geo-map"); - } - - $.Widget.prototype.destroy.apply(this, arguments); - }, - - toMap: function (p) { - p = this._toMap(p); - return this._userGeodetic ? $.geo.proj.toGeodetic(p) : p; - }, - - toPixel: function ( p, _center /* Internal Use Only */, _pixelSize /* Internal Use Only */ ) { - return this._toPixel( $.geo.proj ? $.geo.proj.fromGeodetic( p ) : p, _center, _pixelSize ); - }, - - opacity: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "opacity", value, this._$elem ); - } else { - if ( value >= 0 || value <= 1 ) { - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - service.style.opacity = value; - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - $.geo[ "_serviceTypes" ][ service.type ].opacity( this, service ); - } - } - } - } - }, - - toggle: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "toggle", value, this._$elem ); - } else { - - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - if ( value === undefined ) { - // toggle visibility - value = ( service.style.visibility !== "visible" ); - } - - service.style.visibility = ( value ? "visible" : "hidden" ); - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - service.serviceContainer.toggle( value ); - - if ( value ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service ); - } - } - } - } - }, - - zoom: function (numberOfLevels) { - if (numberOfLevels !== null) { - this._setZoom(this._options["zoom"] + numberOfLevels, false, true); - } - }, - - refresh: function ( force, _serviceContainer ) { - if ( !this._panning ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "refresh", force, this._$elem ); - } else { - this._refresh( force, _serviceContainer ); - this._refreshAllShapes( _serviceContainer ); - } - } - }, - - resize: function ( _trigger /* Internal Use Only */ ) { - var size = this._findMapSize(), - dx = size["width"]/2 - this._contentBounds.width/2, - dy = size["height"]/2 - this._contentBounds.height/2, - i; - - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._$resizeContainer.css( { - width: size["width"], - height: size["height"] - } ); - - for (i = 0; i < this._currentServices.length; i++) { - $.geo["_serviceTypes"][this._currentServices[i].type].resize(this, this._currentServices[i], dx, dy); - } - - this._$elem.find( ".geo-graphics" ).css( { - width: size["width"], - height: size["height"] - }).geographics( "resize", dx, dy ); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._setCenterAndSize(this._center, this._pixelSize, _trigger, true); - }, - - append: function ( shape /* , style, label, refresh */ ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - if ( !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - var shapes, arg, i, realStyle, realLabel, realRefresh; - - if ( $.isArray( shape ) ) { - shapes = shape; - } else if ( shape.type === "FeatureCollection" ) { - shapes = shape.features; - } else { - shapes = [ shape ]; - } - - for ( i = 1; i < arguments.length; i++ ) { - arg = arguments[ i ]; - - if ( arg !== null ) { - if ( typeof arg === "object" ) { - realStyle = arg; - } else if ( typeof arg === "number" || typeof arg === "string" ) { - realLabel = arg; - } else if ( typeof arg === "boolean" ) { - realRefresh = arg; - } - } - } - - for ( i = 0; i < shapes.length; i++ ) { - if ( !$.data( shapes[ i ], "geoBbox" ) ) { - var bbox = $.geo.bbox( shapes[ i ] ); - if ( $.geo.proj && $.geo._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - $.data( shapes[ i ], "geoBbox", bbox ); - } - - this._graphicShapes.push( { - shape: shapes[ i ], - style: realStyle, - label: realLabel - } ); - } - - if ( realRefresh === undefined || realRefresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - empty: function ( refresh ) { - this._graphicShapes = []; - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - }, - - find: function ( selector, pixelTolerance ) { - if ( this._timeoutInteractive ) { - return []; - } - - var isPoint = $.isPlainObject( selector ), - //searchPixel = isPoint ? this._map.toPixel( selector.coordinates ) : undefined, - mapTol = this._map._pixelSize * pixelTolerance, - result = [], - graphicShape, - geometries, - curGeom, - i; - - if ( this._$elem.is( ".geo-map" ) ) { - $( this._$elem.find( ".geo-service" ).get().reverse() ).each( function( ) { - result = $.merge( result, $( this ).geomap( "find", selector, pixelTolerance ) ); - } ); - } - - for ( i = this._graphicShapes.length - 1; i >= 0; i-- ) { - graphicShape = this._graphicShapes[ i ]; - - if ( isPoint ) { - if ( graphicShape.shape.type === "Point" ) { - if ( $.geo.distance( graphicShape.shape, selector ) <= mapTol ) { - result.push( graphicShape.shape ); - } - } else { - var bbox = $.data( graphicShape.shape, "geoBbox" ), - bboxPolygon = { - type: "Polygon", - coordinates: [ [ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ] ] - }, - projectedPoint = { - type: "Point", - coordinates: $.geo.proj && $.geo._isGeodetic( selector.coordinates ) ? $.geo.proj.fromGeodetic( selector.coordinates ) : selector.coordinates - }; - - if ( $.geo.distance( bboxPolygon, projectedPoint, true ) <= mapTol ) { - geometries = $.geo._basic( graphicShape.shape ); - for ( curGeom = 0; curGeom < geometries.length; curGeom++ ) { - if ( $.geo.distance( geometries[ curGeom ], selector ) <= mapTol ) { - result.push( graphicShape.shape ); - break; - } - } - } - } - } else { - result.push( graphicShape.shape ); - } - } - - return result; - }, - - remove: function ( shape, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - var shapes = $.isArray( shape ) ? shape : [ shape ], - rest; - - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - if ( $.inArray( this._graphicShapes[ i ].shape, shapes ) >= 0 ) { - rest = this._graphicShapes.slice( i + 1 ); - this._graphicShapes.length = i; - this._graphicShapes.push.apply( this._graphicShapes, rest ); - i--; - } - } - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - _getBbox: function (center, pixelSize) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - // calculate the internal bbox - var halfWidth = this._contentBounds[ "width" ] / 2 * pixelSize, - halfHeight = this._contentBounds[ "height" ] / 2 * pixelSize; - return [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - }, - - _setBbox: function (value /* , trigger, refresh */ ) { - var center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2], - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height), - zoom = this._getZoom( center, pixelSize ); - - // clamp to zoom - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._setInteractiveCenterAndSize( center, pixelSize ); - this._interactiveTransform( ); - }, - - _getBboxMax: function () { - // calculate the internal bboxMax - var halfWidth = this._contentBounds["width"] / 2 * this._pixelSizeMax, - halfHeight = this._contentBounds["height"] / 2 * this._pixelSizeMax; - return [this._centerMax[0] - halfWidth, this._centerMax[1] - halfHeight, this._centerMax[0] + halfWidth, this._centerMax[1] + halfHeight]; - }, - - _getCenter: function () { - return this._center; - }, - - _getContentBounds: function () { - return this._contentBounds; - }, - - _getServicesContainer: function () { - return this._$servicesContainer; - }, - - _getZoom: function ( center, pixelSize ) { - // calculate the internal zoom level, vs. public zoom property - // this does not take zoomMin or zoomMax into account - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var tilingScheme = this._options["tilingScheme"]; - if ( tilingScheme ) { - if ( tilingScheme.pixelSizes ) { - var roundedPixelSize = Math.floor(pixelSize * 1000), - levels = tilingScheme.pixelSizes.length, - i = levels - 1; - - for ( ; i >= 0; i-- ) { - if ( Math.floor( tilingScheme.pixelSizes[ i ] * 1000 ) >= roundedPixelSize ) { - return i; - } - } - - return 0; - } else { - return Math.round( Math.log( tilingScheme.basePixelSize / pixelSize) / Math.log( 2 ) ); - } - } else { - var ratio = this._contentBounds["width"] / this._contentBounds["height"], - bbox = $.geo.reaspect( this._getBbox( center, pixelSize ), ratio, true ), - bboxMax = $.geo.reaspect(this._getBboxMax(), ratio, true); - - return Math.round( Math.log($.geo.width(bboxMax, true) / $.geo.width(bbox, true)) / Math.log(this._fullZoomFactor) ); - } - }, - - _setZoom: function ( value, trigger /* , refresh */ ) { - // set the map widget's zoom, taking zoomMin and zoomMax into account - this._clearInteractiveTimeout( ); - - value = Math.min( Math.max( value, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ); - - this._setInteractiveCenterAndSize( this._centerInteractive, this._getPixelSize( value ) ); - this._interactiveTransform( ); - this._setInteractiveTimeout( trigger ); - }, - - _createChildren: function () { - this._$existingChildren = this._$elem.children(); - - this._forcePosition(this._$existingChildren); - - this._$existingChildren.detach().css( { - mozUserSelect: "none" - } ); - - - var contentSizeCss = "width:" + this._contentBounds["width"] + "px; height:" + this._contentBounds["height"] + "px; margin:0; padding:0;", - contentPosCss = "position:absolute; left:0; top:0;"; - - this._$elem.prepend( window.toStaticHTML( '
                        ' ) ); - this._$eventTarget = this._$contentFrame = this._$elem.children(':first'); - - this._$contentFrame.append('
                        '); - this._$servicesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append( '
                          ' ); - this._$attrList = this._$contentFrame.children( ":last" ); - - this._$contentFrame.append('
                          '); - this._$drawContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                          '); - this._$measureContainer = this._$contentFrame.children(':last'); - this._$measureLabel = this._$measureContainer.children(); - - this._$contentFrame.append('
                          '); - this._$shapesContainer = this._$contentFrame.children(':last'); - - this._$panContainer = $( [ this._$shapesContainer[ 0 ], this._$drawContainer[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$resizeContainer = $( [ this._$contentFrame[ 0 ], this._$servicesContainer[ 0 ], this._$eventTarget[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$contentFrame.append(this._$existingChildren); - - if ( ! $("#geo-measure-style").length ) { - $("head").prepend( window.toStaticHTML( '' ) ); - } - }, - - _createServices: function () { - var service, i; - - for ( i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap( "destroy" ); - $.geo[ "_serviceTypes" ][ this._currentServices[ i ].type ].destroy( this, this._$servicesContainer, this._currentServices[ i ] ); - } - - this._currentServices = [ ]; - this._$servicesContainer.html( "" ); - this._$attrList.html( "" ); - - for ( i = 0; i < this._options[ "services" ].length; i++ ) { - service = this._currentServices[ i ] = $.extend( { }, this._options[ "services" ][ i ] ); - - // keep a reference to the original - service.serviceObject = this._options[ "services" ][ i ]; - - // default the service style property on our copy - service.style = $.extend( { - visibility: "visible", - opacity: 1 - }, service.style ); - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = 'class="geo-service ' + ( service["class"] ? service["class"] : '' ) + '"', - scHtml = '
                          ', - serviceContainer; - - this._$servicesContainer.append( window.toStaticHTML( scHtml ) ); - serviceContainer = this._$servicesContainer.children( ":last" ); - service.serviceContainer = serviceContainer; - - $.geo[ "_serviceTypes" ][ service.type ].create( this, serviceContainer, service, i ); - - serviceContainer.data( "geoMap", this ).geomap(); - - if ( service.attr ) { - this._$attrList.append( '
                        • ' + service.attr + '
                        • ' ); - } - } - - // start with our map-level shapesContainer - this._$shapesContainers = this._$shapesContainer; - - this._$attrList.find( "a" ).css( { - position: "relative", - zIndex: 1, - display: "inline-block", - webkitTransform: "translateZ(0)" - } ); - }, - - _createServiceGraphics: function( ) { - // only called in the context of a service-level geomap - var $contentFrame = this._$elem.closest( ".geo-content-frame" ); - this._$elem.append('
                          '); - this._$shapesContainer = this._$elem.children(':last'); - - this._map._$shapesContainers = this._map._$shapesContainers.add( this._$shapesContainer ); - - this._$shapesContainer.geographics( { doubleBuffer: !_gecko }); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - }, - - _refreshDrawing: function ( ) { - this._$drawContainer.geographics("clear"); - - if ( this._drawPixels.length > 0 ) { - var mode = this._options[ "mode" ], - pixels = this._drawPixels, - coords = this._drawCoords, - label, - labelShape, - labelPixel, - widthOver, - heightOver; - - switch ( mode ) { - case "measureLength": - mode = "drawLineString"; - labelShape = { - type: "LineString", - coordinates: coords - }; - label = $.render[ this._tmplLengthId ]( { length: $.geo.length( labelShape, true ) } ); - labelPixel = $.merge( [], pixels[ pixels.length - 1 ] ); - break; - - case "measureArea": - mode = "drawPolygon"; - - labelShape = { - type: "Polygon", - coordinates: [ $.merge( [ ], coords ) ] - }; - labelShape.coordinates[ 0 ].push( coords[ 0 ] ); - - label = $.render[ this._tmplAreaId ]( { area: $.geo.area( labelShape, true ) } ); - labelPixel = this._toPixel( $.geo.centroid( labelShape ).coordinates ); - pixels = [ pixels ]; - break; - - case "drawPolygon": - pixels = [ pixels ]; - break; - } - - this._$drawContainer.geographics( mode, pixels ); - - if ( label ) { - this._$measureLabel.html( label ); - - widthOver = this._contentBounds.width - ( this._$measureLabel.outerWidth( true ) + labelPixel[ 0 ] ); - heightOver = this._contentBounds.height - ( this._$measureLabel.outerHeight( true ) + labelPixel[ 1 ] ); - - if ( widthOver < 0 ) { - labelPixel[ 0 ] += widthOver; - } - - if ( heightOver < 0 ) { - labelPixel[ 1 ] += heightOver; - } - - this._$measureLabel.css( { - left: Math.max( labelPixel[ 0 ], 0 ), - top: Math.max( labelPixel[ 1 ], 0 ) - } ).show(); - } - } - }, - - _resetDrawing: function () { - this._drawPixels = []; - this._drawCoords = []; - this._$drawContainer.geographics("clear"); - this._$measureLabel.hide(); - }, - - _refreshAllShapes: function ( _serviceContainer ) { - this._timeoutRefreshShapes = null; - - var service, - geoService, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - geoService = service.serviceContainer.data( "geoService" ); - - if ( geoService._createdGraphics ) { - geoService._$shapesContainer.geographics( "clear" ); - if ( geoService._graphicShapes.length > 0 ) { - geoService._refreshShapes( geoService._$shapesContainer, geoService._graphicShapes, geoService._graphicShapes, geoService._graphicShapes ); - } - } - } - } - - if ( this._createdGraphics && !_serviceContainer ) { - this._$shapesContainer.geographics( "clear" ); - if ( this._graphicShapes.length > 0 ) { - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - } - }, - - - _refreshShapes: function (geographics, shapes, styles, labels, center, pixelSize) { - var i, mgi, - shape, - shapeBbox, - style, - label, - hasLabel, - labelPixel, - centroid, - bbox = this._map._getBbox(center, pixelSize); - - for (i = 0; i < shapes.length; i++) { - shape = shapes[i].shape || shapes[i]; - shape = shape.geometry || shape; - shapeBbox = $.data(shape, "geoBbox"); - - if ( shapeBbox && $.geo._bboxDisjoint( bbox, shapeBbox ) ) { - continue; - } - - style = $.isArray(styles) ? styles[i].style : styles; - label = $.isArray(labels) ? labels[i].label : labels; - hasLabel = ( label !== undefined ); - labelPixel = undefined; - centroid = $.geo.centroid( shape ); - - switch (shape.type) { - case "Point": - labelPixel = this._map.toPixel( shape.coordinates, center, pixelSize ); - this._$shapesContainer.geographics("drawPoint", labelPixel, style); - break; - case "LineString": - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.pointAlong( shape, 0.5 ).coordinates, center, pixelSize ); - } - break; - case "Polygon": - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiPoint": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPoint", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiLineString": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - case "MultiPolygon": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel && centroid ) { - labelPixel = this._map.toPixel( centroid.coordinates, center, pixelSize ); - } - break; - - case "GeometryCollection": - this._refreshShapes(geographics, shape.geometries, style, label, center, pixelSize); - break; - } - - if ( hasLabel && labelPixel ) { - this._$shapesContainer.geographics( "drawLabel", labelPixel, label ); - } - } - }, - - _findMapSize: function () { - // really, really attempt to find a size for this thing - // even if it's hidden (look at parents) - var size = { width: 0, height: 0 }, - sizeContainer = this._$elem; - - while (sizeContainer.size() && !(size["width"] > 0 && size["height"] > 0)) { - size = { width: sizeContainer.width(), height: sizeContainer.height() }; - if (size["width"] <= 0 || size["height"] <= 0) { - size = { width: parseInt(sizeContainer.css("width"), 10), height: parseInt(sizeContainer.css("height"), 10) }; - } - sizeContainer = sizeContainer.parent(); - } - return size; - }, - - _forcePosition: function (elem) { - var cssPosition = elem.css("position"); - if (cssPosition !== "relative" && cssPosition !== "absolute" && cssPosition !== "fixed") { - elem.css("position", "relative"); - } - }, - - _getPixelSize: function ( zoom ) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme !== null) { - if (zoom === 0) { - return tilingScheme.pixelSizes ? tilingScheme.pixelSizes[0] : tilingScheme.basePixelSize; - } - - zoom = Math.round(zoom); - zoom = Math.max(zoom, 0); - var levels = tilingScheme.pixelSizes ? tilingScheme.pixelSizes.length : tilingScheme.levels; - zoom = Math.min(zoom, levels - 1); - - if ( tilingScheme.pixelSizes ) { - return tilingScheme.pixelSizes[zoom]; - } else { - return tilingScheme.basePixelSize / Math.pow(2, zoom); - } - } else { - var bbox = $.geo.scaleBy( this._getBboxMax(), 1 / Math.pow( this._fullZoomFactor, zoom ), true ); - return Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - } - }, - - _getZoomCenterAndSize: function ( anchor, zoomDelta, full ) { - var zoomFactor = ( full ? this._fullZoomFactor : this._partialZoomFactor ), - scale = Math.pow( zoomFactor, -zoomDelta ), - pixelSize = this._pixelSizeInteractive * scale; - - if ( this._options[ "tilingScheme" ] ) { - // clamp to min/max pixelSize - pixelSize = Math.min( Math.max( pixelSize, this._pixelSizeMin ), this._pixelSizeMax ); - } - - var zoom = this._getZoom(this._centerInteractive, pixelSize); - - // clamp to zoom - if ( full && this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoomDelta < 0 && zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._pixelSizeInteractive; - } else if ( zoomDelta > 0 && zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._pixelSizeInteractive; - } - } - - var ratio = pixelSize / this._pixelSizeInteractive, - anchorMapCoord = this._toMap( anchor, this._centerInteractive, this._pixelSizeInteractive ), - centerDelta = [(this._centerInteractive[0] - anchorMapCoord[0]) * ratio, (this._centerInteractive[1] - anchorMapCoord[1]) * ratio], - scaleCenter = [anchorMapCoord[0] + centerDelta[0], anchorMapCoord[1] + centerDelta[1]]; - - return { pixelSize: pixelSize, center: scaleCenter }; - }, - - _panFinalize: function () { - if (this._panning) { - this._velocity = [0, 0]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._inOp = false; - this._anchor = this._current; - this._mouseDown = this._toolPan = this._panning = false; - } - }, - - _panMove: function () { - if ( ! this._options[ "pannable" ] ) { - return; - } - - var dx = this._current[0] - this._lastDrag[0], - dy = this._current[1] - this._lastDrag[1]; - - if (this._toolPan || dx > 3 || dx < -3 || dy > 3 || dy < -3) { - if (!this._toolPan) { - this._toolPan = true; - this._$eventTarget.css("cursor", this._options["cursors"]["pan"]); - } - - if (this._mouseDown) { - this._velocity = [dx, dy]; - } - - if (dx !== 0 || dy !== 0) { - this._panning = true; - this._lastDrag = this._current; - - this._centerInteractive[ 0 ] -= ( dx * this._pixelSizeInteractive ); - this._centerInteractive[ 1 ] += ( ( this._options[ "axisLayout" ] === "image" ? -1 : 1 ) * dy * this._pixelSizeInteractive ); - this._setInteractiveCenterAndSize( this._centerInteractive, this._pixelSizeInteractive ); - this._interactiveTransform( ); - } - } - }, - - _clearInteractiveTimeout: function() { - if ( this._timeoutRefreshShapes ) { - clearTimeout( this._timeoutRefreshShapes ); - this._timeoutRefreshShapes = null; - } - - if ( this._timeoutInteractive ) { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - return true; - } else { - this._centerInteractive[ 0 ] = this._center[ 0 ]; - this._centerInteractive[ 1 ] = this._center[ 1 ]; - this._pixelSizeInteractive = this._pixelSize; - return false; - } - }, - - _interactiveTransform: function( ) { - var service, - - scalePixelSize = this._pixelSize, - scaleRatio = scalePixelSize / this._pixelSizeInteractive; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = this._toMap( [ 0, 0 ] ), - newPixelPoint = this._toPixel( oldMapOrigin, this._centerInteractive, this._pixelSizeInteractive ); - - - this._$shapesContainers.geographics("interactiveTransform", newPixelPoint, scaleRatio); - } - - for ( var i = 0; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo[ "_serviceTypes" ][ service.type ].interactiveTransform( this, service, this._centerInteractive, this._pixelSizeInteractive ); - } - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel( this._drawCoords, this._centerInteractive, this._pixelSizeInteractive ); - this._refreshDrawing(); - } - }, - - _interactiveTimeout: function( ) { - if ( this._isMultiTouch ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - } else if ( this._created && this._timeoutInteractive ) { - this._setCenterAndSize( this._centerInteractive, this._pixelSizeInteractive, this._triggerInteractive, true ); - this._timeoutInteractive = null; - this._triggerInteractive = false; - - this._timeoutRefreshShapes = setTimeout( $.proxy( this._refreshAllShapes, this ), 128 ); - } - }, - - _setInteractiveTimeout: function( trigger ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - this._triggerInteractive |= trigger; - }, - - _refresh: function ( force, _serviceContainer ) { - var service, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] === _serviceContainer[ 0 ] ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service, force ); - } - } - }, - - _setInteractiveCenterAndSize: function ( center, pixelSize ) { - // set the temporary (interactive) center & size - // also, update the public-facing options - // this does not take zoomMin or zoomMax into account - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - this._pixelSizeInteractive = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox( center, pixelSize ) ); - this._options["center"] = $.geo.proj.toGeodetic( center ); - } else { - this._options["bbox"] = this._getBbox( center, pixelSize ); - this._options["center"][ 0 ] = center[ 0 ]; - this._options["center"][ 1 ] = center[ 1 ]; - } - - this._options["pixelSize"] = pixelSize; - this._options["zoom"] = this._getZoom( center, pixelSize ); - }, - - _setCenterAndSize: function (center, pixelSize, trigger, refresh) { - if ( ! $.isArray( center ) || center.length !== 2 || typeof center[ 0 ] !== "number" || typeof center[ 1 ] !== "number" ) { - return; - } - - // the final call during any extent change - // only called by timeoutInteractive & resize - // clamp to zoom - var zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - - if ( this._created ) { - // one last interactiveTransform to put pinched map into place - this._interactiveTransform( ); - } - - this._options["pixelSize"] = this._pixelSize = pixelSize; - - this._center[ 0 ] = center[ 0 ]; - this._center[ 1 ] = center[ 1 ]; - - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox() ); - this._options["center"] = $.geo.proj.toGeodetic( this._center ); - } else { - this._options["bbox"] = this._getBbox(); - this._options["center"] = $.merge( [ ], center ); - } - - this._options["zoom"] = zoom; - - if (trigger) { - this._trigger("bboxchange", window.event, { bbox: $.merge( [ ], this._options["bbox"] ) }); - } - - if (refresh) { - this._refresh(); - this._refreshAllShapes( ); - this._refreshDrawing(); - } - }, - - _requestQueued: function ( ) { - if ( this._loadCount === 0 ) { - this._trigger( "loadstart", window.event ); - } - this._loadCount++; - }, - - _requestComplete: function ( ) { - this._loadCount--; - if ( this._loadCount <= 0 ) { - this._loadCount = 0; - this._trigger( "loadend", window.event ); - } - }, - - _toMap: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - xRatio = $.geo.width(bbox, true) / width, - yRatio = $.geo.height(bbox, true) / height, - yOffset, - image = this._options[ "axisLayout" ] === "image", - result = [], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - yOffset = (p[ i ][ j ][ k ][1] * yRatio); - result[ i ][ j ][ k ] = [ - bbox[ 0 ] + ( p[ i ][ j ][ k ][ 0 ] * xRatio ), - image ? bbox[ 1 ] + yOffset : bbox[ 3 ] - yOffset - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _toPixel: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - bboxWidth = $.geo.width(bbox, true), - bboxHeight = $.geo.height(bbox, true), - image = this._options[ "axisLayout" ] === "image", - xRatio = width / bboxWidth, - yRatio = height / bboxHeight, - result = [ ], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = [ - Math.round( ( p[ i ][ j ][ k ][ 0 ] - bbox[ 0 ] ) * xRatio ), - Math.round( ( image ? p[ i ][ j ][ k ][ 1 ] - bbox[ 1 ] : bbox[ 3 ] - p[ i ][ j ][ k ][ 1 ] ) * yRatio ) - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _document_keydown: function (e) { - var len = this._drawCoords.length; - if (len > 0 && e.which === 27) { - if (len <= 2) { - this._resetDrawing(); - this._inOp = false; - } else { - this._drawCoords[len - 2] = $.merge( [], this._drawCoords[ len - 1 ] ); - this._drawPixels[len - 2] = $.merge( [], this._drawPixels[ len - 1 ] ); - - this._drawCoords.length--; - this._drawPixels.length--; - - this._refreshDrawing(); - } - } - }, - - _eventTarget_dblclick_zoom: function(e) { - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - this._trigger("dblclick", e, { type: "Point", coordinates: this._toMap(this._current, this._centerInteractive, this._pixelSizeInteractive ) }); - - if (!e.isDefaultPrevented()) { - var centerAndSize = this._getZoomCenterAndSize(this._current, 1, true ); - - this._setInteractiveCenterAndSize( centerAndSize.center, centerAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - }, - - _eventTarget_dblclick: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - switch (this._options["mode"]) { - case "drawLineString": - case "measureLength": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] === this._drawCoords[1][0] && - this._drawCoords[0][1] === this._drawCoords[1][1] ) ) { - this._drawCoords.length--; - this._trigger( "shape", e, { - type: "LineString", - coordinates: this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords - } ); - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "drawPolygon": - case "measureArea": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] === this._drawCoords[1][0] && - this._drawCoords[0][1] === this._drawCoords[1][1] ) ) { - var endIndex = this._drawCoords.length - 1; - if (endIndex > 2) { - this._drawCoords[endIndex] = $.merge( [], this._drawCoords[0] ); - this._trigger( "shape", e, { - type: "Polygon", - coordinates: [ this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords ] - } ); - } - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - default: - this._eventTarget_dblclick_zoom(e); - break; - } - - this._inOp = false; - }, - - _eventTarget_touchstart: function (e) { - if ( typeof( document.elementFromPoint ) !== "undefined" ) { - var elFromPt = document.elementFromPoint( e.pageX, e.pageY ); - if ( elFromPt && elFromPt.nodeName === "A" ) { - return; - } - } - - var mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ); - - if ( mode === "static" ) { - return; - } - - if ( !this._pointerEvents && !this._supportTouch && e.which !== 1 ) { - return; - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var offset = $(e.currentTarget).offset(), - touches = e.originalEvent.changedTouches; - - if ( this._pointerEvents ) { - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 ) { - // switch to multitouch - e.currentTarget.setPointerCapture( e.originalEvent.pointerId ); - - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( e.originalEvent ); - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._anchor = $.geo.center( this._multiTouchCurrentBbox, true ); - this._current = $.merge( [], this._anchor ); - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - } else if ( this._multiTouchAnchor.length < 2 ) { - e.currentTarget.setPointerCapture( e.originalEvent.pointerId ); - - this._multiTouchAnchor.push( e.originalEvent ); - - this._multiTouchCurrentBbox = [ - this._multiTouchAnchor[0].pageX - offset.left, - this._multiTouchAnchor[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ this._multiTouchAnchor[0].pageX - offset.left, this._multiTouchAnchor[0].pageY - offset.top ]; - } - } else if ( this._supportTouch && touches ) { - this._multiTouchAnchor = $.merge( [ ], touches ); - - this._isMultiTouch = this._multiTouchAnchor.length > 1; - - if ( this._isMultiTouch ) { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - touches[1].pageX - offset.left, - touches[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ touches[0].pageX - offset.left, touches[0].pageY - offset.top ]; - } - } else { - this._current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - var downDate = $.now(); - if (downDate - this._downDate < 750) { - if (this._isTap) { - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance > 8) { - this._isTap = false; - } else { - this._current = $.merge( [ ], this._anchor ); - } - } - - if (this._isDbltap) { - this._isDbltap = false; - } else { - this._isDbltap = this._isTap; - } - } else { - this._isDbltap = false; - } - this._isTap = true; - this._downDate = downDate; - } - - this._mouseDown = true; - this._anchor = $.merge( [ ], this._current ); - - if (!this._inOp && e.shiftKey && shift !== "off") { - this._shiftDown = true; - this._$eventTarget.css( "cursor", this._options[ "cursors" ][ shift === "default" ? defaultShift : shift ] ); - } else if ( !this._isMultiTouch && ( this._options[ "pannable" ] || mode === "dragBox" || mode === "dragCircle" ) ) { - this._inOp = true; - - if ( mode !== "zoom" && mode !== "dragBox" && mode !== "dragCircle" ) { - this._lastDrag = this._current; - - if (e.currentTarget.setCapture) { - e.currentTarget.setCapture(); - } - } - } - - e.preventDefault(); - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - }, - - _dragTarget_touchmove: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - var doInteractiveTimeout = false; - if ( this._mouseDown ) { - doInteractiveTimeout = this._clearInteractiveTimeout( ); - } - - var offset = this._$eventTarget.offset(), - drawCoordsLen = this._drawCoords.length, - touches = e.originalEvent.changedTouches, - current = null, - anchorDistance, - currentDistance, - wheelLevel, - delta, - pinchCenterAndSize, - i; - - if ( this._pointerEvents ) { - if ( this._isMultiTouch ) { - if ( e.originalEvent.pointerId === this._multiTouchAnchor[ 0 ].pointerId ) { - this._multiTouchCurrentBbox[ 0 ] = e.originalEvent.pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = e.originalEvent.pageY - offset.top; - } else if ( e.originalEvent.pointerId === this._multiTouchAnchor[ 1 ].pointerId ) { - this._multiTouchCurrentBbox[ 2 ] = e.originalEvent.pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = e.originalEvent.pageY - offset.top; - } else { - // untracked pointer - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ); - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - } else { - this._multiTouchAnchor[ 0 ] = e.originalEvent; - - this._multiTouchCurrentBbox = [ - this._multiTouchAnchor[0].pageX - offset.left, - this._multiTouchAnchor[0].pageY - offset.top, - NaN, - NaN - ]; - - current = [e.originalEvent.pageX - offset.left, e.originalEvent.pageY - offset.top]; - } - } else if ( this._supportTouch && touches ) { - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 && touches[ 0 ].identifier !== this._multiTouchAnchor[ 0 ].identifier ) { - // switch to multitouch - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( touches[ 0 ] ); - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._anchor = this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - if ( this._isMultiTouch ) { - - for ( i = 0; i < touches.length; i++ ) { - if ( touches[ i ].identifier === this._multiTouchAnchor[ 0 ].identifier ) { - this._multiTouchCurrentBbox[ 0 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = touches[ i ].pageY - offset.top; - } else if ( touches[ i ].identifier === this._multiTouchAnchor[ 1 ].identifier ) { - this._multiTouchCurrentBbox[ 2 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = touches[ i ].pageY - offset.top; - } - } - - anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ); - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if ( current === null ) { - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - if (current[0] === this._lastMove[0] && current[1] === this._lastMove[1]) { - if ( this._inOp ) { - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } else { - // fixes: [bug] highlight pop - return false; - } - } - - if ( _ieVersion === 7 ) { - this._isDbltap = this._isTap = false; - } - - if (this._mouseDown) { - this._current = current; - this._moveDate = $.now(); - } - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - var mode = this._options["mode"], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - dx, dy, circleSize; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - switch (mode) { - case "zoom": - case "dragBox": - if ( this._mouseDown ) { - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawBbox", [ - this._anchor[ 0 ], - this._anchor[ 1 ], - current[ 0 ], - current[ 1 ] - ] ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "dragCircle": - if ( this._mouseDown ) { - dx = current[ 0 ] - this._anchor[ 0 ]; - dy = current[ 1 ] - this._anchor[ 1 ]; - circleSize = Math.sqrt( ( dx * dx) + ( dy * dy ) ) * 2; - //circleSize = Math.max( Math.abs( current[ 0 ] - this._anchor[ 0 ] ), Math.abs( current[ 1 ] - this._anchor[ 1 ] ) ) * 2; - - // not part of _refreshDrawing - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawArc", this._anchor, 0, 360, { - width: circleSize, - height: circleSize - } ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - if (drawCoordsLen > 0) { - this._drawCoords[drawCoordsLen - 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[drawCoordsLen - 1] = current; - - this._refreshDrawing(); - } - - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - default: - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - } - - this._lastMove = current; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchstop: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if ( !this._mouseDown ) { - if ( _ieVersion === 7 ) { - // ie7 doesn't appear to trigger dblclick on this._$eventTarget, - // we fake regular click here to cause soft dblclick - this._eventTarget_touchstart(e); - } else { - // Chrome & Firefox trigger a rogue mouseup event when doing a dblclick maximize in Windows(/Linux?) - // ignore it - return; - } - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var mouseWasDown = this._mouseDown, - wasToolPan = this._toolPan, - offset = this._$eventTarget.offset(), - mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - current = null, i, clickDate, - dx, dy, - coordBuffer, - triggerShape; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - if ( this._pointerEvents ) { - if ( e.originalEvent.pointerId === this._multiTouchAnchor[ 0 ].pointerId || e.originalEvent.pointerId === this._multiTouchAnchor[ 1 ].pointerId ) { - e.currentTarget.releasePointerCapture( e.originalEvent.pointerId ); - - current = [e.originalEvent.pageX - offset.left, e.originalEvent.pageY - offset.top]; - - this._multiTouchAnchor = []; - this._inOp = false; - } else { - // untracked pointer - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return; - } - - } else if (this._supportTouch && e.originalEvent.changedTouches) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - this._multiTouchAnchor = []; - this._inOp = false; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - if (this._isTap) { - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - if (Math.sqrt((dx * dx) + (dy * dy)) <= 8) { - current = $.merge( [ ], this._anchor ); - } - } - } - - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._shiftDown = this._mouseDown = this._toolPan = false; - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isMultiTouch = false; - - this._wheelLevel = 0; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return; - } - - if (document.releaseCapture) { - document.releaseCapture(); - } - - if (mouseWasDown) { - clickDate = $.now(); - this._current = current; - - switch ( mode ) { - case "zoom": - case "dragBox": - if ( dx !== 0 || dy !== 0 ) { - var minSize = this._pixelSize * 6, - bboxCoords = this._toMap( [ this._anchor, current ] ), - bbox = [ - Math.min( bboxCoords[0][0], bboxCoords[1][0] ), - Math.min( bboxCoords[0][1], bboxCoords[1][1] ), - Math.max( bboxCoords[0][0], bboxCoords[1][0] ), - Math.max( bboxCoords[0][1], bboxCoords[1][1] ) - ]; - - if ( mode === "zoom" ) { - if ( ( bbox[2] - bbox[0] ) < minSize && ( bbox[3] - bbox[1] ) < minSize ) { - bbox = $.geo.scaleBy( this._getBbox( $.geo.center( bbox, true ) ), 0.5, true ); - } - - this._setBbox(bbox, true, true); - doInteractiveTimeout = true; - } else { - triggerShape = $.geo.polygonize( bbox, true ); - triggerShape.bbox = bbox; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - this._trigger( "shape", e, triggerShape ); - } - } else { - if ( mode === "dragBox" ) { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - } - - this._resetDrawing(); - break; - - case "dragCircle": - if ( dx !== 0 || dy !== 0 ) { - var image = this._options[ "axisLayout" ] === "image", - d = Math.sqrt( ( dx * dx) + ( dy * dy ) ), - n = 180, - a; - - this._drawPixels.length = n + 1; - - for ( i = 0; i < n; i++ ) { - a = ( i * 360 / n ) * ( Math.PI / 180 ); - this._drawPixels[ i ] = [ - this._anchor[ 0 ] + Math.cos( a ) * d, - this._anchor[ 1 ] + Math.sin( a ) * d - ]; - } - - this._drawPixels[ n ] = [ - this._drawPixels[ 0 ][ 0 ], - this._drawPixels[ 0 ][ 1 ] - ]; - - // using coordBuffer for bbox coords - coordBuffer = this._toMap( [ - [ this._anchor[ 0 ] - d, this._anchor[ 1 ] + ( image ? -d : d ) ], - [ this._anchor[ 0 ] + d, this._anchor[ 1 ] + ( image ? d : -d ) ] - ] ); - - triggerShape = { - type: "Polygon", - coordinates: [ this._toMap( this._drawPixels ) ], - bbox: [ coordBuffer[ 0 ][ 0 ], coordBuffer[ 0 ][ 1 ], coordBuffer[ 1 ][ 0 ], coordBuffer[ 1 ][ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - - this._resetDrawing(); - } else { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - break; - - case "drawPoint": - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - var geomap = this; - this._drawTimeout = setTimeout(function () { - if (geomap._drawTimeout) { - geomap._trigger("shape", e, { type: "Point", coordinates: geomap.toMap(current) }); - geomap._inOp = false; - geomap._drawTimeout = null; - } - }, 250); - } - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (wasToolPan) { - this._panFinalize(); - } else { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - - if (!e.isDefaultPrevented()) { - i = (this._drawCoords.length === 0 ? 0 : this._drawCoords.length - 1); - - this._drawCoords[i] = this._toMap(current); - this._drawPixels[i] = current; - - if (i < 2 || !(this._drawCoords[i][0] === this._drawCoords[i-1][0] && - this._drawCoords[i][1] === this._drawCoords[i-1][1])) { - this._drawCoords[i + 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[i + 1] = current; - } - - this._refreshDrawing(); - } - } - break; - - default: - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - this._inOp = false; - } - } - break; - } - - this._clickDate = clickDate; - - if (this._softDblClick && this._isDbltap) { - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - this._$eventTarget.trigger("softdblclick", e); - return false; - } - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _eventTarget_mousewheel: function ( e ) { - if ( this._options[ "mode" ] === "static" || this._options[ "scroll" ] === "off" ) { - return; - } - - e.preventDefault(); - - if ( this._mouseDown ) { - return false; - } - - if ( e.deltaY !== 0 ) { - if ( this._timeoutWheel ) { - clearTimeout( this._timeoutWheel ); - this._timeoutWheel = null; - } - - var geomap = this; - var currentTarget = e.currentTarget; - var deltaY = e.deltaY; - var pageX = e.pageX; - var pageY = e.pageY; - - this._timeoutWheel = setTimeout( function () { - geomap._clearInteractiveTimeout( ); - - var delta = deltaY > 0 ? 1 : -1; - - var offset = $(currentTarget).offset(); - geomap._anchor = [pageX - offset.left, pageY - offset.top]; - - var wheelCenterAndSize = geomap._getZoomCenterAndSize( geomap._anchor, delta, geomap._options[ "tilingScheme" ] !== null ); - - geomap._setInteractiveCenterAndSize( wheelCenterAndSize.center, wheelCenterAndSize.pixelSize ); - geomap._interactiveTransform( ); - - geomap._setInteractiveTimeout( true ); - }, 30 ); - - } - - return false; - } - } - ); -}(jQuery, window)); - - -(function ($, window, undefined) { - $.geo._serviceTypes.tiled = (function () { - var rTmplString = new RegExp( "<.*>|{{.*}}" ); - - return { - _serviceId: 0, - _tmplGeoSrcId: "", - - - create: function (map, serviceContainer, service /* , index */) { - this._serviceId = map._serviceIdSeed++; - this._tmplGeoSrcId = "geoSrc" + this._serviceId; - - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0, - reloadTiles: false - }; - - var scHtml = '
                          '; - - serviceContainer.append( window.toStaticHTML( scHtml ) ); - - serviceState.serviceContainer = serviceContainer.children( ":last" ); - - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - //console.log( "tiled.interactiveTransform( " + center.join( ", " ) + ", " + pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ), - tilingScheme = map.options[ "tilingScheme" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data("pixelSize"), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapCoord = $scaleContainer.data("scaleOrigin"), - newPixelPoint = map._toPixel(oldMapCoord, center, pixelSize); - - $scaleContainer.css( { - left: Math.round(newPixelPoint[0]) + "px", - top: Math.round(newPixelPoint[1]) + "px", - width: tilingScheme.tileWidth * scaleRatio, - height: tilingScheme.tileHeight * scaleRatio - } ); - - /* - if ( $("body")[0].filters !== undefined ) { - $scaleContainer.children().each( function ( i ) { - $( this ).css( "filter", "progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11=" + scaleRatio + ",M22=" + scaleRatio + ",sizingmethod='auto expand')" ); - } ); - } - */ - } - }); - } - }, - - refresh: function (map, service, force) { - //console.log( "tiled.refresh( " + map._center.join( ", " ) + ", " + map._pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ); - - this._cancelUnloaded(map, service); - - if ( serviceState && force ) { - // if hidden atm, we want to make sure we reload this service after it becomes visible - serviceState.reloadTiles = true; - } - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - $serviceContainer = serviceState.serviceContainer, - - image = map.options[ "axisLayout" ] === "image", - ySign = image ? +1 : -1, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - - tileX = Math.floor((bbox[0] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.max( Math.floor( ( image ? bbox[1] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 3 ] ) / (pixelSize * tileHeight) ), 0 ), - tileX2 = Math.ceil((bbox[2] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil( ( image ? bbox[3] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 1 ] ) / (pixelSize * tileHeight) ), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] + ySign * bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMinOrMaxY = tilingScheme.origin[1] + ySign * (fullYAtScale * tileHeight) * pixelSize, - - serviceLeft = Math.round((fullXMinX - bbox[0]) / pixelSize), - serviceTop = Math.round( ( image ? fullYMinOrMaxY - bbox[1] : bbox[3] - fullYMinOrMaxY ) / pixelSize), - - scaleContainers = $serviceContainer.children().show(), - scaleContainer = scaleContainers.filter("[data-pixel-size='" + pixelSize + "']").appendTo($serviceContainer), - - opacity = service.style.opacity, - - x, y, - - loadImageDeferredDone = function( url ) { - // when a Deferred call is done, add the image to the map - // a reference to the correct img element is on the Deferred object itself - serviceObj._loadImage( this.img, url, pixelSize, map, serviceState, opacity ); - }, - - loadImageDeferredFail = function( ) { - delete this.img; - serviceState.loadCount--; - map._requestComplete(); - }; - - if (serviceState.reloadTiles) { - scaleContainers.find("img").attr("data-dirty", "true"); - } - - if (!scaleContainer.size()) { - $serviceContainer.append( window.toStaticHTML( "
                          " ) ); - scaleContainer = $serviceContainer.children(":last").data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - } else { - scaleContainer.css({ - left: (serviceLeft % tileWidth) + "px", - top: (serviceTop % tileHeight) + "px" - }).data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - - scaleContainer.children().each( function () { - var $img = $(this), - tile = $img.attr("data-tile").split(","); - - $img.css({ - left: Math.round(((parseInt(tile[0], 10) - fullXAtScale) * 100) + (serviceLeft - (serviceLeft % tileWidth)) / tileWidth * 100) + "%", - top: Math.round(((parseInt(tile[1], 10) - fullYAtScale) * 100) + (serviceTop - (serviceTop % tileHeight)) / tileHeight * 100) + "%" - }); - - if (opacity < 1) { - $img.fadeTo(0, opacity); - } - } ); - } - - for (x = tileX; x < tileX2; x++) { - for (y = tileY; y < tileY2; y++) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ($img.size() === 0 || serviceState.reloadTiles) { - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] + ySign * (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] + ySign * ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - urlArgs = { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }, - isFunc = $.isFunction( service[ 'src' ] ), - imageUrl; - - if ( isFunc ) { - imageUrl = service[ 'src' ]( urlArgs ); - } else { - if ( rTmplString.test( service[ 'src' ] ) ) { - $.templates( this._tmplGeoSrcId, service[ 'src' ] ); - imageUrl = $.render[ this._tmplGeoSrcId ]( urlArgs ); - } else { - imageUrl = service[ 'src' ]; - } - } - - serviceState.loadCount++; - map._requestQueued(); - - if (serviceState.reloadTiles && $img.size() > 0) { - $img.attr("src", imageUrl); - } else { - var imgMarkup = ""; - - scaleContainer.append( window.toStaticHTML( imgMarkup ) ); - $img = scaleContainer.children(":last"); - } - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl && $.isFunction( imageUrl.promise ) ) { - // assume Deferred - $.extend( imageUrl.promise( ), { img: $img } ); - imageUrl.done( loadImageDeferredDone ).fail( loadImageDeferredFail ); - } else { - $img.remove( ); - } - } - } - } - - scaleContainers.find("[data-dirty]").remove(); - serviceState.reloadTiles = false; - } - }, - - resize: function ( /* map, service, dx, dy */ ) { - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.css( "display", service.style.visibility === "visible" ? "block" : "none" ); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if (serviceState && serviceState.loadCount > 0) { - /* - * #193 - disabled until we can do this without canceling all AJAX requests - * - if ( window.stop !== undefined ) { - window.stop(); - } else if( document.execCommand !== undefined ) { - document.execCommand("Stop", false); - } - */ - - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery, window)); - -(function ($, window, undefined) { - $.geo._serviceTypes.shingled = (function () { - var rTmplString = new RegExp( "<.*>|{{.*}}" ); - - return { - _serviceId: 0, - _tmplGeoSrcId: "", - - create: function ( map, serviceContainer, service /* , index */ ) { - this._serviceId = map._serviceIdSeed++; - this._tmplGeoSrcId = "geoSrc" + this._serviceId; - - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0 - }; - - var scHtml = '
                          '; - - serviceContainer.append( window.toStaticHTML( scHtml ) ); - - serviceState.serviceContainer = serviceContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - var serviceState = $.data( service, "geoServiceState" ), - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds[ "width" ], - mapHeight = contentBounds[ "height" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data( "pixelSize" ), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin, center, pixelSize ); - - $scaleContainer.css( { - left: Math.round( newPixelPoint[ 0 ] ), - top: Math.round( newPixelPoint[ 1 ] ), - width: mapWidth * scaleRatio, - height: mapHeight * scaleRatio - } ); - } - }); - } - }, - - refresh: function (map, service, force) { - var serviceState = $.data(service, "geoServiceState"); - - this._cancelUnloaded(map, service); - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainer = serviceContainer.children('[data-pixel-size="' + pixelSize + '"]'), - - opacity = service.style.opacity, - - $img; - - if (opacity < 1 || force || service.shinglesMax === 1) { - serviceContainer.find("img").attr("data-keep-alive", "0"); - } else if ( service.shinglesMax > 1 ) { - serviceContainer.find("img").slice( 0, -( service.shinglesMax - 1 ) ).attr("data-keep-alive", "0"); - } - - if ( !scaleContainer.size() ) { - serviceContainer.append( window.toStaticHTML( '
                          ' ) ); - scaleContainer = serviceContainer.children(":last"); - } - - var urlArgs = { - bbox: bbox, - width: mapWidth, - height: mapHeight, - zoom: map._getZoom(), - tile: null, - index: 0 - }, - isFunc = $.isFunction( service[ 'src' ] ), - imageUrl, - imagePos = scaleContainer.position( ); - - imagePos.left = - ( imagePos.left ); - imagePos.top = - ( imagePos.top ); - - if ( isFunc ) { - imageUrl = service[ 'src' ]( urlArgs ); - } else { - if ( rTmplString.test( service[ 'src' ] ) ) { - $.templates( this._tmplGeoSrcId, service[ 'src' ] ); - imageUrl = $.render[ this._tmplGeoSrcId ]( urlArgs ); - } else { - imageUrl = service[ 'src' ]; - } - } - - serviceState.loadCount++; - map._requestQueued(); - - scaleContainer.append( window.toStaticHTML( '' ) ); - $img = scaleContainer.children(":last").data("center", map._center); - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl ) { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, map, serviceState, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - map._requestComplete(); - } ); - } - - } - }, - - resize: function ( map, service /* , dx, dy */ ) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState && service && service.style.visibility === "visible" ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainers = serviceContainer.children(); - - scaleContainers.attr("data-pixel-size", "0"); - - scaleContainers.each( function ( ) { - var $scaleContainer = $(this), - position = $scaleContainer.position( ); - - $scaleContainer.css( { - left: position.left + ( mapWidth - $scaleContainer.width( ) ) / 2, - top: position.top + ( mapHeight - $scaleContainer.height( ) ) / 2 - } ); - - } ); - } - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.css("display", service.style.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - // #newpanzoom - serviceContainer.children(':not([data-pixel-size="' + pixelSize + '"])').remove(); - - serviceContainer.find( "img[data-keep-alive]" ).remove( ); - - serviceState.loadCount = 0; - } - }).error(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery, window)); diff --git a/dist/jquery.geo-1.0.0-test.min.js b/dist/jquery.geo-1.0.0-test.min.js deleted file mode 100644 index 911ad9f..0000000 --- a/dist/jquery.geo-1.0.0-test.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! jQuery Geo - v1.0.0-test - 2016-06-05 -* http://jquerygeo.com -* Copyright (c) 2016 Ryan Morrison-Westphal; Licensed MIT */ -document.createElement("canvas").getContext||!function(){function a(){return this.context_||(this.context_=new q(this))}function b(a,b,c){var d=G.call(arguments,2);return function(){return a.apply(b,d.concat(G.call(arguments)))}}function c(a,b,c){a.namespaces[b]||a.namespaces.add(b,c,"#default#VML")}function d(a){if(c(a,"g_vml_","urn:schemas-microsoft-com:vml"),c(a,"g_o_","urn:schemas-microsoft-com:office:office"),!a.styleSheets.ex_canvas_){var b=a.createStyleSheet();b.owningElement.id="ex_canvas_",b.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function e(a){var b=a.srcElement;switch(a.propertyName){case"width":b.getContext().clearRect(),b.style.width=b.attributes.width.nodeValue+"px",b.firstChild.style.width=b.clientWidth+"px";break;case"height":b.getContext().clearRect(),b.style.height=b.attributes.height.nodeValue+"px",b.firstChild.style.height=b.clientHeight+"px"}}function f(a){var b=a.srcElement;b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px",b.firstChild.style.height=b.clientHeight+"px")}function g(){return[[1,0,0],[0,1,0],[0,0,1]]}function h(a,b){for(var c=g(),d=0;3>d;d++)for(var e=0;3>e;e++){for(var f=0,h=0;3>h;h++)f+=a[d][h]*b[h][e];c[d][e]=f}return c}function i(a,b){b.fillStyle=a.fillStyle,b.lineCap=a.lineCap,b.lineJoin=a.lineJoin,b.lineWidth=a.lineWidth,b.miterLimit=a.miterLimit,b.shadowBlur=a.shadowBlur,b.shadowColor=a.shadowColor,b.shadowOffsetX=a.shadowOffsetX,b.shadowOffsetY=a.shadowOffsetY,b.strokeStyle=a.strokeStyle,b.globalAlpha=a.globalAlpha,b.font=a.font,b.textAlign=a.textAlign,b.textBaseline=a.textBaseline,b.arcScaleX_=a.arcScaleX_,b.arcScaleY_=a.arcScaleY_,b.lineScale_=a.lineScale_}function j(a){var b=a.indexOf("(",3),c=a.indexOf(")",b+1),d=a.substring(b+1,c).split(",");return(4!=d.length||"a"!=a.charAt(3))&&(d[3]=1),d}function k(a){return parseFloat(a)/100}function l(a,b,c){return Math.min(c,Math.max(b,a))}function m(a){var b,c,d,e,f,g;if(e=parseFloat(a[0])/360%360,0>e&&e++,f=l(k(a[1]),0,1),g=l(k(a[2]),0,1),0==f)b=c=d=g;else{var h=.5>g?g*(1+f):g+f-g*f,i=2*g-h;b=n(i,h,e+1/3),c=n(i,h,e),d=n(i,h,e-1/3)}return"#"+I[Math.floor(255*b)]+I[Math.floor(255*c)]+I[Math.floor(255*d)]}function n(a,b,c){return 0>c&&c++,c>1&&c--,1>6*c?a+6*(b-a)*c:1>2*c?b:2>3*c?a+(b-a)*(2/3-c)*6:a}function o(a){if(a in L)return L[a];var b,c=1;if(a=String(a),"#"==a.charAt(0))b=a;else if(/^rgb/.test(a)){for(var d,e=j(a),b="#",f=0;3>f;f++)d=-1!=e[f].indexOf("%")?Math.floor(255*k(e[f])):+e[f],b+=I[l(d,0,255)];c=+e[3]}else if(/^hsl/.test(a)){var e=j(a);b=m(e),c=e[3]}else b=a;return L[a]={color:b,alpha:c}}function p(a){return M[a]||"square"}function q(a){this.m_=g(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.strokeStyle="#000",this.fillStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=1*E,this.globalAlpha=1,this.canvas=a;var b="width:"+a.clientWidth+"px;height:"+a.clientHeight+"px;overflow:hidden;position:absolute",c=a.ownerDocument.createElement("div");c.style.cssText=b,a.appendChild(c);var d=c.cloneNode(!1);d.style.backgroundColor="red",d.style.filter="alpha(opacity=0)",a.appendChild(d),this.element_=c,this.arcScaleX_=1,this.arcScaleY_=1,this.lineScale_=1}function r(a,b,c,d){a.currentPath_.push({type:"bezierCurveTo",cp1x:b.x,cp1y:b.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y}),a.currentX_=d.x,a.currentY_=d.y}function s(a,b){var c=o(a.strokeStyle),d=c.color,e=c.alpha*a.globalAlpha,f=a.lineScale_*a.lineWidth;1>f&&(e*=f),b.push("')}function t(a,b,c,d){var e=(a.fillStyle,a.arcScaleX_,a.arcScaleY_,d.x-c.x,d.y-c.y,o(a.fillStyle)),f=e.color,g=e.alpha*a.globalAlpha;b.push('')}function u(a,b,c){var d=a.m_;return{x:E*(b*d[0][0]+c*d[1][0]+d[2][0])-F,y:E*(b*d[0][1]+c*d[1][1]+d[2][1])-F}}function v(a){return isFinite(a[0][0])&&isFinite(a[0][1])&&isFinite(a[1][0])&&isFinite(a[1][1])&&isFinite(a[2][0])&&isFinite(a[2][1])}function w(a,b,c){if(v(b)&&(a.m_=b,c)){var d=b[0][0]*b[1][1]-b[0][1]*b[1][0];a.lineScale_=D(C(d))}}function x(a){this.code=this[a],this.message=a+": DOM Exception "+this.code}var y=Math,z=y.round,A=y.sin,B=y.cos,C=y.abs,D=y.sqrt,E=10,F=E/2,G=(+navigator.userAgent.match(/MSIE ([\d.]+)?/)[1],Array.prototype.slice);d(document);var H={init:function(a){var c=a||document;c.createElement("canvas"),c.attachEvent("onreadystatechange",b(this.init_,this,c))},init_:function(a){for(var b=a.getElementsByTagName("canvas"),c=0;cJ;J++)for(var K=0;16>K;K++)I[16*J+K]=J.toString(16)+K.toString(16);var L={},M={butt:"flat",round:"round"},N=q.prototype;N.clearRect=function(){this.textMeasureEl_&&(this.textMeasureEl_.removeNode(!0),this.textMeasureEl_=null),this.element_.innerHTML=""},N.beginPath=function(){this.currentPath_=[]},N.moveTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"moveTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.lineTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"lineTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.bezierCurveTo=function(a,b,c,d,e,f){var g=u(this,e,f),h=u(this,a,b),i=u(this,c,d);r(this,h,i,g)},N.quadraticCurveTo=function(a,b,c,d){var e=u(this,a,b),f=u(this,c,d),g={x:this.currentX_+2/3*(e.x-this.currentX_),y:this.currentY_+2/3*(e.y-this.currentY_)},h={x:g.x+(f.x-this.currentX_)/3,y:g.y+(f.y-this.currentY_)/3};r(this,g,h,f)},N.arc=function(a,b,c,d,e,f){c*=E;var g=f?"at":"wa",h=a+B(d)*c-F,i=b+A(d)*c-F,j=a+B(e)*c-F,k=b+A(e)*c-F;h!=j||f||(h+=.125);var l=u(this,a,b),m=u(this,h,i),n=u(this,j,k);this.currentPath_.push({type:g,x:l.x,y:l.y,radius:c,xStart:m.x,yStart:m.y,xEnd:n.x,yEnd:n.y})},N.stroke=function(a){var b=[],c=10,d=10;b.push("f.x)&&(f.x=i.x),(null==e.y||i.yf.y)&&(f.y=i.y))}b.push(' ">'),a?t(this,b,e,f):s(this,b),b.push(""),this.element_.insertAdjacentHTML("beforeEnd",b.join(""))},N.fill=function(){this.stroke(!0)},N.closePath=function(){this.currentPath_.push({type:"close"})},N.save=function(){var a={};i(this,a),this.aStack_.push(a),this.mStack_.push(this.m_),this.m_=h(g(),this.m_)},N.restore=function(){this.aStack_.length&&(i(this.aStack_.pop(),this),this.m_=this.mStack_.pop())},N.translate=function(a,b){var c=[[1,0,0],[0,1,0],[a,b,1]];w(this,h(c,this.m_),!1)},N.scale=function(a,b){this.arcScaleX_*=a,this.arcScaleY_*=b;var c=[[a,0,0],[0,b,0],[0,0,1]];w(this,h(c,this.m_),!0)};var O=x.prototype=new Error;O.INDEX_SIZE_ERR=1,O.DOMSTRING_SIZE_ERR=2,O.HIERARCHY_REQUEST_ERR=3,O.WRONG_DOCUMENT_ERR=4,O.INVALID_CHARACTER_ERR=5,O.NO_DATA_ALLOWED_ERR=6,O.NO_MODIFICATION_ALLOWED_ERR=7,O.NOT_FOUND_ERR=8,O.NOT_SUPPORTED_ERR=9,O.INUSE_ATTRIBUTE_ERR=10,O.INVALID_STATE_ERR=11,O.SYNTAX_ERR=12,O.INVALID_MODIFICATION_ERR=13,O.NAMESPACE_ERR=14,O.INVALID_ACCESS_ERR=15,O.VALIDATION_ERR=16,O.TYPE_MISMATCH_ERR=17,G_vmlCanvasManager=H,CanvasRenderingContext2D=q,DOMException=x}(),this.jsviews||this.jQuery&&jQuery.views||function(a,b){function c(a,b){var c="\\"+a.charAt(0),d="\\"+a.charAt(1),e="\\"+b.charAt(0),f="\\"+b.charAt(1);return Q.rTag=u=d+"(?:(?:(\\w+(?=[\\/\\s"+e+"]))|(?:(\\w+)?(:)|(>)|(\\*)))\\s*((?:[^"+e+"]|"+e+"(?!"+f+"))*?)(\\/)?|(?:\\/(\\w+)))"+e,u=new RegExp(c+u+f,"g"),v=new RegExp("<.*>|"+a+".*"+b),this}function d(a){var c=this,d=c.tmpl.helpers||{};return a=(c.ctx[a]!==b?c.ctx:d[a]!==b?d:k[a]!==b?k:{})[a],"function"!=typeof a?a:function(){return a.apply(c,arguments)}}function e(a,b,c){var d=b.tmpl.converters;return a=d&&d[a]||l[a],a?a.call(b,c):c}function f(a,c,d,e,f){f.props=f.props||{};var g,h=f.props.tmpl,k=c.tmpl.tags,l=c.tmpl.templates,n=arguments,o=k&&k[a]||j[a];return o?(e=e&&c.tmpl.tmpls[e-1],h=h||e||b,f.tmpl=""+h===h?l&&l[h]||i[h]||i(h):h,f.isTag=A,f.converter=d,f.view=c,f.renderContent=m,c.ctx&&w(f.ctx,c.ctx),g=o.apply(f,n.length>5?O.call(n,5):[]),g||(g==b?"":g.toString())):""}function g(a,c,e,f,g,h){var i=e.views,j={tmpl:g,path:c,parent:e,data:f,ctx:a,views:t.isArray(f)?[]:{},hlp:d};return t.isArray(i)?i.splice(j.index=h!==b?h:i.length,0,j):i[j.index="_"+I++]=j,j}function h(a,c,d,e,f){var g,h;if(d&&"object"==typeof d&&!d.nodeType){for(g in d)c(g,d[g]);return a}return d&&e!==b?""+d===d&&(null===e?delete c[d]:(e=f?f(d,e):e)&&(c[d]=e)):f&&(e=f(b,e||d)),(h=y.onStoreItem)&&h(c,d,e,f),e}function i(a,b){return h(this,i,a,b,q)}function j(a,b){return h(this,j,a,b)}function k(a,b){return h(this,k,a,b)}function l(a,b){return h(this,l,a,b)}function m(a,c,d,e,f){var h,j,k,l,m,n,o,p,q,r,s={},u=f===A,v=this,x="";if(v.isTag?(q=v.tmpl,c=c||v.ctx,d=d||v.view,e=e||v.path,f=f||v.index,s=v.props):q=v.jquery&&v[0]||v,d=d||Q.topView,p=d.ctx,r=q.layout,a===d&&(a=d.data,r=A),c=c&&c===p?p:p?(p=w({},p),c?w(p,c):p):c||{},s.link===z&&(c.link=z),q.fn||(q=i[q]||i(q)),m=c.link&&y.onRenderItem,n=c.link&&y.onRenderItems,q){if(t.isArray(a)&&!r)for(l=u?d:f!==b&&d||g(c,e,d,a,q,f),h=0,j=a.length;j>h;h++)k=a[h],o=q.fn(k,g(c,e,l,k,q,(f||0)+h),Q),x+=m?m(o,s):o;else l=u?d:g(c,e,d,a,q,f),x+=a||r?q.fn(a,l,Q):"";return d.topKey=l.index,n?n(x,e,l.index,q,s):x}return""}function n(){throw"Syntax error"}function o(a,b,c){function d(b){b-=D,b&&J.push(a.substr(D,b).replace(E,"\\n"))}function e(b,e,g,h,i,j,k,l,m,n){i&&(h=":",g="html");var o="",q="",r=!l&&!h;if(e=e||h,d(n),D=n+b.length,j?y&&J.push(["*",k.replace(F,"$1")]):e?("else"===e&&(K[5]=a.substring(K[5],n),K=I.pop(),J=K[3],r=A),k=k?p(k,c).replace(H,function(a,b,c){return b?q+=c+",":o+=c+",",""}):"",o=o.slice(0,-1),k=k.slice(0,-1),f=[e,g||"",k,r&&[],"{"+(o?"props:{"+o+"},":"")+"path:'"+k+"'"+(q?",ctx:{"+q.slice(0,-1)+"}":"")+"}"],r&&(I.push(K),K=f,K[5]=D),J.push(f)):m&&(K[5]=a.substring(K[5],n),K=I.pop()),!K)throw"Expected block tag";J=K[3]}var f,g,h,i,j,k,l,m,n,q,s,t,v,w,x,y,z=b?{allowCode:y=b.allowCode,debug:b.debug}:{},B=b&&b.tmpls,C=[],D=0,I=[],J=C,K=[,,,C],L=0;for(a=a.replace(G,"\\$1"),a.replace(u,e),d(a.length),i=C.length,j=i?"":'"";',h=0;i>h;h++)g=C[h],"*"===g[0]?j=j.slice(0,h?-1:-3)+";"+g[1]+(i>h+1?"ret+=":""):""+g===g?j+='"'+g+'"+':(s=g[0],t=g[1],v=g[2],J=g[3],w=g[4],a=g[5],J&&(x=r(a,z,b,L++),o(a,x),B.push(x)),q=q||w.indexOf("view")>-1,j+=(":"===s?"html"===t?(l=A,"e("+v):t?(n=A,'c("'+t+'",view,'+v):(m=A,"((v="+v+')!=u?v:""'):(k=A,'t("'+s+'",view,"'+(t||"")+'",'+(J?B.length:'""')+","+w+(v?",":"")+v))+")+");return j=new Function("data, view, j, b, u",M+(m?"v,":"")+(k?"t=j.tag,":"")+(n?"c=j.convert,":"")+(l?"e=j.converters.html,":"")+"ret; try{\n\n"+(z.debug?"debugger;":"")+(y?"ret=":"return ")+j.slice(0,-1)+";\n\n"+(y?"return ret;":"")+"}catch(e){return j.err(e);}"),b&&(b.fn=j,b.useVw=n||q||k),j}function p(a,b){function c(a,c,i,j,k,l,m,o,p,q,r,s,t,u,v,w){function x(a,c,d,e,f,g,h){if(c){var i=(d?'view.hlp("'+d+'")':e?"view":"data")+(h?(f?"."+f:d?"":e?"":"."+c)+(g||""):(h=d?"":e?f||"":c,""));return b&&"("!==p&&(i="b("+i+',"'+h+'")'),i+(h?"."+h:"")}return a}return k=k||"",i=i||c||r,j=j||o,p=p||v||"",k=k||"",l?void n():h?(h=!s,h?a:'"'):g?(g=!t,g?a:'"'):(i?(f++,i):"")+(w?f?"":d?(d=z,"\b"):",":m?(f&&n(),d=A,"\b"+j+":"):j?j.replace(C,x)+(p?(e[++f]=A,p):k):k?a:u?(e[f--]=z,u+(p?(e[++f]=A,p):"")):q?(e[f]||n(),","):c?"":(h=s,g=t,'"'))}var d,e={},f=0,g=z,h=z;return a=(a+" ").replace(D,c)}function q(a,c,d,e){function f(b){return""+b===b||b.nodeType>0?(h=b.nodeType>0?b:!v.test(b)&&B&&B(b)[0],h&&h.type&&(b=i[h.getAttribute(L)],b||(a=a||"_"+J++,h.setAttribute(L,a),b=q(a,h.innerHTML,d,e),i[a]=b)),b):void 0}var g,h,j,k,l;if(g=f(c),e=e||(c.markup?c:{}),e.name=a,k=e.templates,!g&&c.markup&&(g=f(c.markup))&&(!g.fn||g.debug===c.debug&&g.allowCode===c.allowCode||(g=g.markup)),g!==b){a&&!d&&(P[a]=function(){return c.render.apply(c,arguments)}),g.fn||c.fn?g.fn&&(c=a&&a!==g.name?w(w({},g),e):g):(c=r(g,e,d,0),o(g,c));for(j in k)l=k[j],l.name!==j&&(k[j]=q(j,l,c));return c}}function r(a,b,c,d){function e(a){c[a]&&(f[a]=w(w({},c[a]),b[a]))}b=b||{};var f={markup:a,tmpls:[],links:[],render:m};return c&&(c.templates&&(f.templates=w(w({},c.templates),b.templates)),f.parent=c,f.name=c.name+"["+d+"]",f.index=d),w(f,b),c&&(e("templates"),e("tags"),e("helpers"),e("converters")),f}function s(a){return K[a]||(K[a]="&#"+a.charCodeAt(0)+";")}var t,u,v,w,x="v1.0pre",y={},z=!1,A=!0,B=a.jQuery,C=/^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g,D=/(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,E=/\r?\n/g,F=/\\(['"])/g,G=/\\?(['"])/g,H=/\x08(~)?([^\x08]+)\x08/g,I=0,J=0,K={"&":"&","<":"<",">":">"},L="data-jsv-tmpl",M="var j=j||"+(B?"jQuery.":"js")+"views,",N=/[\x00"&'<>]/g,O=Array.prototype.slice,P={},Q={jsviews:x,sub:y,debugMode:A,err:function(a){return Q.debugMode?"
                          Error: "+(a.message||a)+". ":'""'},tmplFn:o,render:P,templates:i,tags:j,helpers:k,converters:l,View:g,convert:e,delimiters:c,tag:f};B?(t=B,t.templates=i,t.render=P,t.views=Q,t.fn.render=m):(t=a.jsviews=Q,t.extend=function(a,b){var c;a=a||{};for(c in b)a[c]=b[c];return a},t.isArray=Array&&Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)}),w=t.extend,Q.topView={views:{},tmpl:{},hlp:d,ctx:Q.helpers},j({"if":function(){var a=this,c=a.view;return c.onElse=function(a,d){for(var e=0,f=d.length;f&&!d[e++];)if(e===f)return"";return c.onElse=b,a.path="",a.renderContent(c)},c.onElse(this,arguments)},"else":function(){var a=this.view;return a.onElse?a.onElse(this,arguments):""},"for":function(){var a,b=this,c="",d=arguments,e=d.length;for(b.props.layout&&(b.tmpl.layout=A),a=0;e>a;a++)c+=b.renderContent(d[a]);return c},"=":function(a){return a},"*":function(a){return a}}),l({html:function(a){return a!=b?String(a).replace(N,s):""}}),c("{{","}}")}(this),function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})}),$.widget||!function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d,e=0;null!=(d=b[e]);e++)try{a(d).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){return c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}}),d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e,f=b.split(".")[0];b=b.split(".")[1],e=f+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][e]=function(c){return!!a.data(c,b)},a[f]=a[f]||{},a[f][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[f][b].prototype=a.extend(!0,g,{namespace:f,widgetName:b,widgetEventPrefix:a[f][b].prototype.widgetEventPrefix||b,widgetBaseClass:e},d),a.widget.bridge(b,a[f][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f="string"==typeof e,g=Array.prototype.slice.call(arguments,1),h=this;return e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e,f&&"_"===e.charAt(0)?h:(f?this.each(function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;return f!==d&&f!==b?(h=f,!1):void 0}):this.each(function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))}),h)}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(0===arguments.length)return a.extend({},this.options);if("string"==typeof c){if(d===b)return this.options[c];e={},e[c]=d}return this._setOptions(e),this},_setOptions:function(b){var c=this;return a.each(b,function(a,b){c._setOption(a,b)}),this},_setOption:function(a,b){return this.options[a]=b,"disabled"===a&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",b),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];if(d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}}(jQuery),function(a,b,c){b.toStaticHTML=b.toStaticHTML||function(a){return a};var d=Number.POSITIVE_INFINITY,e=Number.NEGATIVE_INFINITY;a.geo={_allCoordinates:function(b){for(var c=this._flatten(b),d=0,e=[];d1&&!a.isArray(b[0]))return b[0]>=-180.001&&b[0]<=180.001&&b[1]>=-90.001&&b[1]<=90.001;b=b[0]}return!1},center:function(b,c){var d=!1;!c&&a.geo.proj&&this._isGeodetic(b)&&(d=!0,b=a.geo.proj.fromGeodetic(b));var e=[(b[0]+b[2])/2,(b[1]+b[3])/2];return d?a.geo.proj.toGeodetic(e):e},expandBy:function(b,c,d,e){var f=!1;return!e&&a.geo.proj&&this._isGeodetic(b)&&(f=!0,b=a.geo.proj.fromGeodetic(b)),b=[b[0]-c,b[1]-d,b[2]+c,b[3]+d],f?a.geo.proj.toGeodetic(b):b},height:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[3]-b[1]},_in:function(a,b){return a[0]<=b[0]&&a[1]<=b[1]&&a[2]>=b[2]&&a[3]>=b[3]},_bboxDisjoint:function(a,b){return b[0]>a[2]||b[2]a[3]||b[3]0&&(h/i>c?(f=h/2,g=f/c):(g=i/2,f=g*c),b=[j[0]-f,j[1]-g,j[0]+f,j[1]+g]),e?a.geo.proj.toGeodetic(b):b},recenter:function(b,c,d){var e=!1;!d&&a.geo.proj&&(this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b)),this._isGeodetic(c)&&(c=a.geo.proj.fromGeodetic(c)));var f=(b[2]-b[0])/2,g=(b[3]-b[1])/2;return b=[c[0]-f,c[1]-g,c[0]+f,c[1]+g],e?a.geo.proj.toGeodetic(b):b},scaleBy:function(b,c,d){var e=!1;!d&&a.geo.proj&&this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b));var f=this.center(b,!0),g=(b[2]-b[0])*c/2,h=(b[3]-b[1])*c/2;return b=[f[0]-g,f[1]-h,f[0]+g,f[1]+h],e?a.geo.proj.toGeodetic(b):b},width:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[2]-b[0]},bbox:function(b,f){var g,h=!1;if(!b)return c;if(b.bbox)g=!f&&a.geo.proj&&this._isGeodetic(b.bbox)?a.geo.proj.fromGeodetic(b.bbox):b.bbox;else{g=[d,d,e,e];var i=this._allCoordinates(b),j=0;if(0===i.length)return c;for(!f&&a.geo.proj&&this._isGeodetic(i)&&(h=!0,i=a.geo.proj.fromGeodetic(i));j0?(g[0]=Math.min(Math.max(k[0][0],m[0]),m[2]),g[1]=Math.min(Math.max(k[0][1],m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g}):c:(j*=3,g[0]=Math.min(Math.max(g[0]/j,m[0]),m[2]),g[1]=Math.min(Math.max(g[1]/j,m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g});case"MultiPoint":if(b.coordinates.length>0)return g=b.coordinates[0],{type:"Point",coordinates:[g[0],g[1]]};break;case"MultiLineString":case"MultiPolygon":if(b.coordinates.length>0)return this.centroid({type:b.type.substr(5),coordinates:b.coordinates[0]},f)}return c},contains:function(a,b){if("Polygon"!==a.type)return!1;switch(b.type){case"Point":return this._containsPolygonPoint(a.coordinates,b.coordinates);case"LineString":return this._containsPolygonLineString(a.coordinates,b.coordinates);case"Polygon":return this._containsPolygonLineString(a.coordinates,b.coordinates[0]);default:return!1}},_containsPolygonPoint:function(a,b){if(0===a.length||a[0].length<4)return!1;for(var c,d,e=0,f=a[0][0],g=1;gb[0]&&e++),f=c;return e%2===1},_containsPolygonLineString:function(a,b){for(var c=0;c0){var e=a[0],f=b[0]-e[0],g=b[1]-e[1];if(1===a.length)return Math.sqrt(f*f+g*g);for(var h=1;hn&&(c=n),e=i,f=l,g=m}}return Math.sqrt(c)},_distanceSegmentPoint:function(a,b,c,d,e,f){var g=a*c+b*d;if(0>=g)return c*c+d*d;var h=a*a+b*b;return g>=h?e*e+f*f:c*c+d*d-g*g/h},_distanceLineStringLineString:function(a,b){for(var c=d,e=0;e=k;k++)h=360*k/j*(Math.PI/180),i.push([g[0]+Math.cos(h)*d,g[1]+Math.sin(h)*d]);return{type:"Polygon",coordinates:[f?a.geo.proj.toGeodetic(i):i]}}return c},_basic:function(a){for(var b,c,d=[],e=0,f=this._flatten(a);eo;q++)n=o,o+=p[q]/m;return e=c-n,k=g[q-1],l=g[q],j=[k[0]+e*(l[0]-k[0]),k[1]+e*(l[1]-k[1])],{type:"Point",coordinates:r?a.geo.proj.toGeodetic(j):j}}},WKT:function(){function b(a){return"POINT "+c(a.coordinates)}function c(a){return a&&a.length?"("+a.join(" ")+")":"EMPTY"}function d(a){return"LINESTRING "+e(a.coordinates)}function e(a){if(a&&a.length){for(var b=[],c=0;c2?{type:"Point",coordinates:[parseFloat(b[1]),parseFloat(b[2])]}:null}function p(a){var b,c,d=a.match(/\s*\((.*)\)/),e=[],f=0;if(d&&d.length>1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f0){for(;g
                          ";while(c[0]);return a>6?a:!a}();a.widget("geo.geographics",{_$elem:c,_options:{},_trueCanvas:!0,_trueDoubleBuffer:!0,_width:0,_height:0,_$canvas:c,_context:c,_$canvasSceneFront:c,_$canvasSceneBack:c,_$canvasSceneStale:c,_$canvasSceneDrawn:c,_timeoutEnd:null,_requireFlip:!1,_blitcanvas:c,_blitcontext:c,_$labelsContainerFront:c,_$labelsContainerBack:c,_labelsHtml:"",options:{style:{borderRadius:"8px",color:"#7f0000",fillOpacity:.2,height:"8px",opacity:1,strokeOpacity:1,strokeWidth:"2px",visibility:"visible",width:"8px"},doubleBuffer:!0},_create:function(){this._$elem=this.element,this._options=this.options,this._$elem.css({webkitTransform:"translateZ(0)",display:"inline-block",overflow:"hidden",textAlign:"left"}),"static"===this._$elem.css("position")&&this._$elem.css("position","relative"),this._$elem.addClass("geo-graphics"),this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10));var c="position:absolute;left:0;top:0;margin:0;padding:0;",e="width:"+this._width+"px;height:"+this._height+"px;",f='width="'+this._width+'" height="'+this._height+'"';this._blitcanvas=document.createElement("canvas"),this._blitcanvas.getContext?(this._$canvas=a(b.toStaticHTML("')),this._blitcanvas.width=1,this._blitcanvas.height=1,this._trueDoubleBuffer=this._blitcanvas.toDataURL().length>6,this._options.doubleBuffer&&this._trueDoubleBuffer||this._$elem.append(this._$canvas),this._context=this._$canvas[0].getContext("2d"),this._blitcanvas.width=this._width,this._blitcanvas.height=this._height,this._blitcontext=this._blitcanvas.getContext("2d"),this._$canvasSceneFront=a(b.toStaticHTML('')).on("load",a.proxy(this._canvasImgLoad,this)),this._$canvasSceneBack=a(b.toStaticHTML('')).on("load",a.proxy(this._canvasImgLoad,this))):8>=d&&(this._trueCanvas=!1,this._$elem.append("
                          '),this._$canvas=this._$elem.children(":last"),G_vmlCanvasManager.initElement(this._$canvas[0]),this._context=this._$canvas[0].getContext("2d"),this._$canvas.children().css({backgroundColor:"transparent",width:this._width,height:this._height})),this._$labelsContainerFront=a(b.toStaticHTML('
                          ')),this._$labelsContainerBack=a(b.toStaticHTML('
                          '))},_setOption:function(b,c){"style"===b&&(c=a.extend({},this._options.style,c)),a.Widget.prototype._setOption.apply(this,arguments)},destroy:function(){a.Widget.prototype.destroy.apply(this,arguments),this._$elem.html(""),this._$elem.removeClass("geo-graphics")},clear:function(){this._context.clearRect(0,0,this._width,this._height),this._labelsHtml="",this._end()},drawArc:function(a,b,c,d){if(d=this._getGraphicStyle(d),"hidden"!==d.visibility&&d.opacity>0&&d.widthValue>0&&d.heightValue>0){var e=Math.min(d.widthValue,d.heightValue)/2;b=b*Math.PI/180,c=c*Math.PI/180,this._context.save(),this._context.translate(a[0],a[1]),d.widthValue>d.heightValue?this._context.scale(d.widthValue/d.heightValue,1):this._context.scale(1,d.heightValue/d.widthValue),this._context.beginPath(),this._context.arc(0,0,e,b,c,!1),this._trueCanvas&&this._context.restore(),d.doFill&&(this._context.fillStyle=d.fill,this._context.globalAlpha=d.opacity*d.fillOpacity,this._context.fill()),d.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=d.strokeWidthValue,this._context.strokeStyle=d.stroke,this._context.globalAlpha=d.opacity*d.strokeOpacity,this._context.stroke()),this._trueCanvas||this._context.restore()}this._end()},drawPoint:function(a,b){b=this._getGraphicStyle(b),b.widthValue===b.heightValue&&b.heightValue===b.borderRadiusValue?this.drawArc(a,0,360,b):"hidden"!==b.visibility&&b.opacity>0&&(b.borderRadiusValue=Math.min(Math.min(b.widthValue,b.heightValue)/2,b.borderRadiusValue),a[0]-=b.widthValue/2,a[1]-=b.heightValue/2,this._context.beginPath(),this._context.moveTo(a[0]+b.borderRadiusValue,a[1]),this._context.lineTo(a[0]+b.widthValue-b.borderRadiusValue,a[1]),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1],a[0]+b.widthValue,a[1]+b.borderRadiusValue),this._context.lineTo(a[0]+b.widthValue,a[1]+b.heightValue-b.borderRadiusValue),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1]+b.heightValue,a[0]+b.widthValue-b.borderRadiusValue,a[1]+b.heightValue),this._context.lineTo(a[0]+b.borderRadiusValue,a[1]+b.heightValue),this._context.quadraticCurveTo(a[0],a[1]+b.heightValue,a[0],a[1]+b.heightValue-b.borderRadiusValue),this._context.lineTo(a[0],a[1]+b.borderRadiusValue),this._context.quadraticCurveTo(a[0],a[1],a[0]+b.borderRadiusValue,a[1]),this._context.closePath(),b.doFill&&(this._context.fillStyle=b.fill,this._context.globalAlpha=b.opacity*b.fillOpacity,this._context.fill()),b.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=b.strokeWidthValue,this._context.strokeStyle=b.stroke,this._context.globalAlpha=b.opacity*b.strokeOpacity,this._context.stroke()),this._end())},drawLineString:function(a,b){this._drawLines([a],!1,b)},drawPolygon:function(a,b){if(this._trueCanvas&&1!==a.length){if(!a||!a.length||a[0].length<3)return;b=this._getGraphicStyle(b),this._blitcontext.globalCompositeOperation="copy";var c,d,e;if("hidden"!==b.visibility&&b.opacity>0){if(this._blitcontext.clearRect(0,0,this._width,this._height),b.doFill&&a.length>1){for(this._blitcontext.globalCompositeOperation="source-out",this._blitcontext.globalAlpha=1,this._blitcontext.beginPath(),d=1;d1))for(d=1;d'+b+""},resize:function(a,b){this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10)),this._trueCanvas?(this._$canvas[0].width=this._width,this._$canvas[0].height=this._height,this._$canvasSceneFront.css({left:a,top:b}),this._$canvasSceneBack.css({width:this._width,height:this._height})):this._$canvas.css({width:this._width,height:this._height});var c=this._$labelsContainerFront.position();this._$labelsContainerFront.css({left:c.left+a,top:c.top+b,width:this._width,height:this._height}),this._$labelsContainerBack.css({width:this._width,height:this._height})},interactiveTransform:function(a,b){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._trueCanvas&&this._options.doubleBuffer&&this._trueDoubleBuffer?(this._canvasSceneLoad(),this._$canvasSceneFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})):this._context.clearRect(0,0,this._width,this._height),this._$labelsContainerFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})},_canvasImgLoad:function(){var a=this;a._$canvasSceneFront=a._$canvasSceneDrawn.prependTo(a._$elem),a._$canvasSceneBack=a._$canvasSceneStale,a._$canvasSceneBack.detach()},_canvasSceneLoad:function(){var a=this;a._requireFlip&&(a._requireFlip=!1,a._$canvasSceneStale=a._$canvasSceneFront,a._$canvasSceneDrawn=a._$canvasSceneBack.css({left:0,top:0,width:a._width,height:a._height}).prop("src",a._$canvas[0].toDataURL()))},_endCallback:function(){var a=this;if(a._timeoutEnd){a._trueCanvas&&a._options.doubleBuffer&&a._trueDoubleBuffer&&this._canvasSceneLoad(),a._$labelsContainerBack.html(b.toStaticHTML(a._labelsHtml)).find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"});var c=a._$labelsContainerFront;a._$labelsContainerFront=a._$labelsContainerBack.css({left:0,top:0,width:a._width,height:a._height}).appendTo(a._$elem),a._$labelsContainerBack=c.detach(),a._timeoutEnd=null}},_end:function(){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._requireFlip=!0,this._timeoutEnd=setTimeout(a.proxy(this._endCallback,this),20)},_getGraphicStyle:function(b){function c(a){return a=parseInt(a,10),+a+""===a?+a:a}return b=a.extend({},this._options.style,b),b.borderRadiusValue=c(b.borderRadius),b.fill=b.fill||b.color,b.doFill=b.fill&&b.fillOpacity>0,b.stroke=b.stroke||b.color,b.strokeWidthValue=c(b.strokeWidth),b.doStroke=b.stroke&&b.strokeOpacity>0&&b.strokeWidthValue>0,b.widthValue=c(b.width),b.heightValue=c(b.height),b},_drawLines:function(a,b,c){if(a&&a.length&&!(a[0].length<2)){var d,e;if(c=this._getGraphicStyle(c),"hidden"!==c.visibility&&c.opacity>0){for(this._context.beginPath(),d=0;d
                          ";while(c[0]);return a>6?a:!a}(),f=function(){return(navigator.userAgent.match(/gecko\/*\d/i)||[]).length>0}(),g={bbox:[-180,-85,180,85],bboxMax:[-180,-85,180,85],center:[0,0],cursors:{"static":"default",pan:"url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move",click:"crosshair",zoom:"crosshair",dragBox:"crosshair",dragCircle:"crosshair",drawPoint:"crosshair",drawLineString:"crosshair",drawPolygon:"crosshair",measureLength:"crosshair",measureArea:"crosshair"},measureLabels:{length:"{{:length.toFixed( 2 )}} m",area:"{{:area.toFixed( 2 )}} sq m"},drawStyle:{},shapeStyle:{},mode:"pan",pannable:!0,scroll:"default",shift:"default",services:[{"class":"osm",type:"tiled",src:function(a){return"//otile"+(a.index%4+1)+("https:"===location.protocol?"-s":"")+".mqcdn.com/tiles/1.0.0/osm/"+a.zoom+"/"+a.tile.column+"/"+a.tile.row+".png"},attr:'Tiles Courtesy of MapQuest '}],tilingScheme:{tileWidth:256,tileHeight:256,levels:18,basePixelSize:156543.03392799935,origin:[-20037508.342787,20037508.342787]},axisLayout:"map",zoom:0,zoomMin:0,zoomMax:Number.POSITIVE_INFINITY,zoomFactor:2,pixelSize:0};a.widget("geo.geomap",{_$elem:c,_map:c,_created:!1,_createdGraphics:!1,_widgetId:0,_tmplLengthId:"",_tmplAreaId:"",_contentBounds:{},_$resizeContainer:c,_$eventTarget:c,_$contentFrame:c,_$existingChildren:c,_$attrList:c,_$servicesContainer:c,_$shapesContainers:c,_$panContainer:c,_$shapesContainer:c,_$drawContainer:c,_$measureContainer:c,_$measureLabel:c,_dpi:96,_currentServices:[],_center:c,_pixelSize:c,_centerMax:c,_pixelSizeMax:c,_pixelSizeMin:c,_userGeodetic:!0,_centerInteractive:c,_pixelSizeInteractive:c,_timeoutInteractive:null,_timeoutWheel:null,_triggerInteractive:!1,_timeoutRefreshShapes:null,_loadCount:0,_wheelLevel:0,_fullZoomFactor:2,_partialZoomFactor:1.18920711500273,_mouseDown:c,_inOp:c,_toolPan:c,_shiftDown:c,_anchor:c,_current:c,_downDate:c,_moveDate:c,_clickDate:c,_lastMove:c,_lastDrag:c,_windowHandler:null,_resizeTimeout:null,_panning:c,_velocity:c,_friction:c,_pointerEvents:c,_supportTouch:c,_softDblClick:c,_isTap:c,_isDbltap:c,_isMultiTouch:c,_multiTouchAnchor:[],_multiTouchAnchorBbox:c,_multiTouchCurrentBbox:c,_drawTimeout:null,_drawPixels:[],_drawCoords:[],_graphicShapes:[],_initOptions:{},_options:{},options:a.extend({},g),_createWidget:function(b,c){if(this._$elem=a(c),this._$elem.is(".geo-service"))return this._graphicShapes=[],void a.Widget.prototype._createWidget.apply(this,arguments);this._widgetId=d++,this._serviceIdSeed=0,this._tmplLengthId="geoMeasureLength"+this._widgetId,this._tmplAreaId="geoMeasureArea"+this._widgetId,this._$elem.addClass("geo-map").css({webkitTransform:"translateZ(0)",touchAction:"none"}),this._initOptions=b||{},this._forcePosition(this._$elem),this._$elem.css("text-align","left");var e=this._findMapSize();this._contentBounds={x:parseInt(this._$elem.css("padding-left"),10),y:parseInt(this._$elem.css("padding-top"),10),width:e.width,height:e.height},this._createChildren(),this._center=[0,0],this._centerMax=[0,0],this._centerInteractive=[0,0],this.options.pixelSize=this._pixelSize=this._pixelSizeMax=156543.03392799935,this._pixelSizeMin=this._pixelSizeMax/Math.pow(2,17),this._mouseDown=this._inOp=this._toolPan=this._shiftDown=this._panning=this._isTap=this._isDbltap=this._isMultiTouch=!1,this._anchor=[0,0],this._current=[0,0],this._lastMove=[0,0],this._lastDrag=[0,0],this._velocity=[0,0],this._friction=[.8,.8],this._downDate=this._moveDate=this._clickDate=0,this._drawPixels=[],this._drawCoords=[],this._graphicShapes=[],a.Widget.prototype._createWidget.apply(this,arguments)},_create:function(){if(this._options=this.options,this._$elem.is(".geo-service"))return this._map=this._$elem.data("geoMap"),void this._$elem.data("geoService",this);this._map=this,this._pointerEvents=b.PointerEvent,this._supportTouch="ontouchend"in document,this._softDblClick=this._pointerEvents||this._supportTouch||7===e;var d=this,g=this._pointerEvents?"pointerdown":this._supportTouch?"touchstart mousedown":"mousedown",h=this._pointerEvents?"pointerup pointercancel":this._supportTouch?"touchend touchcancel mouseup":"mouseup",i=this._pointerEvents?"pointermove":this._supportTouch?"touchmove mousemove":"mousemove";a(document).keydown(a.proxy(this._document_keydown,this)),this._softDblClick?this._$eventTarget.on("softdblclick",a.proxy(this._eventTarget_dblclick,this)):this._$eventTarget.dblclick(a.proxy(this._eventTarget_dblclick,this)),this._$eventTarget.bind(g,a.proxy(this._eventTarget_touchstart,this));var j=this._$eventTarget[0].setCapture||this._pointerEvents?this._$eventTarget:a(document);j.bind(i,a.proxy(this._dragTarget_touchmove,this)),j.bind(h,a.proxy(this._dragTarget_touchstop,this)),this._$eventTarget.mousewheel(a.proxy(this._eventTarget_mousewheel,this)),this._windowHandler=function(){d._resizeTimeout&&clearTimeout(d._resizeTimeout),d._resizeTimeout=setTimeout(function(){d._created&&d._$elem.geomap("resize",!0)},500)},a(b).resize(this._windowHandler),this._$drawContainer.geographics({style:this._initOptions.drawStyle||{},doubleBuffer:!1}),this._options.drawStyle=this._$drawContainer.geographics("option","style"),this._$shapesContainer.geographics({style:this._initOptions.shapeStyle||{},doubleBuffer:!f}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style"),this._initOptions&&(this._initOptions.tilingScheme!==c&&this._setOption("tilingScheme",this._initOptions.tilingScheme||null,!1),this._initOptions.services&&(this._options.services=a.merge([],this._initOptions.services)),this._initOptions.bboxMax&&(this._setOption("bboxMax",this._initOptions.bboxMax,!1),this._setOption("bbox",this._initOptions.bboxMax,!1)),this._initOptions.zoomMin!==c&&this._setOption("zoomMin",this._initOptions.zoomMin,!1),this._initOptions.zoomMax!==c&&this._setOption("zoomMax",this._initOptions.zoomMax,!1),this._initOptions.zoomFactor!==c&&(this._setOption("zoomFactor",this._initOptions.zoomFactor,!1),this._fullZoomFactor=this._initOptions.zoomFactor,this._partialZoomFactor=Math.pow(4,1/this._fullZoomFactor)),this._initOptions.bbox&&this._setOption("bbox",this._initOptions.bbox,!1),this._initOptions.center&&this._setOption("center",this._initOptions.center,!1),this._initOptions.zoom!==c&&this._setOption("zoom",this._initOptions.zoom,!1)),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area),this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._createServices(),this._refresh(),this._created=!0},_setOption:function(b,d,e){if("pixelSize"!==b){e=e===c||e,this._$elem.is(".geo-map")&&this._panFinalize();var f,g,h,i;switch(b){case"bbox":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),f=[d[0]+(d[2]-d[0])/2,d[1]+(d[3]-d[1])/2],g=Math.max(a.geo.width(d,!0)/this._contentBounds.width,a.geo.height(d,!0)/this._contentBounds.height),i=this._getZoom(f,g),this._options.tilingScheme?g=this._getPixelSize(Math.min(Math.max(i,this._options.zoomMin),this._options.zoomMax)):ithis._options.zoomMax&&(g=this._getPixelSize(this._options.zoomMax)),this._created?(this._setInteractiveCenterAndSize(f,g),this._setInteractiveTimeout(!1)):this._setCenterAndSize(f,g,!1,e),d=this._getBbox(f,g);break;case"bboxMax":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d);break;case"center":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),this._created?(this._setInteractiveCenterAndSize(d,this._pixelSizeInteractive),this._interactiveTransform(),this._setInteractiveTimeout(!1)):this._setCenterAndSize(d,this._pixelSize,!1,e);break;case"measureLabels":d=a.extend(this._options.measureLabels,d),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area);break;case"drawStyle":this._$drawContainer&&(this._$drawContainer.geographics("option","style",d),d=this._$drawContainer.geographics("option","style"));break;case"shapeStyle":this._$elem.is(".geo-service")&&!this._createdGraphics&&this._createServiceGraphics(),this._createdGraphics&&(this._$shapesContainer.geographics("option","style",d),d=this._$shapesContainer.geographics("option","style"));break;case"mode":this._resetDrawing(),this._$eventTarget.css("cursor",this._options.cursors[d]);break;case"zoom":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj,this._created?this._setZoom(d,!1,e):(d=Math.max(d,0),this._setCenterAndSize(this._center,this._getPixelSize(d),!1,e))}switch(a.Widget.prototype._setOption.apply(this,arguments),b){case"bbox":case"center":this._userGeodetic&&(this._options.bbox=a.geo.proj.toGeodetic(this._options.bbox),this._options.center=a.geo.proj.toGeodetic(this._center));break;case"tilingScheme":null!==d&&(this._pixelSizeMax=this._getPixelSize(0),this._pixelSizeMin=this._getPixelSize(d.pixelSizes?d.pixelSizes.length-1:d.levels-1),this._centerMax=[d.origin[0]+this._pixelSizeMax*d.tileWidth/2,d.origin[1]+this._pixelSizeMax*d.tileHeight/2]);break;case"bboxMax":h=this._userGeodetic?a.geo.proj.fromGeodetic(d):d,this._centerMax=a.geo.center(h),this._pixelSizeMax=Math.max(a.geo.width(h,!0)/this._contentBounds.width,a.geo.height(h,!0)/this._contentBounds.height);break;case"services":this._createServices(),e&&(this._refresh(),this._refreshAllShapes());break;case"shapeStyle":e&&this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))}}},destroy:function(){if(this._$elem.is(".geo-service"))this._createdGraphics&&(this._$shapesContainer.geographics("destroy"),this._$shapesContainer=c,this._createdGraphics=!1);else{clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,this._created=!1,a(b).unbind("resize",this._windowHandler);for(var d=0;d=0||1>=b)for(var d=0;d0)){this._createdGraphics||this._createServiceGraphics();var d,e,f,g,h,i;for(d=a.isArray(b)?b:"FeatureCollection"===b.type?b.features:[b],f=1;f=0;g--)if(d=this._graphicShapes[g],h)if("Point"===d.shape.type)a.geo.distance(d.shape,b)<=i&&j.push(d.shape);else{var k=a.data(d.shape,"geoBbox"),l={type:"Polygon",coordinates:[[[k[0],k[1]],[k[0],k[3]],[k[2],k[3]],[k[2],k[1]],[k[0],k[1]]]]},m={type:"Point",coordinates:a.geo.proj&&a.geo._isGeodetic(b.coordinates)?a.geo.proj.fromGeodetic(b.coordinates):b.coordinates};if(a.geo.distance(l,m,!0)<=i)for(e=a.geo._basic(d.shape),f=0;f0)){for(var e,f=a.isArray(b)?b:[b],g=0;g=0&&(e=this._graphicShapes.slice(g+1),this._graphicShapes.length=g,this._graphicShapes.push.apply(this._graphicShapes,e),g--);(d===c||d)&&(this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh(),this._refreshAllShapes())}},_getBbox:function(a,b){a=a||this._center,b=b||this._pixelSize;var c=this._contentBounds.width/2*b,d=this._contentBounds.height/2*b;return[a[0]-c,a[1]-d,a[0]+c,a[1]+d]},_setBbox:function(b){var c=[b[0]+(b[2]-b[0])/2,b[1]+(b[3]-b[1])/2],d=Math.max(a.geo.width(b,!0)/this._contentBounds.width,a.geo.height(b,!0)/this._contentBounds.height),e=this._getZoom(c,d);this._options.tilingScheme?d=this._getPixelSize(Math.min(Math.max(e,this._options.zoomMin),this._options.zoomMax)):ethis._options.zoomMax&&(d=this._getPixelSize(this._options.zoomMax)),this._setInteractiveCenterAndSize(c,d),this._interactiveTransform()},_getBboxMax:function(){var a=this._contentBounds.width/2*this._pixelSizeMax,b=this._contentBounds.height/2*this._pixelSizeMax;return[this._centerMax[0]-a,this._centerMax[1]-b,this._centerMax[0]+a,this._centerMax[1]+b]},_getCenter:function(){return this._center},_getContentBounds:function(){return this._contentBounds},_getServicesContainer:function(){return this._$servicesContainer},_getZoom:function(b,c){b=b||this._center,c=c||this._pixelSize;var d=this._options.tilingScheme;if(d){if(d.pixelSizes){for(var e=Math.floor(1e3*c),f=d.pixelSizes.length,g=f-1;g>=0;g--)if(Math.floor(1e3*d.pixelSizes[g])>=e)return g;return 0}return Math.round(Math.log(d.basePixelSize/c)/Math.log(2))}var h=this._contentBounds.width/this._contentBounds.height,i=a.geo.reaspect(this._getBbox(b,c),h,!0),j=a.geo.reaspect(this._getBboxMax(),h,!0);return Math.round(Math.log(a.geo.width(j,!0)/a.geo.width(i,!0))/Math.log(this._fullZoomFactor))},_setZoom:function(a,b){this._clearInteractiveTimeout(),a=Math.min(Math.max(a,this._options.zoomMin),this._options.zoomMax),this._setInteractiveCenterAndSize(this._centerInteractive,this._getPixelSize(a)),this._interactiveTransform(),this._setInteractiveTimeout(b)},_createChildren:function(){this._$existingChildren=this._$elem.children(),this._forcePosition(this._$existingChildren),this._$existingChildren.detach().css({mozUserSelect:"none"});var c="width:"+this._contentBounds.width+"px; height:"+this._contentBounds.height+"px; margin:0; padding:0;",d="position:absolute; left:0; top:0;";this._$elem.prepend(b.toStaticHTML('
                          ')),this._$eventTarget=this._$contentFrame=this._$elem.children(":first"),this._$contentFrame.append('
                          '),this._$servicesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                            '),this._$attrList=this._$contentFrame.children(":last"),this._$contentFrame.append('
                            '),this._$drawContainer=this._$contentFrame.children(":last"), -this._$contentFrame.append('
                            '),this._$measureContainer=this._$contentFrame.children(":last"),this._$measureLabel=this._$measureContainer.children(),this._$contentFrame.append('
                            '),this._$shapesContainer=this._$contentFrame.children(":last"),this._$panContainer=a([this._$shapesContainer[0],this._$drawContainer[0],this._$measureContainer[0]]),this._$resizeContainer=a([this._$contentFrame[0],this._$servicesContainer[0],this._$eventTarget[0],this._$measureContainer[0]]),this._$contentFrame.append(this._$existingChildren),a("#geo-measure-style").length||a("head").prepend(b.toStaticHTML('"))},_createServices:function(){var c,d;for(d=0;d';this._$servicesContainer.append(b.toStaticHTML(h)),e=this._$servicesContainer.children(":last"),c.serviceContainer=e,a.geo._serviceTypes[c.type].create(this,e,c,d),e.data("geoMap",this).geomap(),c.attr&&this._$attrList.append("
                          • "+c.attr+"
                          • ")}this._$shapesContainers=this._$shapesContainer,this._$attrList.find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"})},_createServiceGraphics:function(){var a=this._$elem.closest(".geo-content-frame");this._$elem.append('
                            '),this._$shapesContainer=this._$elem.children(":last"),this._map._$shapesContainers=this._map._$shapesContainers.add(this._$shapesContainer),this._$shapesContainer.geographics({doubleBuffer:!f}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style")},_refreshDrawing:function(){if(this._$drawContainer.geographics("clear"),this._drawPixels.length>0){var b,c,d,e,f,g=this._options.mode,h=this._drawPixels,i=this._drawCoords;switch(g){case"measureLength":g="drawLineString",c={type:"LineString",coordinates:i},b=a.render[this._tmplLengthId]({length:a.geo.length(c,!0)}),d=a.merge([],h[h.length-1]);break;case"measureArea":g="drawPolygon",c={type:"Polygon",coordinates:[a.merge([],i)]},c.coordinates[0].push(i[0]),b=a.render[this._tmplAreaId]({area:a.geo.area(c,!0)}),d=this._toPixel(a.geo.centroid(c).coordinates),h=[h];break;case"drawPolygon":h=[h]}this._$drawContainer.geographics(g,h),b&&(this._$measureLabel.html(b),e=this._contentBounds.width-(this._$measureLabel.outerWidth(!0)+d[0]),f=this._contentBounds.height-(this._$measureLabel.outerHeight(!0)+d[1]),0>e&&(d[0]+=e),0>f&&(d[1]+=f),this._$measureLabel.css({left:Math.max(d[0],0),top:Math.max(d[1],0)}).show())}},_resetDrawing:function(){this._drawPixels=[],this._drawCoords=[],this._$drawContainer.geographics("clear"),this._$measureLabel.hide()},_refreshAllShapes:function(a){this._timeoutRefreshShapes=null;for(var b,c,d=0;d0&&c._refreshShapes(c._$shapesContainer,c._graphicShapes,c._graphicShapes,c._graphicShapes)));this._createdGraphics&&!a&&(this._$shapesContainer.geographics("clear"),this._graphicShapes.length>0&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))},_refreshShapes:function(b,d,e,f,g,h){var i,j,k,l,m,n,o,p,q,r=this._map._getBbox(g,h);for(i=0;i0&&a.height>0);)a={width:b.width(),height:b.height()},(a.width<=0||a.height<=0)&&(a={width:parseInt(b.css("width"),10),height:parseInt(b.css("height"),10)}),b=b.parent();return a},_forcePosition:function(a){var b=a.css("position");"relative"!==b&&"absolute"!==b&&"fixed"!==b&&a.css("position","relative")},_getPixelSize:function(b){var c=this._options.tilingScheme;if(null!==c){if(0===b)return c.pixelSizes?c.pixelSizes[0]:c.basePixelSize;b=Math.round(b),b=Math.max(b,0);var d=c.pixelSizes?c.pixelSizes.length:c.levels;return b=Math.min(b,d-1),c.pixelSizes?c.pixelSizes[b]:c.basePixelSize/Math.pow(2,b)}var e=a.geo.scaleBy(this._getBboxMax(),1/Math.pow(this._fullZoomFactor,b),!0);return Math.max(a.geo.width(e,!0)/this._contentBounds.width,a.geo.height(e,!0)/this._contentBounds.height)},_getZoomCenterAndSize:function(a,b,c){var d=c?this._fullZoomFactor:this._partialZoomFactor,e=Math.pow(d,-b),f=this._pixelSizeInteractive*e;this._options.tilingScheme&&(f=Math.min(Math.max(f,this._pixelSizeMin),this._pixelSizeMax));var g=this._getZoom(this._centerInteractive,f);c&&this._options.tilingScheme?f=this._getPixelSize(Math.min(Math.max(g,this._options.zoomMin),this._options.zoomMax)):0>b&&g0&&g>this._options.zoomMax&&(f=this._pixelSizeInteractive);var h=f/this._pixelSizeInteractive,i=this._toMap(a,this._centerInteractive,this._pixelSizeInteractive),j=[(this._centerInteractive[0]-i[0])*h,(this._centerInteractive[1]-i[1])*h],k=[i[0]+j[0],i[1]+j[1]];return{pixelSize:f,center:k}},_panFinalize:function(){this._panning&&(this._velocity=[0,0],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._inOp=!1,this._anchor=this._current,this._mouseDown=this._toolPan=this._panning=!1)},_panMove:function(){if(this._options.pannable){var a=this._current[0]-this._lastDrag[0],b=this._current[1]-this._lastDrag[1];(this._toolPan||a>3||-3>a||b>3||-3>b)&&(this._toolPan||(this._toolPan=!0,this._$eventTarget.css("cursor",this._options.cursors.pan)),this._mouseDown&&(this._velocity=[a,b]),(0!==a||0!==b)&&(this._panning=!0,this._lastDrag=this._current,this._centerInteractive[0]-=a*this._pixelSizeInteractive,this._centerInteractive[1]+=("image"===this._options.axisLayout?-1:1)*b*this._pixelSizeInteractive,this._setInteractiveCenterAndSize(this._centerInteractive,this._pixelSizeInteractive),this._interactiveTransform()))}},_clearInteractiveTimeout:function(){return this._timeoutRefreshShapes&&(clearTimeout(this._timeoutRefreshShapes),this._timeoutRefreshShapes=null),this._timeoutInteractive?(clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,!0):(this._centerInteractive[0]=this._center[0],this._centerInteractive[1]=this._center[1],this._pixelSizeInteractive=this._pixelSize,!1)},_interactiveTransform:function(){var b,c=this._pixelSize,d=c/this._pixelSizeInteractive;if(c>0){d=Math.round(1e3*d)/1e3;var e=this._toMap([0,0]),f=this._toPixel(e,this._centerInteractive,this._pixelSizeInteractive);this._$shapesContainers.geographics("interactiveTransform",f,d)}for(var g=0;g0&&(this._drawPixels=this._toPixel(this._drawCoords,this._centerInteractive,this._pixelSizeInteractive),this._refreshDrawing())},_interactiveTimeout:function(){this._isMultiTouch?this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128):this._created&&this._timeoutInteractive&&(this._setCenterAndSize(this._centerInteractive,this._pixelSizeInteractive,this._triggerInteractive,!0),this._timeoutInteractive=null,this._triggerInteractive=!1,this._timeoutRefreshShapes=setTimeout(a.proxy(this._refreshAllShapes,this),128))},_setInteractiveTimeout:function(b){this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128),this._triggerInteractive|=b},_refresh:function(b,c){for(var d,e=0;ethis._options.zoomMax&&(this._pixelSizeInteractive=d=this._getPixelSize(this._options.zoomMax)),this._centerInteractive[0]=c[0],this._centerInteractive[1]=c[1],this._created&&this._interactiveTransform(),this._options.pixelSize=this._pixelSize=d,this._center[0]=c[0],this._center[1]=c[1],this._userGeodetic?(this._options.bbox=a.geo.proj.toGeodetic(this._getBbox()),this._options.center=a.geo.proj.toGeodetic(this._center)):(this._options.bbox=this._getBbox(),this._options.center=a.merge([],c)),this._options.zoom=g,e&&this._trigger("bboxchange",b.event,{bbox:a.merge([],this._options.bbox)}),f&&(this._refresh(),this._refreshAllShapes(),this._refreshDrawing())}},_requestQueued:function(){0===this._loadCount&&this._trigger("loadstart",b.event),this._loadCount++},_requestComplete:function(){this._loadCount--,this._loadCount<=0&&(this._loadCount=0,this._trigger("loadend",b.event))},_toMap:function(b,c,d){c=c||this._center,d=d||this._pixelSize;var e,f,g,h,i=a.isArray(b[0]),j=i&&a.isArray(b[0][0]),k=j&&a.isArray(b[0][0][0]),l=this._contentBounds.width,m=this._contentBounds.height,n=l/2*d,o=m/2*d,p=[c[0]-n,c[1]-o,c[0]+n,c[1]+o],q=a.geo.width(p,!0)/l,r=a.geo.height(p,!0)/m,s="image"===this._options.axisLayout,t=[];for(k||(j||(i||(b=[b]),b=[b]),b=[b]),f=0;f0&&27===b.which&&(2>=c?(this._resetDrawing(),this._inOp=!1):(this._drawCoords[c-2]=a.merge([],this._drawCoords[c-1]),this._drawPixels[c-2]=a.merge([],this._drawPixels[c-1]),this._drawCoords.length--,this._drawPixels.length--,this._refreshDrawing()))},_eventTarget_dblclick_zoom:function(a){var b=this._clearInteractiveTimeout();if(this._trigger("dblclick",a,{type:"Point",coordinates:this._toMap(this._current,this._centerInteractive,this._pixelSizeInteractive)}),!a.isDefaultPrevented()){var c=this._getZoomCenterAndSize(this._current,1,!0);this._setInteractiveCenterAndSize(c.center,c.pixelSize),this._interactiveTransform(),b=!0}b&&this._setInteractiveTimeout(!0)},_eventTarget_dblclick:function(c){if("static"!==this._options.mode){switch(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),this._options.mode){case"drawLineString":case"measureLength":this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])?(this._drawCoords.length--,this._trigger("shape",c,{type:"LineString",coordinates:this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords})):this._eventTarget_dblclick_zoom(c),this._resetDrawing();break;case"drawPolygon":case"measureArea":if(this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])){var d=this._drawCoords.length-1;d>2&&(this._drawCoords[d]=a.merge([],this._drawCoords[0]),this._trigger("shape",c,{type:"Polygon",coordinates:[this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords]}))}else this._eventTarget_dblclick_zoom(c);this._resetDrawing();break;default:this._eventTarget_dblclick_zoom(c)}this._inOp=!1}},_eventTarget_touchstart:function(b){if("undefined"!=typeof document.elementFromPoint){var c=document.elementFromPoint(b.pageX,b.pageY);if(c&&"A"===c.nodeName)return}var d=this._options.mode,e=this._options.shift,f="dragBox"===d?"dragBox":"zoom";if("static"!==d&&(this._pointerEvents||this._supportTouch||1===b.which)){var g=this._clearInteractiveTimeout(),h=a(b.currentTarget).offset(),i=b.originalEvent.changedTouches;if(this._pointerEvents){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0)return b.currentTarget.setPointerCapture(b.originalEvent.pointerId),this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-h.left,this._multiTouchAnchor[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=a.geo.center(this._multiTouchCurrentBbox,!0),this._current=a.merge([],this._anchor),g&&this._setInteractiveTimeout(!0),!1;this._multiTouchAnchor.length<2&&(b.currentTarget.setPointerCapture(b.originalEvent.pointerId),this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top,NaN,NaN],this._current=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top])}else this._supportTouch&&i?(this._multiTouchAnchor=a.merge([],i),this._isMultiTouch=this._multiTouchAnchor.length>1,this._isMultiTouch?(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,i[1].pageX-h.left,i[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._current=a.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,NaN,NaN],this._current=[i[0].pageX-h.left,i[0].pageY-h.top])):this._current=[b.pageX-h.left,b.pageY-h.top];if(this._softDblClick){var j=a.now();if(j-this._downDate<750){if(this._isTap){var k=this._current[0]-this._anchor[0],l=this._current[1]-this._anchor[1],m=Math.sqrt(k*k+l*l);m>8?this._isTap=!1:this._current=a.merge([],this._anchor)}this._isDbltap?this._isDbltap=!1:this._isDbltap=this._isTap}else this._isDbltap=!1;this._isTap=!0,this._downDate=j}return this._mouseDown=!0,this._anchor=a.merge([],this._current),!this._inOp&&b.shiftKey&&"off"!==e?(this._shiftDown=!0,this._$eventTarget.css("cursor",this._options.cursors["default"===e?f:e])):this._isMultiTouch||!this._options.pannable&&"dragBox"!==d&&"dragCircle"!==d||(this._inOp=!0,"zoom"!==d&&"dragBox"!==d&&"dragCircle"!==d&&(this._lastDrag=this._current,b.currentTarget.setCapture&&b.currentTarget.setCapture())),b.preventDefault(),g&&this._setInteractiveTimeout(!0),!1}},_dragTarget_touchmove:function(b){if("static"!==this._options.mode){var c=!1;this._mouseDown&&(c=this._clearInteractiveTimeout());var d,f,g,h,i,j,k=this._$eventTarget.offset(),l=this._drawCoords.length,m=b.originalEvent.changedTouches,n=null;if(this._pointerEvents)if(this._isMultiTouch){if(b.originalEvent.pointerId===this._multiTouchAnchor[0].pointerId)this._multiTouchCurrentBbox[0]=b.originalEvent.pageX-k.left,this._multiTouchCurrentBbox[1]=b.originalEvent.pageY-k.top;else{if(b.originalEvent.pointerId!==this._multiTouchAnchor[1].pointerId)return b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1;this._multiTouchCurrentBbox[2]=b.originalEvent.pageX-k.left,this._multiTouchCurrentBbox[3]=b.originalEvent.pageY-k.top}d=a.geo._distancePointPoint([this._multiTouchAnchorBbox[0],this._multiTouchAnchorBbox[1]],[this._multiTouchAnchorBbox[2],this._multiTouchAnchorBbox[3]]),f=a.geo._distancePointPoint([this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1]],[this._multiTouchCurrentBbox[2],this._multiTouchCurrentBbox[3]]),g=(f-d)/d,g*=g>0?5:10,h=g-this._wheelLevel,this._wheelLevel=g,i=this._getZoomCenterAndSize(this._anchor,h,!1),this._setInteractiveCenterAndSize(i.center,i.pixelSize),this._interactiveTransform(),c=!0,n=a.geo.center(this._multiTouchCurrentBbox,!0)}else this._multiTouchAnchor[0]=b.originalEvent,this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-k.left,this._multiTouchAnchor[0].pageY-k.top,NaN,NaN],n=[b.originalEvent.pageX-k.left,b.originalEvent.pageY-k.top];else if(this._supportTouch&&m){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&m[0].identifier!==this._multiTouchAnchor[0].identifier)return this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(m[0]),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-k.left,this._multiTouchAnchor[1].pageY-k.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=this._current=a.geo.center(this._multiTouchCurrentBbox,!0),c&&this._setInteractiveTimeout(!0),!1;if(this._isMultiTouch){for(j=0;j0?5:10,h=g-this._wheelLevel,this._wheelLevel=g,i=this._getZoomCenterAndSize(this._anchor,h,!1),this._setInteractiveCenterAndSize(i.center,i.pixelSize),this._interactiveTransform(),c=!0,n=a.geo.center(this._multiTouchCurrentBbox,!0)}else n=[b.originalEvent.changedTouches[0].pageX-k.left,b.originalEvent.changedTouches[0].pageY-k.top]}else n=[b.pageX-k.left,b.pageY-k.top];if(null===n)return b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1;if(n[0]===this._lastMove[0]&&n[1]===this._lastMove[1])return this._inOp?(b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1):!1;if(7===e&&(this._isDbltap=this._isTap=!1),this._mouseDown&&(this._current=n,this._moveDate=a.now()),this._isMultiTouch)return b.preventDefault(),this._isDbltap=this._isTap=!1,c&&this._setInteractiveTimeout(!0),!1;var o,p,q,r=this._options.mode,s=this._options.shift,t="dragBox"===r?"dragBox":"zoom";switch(this._shiftDown&&(r="default"===s?t:s),r){case"zoom":case"dragBox":this._mouseDown?(this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawBbox",[this._anchor[0],this._anchor[1],n[0],n[1]])):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)});break;case"dragCircle":this._mouseDown?(o=n[0]-this._anchor[0],p=n[1]-this._anchor[1],q=2*Math.sqrt(o*o+p*p),this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawArc",this._anchor,0,360,{width:q,height:q})):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)});break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":this._mouseDown||this._toolPan?(this._panMove(),c=!0):(l>0&&(this._drawCoords[l-1]=this._toMap(n,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[l-1]=n,this._refreshDrawing()),this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)}));break;default:this._mouseDown||this._toolPan?(this._panMove(),c=!0):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)})}return this._lastMove=n,c&&this._setInteractiveTimeout(!0),this._inOp?(b.preventDefault(),!1):void 0}},_dragTarget_touchstop:function(c){if("static"!==this._options.mode){if(!this._mouseDown){if(7!==e)return;this._eventTarget_touchstart(c)}var d,f,g,h,i,j,k=this._clearInteractiveTimeout(),l=this._mouseDown,m=this._toolPan,n=this._$eventTarget.offset(),o=this._options.mode,p=this._options.shift,q="dragBox"===o?"dragBox":"zoom",r=null;if(this._shiftDown&&(o="default"===p?q:p),this._pointerEvents){if(c.originalEvent.pointerId!==this._multiTouchAnchor[0].pointerId&&c.originalEvent.pointerId!==this._multiTouchAnchor[1].pointerId)return c.preventDefault(),void(k&&this._setInteractiveTimeout(!0));c.currentTarget.releasePointerCapture(c.originalEvent.pointerId),r=[c.originalEvent.pageX-n.left,c.originalEvent.pageY-n.top],this._multiTouchAnchor=[],this._inOp=!1}else this._supportTouch&&c.originalEvent.changedTouches?(r=[c.originalEvent.changedTouches[0].pageX-n.left,c.originalEvent.changedTouches[0].pageY-n.top],this._multiTouchAnchor=[],this._inOp=!1):r=[c.pageX-n.left,c.pageY-n.top];if(this._softDblClick&&this._isTap&&(g=r[0]-this._anchor[0],h=r[1]-this._anchor[1],Math.sqrt(g*g+h*h)<=8&&(r=a.merge([],this._anchor))),g=r[0]-this._anchor[0],h=r[1]-this._anchor[1],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._shiftDown=this._mouseDown=this._toolPan=!1,this._isMultiTouch)return c.preventDefault(),this._isMultiTouch=!1,this._wheelLevel=0,void(k&&this._setInteractiveTimeout(!0));if(document.releaseCapture&&document.releaseCapture(),l){switch(f=a.now(),this._current=r,o){case"zoom":case"dragBox":if(0!==g||0!==h){var s=6*this._pixelSize,t=this._toMap([this._anchor,r]),u=[Math.min(t[0][0],t[1][0]),Math.min(t[0][1],t[1][1]),Math.max(t[0][0],t[1][0]),Math.max(t[0][1],t[1][1])];"zoom"===o?(u[2]-u[0]d;d++)v=360*d/y*(Math.PI/180),this._drawPixels[d]=[this._anchor[0]+Math.cos(v)*x,this._anchor[1]+Math.sin(v)*x];this._drawPixels[y]=[this._drawPixels[0][0],this._drawPixels[0][1]],i=this._toMap([[this._anchor[0]-x,this._anchor[1]+(w?-x:x)],[this._anchor[0]+x,this._anchor[1]+(w?x:-x)]]),j={type:"Polygon",coordinates:[this._toMap(this._drawPixels)],bbox:[i[0][0],i[0][1],i[1][0],i[1][1]]},this._userGeodetic&&(j.coordinates=a.geo.proj.toGeodetic(j.coordinates),j.bbox=a.geo.proj.toGeodetic(j.bbox)),this._trigger("shape",c,j),this._resetDrawing()}else i=this._toMap(r),j={type:"Point",coordinates:[i[0],i[1]],bbox:[i[0],i[1],i[0],i[1]]},this._userGeodetic&&(j.coordinates=a.geo.proj.toGeodetic(j.coordinates),j.bbox=a.geo.proj.toGeodetic(j.bbox)),this._trigger("shape",c,j);break;case"drawPoint":if(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),m)this._panFinalize();else if(f-this._clickDate>100){var z=this;this._drawTimeout=setTimeout(function(){z._drawTimeout&&(z._trigger("shape",c,{type:"Point",coordinates:z.toMap(r)}),z._inOp=!1,z._drawTimeout=null)},250)}break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":m?this._panFinalize():(this._trigger("click",c,{type:"Point",coordinates:this.toMap(r)}),c.isDefaultPrevented()||(d=0===this._drawCoords.length?0:this._drawCoords.length-1,this._drawCoords[d]=this._toMap(r),this._drawPixels[d]=r,(2>d||this._drawCoords[d][0]!==this._drawCoords[d-1][0]||this._drawCoords[d][1]!==this._drawCoords[d-1][1])&&(this._drawCoords[d+1]=this._toMap(r,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[d+1]=r),this._refreshDrawing()));break;default:m?this._panFinalize():f-this._clickDate>100&&(this._trigger("click",c,{type:"Point",coordinates:this.toMap(r)}),this._inOp=!1)}if(this._clickDate=f,this._softDblClick&&this._isDbltap)return this._isDbltap=this._isTap=!1,k&&this._setInteractiveTimeout(!0),this._$eventTarget.trigger("softdblclick",c),!1}return k&&this._setInteractiveTimeout(!0),this._inOp?(c.preventDefault(),!1):void 0}},_eventTarget_mousewheel:function(b){if("static"!==this._options.mode&&"off"!==this._options.scroll){if(b.preventDefault(),this._mouseDown)return!1;if(0!==b.deltaY){this._timeoutWheel&&(clearTimeout(this._timeoutWheel),this._timeoutWheel=null);var c=this,d=b.currentTarget,e=b.deltaY,f=b.pageX,g=b.pageY;this._timeoutWheel=setTimeout(function(){c._clearInteractiveTimeout();var b=e>0?1:-1,h=a(d).offset();c._anchor=[f-h.left,g-h.top];var i=c._getZoomCenterAndSize(c._anchor,b,null!==c._options.tilingScheme);c._setInteractiveCenterAndSize(i.center,i.pixelSize),c._interactiveTransform(),c._setInteractiveTimeout(!0)},30)}return!1}}})}(jQuery,window),function(a,b,c){a.geo._serviceTypes.tiled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0,reloadTiles:!1};var g='
                            ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b.options.tilingScheme;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),h=f/e;if(f>0){h=Math.round(1e3*h)/1e3;var i=c.data("scaleOrigin"),j=b._toPixel(i,d,e);c.css({left:Math.round(j[0])+"px",top:Math.round(j[1])+"px",width:g.tileWidth*h,height:g.tileHeight*h})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&f&&(g.reloadTiles=!0),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i,j=d._getBbox(),k=d._pixelSize,l=this,m=g.serviceContainer,n="image"===d.options.axisLayout,o=n?1:-1,p=d.options.tilingScheme,q=p.tileWidth,r=p.tileHeight,s=Math.floor((j[0]-p.origin[0])/(k*q)),t=Math.max(Math.floor((n?j[1]-p.origin[1]:p.origin[1]-j[3])/(k*r)),0),u=Math.ceil((j[2]-p.origin[0])/(k*q)),v=Math.ceil((n?j[3]-p.origin[1]:p.origin[1]-j[1])/(k*r)),w=d._getBboxMax(),x=d._getPixelSize(0),y=x/k,z=Math.floor((w[0]-p.origin[0])/(x*q))*y,A=Math.floor((p.origin[1]+o*w[3])/(x*r))*y,B=p.origin[0]+z*q*k,C=p.origin[1]+o*(A*r)*k,D=Math.round((B-j[0])/k),E=Math.round((n?C-j[1]:j[3]-C)/k),F=m.children().show(),G=F.filter("[data-pixel-size='"+k+"']").appendTo(m),H=e.style.opacity,I=function(a){l._loadImage(this.img,a,k,d,g,H)},J=function(){delete this.img,g.loadCount--,d._requestComplete()};for(g.reloadTiles&&F.find("img").attr("data-dirty","true"),G.size()?(G.css({left:D%q+"px",top:E%r+"px"}).data("scaleOrigin",d._toMap([D%q,E%r])),G.children().each(function(){var b=a(this),c=b.attr("data-tile").split(",");b.css({left:Math.round(100*(parseInt(c[0],10)-z)+(D-D%q)/q*100)+"%",top:Math.round(100*(parseInt(c[1],10)-A)+(E-E%r)/r*100)+"%"}),1>H&&b.fadeTo(0,H)})):(m.append(b.toStaticHTML("
                            ")),G=m.children(":last").data("scaleOrigin",d._toMap([D%q,E%r]))),h=s;u>h;h++)for(i=t;v>i;i++){var K=""+h+","+i,L=G.children("[data-tile='"+K+"']").removeAttr("data-dirty");if(0===L.size()||g.reloadTiles){var M,N=[p.origin[0]+h*q*k,p.origin[1]+o*(i*r)*k],O=[p.origin[0]+((h+1)*q-1)*k,p.origin[1]+o*((i+1)*r-1)*k],P=[N[0],N[1],O[0],O[1]],Q={bbox:P,width:q,height:r,zoom:d._getZoom(),tile:{row:i,column:h},index:Math.abs(i+h)},R=a.isFunction(e.src);if(R?M=e.src(Q):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),M=a.render[this._tmplGeoSrcId](Q)):M=e.src,g.loadCount++,d._requestQueued(),g.reloadTiles&&L.size()>0)L.attr("src",M);else{var S="",G.append(b.toStaticHTML(S)),L=G.children(":last")}"string"==typeof M?l._loadImage(L,M,k,d,g,H):M&&a.isFunction(M.promise)?(a.extend(M.promise(),{img:L}),M.done(I).fail(J)):L.remove()}}F.find("[data-dirty]").remove(),g.reloadTiles=!1}},resize:function(){},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--, -b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){1>g?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).error(function(b){a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).attr("src",c)}}}()}(jQuery,window),function(a,b,c){a.geo._serviceTypes.shingled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0};var g='
                            ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b._getContentBounds(),h=g.width,i=g.height;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),g=f/e;if(f>0){g=Math.round(1e3*g)/1e3;var j=c.data("origin"),k=b._toPixel(j,d,e);c.css({left:Math.round(k[0]),top:Math.round(k[1]),width:h*g,height:i*g})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i=d._getBbox(),j=d._pixelSize,k=this,l=g.serviceContainer,m=d._getContentBounds(),n=m.width,o=m.height,p=l.children('[data-pixel-size="'+j+'"]'),q=e.style.opacity;1>q||f||1===e.shinglesMax?l.find("img").attr("data-keep-alive","0"):e.shinglesMax>1&&l.find("img").slice(0,-(e.shinglesMax-1)).attr("data-keep-alive","0"),p.size()||(l.append(b.toStaticHTML('
                            ')),p=l.children(":last"));var r,s={bbox:i,width:n,height:o,zoom:d._getZoom(),tile:null,index:0},t=a.isFunction(e.src),u=p.position();u.left=-u.left,u.top=-u.top,t?r=e.src(s):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),r=a.render[this._tmplGeoSrcId](s)):r=e.src,g.loadCount++,d._requestQueued(),p.append(b.toStaticHTML('')),h=p.children(":last").data("center",d._center),"string"==typeof r?k._loadImage(h,r,j,d,g,q):r&&r.done(function(a){k._loadImage(h,a,j,d,g,q)}).fail(function(){h.remove(),g.loadCount--,d._requestComplete()})}},resize:function(b,c){var d=a.data(c,"geoServiceState");if(d&&c&&"visible"===c.style.visibility){this._cancelUnloaded(b,c);var e=d.serviceContainer,f=b._getContentBounds(),g=f.width,h=f.height,i=e.children();i.attr("data-pixel-size","0"),i.each(function(){var b=a(this),c=b.position();b.css({left:c.left+(g-b.width())/2,top:c.top+(h-b.height())/2})})}},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--,b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(1>g?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(':not([data-pixel-size="'+d+'"])').remove(),h.find("img[data-keep-alive]").remove(),f.loadCount=0))}).error(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0))}).attr("src",c)}}}()}(jQuery,window); \ No newline at end of file diff --git a/dist/jquery.geo-1.0a3.js b/dist/jquery.geo-1.0a3.js deleted file mode 100644 index 3552d4c..0000000 --- a/dist/jquery.geo-1.0a3.js +++ /dev/null @@ -1,4826 +0,0 @@ -// excanvas -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/* - * AppGeo/geo - * (c) 2007-2011, Applied Geographics, Inc. All rights reserved. - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - */ - - -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -// Known Issues: -// -// * Patterns only support repeat. -// * Radial gradient are not implemented. The VML version of these look very -// different from the canvas one. -// * Clipping paths are not implemented. -// * Coordsize. The width and height attribute have higher priority than the -// width and height style values which isn't correct. -// * Painting mode isn't implemented. -// * Canvas width/height should is using content-box by default. IE in -// Quirks mode will draw the canvas using border-box. Either change your -// doctype to HTML5 -// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) -// or use Box Sizing Behavior from WebFX -// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) -// * Non uniform scaling does not correctly scale strokes. -// * Optimize. There is always room for speed improvements. - -// Only add this code if we do not already have a canvas implementation -if (!document.createElement('canvas').getContext) { - - (function () { - - // alias some functions to make (compiled) code shorter - var m = Math; - var mr = m.round; - var ms = m.sin; - var mc = m.cos; - var abs = m.abs; - var sqrt = m.sqrt; - - // this is used for sub pixel precision - var Z = 10; - var Z2 = Z / 2; - - var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; - - /** - * This funtion is assigned to the elements as element.getContext(). - * @this {HTMLElement} - * @return {CanvasRenderingContext2D_} - */ - function getContext() { - return this.context_ || - (this.context_ = new CanvasRenderingContext2D_(this)); - } - - var slice = Array.prototype.slice; - - /** - * Binds a function to an object. The returned function will always use the - * passed in {@code obj} as {@code this}. - * - * Example: - * - * g = bind(f, obj, a, b) - * g(c, d) // will do f.call(obj, a, b, c, d) - * - * @param {Function} f The function to bind the object to - * @param {Object} obj The object that should act as this when the function - * is called - * @param {*} var_args Rest arguments that will be used as the initial - * arguments when the function is called - * @return {Function} A new function that has bound this - */ - function bind(f, obj, var_args) { - var a = slice.call(arguments, 2); - return function () { - return f.apply(obj, a.concat(slice.call(arguments))); - }; - } - - function encodeHtmlAttribute(s) { - return String(s).replace(/&/g, '&').replace(/"/g, '"'); - } - - function addNamespace(doc, prefix, urn) { - if (!doc.namespaces[prefix]) { - doc.namespaces.add(prefix, urn, '#default#VML'); - } - } - - function addNamespacesAndStylesheet(doc) { - addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); - addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); - - // Setup default CSS. Only add one style sheet per document - if (!doc.styleSheets['ex_canvas_']) { - var ss = doc.createStyleSheet(); - ss.owningElement.id = 'ex_canvas_'; - ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + - // default size is 300x150 in Gecko and Opera - 'text-align:left;width:300px;height:150px}'; - } - } - - // Add namespaces and stylesheet at startup. - addNamespacesAndStylesheet(document); - - var G_vmlCanvasManager_ = { - init: function (opt_doc) { - var doc = opt_doc || document; - // Create a dummy element so that IE will allow canvas elements to be - // recognized. - doc.createElement('canvas'); - doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); - }, - - init_: function (doc) { - // find all canvas elements - var els = doc.getElementsByTagName('canvas'); - for (var i = 0; i < els.length; i++) { - this.initElement(els[i]); - } - }, - - /** - * Public initializes a canvas element so that it can be used as canvas - * element from now on. This is called automatically before the page is - * loaded but if you are creating elements using createElement you need to - * make sure this is called on the element. - * @param {HTMLElement} el The canvas element to initialize. - * @return {HTMLElement} the element that was created. - */ - initElement: function (el) { - if (!el.getContext) { - el.getContext = getContext; - - // Add namespaces and stylesheet to document of the element. - addNamespacesAndStylesheet(el.ownerDocument); - - // Remove fallback content. There is no way to hide text nodes so we - // just remove all childNodes. We could hide all elements and remove - // text nodes but who really cares about the fallback content. - el.innerHTML = ''; - - // do not use inline function because that will leak memory - el.attachEvent('onpropertychange', onPropertyChange); - el.attachEvent('onresize', onResize); - - var attrs = el.attributes; - if (attrs.width && attrs.width.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setWidth_(attrs.width.nodeValue); - el.style.width = attrs.width.nodeValue + 'px'; - } else { - el.width = el.clientWidth; - } - if (attrs.height && attrs.height.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setHeight_(attrs.height.nodeValue); - el.style.height = attrs.height.nodeValue + 'px'; - } else { - el.height = el.clientHeight; - } - //el.getContext().setCoordsize_() - } - return el; - } - }; - - function onPropertyChange(e) { - var el = e.srcElement; - - switch (e.propertyName) { - case 'width': - el.getContext().clearRect(); - el.style.width = el.attributes.width.nodeValue + 'px'; - // In IE8 this does not trigger onresize. - el.firstChild.style.width = el.clientWidth + 'px'; - break; - case 'height': - el.getContext().clearRect(); - el.style.height = el.attributes.height.nodeValue + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - break; - } - } - - function onResize(e) { - var el = e.srcElement; - if (el.firstChild) { - el.firstChild.style.width = el.clientWidth + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - } - } - - G_vmlCanvasManager_.init(); - - // precompute "00" to "FF" - var decToHex = []; - for (var i = 0; i < 16; i++) { - for (var j = 0; j < 16; j++) { - decToHex[i * 16 + j] = i.toString(16) + j.toString(16); - } - } - - function createMatrixIdentity() { - return [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1] - ]; - } - - function matrixMultiply(m1, m2) { - var result = createMatrixIdentity(); - - for (var x = 0; x < 3; x++) { - for (var y = 0; y < 3; y++) { - var sum = 0; - - for (var z = 0; z < 3; z++) { - sum += m1[x][z] * m2[z][y]; - } - - result[x][y] = sum; - } - } - return result; - } - - function copyState(o1, o2) { - o2.fillStyle = o1.fillStyle; - o2.lineCap = o1.lineCap; - o2.lineJoin = o1.lineJoin; - o2.lineWidth = o1.lineWidth; - o2.miterLimit = o1.miterLimit; - o2.shadowBlur = o1.shadowBlur; - o2.shadowColor = o1.shadowColor; - o2.shadowOffsetX = o1.shadowOffsetX; - o2.shadowOffsetY = o1.shadowOffsetY; - o2.strokeStyle = o1.strokeStyle; - o2.globalAlpha = o1.globalAlpha; - o2.font = o1.font; - o2.textAlign = o1.textAlign; - o2.textBaseline = o1.textBaseline; - o2.arcScaleX_ = o1.arcScaleX_; - o2.arcScaleY_ = o1.arcScaleY_; - o2.lineScale_ = o1.lineScale_; - } - - // var colorData = { - // aliceblue: '#F0F8FF', - // antiquewhite: '#FAEBD7', - // aquamarine: '#7FFFD4', - // azure: '#F0FFFF', - // beige: '#F5F5DC', - // bisque: '#FFE4C4', - // black: '#000000', - // blanchedalmond: '#FFEBCD', - // blueviolet: '#8A2BE2', - // brown: '#A52A2A', - // burlywood: '#DEB887', - // cadetblue: '#5F9EA0', - // chartreuse: '#7FFF00', - // chocolate: '#D2691E', - // coral: '#FF7F50', - // cornflowerblue: '#6495ED', - // cornsilk: '#FFF8DC', - // crimson: '#DC143C', - // cyan: '#00FFFF', - // darkblue: '#00008B', - // darkcyan: '#008B8B', - // darkgoldenrod: '#B8860B', - // darkgray: '#A9A9A9', - // darkgreen: '#006400', - // darkgrey: '#A9A9A9', - // darkkhaki: '#BDB76B', - // darkmagenta: '#8B008B', - // darkolivegreen: '#556B2F', - // darkorange: '#FF8C00', - // darkorchid: '#9932CC', - // darkred: '#8B0000', - // darksalmon: '#E9967A', - // darkseagreen: '#8FBC8F', - // darkslateblue: '#483D8B', - // darkslategray: '#2F4F4F', - // darkslategrey: '#2F4F4F', - // darkturquoise: '#00CED1', - // darkviolet: '#9400D3', - // deeppink: '#FF1493', - // deepskyblue: '#00BFFF', - // dimgray: '#696969', - // dimgrey: '#696969', - // dodgerblue: '#1E90FF', - // firebrick: '#B22222', - // floralwhite: '#FFFAF0', - // forestgreen: '#228B22', - // gainsboro: '#DCDCDC', - // ghostwhite: '#F8F8FF', - // gold: '#FFD700', - // goldenrod: '#DAA520', - // grey: '#808080', - // greenyellow: '#ADFF2F', - // honeydew: '#F0FFF0', - // hotpink: '#FF69B4', - // indianred: '#CD5C5C', - // indigo: '#4B0082', - // ivory: '#FFFFF0', - // khaki: '#F0E68C', - // lavender: '#E6E6FA', - // lavenderblush: '#FFF0F5', - // lawngreen: '#7CFC00', - // lemonchiffon: '#FFFACD', - // lightblue: '#ADD8E6', - // lightcoral: '#F08080', - // lightcyan: '#E0FFFF', - // lightgoldenrodyellow: '#FAFAD2', - // lightgreen: '#90EE90', - // lightgrey: '#D3D3D3', - // lightpink: '#FFB6C1', - // lightsalmon: '#FFA07A', - // lightseagreen: '#20B2AA', - // lightskyblue: '#87CEFA', - // lightslategray: '#778899', - // lightslategrey: '#778899', - // lightsteelblue: '#B0C4DE', - // lightyellow: '#FFFFE0', - // limegreen: '#32CD32', - // linen: '#FAF0E6', - // magenta: '#FF00FF', - // mediumaquamarine: '#66CDAA', - // mediumblue: '#0000CD', - // mediumorchid: '#BA55D3', - // mediumpurple: '#9370DB', - // mediumseagreen: '#3CB371', - // mediumslateblue: '#7B68EE', - // mediumspringgreen: '#00FA9A', - // mediumturquoise: '#48D1CC', - // mediumvioletred: '#C71585', - // midnightblue: '#191970', - // mintcream: '#F5FFFA', - // mistyrose: '#FFE4E1', - // moccasin: '#FFE4B5', - // navajowhite: '#FFDEAD', - // oldlace: '#FDF5E6', - // olivedrab: '#6B8E23', - // orange: '#FFA500', - // orangered: '#FF4500', - // orchid: '#DA70D6', - // palegoldenrod: '#EEE8AA', - // palegreen: '#98FB98', - // paleturquoise: '#AFEEEE', - // palevioletred: '#DB7093', - // papayawhip: '#FFEFD5', - // peachpuff: '#FFDAB9', - // peru: '#CD853F', - // pink: '#FFC0CB', - // plum: '#DDA0DD', - // powderblue: '#B0E0E6', - // rosybrown: '#BC8F8F', - // royalblue: '#4169E1', - // saddlebrown: '#8B4513', - // salmon: '#FA8072', - // sandybrown: '#F4A460', - // seagreen: '#2E8B57', - // seashell: '#FFF5EE', - // sienna: '#A0522D', - // skyblue: '#87CEEB', - // slateblue: '#6A5ACD', - // slategray: '#708090', - // slategrey: '#708090', - // snow: '#FFFAFA', - // springgreen: '#00FF7F', - // steelblue: '#4682B4', - // tan: '#D2B48C', - // thistle: '#D8BFD8', - // tomato: '#FF6347', - // turquoise: '#40E0D0', - // violet: '#EE82EE', - // wheat: '#F5DEB3', - // whitesmoke: '#F5F5F5', - // yellowgreen: '#9ACD32' - // }; - - - function getRgbHslContent(styleString) { - var start = styleString.indexOf('(', 3); - var end = styleString.indexOf(')', start + 1); - var parts = styleString.substring(start + 1, end).split(','); - // add alpha if needed - if (parts.length != 4 || styleString.charAt(3) != 'a') { - parts[3] = 1; - } - return parts; - } - - function percent(s) { - return parseFloat(s) / 100; - } - - function clamp(v, min, max) { - return Math.min(max, Math.max(min, v)); - } - - function hslToRgb(parts) { - var r, g, b, h, s, l; - h = parseFloat(parts[0]) / 360 % 360; - if (h < 0) - h++; - s = clamp(percent(parts[1]), 0, 1); - l = clamp(percent(parts[2]), 0, 1); - if (s == 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1 / 3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1 / 3); - } - - return '#' + decToHex[Math.floor(r * 255)] + - decToHex[Math.floor(g * 255)] + - decToHex[Math.floor(b * 255)]; - } - - function hueToRgb(m1, m2, h) { - if (h < 0) - h++; - if (h > 1) - h--; - - if (6 * h < 1) - return m1 + (m2 - m1) * 6 * h; - else if (2 * h < 1) - return m2; - else if (3 * h < 2) - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - else - return m1; - } - - var processStyleCache = {}; - - function processStyle(styleString) { - if (styleString in processStyleCache) { - return processStyleCache[styleString]; - } - - var str, alpha = 1; - - styleString = String(styleString); - if (styleString.charAt(0) == '#') { - str = styleString; - } else if (/^rgb/.test(styleString)) { - var parts = getRgbHslContent(styleString); - var str = '#', n; - for (var i = 0; i < 3; i++) { - if (parts[i].indexOf('%') != -1) { - n = Math.floor(percent(parts[i]) * 255); - } else { - n = +parts[i]; - } - str += decToHex[clamp(n, 0, 255)]; - } - alpha = +parts[3]; - } else if (/^hsl/.test(styleString)) { - var parts = getRgbHslContent(styleString); - str = hslToRgb(parts); - alpha = parts[3]; - } else { - str = /*colorData[styleString] ||*/styleString; - } - return processStyleCache[styleString] = { color: str, alpha: alpha }; - } - - var DEFAULT_STYLE = { - style: 'normal', - variant: 'normal', - weight: 'normal', - size: 10, - family: 'sans-serif' - }; - - // Internal text style cache - // var fontStyleCache = {}; - - // function processFontStyle(styleString) { - // if (fontStyleCache[styleString]) { - // return fontStyleCache[styleString]; - // } - - // var el = document.createElement('div'); - // var style = el.style; - // try { - // style.font = styleString; - // } catch (ex) { - // // Ignore failures to set to invalid font. - // } - - // return fontStyleCache[styleString] = { - // style: style.fontStyle || DEFAULT_STYLE.style, - // variant: style.fontVariant || DEFAULT_STYLE.variant, - // weight: style.fontWeight || DEFAULT_STYLE.weight, - // size: style.fontSize || DEFAULT_STYLE.size, - // family: style.fontFamily || DEFAULT_STYLE.family - // }; - // } - - // function getComputedStyle(style, element) { - // var computedStyle = {}; - - // for (var p in style) { - // computedStyle[p] = style[p]; - // } - - // // Compute the size - // var canvasFontSize = parseFloat(element.currentStyle.fontSize), - // fontSize = parseFloat(style.size); - - // if (typeof style.size == 'number') { - // computedStyle.size = style.size; - // } else if (style.size.indexOf('px') != -1) { - // computedStyle.size = fontSize; - // } else if (style.size.indexOf('em') != -1) { - // computedStyle.size = canvasFontSize * fontSize; - // } else if(style.size.indexOf('%') != -1) { - // computedStyle.size = (canvasFontSize / 100) * fontSize; - // } else if (style.size.indexOf('pt') != -1) { - // computedStyle.size = fontSize / .75; - // } else { - // computedStyle.size = canvasFontSize; - // } - - // // Different scaling between normal text and VML text. This was found using - // // trial and error to get the same size as non VML text. - // computedStyle.size *= 0.981; - - // return computedStyle; - // } - - // function buildStyle(style) { - // return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + - // style.size + 'px ' + style.family; - // } - - var lineCapMap = { - 'butt': 'flat', - 'round': 'round' - }; - - function processLineCap(lineCap) { - return lineCapMap[lineCap] || 'square'; - } - - /** - * This class implements CanvasRenderingContext2D interface as described by - * the WHATWG. - * @param {HTMLElement} canvasElement The element that the 2D context should - * be associated with - */ - function CanvasRenderingContext2D_(canvasElement) { - this.m_ = createMatrixIdentity(); - - this.mStack_ = []; - this.aStack_ = []; - this.currentPath_ = []; - - // Canvas context properties - this.strokeStyle = '#000'; - this.fillStyle = '#000'; - - this.lineWidth = 1; - this.lineJoin = 'miter'; - this.lineCap = 'butt'; - this.miterLimit = Z * 1; - this.globalAlpha = 1; - //this.font = '10px sans-serif'; - //this.textAlign = 'left'; - //this.textBaseline = 'alphabetic'; - this.canvas = canvasElement; - - var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + - canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; - var el = canvasElement.ownerDocument.createElement('div'); - el.style.cssText = cssText; - canvasElement.appendChild(el); - - var overlayEl = el.cloneNode(false); - // Use a non transparent background. - overlayEl.style.backgroundColor = 'red'; - overlayEl.style.filter = 'alpha(opacity=0)'; - canvasElement.appendChild(overlayEl); - - this.element_ = el; - this.arcScaleX_ = 1; - this.arcScaleY_ = 1; - this.lineScale_ = 1; - } - - var contextPrototype = CanvasRenderingContext2D_.prototype; - contextPrototype.clearRect = function () { - if (this.textMeasureEl_) { - this.textMeasureEl_.removeNode(true); - this.textMeasureEl_ = null; - } - this.element_.innerHTML = ''; - }; - - contextPrototype.beginPath = function () { - // TODO: Branch current matrix so that save/restore has no effect - // as per safari docs. - this.currentPath_ = []; - }; - - contextPrototype.moveTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'moveTo', x: p.x, y: p.y }); - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.lineTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'lineTo', x: p.x, y: p.y }); - - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY) { - var p = getCoords(this, aX, aY); - var cp1 = getCoords(this, aCP1x, aCP1y); - var cp2 = getCoords(this, aCP2x, aCP2y); - bezierCurveTo(this, cp1, cp2, p); - }; - - // Helper function that takes the already fixed cordinates. - function bezierCurveTo(self, cp1, cp2, p) { - self.currentPath_.push({ - type: 'bezierCurveTo', - cp1x: cp1.x, - cp1y: cp1.y, - cp2x: cp2.x, - cp2y: cp2.y, - x: p.x, - y: p.y - }); - self.currentX_ = p.x; - self.currentY_ = p.y; - } - - contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { - // the following is lifted almost directly from - // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes - - var cp = getCoords(this, aCPx, aCPy); - var p = getCoords(this, aX, aY); - - var cp1 = { - x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), - y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) - }; - var cp2 = { - x: cp1.x + (p.x - this.currentX_) / 3.0, - y: cp1.y + (p.y - this.currentY_) / 3.0 - }; - - bezierCurveTo(this, cp1, cp2, p); - }; - - contextPrototype.arc = function (aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise) { - aRadius *= Z; - var arcType = aClockwise ? 'at' : 'wa'; - - var xStart = aX + mc(aStartAngle) * aRadius - Z2; - var yStart = aY + ms(aStartAngle) * aRadius - Z2; - - var xEnd = aX + mc(aEndAngle) * aRadius - Z2; - var yEnd = aY + ms(aEndAngle) * aRadius - Z2; - - // IE won't render arches drawn counter clockwise if xStart == xEnd. - if (xStart == xEnd && !aClockwise) { - xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something - // that can be represented in binary - } - - var p = getCoords(this, aX, aY); - var pStart = getCoords(this, xStart, yStart); - var pEnd = getCoords(this, xEnd, yEnd); - - this.currentPath_.push({ type: arcType, - x: p.x, - y: p.y, - radius: aRadius, - xStart: pStart.x, - yStart: pStart.y, - xEnd: pEnd.x, - yEnd: pEnd.y - }); - - }; - - // contextPrototype.rect = function(aX, aY, aWidth, aHeight) { - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // }; - - // contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.stroke(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.fill(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { - // var gradient = new CanvasGradient_('gradient'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // return gradient; - // }; - - // contextPrototype.createRadialGradient = function(aX0, aY0, aR0, - // aX1, aY1, aR1) { - // var gradient = new CanvasGradient_('gradientradial'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.r0_ = aR0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // gradient.r1_ = aR1; - // return gradient; - // }; - - // contextPrototype.drawImage = function(image, var_args) { - // var dx, dy, dw, dh, sx, sy, sw, sh; - - // // to find the original width we overide the width and height - // var oldRuntimeWidth = image.runtimeStyle.width; - // var oldRuntimeHeight = image.runtimeStyle.height; - // image.runtimeStyle.width = 'auto'; - // image.runtimeStyle.height = 'auto'; - - // // get the original size - // var w = image.width; - // var h = image.height; - - // // and remove overides - // image.runtimeStyle.width = oldRuntimeWidth; - // image.runtimeStyle.height = oldRuntimeHeight; - - // if (arguments.length == 3) { - // dx = arguments[1]; - // dy = arguments[2]; - // sx = sy = 0; - // sw = dw = w; - // sh = dh = h; - // } else if (arguments.length == 5) { - // dx = arguments[1]; - // dy = arguments[2]; - // dw = arguments[3]; - // dh = arguments[4]; - // sx = sy = 0; - // sw = w; - // sh = h; - // } else if (arguments.length == 9) { - // sx = arguments[1]; - // sy = arguments[2]; - // sw = arguments[3]; - // sh = arguments[4]; - // dx = arguments[5]; - // dy = arguments[6]; - // dw = arguments[7]; - // dh = arguments[8]; - // } else { - // throw Error('Invalid number of arguments'); - // } - - // var d = getCoords(this, dx, dy); - - // var w2 = sw / 2; - // var h2 = sh / 2; - - // var vmlStr = []; - - // var W = 10; - // var H = 10; - - // // For some reason that I've now forgotten, using divs didn't work - // vmlStr.push(' ' , - // '', - // ''); - - // this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); - // }; - - contextPrototype.stroke = function (aFill) { - var lineStr = []; - var lineOpen = false; - - var W = 10; - var H = 10; - - lineStr.push(''); - - if (!aFill) { - appendStroke(this, lineStr); - } else { - appendFill(this, lineStr, min, max); - } - - lineStr.push(''); - - this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - }; - - function appendStroke(ctx, lineStr) { - var a = processStyle(ctx.strokeStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - var lineWidth = ctx.lineScale_ * ctx.lineWidth; - - // VML cannot correctly render a line if the width is less than 1px. - // In that case, we dilute the color to make the line look thinner. - if (lineWidth < 1) { - opacity *= lineWidth; - } - - lineStr.push( - '' - ); - } - - function appendFill(ctx, lineStr, min, max) { - var fillStyle = ctx.fillStyle; - var arcScaleX = ctx.arcScaleX_; - var arcScaleY = ctx.arcScaleY_; - var width = max.x - min.x; - var height = max.y - min.y; - // if (fillStyle instanceof CanvasGradient_) { - // // TODO: Gradients transformed with the transformation matrix. - // var angle = 0; - // var focus = {x: 0, y: 0}; - - // // additional offset - // var shift = 0; - // // scale factor for offset - // var expansion = 1; - - // if (fillStyle.type_ == 'gradient') { - // var x0 = fillStyle.x0_ / arcScaleX; - // var y0 = fillStyle.y0_ / arcScaleY; - // var x1 = fillStyle.x1_ / arcScaleX; - // var y1 = fillStyle.y1_ / arcScaleY; - // var p0 = getCoords(ctx, x0, y0); - // var p1 = getCoords(ctx, x1, y1); - // var dx = p1.x - p0.x; - // var dy = p1.y - p0.y; - // angle = Math.atan2(dx, dy) * 180 / Math.PI; - - // // The angle should be a non-negative number. - // if (angle < 0) { - // angle += 360; - // } - - // // Very small angles produce an unexpected result because they are - // // converted to a scientific notation string. - // if (angle < 1e-6) { - // angle = 0; - // } - // } else { - // var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); - // focus = { - // x: (p0.x - min.x) / width, - // y: (p0.y - min.y) / height - // }; - - // width /= arcScaleX * Z; - // height /= arcScaleY * Z; - // var dimension = m.max(width, height); - // shift = 2 * fillStyle.r0_ / dimension; - // expansion = 2 * fillStyle.r1_ / dimension - shift; - // } - - // // We need to sort the color stops in ascending order by offset, - // // otherwise IE won't interpret it correctly. - // var stops = fillStyle.colors_; - // stops.sort(function(cs1, cs2) { - // return cs1.offset - cs2.offset; - // }); - - // var length = stops.length; - // var color1 = stops[0].color; - // var color2 = stops[length - 1].color; - // var opacity1 = stops[0].alpha * ctx.globalAlpha; - // var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; - - // var colors = []; - // for (var i = 0; i < length; i++) { - // var stop = stops[i]; - // colors.push(stop.offset * expansion + shift + ' ' + stop.color); - // } - - // // When colors attribute is used, the meanings of opacity and o:opacity2 - // // are reversed. - // lineStr.push(''); - // } else if (fillStyle instanceof CanvasPattern_) { - // if (width && height) { - // var deltaLeft = -min.x; - // var deltaTop = -min.y; - // lineStr.push(''); - // } - // } else { - var a = processStyle(ctx.fillStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - lineStr.push(''); - // } - } - - contextPrototype.fill = function () { - this.stroke(true); - }; - - contextPrototype.closePath = function () { - this.currentPath_.push({ type: 'close' }); - }; - - function getCoords(ctx, aX, aY) { - var m = ctx.m_; - return { - x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, - y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 - }; - }; - - contextPrototype.save = function () { - var o = {}; - copyState(this, o); - this.aStack_.push(o); - this.mStack_.push(this.m_); - this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); - }; - - contextPrototype.restore = function () { - if (this.aStack_.length) { - copyState(this.aStack_.pop(), this); - this.m_ = this.mStack_.pop(); - } - }; - - function matrixIsFinite(m) { - return isFinite(m[0][0]) && isFinite(m[0][1]) && - isFinite(m[1][0]) && isFinite(m[1][1]) && - isFinite(m[2][0]) && isFinite(m[2][1]); - } - - function setM(ctx, m, updateLineScale) { - if (!matrixIsFinite(m)) { - return; - } - ctx.m_ = m; - - if (updateLineScale) { - // Get the line scale. - // Determinant of this.m_ means how much the area is enlarged by the - // transformation. So its square root can be used as a scale factor - // for width. - var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; - ctx.lineScale_ = sqrt(abs(det)); - } - } - - contextPrototype.translate = function (aX, aY) { - var m1 = [ - [1, 0, 0], - [0, 1, 0], - [aX, aY, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), false); - }; - - // contextPrototype.rotate = function(aRot) { - // var c = mc(aRot); - // var s = ms(aRot); - - // var m1 = [ - // [c, s, 0], - // [-s, c, 0], - // [0, 0, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), false); - // }; - - contextPrototype.scale = function (aX, aY) { - this.arcScaleX_ *= aX; - this.arcScaleY_ *= aY; - var m1 = [ - [aX, 0, 0], - [0, aY, 0], - [0, 0, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), true); - }; - - // contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { - // var m1 = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), true); - // }; - - // contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { - // var m = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, m, true); - // }; - - /** - * The text drawing function. - * The maxWidth argument isn't taken in account, since no browser supports - * it yet. - */ - // contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { - // var m = this.m_, - // delta = 1000, - // left = 0, - // right = delta, - // offset = {x: 0, y: 0}, - // lineStr = []; - - // var fontStyle = getComputedStyle(processFontStyle(this.font), - // this.element_); - - // var fontStyleString = buildStyle(fontStyle); - - // var elementStyle = this.element_.currentStyle; - // var textAlign = this.textAlign.toLowerCase(); - // switch (textAlign) { - // case 'left': - // case 'center': - // case 'right': - // break; - // case 'end': - // textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; - // break; - // case 'start': - // textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; - // break; - // default: - // textAlign = 'left'; - // } - - // // 1.75 is an arbitrary number, as there is no info about the text baseline - // switch (this.textBaseline) { - // case 'hanging': - // case 'top': - // offset.y = fontStyle.size / 1.75; - // break; - // case 'middle': - // break; - // default: - // case null: - // case 'alphabetic': - // case 'ideographic': - // case 'bottom': - // offset.y = -fontStyle.size / 2.25; - // break; - // } - - // switch(textAlign) { - // case 'right': - // left = delta; - // right = 0.05; - // break; - // case 'center': - // left = right = delta / 2; - // break; - // } - - // var d = getCoords(this, x + offset.x, y + offset.y); - - // lineStr.push(''); - - // if (stroke) { - // appendStroke(this, lineStr); - // } else { - // // TODO: Fix the min and max params. - // appendFill(this, lineStr, {x: -left, y: 0}, - // {x: right, y: fontStyle.size}); - // } - - // var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + - // m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; - - // var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); - - // lineStr.push('', - // '', - // ''); - - // this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - // }; - - // contextPrototype.fillText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, false); - // }; - - // contextPrototype.strokeText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, true); - // }; - - // contextPrototype.measureText = function(text) { - // if (!this.textMeasureEl_) { - // var s = ''; - // this.element_.insertAdjacentHTML('beforeEnd', s); - // this.textMeasureEl_ = this.element_.lastChild; - // } - // var doc = this.element_.ownerDocument; - // this.textMeasureEl_.innerHTML = ''; - // this.textMeasureEl_.style.font = this.font; - // // Don't use innerHTML or innerText because they allow markup/whitespace. - // this.textMeasureEl_.appendChild(doc.createTextNode(text)); - // return {width: this.textMeasureEl_.offsetWidth}; - // }; - - /******** STUBS ********/ - // contextPrototype.clip = function() { - // // TODO: Implement - // }; - - // contextPrototype.arcTo = function() { - // // TODO: Implement - // }; - - // contextPrototype.createPattern = function(image, repetition) { - // return new CanvasPattern_(image, repetition); - // }; - - // // Gradient / Pattern Stubs - // function CanvasGradient_(aType) { - // this.type_ = aType; - // this.x0_ = 0; - // this.y0_ = 0; - // this.r0_ = 0; - // this.x1_ = 0; - // this.y1_ = 0; - // this.r1_ = 0; - // this.colors_ = []; - // } - - // CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { - // aColor = processStyle(aColor); - // this.colors_.push({offset: aOffset, - // color: aColor.color, - // alpha: aColor.alpha}); - // }; - - // function CanvasPattern_(image, repetition) { - // assertImageIsValid(image); - // switch (repetition) { - // case 'repeat': - // case null: - // case '': - // this.repetition_ = 'repeat'; - // break - // case 'repeat-x': - // case 'repeat-y': - // case 'no-repeat': - // this.repetition_ = repetition; - // break; - // default: - // throwException('SYNTAX_ERR'); - // } - - // this.src_ = image.src; - // this.width_ = image.width; - // this.height_ = image.height; - // } - - function throwException(s) { - throw new DOMException_(s); - } - - // function assertImageIsValid(img) { - // if (!img || img.nodeType != 1 || img.tagName != 'IMG') { - // throwException('TYPE_MISMATCH_ERR'); - // } - // if (img.readyState != 'complete') { - // throwException('INVALID_STATE_ERR'); - // } - // } - - function DOMException_(s) { - this.code = this[s]; - this.message = s + ': DOM Exception ' + this.code; - } - var p = DOMException_.prototype = new Error; - p.INDEX_SIZE_ERR = 1; - p.DOMSTRING_SIZE_ERR = 2; - p.HIERARCHY_REQUEST_ERR = 3; - p.WRONG_DOCUMENT_ERR = 4; - p.INVALID_CHARACTER_ERR = 5; - p.NO_DATA_ALLOWED_ERR = 6; - p.NO_MODIFICATION_ALLOWED_ERR = 7; - p.NOT_FOUND_ERR = 8; - p.NOT_SUPPORTED_ERR = 9; - p.INUSE_ATTRIBUTE_ERR = 10; - p.INVALID_STATE_ERR = 11; - p.SYNTAX_ERR = 12; - p.INVALID_MODIFICATION_ERR = 13; - p.NAMESPACE_ERR = 14; - p.INVALID_ACCESS_ERR = 15; - p.VALIDATION_ERR = 16; - p.TYPE_MISMATCH_ERR = 17; - - // set up externs - G_vmlCanvasManager = G_vmlCanvasManager_; - CanvasRenderingContext2D = CanvasRenderingContext2D_; - //CanvasGradient = CanvasGradient_; - //CanvasPattern = CanvasPattern_; - DOMException = DOMException_; - })(); - -} // if -/* Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net) - * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) - * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. - * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. - * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. - * - * Version: 3.0.2 - * - * Requires: 1.2.2+ - */ -(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery); - -/*! - * jQuery UI Widget @VERSION - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ -if (!$.widget) { -(function( $, undefined ) { - -var slice = Array.prototype.slice; - -var _cleanData = $.cleanData; -$.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - $( elem ).triggerHandler( "remove" ); - } - _cleanData( elems ); -}; - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - // create the constructor using $.extend() so we can carry over any - // static properties stored on the existing constructor (if there is one) - $[ namespace ][ name ] = $.extend( function( options, element ) { - // allow instantiation without "new" keyword - if ( !this._createWidget ) { - return new $[ namespace ][ name ]( options, element ); - } - - // allow instantiation without initializing for simple inheritance - // must use "new" keyword (the code above always passes args) - if ( arguments.length ) { - this._createWidget( options, element ); - } - }, $[ namespace ][ name ] ); - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $.each( prototype, function( prop, value ) { - if ( $.isFunction( value ) ) { - prototype[ prop ] = (function() { - var _super = function( method ) { - return base.prototype[ method ].apply( this, slice.call( arguments, 1 ) ); - }; - var _superApply = function( method, args ) { - return base.prototype[ method ].apply( this, args ); - }; - return function() { - var __super = this._super, - __superApply = this._superApply, - returnValue; - - this._super = _super; - this._superApply = _superApply; - - returnValue = value.apply( this, arguments ); - - this._super = __super; - this._superApply = __superApply; - - return returnValue; - }; - }()); - } - }); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ); - if ( !instance ) { - return $.error( "cannot call methods on " + name + " prior to initialization; " + - "attempted to call method '" + options + "'" ); - } - if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { - return $.error( "no such method '" + options + "' for " + name + " widget instance" ); - } - var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - object( options, this ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without "new" keyword - if ( !this._createWidget ) { - return new $[ namespace ][ name ]( options, element ); - } - - // allow instantiation without initializing for simple inheritance - // must use "new" keyword (the code above always passes args) - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - defaultElement: "
                            ", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - element = $( element || this.defaultElement || this )[ 0 ]; - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - this.bindings = $(); - this.hoverable = $(); - this.focusable = $(); - - if ( element !== this ) { - $.data( element, this.widgetName, this ); - this._bind({ remove: "destroy" }); - } - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: $.noop, - _init: $.noop, - - destroy: function() { - this._destroy(); - // we can probably remove the unbind calls in 2.0 - // all event bindings should go through this._bind() - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - - // clean up events and states - this.bindings.unbind( "." + this.widgetName ); - this.hoverable.removeClass( "ui-state-hover" ); - this.focusable.removeClass( "ui-state-focus" ); - }, - _destroy: $.noop, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - .toggleClass( this.widgetBaseClass + "-disabled ui-state-disabled", !!value ) - .attr( "aria-disabled", value ); - this.hoverable.removeClass( "ui-state-hover" ); - this.focusable.removeClass( "ui-state-focus" ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _bind: function( element, handlers ) { - // no element argument, shuffle and use this.element - if ( !handlers ) { - handlers = element; - element = this.element; - } else { - // accept selectors, DOM elements - element = $( element ); - this.bindings = this.bindings.add( element ); - } - var instance = this; - $.each( handlers, function( event, handler ) { - element.bind( event + "." + instance.widgetName, function() { - // allow widgets to customize the disabled handling - // - disabled as an array instead of boolean - // - disabled class as method for disabling individual parts - if ( instance.options.disabled === true || - $( this ).hasClass( "ui-state-disabled" ) ) { - return; - } - return ( typeof handler === "string" ? instance[ handler ] : handler ) - .apply( instance, arguments ); - }); - }); - }, - - _hoverable: function( element ) { - this.hoverable = this.hoverable.add( element ); - this._bind( element, { - mouseenter: function( event ) { - $( event.currentTarget ).addClass( "ui-state-hover" ); - }, - mouseleave: function( event ) { - $( event.currentTarget ).removeClass( "ui-state-hover" ); - } - }); - }, - - _focusable: function( element ) { - this.focusable = this.focusable.add( element ); - this._bind( element, { - focusin: function( event ) { - $( event.currentTarget ).addClass( "ui-state-focus" ); - }, - focusout: function( event ) { - $( event.currentTarget ).removeClass( "ui-state-focus" ); - } - }); - }, - - _trigger: function( type, event, data ) { - var callback = this.options[ type ], - args; - - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - data = data || {}; - - // copy original event properties over to the new event - // this would happen if we could call $.event.fix instead of $.Event - // but we don't have a way to force an event to be fixed multiple times - if ( event.originalEvent ) { - for ( var i = $.event.props.length, prop; i; ) { - prop = $.event.props[ --i ]; - event[ prop ] = event.originalEvent[ prop ]; - } - } - - this.element.trigger( event, data ); - - args = $.isArray( data ) ? - [ event ].concat( data ) : - [ event, data ]; - - return !( $.isFunction( callback ) && - callback.apply( this.element[0], args ) === false || - event.isDefaultPrevented() ); - } -}; - -})( jQuery ); -}(function ($, window, undefined) { - var pos_oo = Number.POSITIVE_INFINITY, - neg_oo = Number.NEGATIVE_INFINITY; - - $.geo = { - // - // utility functions - // - - _allCoordinates: function (geom) { - // return array of all positions in all geometries of geom - // not in JTS - var geometries = this._flatten(geom), - curGeom = 0, - result = []; - - for (; curGeom < geometries.length; curGeom++) { - var coordinates = geometries[curGeom].coordinates, - isArray = coordinates && $.isArray(coordinates[0]), - isDblArray = isArray && $.isArray(coordinates[0][0]), - isTriArray = isDblArray && $.isArray(coordinates[0][0][0]), - i, j, k; - - if (!isTriArray) { - if (!isDblArray) { - if (!isArray) { - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - for (k = 0; k < coordinates[i][j].length; k++) { - result.push(coordinates[i][j][k]); - } - } - } - } - return result; - }, - - // - // bbox functions - // - - center: function (bbox, _ignoreGeo /* Internal Use Only */) { - // Envelope.centre in JTS - // bbox only, use centroid for geom - if (!_ignoreGeo && $.geo.proj) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - var center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return !_ignoreGeo && $.geo.proj ? $.geo.proj.toGeodetic(center) : center; - }, - - expandBy: function (bbox, dx, dy) { - if ($.geo.proj) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - bbox = [bbox[0] - dx, bbox[1] - dy, bbox[2] + dx, bbox[3] + dy]; - return $.geo.proj ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - height: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if (!_ignoreGeo && $.geo.proj) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - return bbox[3] - bbox[1]; - }, - - _in: function(bbox1, bbox2) { - return bbox1[0] <= bbox2[0] && - bbox1[1] <= bbox2[1] && - bbox1[2] >= bbox2[2] && - bbox1[3] >= bbox2[3]; - }, - - _bboxDisjoint: function( bbox1, bbox2 ) { - return bbox2[ 0 ] > bbox1[ 2 ] || - bbox2[ 2 ] < bbox1[ 0 ] || - bbox2[ 1 ] > bbox1[ 3 ] || - bbox2[ 3 ] < bbox1[ 1 ]; - }, - - reaspect: function (bbox, ratio, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - if (!_ignoreGeo && $.geo.proj) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - var width = this.width(bbox, true), - height = this.height(bbox, true), - center = this.center(bbox, true), - dx, dy; - - if (width != 0 && height != 0 && ratio > 0) { - if (width / height > ratio) { - dx = width / 2; - dy = dx / ratio; - } else { - dy = height / 2; - dx = dy * ratio; - } - - bbox = [center[0] - dx, center[1] - dy, center[0] + dx, center[1] + dy]; - } - return $.geo.proj ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - scaleBy: function ( bbox, scale, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - if (!_ignoreGeo && $.geo.proj) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - var c = this.center(bbox, true), - dx = (bbox[2] - bbox[0]) * scale / 2, - dy = (bbox[3] - bbox[1]) * scale / 2; - bbox = [c[0] - dx, c[1] - dy, c[0] + dx, c[1] + dy]; - return !_ignoreGeo && $.geo.proj ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - width: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if (!_ignoreGeo && $.geo.proj) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - return bbox[2] - bbox[0]; - }, - - // - // geometry functions - // - - // bbox (Geometry.getEnvelope in JTS) - - bbox: function ( geom, _ignoreGeo /* Internal Use Only */ ) { - if ( !geom ) { - return undefined; - } else if ( geom.bbox ) { - result = !_ignoreGeo && $.geo.proj ? $.geo.proj.fromGeodetic( geom.bbox ) : geom.bbox; - } else { - result = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var coordinates = this._allCoordinates( geom ), - curCoord = 0; - - if ( coordinates.length == 0 ) { - return undefined; - } - - if ( $.geo.proj ) { - coordinates = $.geo.proj.fromGeodetic( coordinates ); - } - - for ( ; curCoord < coordinates.length; curCoord++ ) { - result[0] = Math.min(coordinates[curCoord][0], result[0]); - result[1] = Math.min(coordinates[curCoord][1], result[1]); - result[2] = Math.max(coordinates[curCoord][0], result[2]); - result[3] = Math.max(coordinates[curCoord][1], result[3]); - } - } - - return $.geo.proj ? $.geo.proj.toGeodetic(result) : result; - }, - - // centroid - - centroid: function( geom, _ignoreGeo /* Internal Use Only */ ) { - switch (geom.type) { - case "Point": - return $.extend({}, geom); - - case "LineString": - case "Polygon": - var a = 0, - c = [0, 0], - coords = $.merge( [ ], geom.type == "Polygon" ? geom.coordinates[0] : geom.coordinates ), - i = 1, j, n; - - if ( !_ignoreGeo && $.geo.proj ) { - coords = $.geo.proj.fromGeodetic(coords); - } - - //if (coords[0][0] != coords[coords.length - 1][0] || coords[0][1] != coords[coords.length - 1][1]) { - // coords.push(coords[0]); - //} - - for (; i <= coords.length; i++) { - j = i % coords.length; - n = (coords[i - 1][0] * coords[j][1]) - (coords[j][0] * coords[i - 1][1]); - a += n; - c[0] += (coords[i - 1][0] + coords[j][0]) * n; - c[1] += (coords[i - 1][1] + coords[j][1]) * n; - } - - if (a == 0) { - if (coords.length > 0) { - c[0] = coords[0][0]; - c[1] = coords[0][1]; - return { type: "Point", coordinates: !_ignoreGeo && $.geo.proj ? $.geo.proj.toGeodetic(c) : c }; - } else { - return undefined; - } - } - - a *= 3; - c[0] /= a; - c[1] /= a; - - return { type: "Point", coordinates: !_ignoreGeo && $.geo.proj ? $.geo.proj.toGeodetic(c) : c }; - } - return undefined; - }, - - // contains - - contains: function (geom1, geom2) { - if (geom1.type != "Polygon") { - return false; - } - - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1.coordinates, geom2.coordinates); - - case "LineString": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates); - - case "Polygon": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates[0]); - - default: - return false; - } - }, - - _containsPolygonPoint: function (polygonCoordinates, pointCoordinate) { - if (polygonCoordinates.length == 0 || polygonCoordinates[0].length < 4) { - return false; - } - - var rayCross = 0, - a = polygonCoordinates[0][0], - i = 1, - b, - x; - - for (; i < polygonCoordinates[0].length; i++) { - b = polygonCoordinates[0][i]; - - if ((a[1] <= pointCoordinate[1] && pointCoordinate[1] < b[1]) || (b[1] <= pointCoordinate[1] && pointCoordinate[1] < a[1]) && (pointCoordinate[0] < a[0] || pointCoordinate[0] < b[0])) { - x = a[0] + (b[0] - a[0]) * (pointCoordinate[1] - a[1]) / (b[1] - a[1]); - - if (x > pointCoordinate[0]) { - rayCross++; - } - } - - a = b; - } - - return rayCross % 2 == 1; - }, - - _containsPolygonLineString: function (polygonCoordinates, lineStringCoordinates) { - for (var i = 0; i < lineStringCoordinates.length; i++) { - if (!this._containsPolygonPoint(polygonCoordinates, lineStringCoordinates[i])) { - return false; - } - } - return true; - }, - - // distance - - distance: function ( geom1, geom2, _ignoreGeo /* Internal Use Only */ ) { - var geom1CoordinatesProjected = !_ignoreGeo && $.geo.proj ? $.geo.proj.fromGeodetic(geom1.coordinates) : geom1.coordinates, - geom2CoordinatesProjected = !_ignoreGeo && $.geo.proj ? $.geo.proj.fromGeodetic(geom2.coordinates) : geom2.coordinates; - - switch (geom1.type) { - case "Point": - switch (geom2.type) { - case "Point": - return this._distancePointPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "LineString": - return this._distanceLineStringPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "Polygon": - return this._containsPolygonPoint(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "LineString": - switch (geom2.type) { - case "Point": - return this._distanceLineStringPoint(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "LineString": - return this._distanceLineStringLineString(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "Polygon": - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "LineString": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected[0]) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected[0]); - default: - return undefined; - } - break; - } - }, - - _distancePointPoint: function (coordinate1, coordinate2) { - var dx = coordinate2[0] - coordinate1[0], - dy = coordinate2[1] - coordinate1[1]; - return Math.sqrt((dx * dx) + (dy * dy)); - }, - - _distanceLineStringPoint: function (lineStringCoordinates, pointCoordinate) { - var minDist = pos_oo; - - if (lineStringCoordinates.length > 0) { - var a = lineStringCoordinates[0], - - apx = pointCoordinate[0] - a[0], - apy = pointCoordinate[1] - a[1]; - - if (lineStringCoordinates.length == 1) { - return Math.sqrt(apx * apx + apy * apy); - } else { - for (var i = 1; i < lineStringCoordinates.length; i++) { - var b = lineStringCoordinates[i], - - abx = b[0] - a[0], - aby = b[1] - a[1], - bpx = pointCoordinate[0] - b[0], - bpy = pointCoordinate[1] - b[1], - - d = this._distanceSegmentPoint(abx, aby, apx, apy, bpx, bpy); - - if (d == 0) { - return 0; - } - - if (d < minDist) { - minDist = d; - } - - a = b; - apx = bpx; - apy = bpy; - } - } - } - - return Math.sqrt(minDist); - }, - - _distanceSegmentPoint: function (abx, aby, apx, apy, bpx, bpy) { - var dot1 = abx * apx + aby * apy; - - if (dot1 <= 0) { - return apx * apx + apy * apy; - } - - var dot2 = abx * abx + aby * aby; - - if (dot1 >= dot2) { - return bpx * bpx + bpy * bpy; - } - - return apx * apx + apy * apy - dot1 * dot1 / dot2; - }, - - _distanceLineStringLineString: function (lineStringCoordinates1, lineStringCoordinates2) { - var minDist = pos_oo; - for (var i = 0; i < lineStringCoordinates2.length; i++) { - minDist = Math.min(minDist, this._distanceLineStringPoint(lineStringCoordinates1, lineStringCoordinates2[i])); - } - return minDist; - }, - - // - // feature - // - - _flatten: function (geom) { - // return an array of all basic geometries - // not in JTS - var geometries = [], - curGeom = 0; - switch (geom.type) { - case "Feature": - $.merge(geometries, this._flatten(geom.geometry)); - break; - - case "FeatureCollection": - for (; curGeom < geom.features.length; curGeom++) { - $.merge(geometries, this._flatten(geom.features[curGeom].geometry)); - } - break; - - case "GeometryCollection": - for (; curGeom < geom.geometries.length; curGeom++) { - $.merge(geometries, this._flatten(geom.geometries[curGeom])); - } - break; - - default: - geometries[0] = geom; - break; - } - return geometries; - }, - - // - // WKT functions - // - - _WKT: (function () { - function pointToString(value) { - return "POINT " + pointToUntaggedString(value.coordinates); - } - - function pointToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - return "(" + coordinates.join(" ") + ")"; - } - } - - function lineStringToString(value) { - return "LINESTRING " + lineStringToUntaggedString(value.coordinates); - } - - function lineStringToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var points = [] - - for (var i = 0; i < coordinates.length; i++) { - points.push(coordinates[i].join(" ")); - } - - return "(" + points + ")"; - } - } - - function polygonToString(value) { - return "POLYGON " + polygonToUntaggedString(value.coordinates); - } - - function polygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMTPY"; - } else { - var lineStrings = []; - - for (var i = 0; i < coordinates.length; i++) { - lineStrings.push(lineStringToUntaggedString(coordinates[i])); - } - - return "(" + lineStrings + ")"; - } - } - - function multiPointToString(value) { - return "MULTIPOINT " + lineStringToUntaggedString(value.coordinates); - } - - function multiLineStringToString(value) { - return "MULTILINSTRING " + polygonToUntaggedString(value.coordinates); - } - - function multiPolygonToString(value) { - return "MULTIPOLYGON " + multiPolygonToUntaggedString(value.coordinates); - } - - function multiPolygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var polygons = []; - for (var i = 0; i < coordinates.length; i++) { - polygons.push(polygonToUntaggedString(coordinates[i])); - } - return "(" + polygons + ")"; - } - } - - function geometryCollectionToString(value) { - return "GEOMETRYCOLLECTION " + geometryCollectionToUntaggedString(value.geometries); - } - - function geometryCollectionToUntaggedString(geometries) { - if (!(geometries && geometries.length)) { - return "EMPTY"; - } else { - var geometryText = []; - for (var i = 0; i < geometries.length; i++) { - geometryText.push(stringify(geometries[i])); - } - return "(" + geometries + ")"; - } - } - - function stringify(value) { - if (!(value && value.type)) { - return ""; - } else { - switch (value.type) { - case "Point": - return pointToString(value); - - case "LineString": - return lineStringToString(value); - - case "Polygon": - return polygonToString(value); - - case "MultiPoint": - return multiPointToString(value); - - case "MultiLineString": - return multiLineStringToString(value); - - case "MultiPolygon": - return multiPolygonToString(value); - - case "GeometryCollection": - return geometryCollectionToString(value); - - default: - return ""; - } - } - } - - function pointParseUntagged(wkt) { - var pointString = wkt.match(/\(\s*([\d\.-]+)\s+([\d\.-]+)\s*\)/); - return pointString && pointString.length >= 2 ? { - type: "Point", - coordinates: [ - parseFloat(pointString[1]), - parseFloat(pointString[2]) - ] - } : null; - } - - function parse(wkt) { - wkt = $.trim(wkt); - - var typeIndex = wkt.indexOf(" "); - - switch (wkt.substr(0, typeIndex).toUpperCase()) { - case "POINT": - return pointParseUntagged(wkt.substr(typeIndex + 1)); - } - } - - return { - stringify: stringify, - - parse: parse - }; - })(), - - // - // projection functions - // - - proj: (function () { - var halfPi = 1.5707963267948966192, - quarterPi = 0.7853981633974483096, - radiansPerDegree = 0.0174532925199432958, - degreesPerRadian = 57.295779513082320877, - semiMajorAxis = 6378137; - - return { - fromGeodeticPos: function (coordinate) { - if (!coordinate) { - debugger; - } - return [ - semiMajorAxis * coordinate[ 0 ] * radiansPerDegree, - semiMajorAxis * Math.log(Math.tan(quarterPi + coordinate[ 1 ] * radiansPerDegree / 2)) - ]; - }, - - fromGeodetic: function (coordinates) { - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - fromGeodeticPos = this.fromGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length == 4) { - // bbox - var min = fromGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = fromGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = fromGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - }, - - toGeodeticPos: function (coordinate) { - return [ - (coordinate[ 0 ] / semiMajorAxis) * degreesPerRadian, - (halfPi - 2 * Math.atan(1 / Math.exp(coordinate[ 1 ] / semiMajorAxis))) * degreesPerRadian - ]; - }, - - toGeodetic: function (coordinates) { - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - toGeodeticPos = this.toGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length == 4) { - // bbox - var min = toGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = toGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ]; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = toGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - } - } - })(), - - // - // service types (defined in other files) - // - - _serviceTypes: {} - } -})(jQuery, this); -(function ($, undefined) { - - var _ieVersion = (function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - while (div.innerHTML = "", a[0]) { } - return v > 6 ? v : !v; - } ()); - - $.widget("geo.geographics", { - _$elem: undefined, - _options: {}, - _trueCanvas: true, - - _width: 0, - _height: 0, - - _$canvas: undefined, - _context: undefined, - - options: { - style: { - borderRadius: "8px", - color: "#7f0000", - //fill: undefined, - fillOpacity: .2, - height: "8px", - opacity: 1, - //stroke: undefined, - strokeOpacity: 1, - strokeWidth: "2px", - visibility: "visible", - width: "8px" - } - }, - - _create: function () { - this._$elem = this.element; - this._options = this.options; - - this._$elem.css({ display: "inline-block", overflow: "hidden", textAlign: "left" }); - - if (this._$elem.css("position") == "static") { - this._$elem.css("position", "relative"); - } - - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width")); - this._height = parseInt(this._$elem.css("height")); - } - - if (document.createElement('canvas').getContext) { - this._$elem.append(''); - this._$canvas = this._$elem.children(':last'); - this._context = this._$canvas[0].getContext("2d"); - } else if (_ieVersion <= 8) { - this._trueCanvas = false; - this._$elem.append('
                            '); - this._$canvas = this._$elem.children(':last'); - - G_vmlCanvasManager.initElement(this._$canvas[0]); - this._context = this._$canvas[0].getContext("2d"); - this._$canvas.children().css({ backgroundColor: "transparent", width: this._width, height: this._height }); - } - }, - - _setOption: function (key, value) { - if (key == "style") { - value = $.extend({}, this._options.style, value); - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - destroy: function () { - $.Widget.prototype.destroy.apply(this, arguments); - this._$elem.html(""); - }, - - clear: function () { - this._context.clearRect(0, 0, this._width, this._height); - }, - - drawArc: function (coordinates, startAngle, sweepAngle, style) { - style = this._getGraphicStyle(style); - - if (style.visibility != "hidden" && style.opacity > 0 && style.widthValue > 0 && style.heightValue > 0) { - var r = Math.min(style.widthValue, style.heightValue) / 2; - - startAngle = (startAngle * Math.PI / 180); - sweepAngle = (sweepAngle * Math.PI / 180); - - this._context.save(); - this._context.translate(coordinates[0], coordinates[1]); - if (style.widthValue > style.heightValue) { - this._context.scale(style.widthValue / style.heightValue, 1); - } else { - this._context.scale(1, style.heightValue / style.widthValue); - } - - this._context.beginPath(); - this._context.arc(0, 0, r, startAngle, sweepAngle, false); - - if (this._trueCanvas) { - this._context.restore(); - } - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - if (!this._trueCanvas) { - this._context.restore(); - } - } - }, - - drawPoint: function (coordinates, style) { - var style = this._getGraphicStyle(style); - if (style.widthValue == style.heightValue && style.heightValue == style.borderRadiusValue) { - this.drawArc(coordinates, 0, 360, style); - } else if (style.visibility != "hidden" && style.opacity > 0) { - style.borderRadiusValue = Math.min(Math.min(style.widthValue, style.heightValue) / 2, style.borderRadiusValue); - coordinates[0] -= style.widthValue / 2; - coordinates[1] -= style.heightValue / 2; - this._context.beginPath(); - this._context.moveTo(coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.lineTo(coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1]); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1], coordinates[0] + style.widthValue, coordinates[1] + style.borderRadiusValue); - this._context.lineTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue, coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.lineTo(coordinates[0] + style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1] + style.heightValue, coordinates[0], coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.lineTo(coordinates[0], coordinates[1] + style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1], coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.closePath(); - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - - this._context.stroke(); - } - } - }, - - drawLineString: function (coordinates, style) { - this._drawLines([coordinates], false, style); - }, - - drawPolygon: function (coordinates, style) { - this._drawLines(coordinates, true, style); - }, - - drawBbox: function (bbox, style) { - this._drawLines([[ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ]], true, style); - }, - - _getGraphicStyle: function (style) { - function safeParse(value) { - value = parseInt(value); - return (+value + '') === value ? +value : value; - } - - style = $.extend({}, this._options.style, style); - style.borderRadiusValue = safeParse(style.borderRadius); - style.fill = style.fill || style.color; - style.doFill = style.fill && style.fillOpacity > 0; - style.stroke = style.stroke || style.color; - style.strokeWidthValue = safeParse(style.strokeWidth); - style.doStroke = style.stroke && style.strokeOpacity > 0 && style.strokeWidthValue > 0; - style.widthValue = safeParse(style.width); - style.heightValue = safeParse(style.height); - return style; - }, - - _drawLines: function (coordinates, close, style) { - if (!coordinates || !coordinates.length || coordinates[0].length < 2) { - return; - } - - var style = this._getGraphicStyle(style), - i, j; - - if (style.visibility != "hidden" && style.opacity > 0) { - this._context.beginPath(); - this._context.moveTo(coordinates[0][0][0], coordinates[0][0][1]); - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - this._context.lineTo(coordinates[i][j][0], coordinates[i][j][1]); - } - } - - if (close) { - this._context.closePath(); - } - - if (close && style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineCap = this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - } - } - }); - - -})(jQuery); - -(function ($, undefined) { - var _ieVersion = (function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - while (div.innerHTML = "", a[0]) { } - return v > 6 ? v : !v; - } ()), - - _defaultOptions = { - bbox: [-180, -85, 180, 85], - bboxMax: [-180, -85, 180, 85], - center: [0, 0], - cursors: { - pan: "move", - zoom: "crosshair", - drawPoint: "crosshair", - drawLineString: "crosshair", - drawPolygon: "crosshair" - }, - drawStyle: {}, - shapeStyle: {}, - mode: "pan", - services: [ - { - "class": "osm", - type: "tiled", - getUrl: function (view) { - return "http://tile.openstreetmap.org/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; - }, - attr: "© OpenStreetMap & contributors, CC-BY-SA" - } - ], - tilingScheme: { - tileWidth: 256, - tileHeight: 256, - levels: 18, - basePixelSize: 156543.03392799936, - origin: [-20037508.342787, 20037508.342787] - }, - zoom: 0, - pixelSize: 0 - }; - - $.widget("geo.geomap", { - // private widget members - _$elem: undefined, - _created: false, - - _contentBounds: {}, - - _$contentFrame: undefined, - _$existingChildren: undefined, - _$servicesContainer: undefined, - _$drawContainer: undefined, - _$shapesContainer: undefined, - _$textContainer: undefined, - _$textContent: undefined, - _$eventTarget: undefined, - - _dpi: 96, - - _currentServices: [], //< internal copy - - _center: undefined, - _pixelSize: undefined, - _centerMax: undefined, - _pixelSizeMax: undefined, - - _wheelZoomFactor: 1.18920711500273, - _wheelTimeout: null, - _wheelLevel: 0, - - _zoomFactor: 2, - - _mouseDown: undefined, - _inOp: undefined, - _toolPan: undefined, - _shiftZoom: undefined, - _anchor: undefined, - _current: undefined, - _downDate: undefined, - _moveDate: undefined, - _clickDate: undefined, - _lastMove: undefined, - _lastDrag: undefined, - - _windowHandler: null, - _resizeTimeout: null, - - _panning: undefined, - _velocity: undefined, - _friction: undefined, - - _supportTouch: undefined, - _softDblClick: undefined, - _isTap: undefined, - _isDbltap: undefined, - - _drawTimeout: null, //< used in drawPoint mode so we don't send two shape events on dbltap - _drawPixels: [], //< an array of coordinate arrays for drawing lines & polygons, in pixel coordinates - _drawCoords: [], - - _graphicShapes: [], //< an array of objects containing style object refs & GeoJSON object refs - - _initOptions: {}, - - _options: {}, - - options: $.extend({}, _defaultOptions), - - _createWidget: function (options, element) { - this._$elem = $(element); - - if (this._$elem.is("[data-geo-service]")) { - $.Widget.prototype._createWidget.apply(this, arguments); - return; - } - - this._$elem.attr("data-geo-map", "data-geo-map"); - - this._graphicShapes = []; - - this._initOptions = options || {}; - - this._forcePosition(this._$elem); - - this._$elem.css("text-align", "left"); - - var size = this._findMapSize(); - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left")), - y: parseInt(this._$elem.css("padding-top")), - width: size["width"], - height: size["height"] - }; - - this._createChildren(); - - this._center = this._centerMax = [0, 0]; - - this.options["pixelSize"] = this._pixelSize = this._pixelSizeMax = 156543.03392799936; - - this._mouseDown = - this._inOp = - this._toolPan = - this._shiftZoom = - this._panning = - this._isTap = - this._isDbltap = false; - - this._anchor = - this._current = - this._lastMove = - this._lastDrag = - this._velocity = [0, 0]; - - this._friction = [.8, .8]; - - this._downDate = - this._moveDate = - this._clickDate = 0; - - $.Widget.prototype._createWidget.apply(this, arguments); - }, - - _create: function () { - if (this._$elem.is("[data-geo-service]")) { - return; - } - - this._options = this.options; - - this._supportTouch = "ontouchend" in document; - this._softDblClick = this._supportTouch || _ieVersion == 7; - - var touchStartEvent = this._supportTouch ? "touchstart" : "mousedown", - touchStopEvent = this._supportTouch ? "touchend touchcancel" : "mouseup", - touchMoveEvent = this._supportTouch ? "touchmove" : "mousemove"; - - $(document).keydown($.proxy(this._document_keydown, this)); - - this._$eventTarget.dblclick($.proxy(this._eventTarget_dblclick, this)); - - this._$eventTarget.bind(touchStartEvent, $.proxy(this._eventTarget_touchstart, this)); - - var dragTarget = (this._$eventTarget[0].setCapture) ? this._$eventTarget : $(document); - dragTarget.bind(touchMoveEvent, $.proxy(this._dragTarget_touchmove, this)); - dragTarget.bind(touchStopEvent, $.proxy(this._dragTarget_touchstop, this)); - - this._$eventTarget.mousewheel($.proxy(this._eventTarget_mousewheel, this)); - - var geomap = this; - this._windowHandler = function () { - if (geomap._resizeTimeout) { - clearTimeout(geomap._resizeTimeout); - } - this._resizeTimeout = setTimeout(function () { - if (geomap._created) { - geomap._$elem.geomap("resize"); - } - }, 500); - }; - - $(window).resize(this._windowHandler); - - this._$drawContainer.geographics({ style: this._initOptions.drawStyle || {} }); - this._options["drawStyle"] = this._$drawContainer.geographics("option", "style"); - - this._$shapesContainer.geographics( { style: this._initOptions.shapeStyle || { } } ); - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - - if (this._initOptions) { - if (this._initOptions.bbox) { - this._setOption("bbox", this._initOptions.bbox, false); - } - if (this._initOptions.center) { - this._setOption("center", this._initOptions.center, false); - } - if (this._initOptions.zoom) { - this._setZoom(this._initOptions.zoom, false, false); - } - } - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._createServices(); - - this._refresh(); - - this._created = true; - }, - - _setOption: function (key, value, refresh) { - if ( this._$elem.is( "[data-geo-service]" ) || key == "pixelSize" ) { - return; - } - - refresh = (refresh === undefined || refresh); - - switch (key) { - case "bbox": - if ($.geo.proj) { - value = $.geo.proj.fromGeodetic([[value[0], value[1]], [value[2], value[3]]]); - value = [value[0][0], value[0][1], value[1][0], value[1][1]]; - } - - this._setBbox(value, false, refresh); - value = this._getBbox(); - - if ($.geo.proj) { - value = $.geo.proj.toGeodetic([[value[0], value[1]], [value[2], value[3]]]); - value = [value[0][0], value[0][1], value[1][0], value[1][1]]; - } - break; - - case "center": - this._setCenterAndSize($.geo.proj ? $.geo.proj.fromGeodetic([[value[0], value[1]]])[0] : value, this._pixelSize, false, refresh); - break; - - case "drawStyle": - if (this._$drawContainer) { - this._$drawContainer.geographics("option", "style", value); - value = this._$drawContainer.geographics("option", "style"); - } - break; - - case "shapeStyle": - if (this._$shapesContainer) { - this._$shapesContainer.geographics("option", "style", value); - value = this._$shapesContainer.geographics("option", "style"); - } - break; - - case "mode": - this._$drawContainer.geographics("clear"); - this._$eventTarget.css("cursor", this._options["cursors"][value]); - break; - - case "zoom": - this._setZoom(value, false, refresh); - break; - } - - $.Widget.prototype._setOption.apply(this, arguments); - - switch (key) { - case "services": - this._createServices(); - if (refresh) { - this._refresh(); - } - break; - - case "shapeStyle": - if ( refresh ) { - this._$shapesContainer.geographics("clear"); - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes ); - } - break; - } - }, - - destroy: function () { - if (this._$elem.is("[data-geo-map]")) { - this._created = false; - - $(window).unbind("resize", this._windowHandler); - - for ( var i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[i].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._$shapesContainer.geographics("destroy"); - this._$drawContainer.geographics("destroy"); - - this._$existingChildren.detach(); - this._$elem.html(""); - this._$elem.append(this._$existingChildren); - this._$elem.removeAttr("data-geo-map"); - } - $.Widget.prototype.destroy.apply(this, arguments); - }, - - toMap: function (p) { - p = this._toMap(p); - return $.geo.proj ? $.geo.proj.toGeodetic(p) : p; - }, - - toPixel: function ( p, _center /* Internal Use Only */, _pixelSize /* Internal Use Only */ ) { - p = $.geo.proj ? $.geo.proj.fromGeodetic(p) : p; - return this._toPixel(p, _center, _pixelSize); - }, - - opacity: function (value, _serviceContainer) { - if (this._$elem.is("[data-geo-service]")) { - this._$elem.closest("[data-geo-map]").geomap("opacity", value, this._$elem); - } else { - if (value >= 0 || value <= 1) { - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[i]; - if ( !_serviceContainer || service.serviceContainer[0] == _serviceContainer[0] ) { - this._options["services"][i].opacity = service.opacity = value; - $.geo["_serviceTypes"][service.type].opacity(this, service); - } - } - } - } - }, - - toggle: function (value, _serviceContainer) { - if (this._$elem.is("[data-geo-service]")) { - this._$elem.closest("[data-geo-map]").geomap("toggle", value, this._$elem); - } else { - for (var i = 0; i < this._currentServices.length; i++) { - var service = this._currentServices[i]; - if (!_serviceContainer || service.serviceContainer[0] == _serviceContainer[0]) { - if (value === undefined) { - value = (service.visibility === undefined || service.visibility === "visible" ? false : true); - } - - this._options["services"][i].visibility = service.visibility = ( value ? "visible" : "hidden" ); - $.geo["_serviceTypes"][service.type].toggle(this, service); - - if (value) { - $.geo["_serviceTypes"][service.type].refresh(this, service); - } - } - } - } - }, - - zoom: function (numberOfLevels) { - if (numberOfLevels != null) { - this._setZoom(this._options["zoom"] + numberOfLevels, false, true); - } - }, - - refresh: function () { - this._refresh(); - }, - - resize: function () { - var size = this._findMapSize(), - dx = size["width"]/2 - this._contentBounds.width/2, - dy = size["height"]/2 - this._contentBounds.height/2, - i; - - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left")), - y: parseInt(this._$elem.css("padding-top")), - width: size["width"], - height: size["height"] - }; - - this._$contentFrame.css({ - width: size["width"], - height: size["height"] - }); - - this._$servicesContainer.css({ - width: size["width"], - height: size["height"] - }); - - this._$eventTarget.css({ - width: size["width"], - height: size["height"] - }); - - var shapeStyle = this._$shapesContainer.geographics("option", "style"); - - this._$shapesContainer.geographics("destroy"); - this._$drawContainer.geographics("destroy"); - - for (i = 0; i < this._currentServices.length; i++) { - $.geo["_serviceTypes"][this._currentServices[i].type].resize(this, this._currentServices[i]); - } - - - this._$drawContainer.css({ - width: size.width, - height: size.height - }); - this._$drawContainer.geographics(); - - this._$shapesContainer.css({ - width: size.width, - height: size.height - }); - this._$shapesContainer.geographics( { style: shapeStyle } ); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._setCenterAndSize(this._center, this._pixelSize, false, true); - }, - - append: function ( shape, style, refresh ) { - if ( shape ) { - var shapes, i = 0; - if ( shape.type == "FeatureCollection" ) { - shapes = shape.features; - } else { - shapes = $.isArray( shape ) ? shape : [ shape ]; - } - - if ( typeof style === "boolean" ) { - refresh = style; - style = null; - } - - for ( ; i < shapes.length; i++ ) { - if ( shapes[ i ].type != "Point" ) { - var bbox = $.geo.bbox( shapes[ i ] ); - if ( $.geo.proj ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - $.data( shapes[ i ], "geoBbox", bbox ); - } - - this._graphicShapes.push( { - shape: shapes[ i ], - style: style - } ); - } - - if ( refresh === undefined || refresh ) { - this._refresh( ); - } - } - }, - - empty: function ( refresh ) { - $.each( this._graphicShapes, function( ) { - $.removeData( this, "geoBbox" ); - } ); - this._graphicShapes = []; - if ( refresh === undefined || refresh ) { - this._refresh(); - } - }, - - find: function (point, pixelTolerance) { - var searchPixel = this.toPixel( point.coordinates ), - mapTol = this._pixelSize * pixelTolerance, - result = [], - curGeom; - - $.each( this._graphicShapes, function ( i ) { - if ( this.shape.type == "Point" ) { - if ( $.geo.distance(this.shape, point) <= mapTol ) { - result.push( this.shape ); - } - } else { - var bbox = $.data( this.shape, "geoBbox" ), - bboxPolygon = { - type: "Polygon", - coordinates: [ [ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ] ] - }, - projectedPoint = { - type: "Point", - coordinates: $.geo.proj ? $.geo.proj.fromGeodetic( point.coordinates ) : point.coordinates - }; - - if ( $.geo.distance( bboxPolygon, projectedPoint, true ) <= mapTol ) { - var geometries = $.geo._flatten( this.shape ); - for ( curGeom = 0; curGeom < geometries.length; curGeom++ ) { - if ( $.geo.distance( geometries[curGeom], point ) <= mapTol ) { - result.push( this.shape ); - break; - } - } - } - } - }); - - return result; - }, - - remove: function ( shape, refresh ) { - var geomap = this; - $.each( this._graphicShapes, function ( i ) { - if ( this.shape == shape ) { - $.removeData( shape, "geoBbox" ); - var rest = geomap._graphicShapes.slice( i + 1 ); - geomap._graphicShapes.length = i; - geomap._graphicShapes.push.apply(geomap._graphicShapes, rest); - return false; - } - }); - - if ( refresh === undefined || refresh ) { - this._refresh(); - } - }, - - _getBbox: function (center, pixelSize) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - // calculate the internal bbox - var halfWidth = this._contentBounds["width"] / 2 * pixelSize, - halfHeight = this._contentBounds["height"] / 2 * pixelSize; - return [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight]; - }, - - _setBbox: function (value, trigger, refresh) { - var center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2], - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height); - - if (this._options["tilingScheme"]) { - var zoom = this._getTiledZoom(pixelSize); - pixelSize = this._getTiledPixelSize(zoom); - } - this._setCenterAndSize(center, pixelSize, trigger, refresh); - }, - - _getBboxMax: function () { - // calculate the internal bboxMax - var halfWidth = this._contentBounds["width"] / 2 * this._pixelSizeMax, - halfHeight = this._contentBounds["height"] / 2 * this._pixelSizeMax; - return [this._centerMax[0] - halfWidth, this._centerMax[1] - halfHeight, this._centerMax[0] + halfWidth, this._centerMax[1] + halfHeight]; - }, - - _getCenter: function () { - return this._center; - }, - - _getContentBounds: function () { - return this._contentBounds; - }, - - _getServicesContainer: function () { - return this._$servicesContainer; - }, - - _getZoom: function () { - // calculate the internal zoom level, vs. public zoom property - if (this._options["tilingScheme"]) { - return this._getTiledZoom(this._pixelSize); - } else { - var ratio = this._contentBounds["width"] / this._contentBounds["height"], - bbox = $.geo.reaspect(this._getBbox(), ratio, true), - bboxMax = $.geo.reaspect(this._getBboxMax(), ratio, true); - - return Math.log($.geo.width(bboxMax, true) / $.geo.width(bbox, true)) / Math.log(this._zoomFactor); - } - }, - - _setZoom: function (value, trigger, refresh) { - value = Math.max(value, 0); - - if (this._options["tilingScheme"]) { - this._setCenterAndSize(this._center, this._getTiledPixelSize(value), trigger, refresh); - } else { - var bbox = $.geo.scaleBy(this._getBboxMax(), 1 / Math.pow(this._zoomFactor, value), true), - pixelSize = Math.max($.geo.width(bbox, true) / this._contentBounds.width, $.geo.height(bbox, true) / this._contentBounds.height); - this._setCenterAndSize(this._center, pixelSize, trigger, refresh); - } - }, - - _createChildren: function () { - this._$existingChildren = this._$elem.children().detach(); - - this._forcePosition(this._$existingChildren); - - this._$existingChildren.css("-moz-user-select", "none"); - - this._$elem.prepend("
                            "); - this._$eventTarget = this._$contentFrame = this._$elem.children(':first'); - - this._$contentFrame.append('
                            '); - this._$servicesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                            '); - this._$shapesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                            '); - this._$drawContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append(''); - this._$textContainer = this._$contentFrame.children(':last'); - this._$textContent = this._$textContainer.children(); - - this._$contentFrame.append(this._$existingChildren); - }, - - _createServices: function () { - var i; - - for (i = 0; i < this._currentServices.length; i++) { - this._currentServices[i].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._currentServices = []; - for (i = 0; i < this._options["services"].length; i++) { - this._currentServices[i] = this._options["services"][i]; - this._currentServices[i].serviceContainer = $.geo["_serviceTypes"][this._currentServices[i].type].create(this, this._$servicesContainer, this._currentServices[i], i).geomap(); - } - }, - - _refreshDrawing: function () { - this._$drawContainer.geographics("clear"); - - if ( this._drawPixels.length > 0 ) { - var mode = this._options[ "mode" ], - coords = this._drawPixels; - - if ( mode == "drawPolygon" ) { - coords = [ coords ]; - } - - this._$drawContainer.geographics( mode, coords ); - } - }, - - _resetDrawing: function () { - //this._$textContainer.hide(); - this._drawPixels = []; - this._drawCoords = []; - this._$drawContainer.geographics("clear"); - }, - - _refreshShapes: function (geographics, shapes, styles, center, pixelSize) { - var i, - mgi, - shape, - shapeBbox, - style, - pixelPositions, - bbox = this._getBbox(center, pixelSize), - geomap = this; - - for (i = 0; i < shapes.length; i++) { - shape = shapes[i].shape || shapes[i]; - shape = shape.geometry || shape; - shapeBbox = $.data(shape, "geoBbox"); - - if ( shapeBbox && $.geo._bboxDisjoint( bbox, shapeBbox ) ) { - continue; - } - - style = $.isArray(styles) ? styles[i].style : styles; - - switch (shape.type) { - case "Point": - this._$shapesContainer.geographics("drawPoint", this.toPixel(shape.coordinates, center, pixelSize), style); - break; - case "LineString": - this._$shapesContainer.geographics("drawLineString", this.toPixel(shape.coordinates, center, pixelSize), style); - break; - case "Polygon": - pixelPositions = []; - $.each(shape.coordinates, function (i) { - pixelPositions[i] = geomap.toPixel(this, center, pixelSize); - }); - this._$shapesContainer.geographics("drawPolygon", pixelPositions, style); - break; - case "MultiPoint": - for (mgi = 0; mgi < shape.coordinates; mgi++) { - this._$shapesContainer.geographics("drawPoint", this.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - break; - case "MultiLineString": - for (mgi = 0; mgi < shape.coordinates; mgi++) { - this._$shapesContainer.geographics("drawLineString", this.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - break; - case "MultiPolygon": - for (mgi = 0; mgi < shape.coordinates; mgi++) { - pixelPositions = []; - $.each(shape.coordinates[mgi], function (i) { - pixelPositions[i] = geomap.toPixel(this, center, pixelSize); - }); - this._$shapesContainer.geographics("drawPolygon", pixelPositions, style); - } - break; - - case "GeometryCollection": - geomap._refreshShapes(geographics, shape.geometries, style, center, pixelSize); - break; - } - } - }, - - _findMapSize: function () { - // really, really attempt to find a size for this thing - // even if it's hidden (look at parents) - var size = { width: 0, height: 0 }, - sizeContainer = this._$elem; - - while (sizeContainer.size() && !(size["width"] > 0 && size["height"] > 0)) { - size = { width: sizeContainer.width(), height: sizeContainer.height() }; - if (size["width"] <= 0 || size["height"] <= 0) { - size = { width: parseInt(sizeContainer.css("width")), height: parseInt(sizeContainer.css("height")) }; - } - sizeContainer = sizeContainer.parent(); - } - return size; - }, - - _forcePosition: function (elem) { - var cssPosition = elem.css("position"); - if (cssPosition != "relative" && cssPosition != "absolute" && cssPosition != "fixed") { - elem.css("position", "relative"); - } - }, - - _getTiledPixelSize: function (zoom) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme != null) { - if (zoom === 0) { - return tilingScheme.pixelSizes != null ? tilingScheme.pixelSizes[0] : tilingScheme.basePixelSize; - } - - zoom = Math.round(zoom); - zoom = Math.max(zoom, 0); - var levels = tilingScheme.pixelSizes != null ? tilingScheme.pixelSizes.length : tilingScheme.levels; - zoom = Math.min(zoom, levels - 1); - - if (tilingScheme.pixelSizes != null) { - return tilingScheme.pixelSizes[zoom]; - } else { - return tilingScheme.basePixelSize / Math.pow(2, zoom); - } - } else { - return NaN; - } - }, - - _getTiledZoom: function (pixelSize) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme.pixelSizes != null) { - var roundedPixelSize = Math.floor(pixelSize * 1000), - levels = tilingScheme.pixelSizes != null ? tilingScheme.pixelSizes.length : tilingScheme.levels; - for (var i = levels - 1; i >= 0; i--) { - if (Math.floor(tilingScheme.pixelSizes[i] * 1000) >= roundedPixelSize) { - return i; - } - } - return 0; - } else { - return Math.max(Math.round(Math.log(tilingScheme.basePixelSize / pixelSize) / Math.log(2)), 0); - } - }, - - _getZoomCenterAndSize: function (anchor, zoomDelta, zoomFactor) { - var pixelSize, zoomLevel, scale; - if (this._options["tilingScheme"]) { - zoomLevel = this._getTiledZoom(this._pixelSize) + zoomDelta; - pixelSize = this._getTiledPixelSize(zoomLevel); - } else { - scale = Math.pow(zoomFactor, -zoomDelta); - pixelSize = this._pixelSize * scale; - } - - var - ratio = pixelSize / this._pixelSize, - anchorMapCoord = this._toMap(anchor), - centerDelta = [(this._center[0] - anchorMapCoord[0]) * ratio, (this._center[1] - anchorMapCoord[1]) * ratio], - scaleCenter = [anchorMapCoord[0] + centerDelta[0], anchorMapCoord[1] + centerDelta[1]]; - - return { pixelSize: pixelSize, center: scaleCenter }; - }, - - _mouseWheelFinish: function () { - this._wheelTimeout = null; - - if (this._wheelLevel != 0) { - var wheelCenterAndSize = this._getZoomCenterAndSize(this._anchor, this._wheelLevel, this._wheelZoomFactor); - - this._setCenterAndSize(wheelCenterAndSize.center, wheelCenterAndSize.pixelSize, true, true); - - this._wheelLevel = 0; - } else { - this._refresh(); - } - }, - - _panEnd: function () { - this._velocity = [ - (this._velocity[0] > 0 ? Math.floor(this._velocity[0] * this._friction[0]) : Math.ceil(this._velocity[0] * this._friction[0])), - (this._velocity[1] > 0 ? Math.floor(this._velocity[1] * this._friction[1]) : Math.ceil(this._velocity[1] * this._friction[1])) - ]; - - if (Math.abs(this._velocity[0]) < 4 && Math.abs(this._velocity[1]) < 4) { - this._panFinalize(); - } else { - this._current = [ - this._current[0] + this._velocity[0], - this._current[1] + this._velocity[1] - ]; - - this._panMove(); - setTimeout($.proxy(this._panEnd, this), 30); - } - }, - - _panFinalize: function () { - if (this._panning) { - this._velocity = [0, 0]; - - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - dxMap = -dx * this._pixelSize, - dyMap = dy * this._pixelSize; - - this._$shapesContainer.css({ left: 0, top: 0 }); - - this._setCenterAndSize([this._center[0] + dxMap, this._center[1] + dyMap], this._pixelSize, true, true); - - this._inOp = false; - this._anchor = this._current; - this._toolPan = this._panning = false; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - } - }, - - _panMove: function () { - var dx = this._current[0] - this._lastDrag[0], - dy = this._current[1] - this._lastDrag[1], - i = 0, - service; - - if (this._toolPan || dx > 3 || dx < -3 || dy > 3 || dy < -3) { - if (!this._toolPan) { - this._toolPan = true; - this._$eventTarget.css("cursor", this._options["cursors"]["pan"]); - } - - if (this._mouseDown) { - this._velocity = [dx, dy]; - } - - if (dx != 0 || dy != 0) { - this._panning = true; - this._lastDrag = this._current; - - for (i = 0; i < this._options["services"].length; i++) { - service = this._options["services"][i]; - $.geo["_serviceTypes"][service.type].interactivePan(this, service, dx, dy); - } - - this._$shapesContainer.css({ - left: function (index, value) { - return parseInt(value) + dx; - }, - top: function (index, value) { - return parseInt(value) + dy; - } - }); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._refreshDrawing(); - } - } - }, - - _refresh: function () { - for (var i = 0; i < this._options["services"].length; i++) { - var service = this._options["services"][i]; - if (!this._mouseDown && $.geo["_serviceTypes"][service.type] != null) { - $.geo["_serviceTypes"][service.type].refresh(this, service); - } - } - - if (this._$shapesContainer) { - this._$shapesContainer.geographics("clear"); - if (this._graphicShapes.length > 0) { - this._refreshShapes(this._$shapesContainer, this._graphicShapes, this._graphicShapes); - } - } - }, - - _setCenterAndSize: function (center, pixelSize, trigger, refresh) { - // the final call during any extent change - if (this._pixelSize != pixelSize) { - this._$shapesContainer.geographics("clear"); - for (var i = 0; i < this._options["services"].length; i++) { - var service = this._options["services"][i]; - $.geo["_serviceTypes"][service.type].interactiveScale(this, service, center, pixelSize); - } - } - - this._center = center; - this.options["pixelSize"] = this._pixelSize = pixelSize; - - if ($.geo.proj) { - var bbox = this._getBbox(); - bbox = $.geo.proj.toGeodetic([[bbox[0], bbox[1]], [bbox[2], bbox[3]]]); - bbox = [bbox[0][0], bbox[0][1], bbox[1][0], bbox[1][1]]; - this._options["bbox"] = bbox; - - this._options["center"] = $.geo.proj.toGeodetic([[this._center[0], this._center[1]]])[0]; - } else { - this._options["bbox"] = this._getBbox(); - - this._options["center"] = this._center; - } - - this._options["zoom"] = this._getZoom(); - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel(this._drawCoords); - } - - if (trigger) { - this._trigger("bboxchange", window.event, { bbox: this._options["bbox"] }); - } - - if (refresh) { - this._refresh(); - this._refreshDrawing(); - } - }, - - _toMap: function (p, center, pixelSize) { - // ignores $.geo.proj - var isArray = $.isArray(p[0]); - if (!isArray) { - p = [p]; - } - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - xRatio = $.geo.width(bbox, true) / width, - yRatio = $.geo.height(bbox, true) / height, - result = []; - - $.each(p, function (i) { - var yOffset = (this[1] * yRatio); - result[i] = [bbox[0] + (this[0] * xRatio), bbox[3] - yOffset]; - }); - - return isArray ? result : result[0]; - }, - - _toPixel: function (p, center, pixelSize) { - // ignores $.geo.proj - var isArray = $.isArray(p[0]); - if (!isArray) { - p = [p]; - } - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - bboxWidth = $.geo.width(bbox, true), - bboxHeight = $.geo.height(bbox, true), - result = []; - - $.each(p, function (i) { - result[i] = [ - Math.round((this[0] - bbox[0]) * width / bboxWidth), - Math.round((bbox[3] - this[1]) * height / bboxHeight) - ]; - }); - - return isArray ? result : result[0]; - }, - - _zoomTo: function (coord, zoom, trigger, refresh) { - zoom = zoom < 0 ? 0 : zoom; - - var tiledPixelSize = this._getTiledPixelSize(zoom); - - if (!isNaN(tiledPixelSize)) { - this._setCenterAndSize(coord, tiledPixelSize, trigger, refresh); - } else { - var bboxMax = $.geo._scaleBy(this._getBboxMax(), 1 / Math.pow(this._zoomFactor, zoom), true), - pixelSize = Math.max($.geo.width(bboxMax, true) / this._contentBounds["width"], $.geo.height(bboxMax, true) / this._contentBounds["height"]); - - this._setCenterAndSize(coord, pixelSize, trigger, refresh); - } - }, - - _document_keydown: function (e) { - var len = this._drawCoords.length; - if (len > 0 && e.which == 27) { - if (len <= 2) { - this._resetDrawing(); - this._inOp = false; - } else { - this._drawCoords[len - 2] = $.merge( [], this._drawCoords[ len - 1 ] ); - this._drawPixels[len - 2] = $.merge( [], this._drawPixels[ len - 1 ] ); - - this._drawCoords.length--; - this._drawPixels.length--; - - this._refreshDrawing(); - } - } - }, - - _eventTarget_dblclick_zoom: function(e) { - this._trigger("dblclick", e, { type: "Point", coordinates: this.toMap(this._current) }); - if (!e.isDefaultPrevented()) { - var centerAndSize = this._getZoomCenterAndSize(this._current, 1, this._zoomFactor); - this._setCenterAndSize(centerAndSize.center, centerAndSize.pixelSize, true, true); - } - }, - - _eventTarget_dblclick: function (e) { - this._panFinalize(); - - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - var offset = $(e.currentTarget).offset(); - - switch (this._options["mode"]) { - case "pan": - case "drawPoint": - this._eventTarget_dblclick_zoom(e); - break; - - case "drawLineString": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - this._drawCoords.length--; - this._trigger( "shape", e, { - type: "LineString", - coordinates: $.geo.proj ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords - } ); - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "drawPolygon": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - var endIndex = this._drawCoords.length - 1; - if (endIndex > 2) { - this._drawCoords[endIndex] = $.merge( [], this._drawCoords[0] ); - this._trigger( "shape", e, { - type: "Polygon", - coordinates: [ $.geo.proj ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords ] - } ); - } - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - } - - this._inOp = false; - }, - - _eventTarget_touchstart: function (e) { - if (!this._supportTouch && e.which != 1) { - return; - } - - this._panFinalize(); - this._mouseWheelFinish(); - - var offset = $(e.currentTarget).offset(); - - if (this._supportTouch) { - this._current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } else { - this._current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - var downDate = $.now(); - if (downDate - this._downDate < 750) { - if (this._isTap) { - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance > 10) { - this._isTap = false; - } else { - this._current = this._anchor; - } - } - - if (this._isDbltap) { - this._isDbltap = false; - } else { - this._isDbltap = this._isTap; - } - } else { - this._isDbltap = false; - } - this._isTap = true; - this._downDate = downDate; - } - - - this._mouseDown = true; - this._anchor = this._current; - - if (!this._inOp && e.shiftKey) { - this._shiftZoom = true; - this._$eventTarget.css("cursor", this._options["cursors"]["zoom"]); - } else { - this._inOp = true; - - switch (this._options["mode"]) { - case "pan": - case "drawPoint": - case "drawLineString": - case "drawPolygon": - this._lastDrag = this._current; - - if (e.currentTarget.setCapture) { - e.currentTarget.setCapture(); - } - - break; - } - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchmove: function (e) { - var offset = this._$eventTarget.offset(), - drawCoordsLen = this._drawCoords.length, - current; - - if (this._supportTouch) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (current[0] === this._lastMove[0] && current[1] === this._lastMove[1]) { - if ( this._inOp ) { - e.preventDefault(); - return false; - } - } - - if (this._softDblClick) { - this._isDbltap = this._isTap = false; - } - - if (this._mouseDown) { - this._current = current; - this._moveDate = $.now(); - } - - var mode = this._shiftZoom ? "zoom" : this._options["mode"]; - - switch (mode) { - case "zoom": - if ( this._mouseDown ) { - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawBbox", [ - this._anchor[ 0 ], - this._anchor[ 1 ], - current[ 0 ], - current[ 1 ] - ] ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "pan": - case "drawPoint": - if (this._mouseDown || this._toolPan) { - this._panMove(); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "drawLineString": - case "drawPolygon": - if (this._mouseDown || this._toolPan) { - this._panMove(); - } else { - if (drawCoordsLen > 0) { - this._drawCoords[drawCoordsLen - 1] = this._toMap(current); - this._drawPixels[drawCoordsLen - 1] = current; - - this._refreshDrawing(); - } - - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - } - - this._lastMove = current; - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchstop: function (e) { - if (!this._mouseDown && _ieVersion == 7) { - // ie7 doesn't appear to trigger dblclick on this._$eventTarget, - // we fake regular click here to cause soft dblclick - this._eventTarget_touchstart(e); - } - - var mouseWasDown = this._mouseDown, - wasToolPan = this._toolPan, - offset = this._$eventTarget.offset(), - mode = this._shiftZoom ? "zoom" : this._options["mode"], - current, i, clickDate, - dx, dy; - - if (this._supportTouch) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._shiftZoom = this._mouseDown = this._toolPan = false; - - if (document.releaseCapture) { - document.releaseCapture(); - } - - if (mouseWasDown) { - clickDate = $.now(); - this._current = current; - - switch (mode) { - case "zoom": - if ( dx > 0 || dy > 0 ) { - var minSize = this._pixelSize * 6, - bboxCoords = this._toMap( [ [ - Math.min( this._anchor[ 0 ], current[ 0 ] ), - Math.max( this._anchor[ 1 ], current[ 1 ] ) - ], [ - Math.max( this._anchor[ 0 ], current[ 0 ] ), - Math.min( this._anchor[ 1 ], current[ 1 ] ) - ] - ] ), - bbox = [ - bboxCoords[0][0], - bboxCoords[0][1], - bboxCoords[1][0], - bboxCoords[1][1] - ]; - - if ( ( bbox[2] - bbox[0] ) < minSize && ( bbox[3] - bbox[1] ) < minSize ) { - bbox = $.geo.scaleBy( this._getBbox( $.geo.center( bbox, true ) ), .5, true ); - } - - this._setBbox(bbox, true, true); - } - - this._resetDrawing(); - break; - - case "pan": - if (wasToolPan) { - this._panEnd(); - } else { - if (clickDate - this._clickDate > 100) { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - this._inOp = false; - } - } - break; - - case "drawPoint": - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - var geomap = this; - this._drawTimeout = setTimeout(function () { - if (geomap._drawTimeout) { - geomap._trigger("shape", e, { type: "Point", coordinates: geomap.toMap(current) }); - geomap._inOp = false; - geomap._drawTimeout = false; - } - }, 250); - } - } - break; - - case "drawLineString": - case "drawPolygon": - if (wasToolPan) { - this._panFinalize(); - } else { - i = (this._drawCoords.length == 0 ? 0 : this._drawCoords.length - 1); - - this._drawCoords[i] = this._toMap(current); - this._drawPixels[i] = current; - - if (i < 2 || !(this._drawCoords[i][0] == this._drawCoords[i-1][0] && - this._drawCoords[i][1] == this._drawCoords[i-1][1])) { - this._drawCoords[i + 1] = this._toMap(current); - this._drawPixels[i + 1] = current; - } - - this._refreshDrawing(); - } - break; - } - - this._clickDate = clickDate; - - if (this._softDblClick && this._isDbltap) { - this._isDbltap = this._isTap = false; - this._$eventTarget.trigger("dblclick", e); - } - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _eventTarget_mousewheel: function (e, delta) { - e.preventDefault(); - - this._panFinalize(); - - if (this._mouseDown) { - return false; - } - - if (delta != 0) { - if (this._wheelTimeout) { - window.clearTimeout(this._wheelTimeout); - this._wheelTimeout = null; - } else { - var offset = $(e.currentTarget).offset(); - this._anchor = [e.pageX - offset.left, e.pageY - offset.top]; - } - - this._wheelLevel += delta; - - var wheelCenterAndSize = this._getZoomCenterAndSize(this._anchor, this._wheelLevel, this._wheelZoomFactor); - - this._$shapesContainer.geographics("clear"); - - for (i = 0; i < this._options["services"].length; i++) { - var service = this._options["services"][i]; - $.geo["_serviceTypes"][service.type].interactiveScale(this, service, wheelCenterAndSize.center, wheelCenterAndSize.pixelSize); - } - - this._$shapesContainer.geographics("clear"); - if (this._graphicShapes.length > 0 && this._graphicShapes.length < 256) { - this._refreshShapes(this._$shapesContainer, this._graphicShapes, this._graphicShapes, wheelCenterAndSize.center, wheelCenterAndSize.pixelSize); - } - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel(this._drawCoords, wheelCenterAndSize.center, wheelCenterAndSize.pixelSize); - this._refreshDrawing(); - } - - var geomap = this; - this._wheelTimeout = window.setTimeout(function () { - geomap._mouseWheelFinish(); - }, 1000); - } - - return false; - } - } - ); -})(jQuery); - -(function ($, undefined) { - $.geo._serviceTypes.tiled = (function () { - return { - create: function (map, servicesContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0, - reloadTiles: false - }; - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = service["class"] ? ' class="' + service["class"] + '"' : "", - scHtml = '
                            '; - - servicesContainer.append(scHtml); - - serviceState.serviceContainer = servicesContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, servicesContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactivePan: function ( map, service, dx, dy ) { - var serviceState = $.data( service, "geoServiceState" ); - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).css( { - left: function ( index, value ) { - return parseInt( value ) + dx; - }, - top: function ( index, value ) { - return parseInt( value ) + dy; - } - }); - - if ( service && ( service.visibility === undefined || service.visibility === "visible" ) ) { - var pixelSize = map._pixelSize, - - serviceContainer = serviceState.serviceContainer, - scaleContainer = serviceContainer.children("[data-pixelSize='" + pixelSize + "']"), - - /* same as refresh 1 */ - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - /* end same as refresh 1 */ - - halfWidth = mapWidth / 2 * pixelSize, - halfHeight = mapHeight / 2 * pixelSize, - - currentPosition = scaleContainer.position(), - scaleOriginParts = scaleContainer.data("scaleOrigin").split(","), - totalDx = parseInt(scaleOriginParts[0]) - currentPosition.left, - totalDy = parseInt(scaleOriginParts[1]) - currentPosition.top, - - mapCenterOriginal = map._getCenter(), - mapCenter = [mapCenterOriginal[0] + totalDx * pixelSize, mapCenterOriginal[1] - totalDy * pixelSize], - - /* same as refresh 2 */ - tileX = Math.floor(((mapCenter[0] - halfWidth) - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.floor((tilingScheme.origin[1] - (mapCenter[1] + halfHeight)) / (pixelSize * tileHeight)), - tileX2 = Math.ceil(((mapCenter[0] + halfWidth) - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil((tilingScheme.origin[1] - (mapCenter[1] - halfHeight)) / (pixelSize * tileHeight)), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getTiledPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] - bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMaxY = tilingScheme.origin[1] - (fullYAtScale * tileHeight) * pixelSize, - /* end same as refresh 2 */ - - serviceLeft = Math.round((fullXMinX - (mapCenterOriginal[0] - halfWidth)) / pixelSize), - serviceTop = Math.round(((mapCenterOriginal[1] + halfHeight) - fullYMaxY) / pixelSize), - - opacity = (service.opacity === undefined ? 1 : service.opacity), - - x, y; - - for ( x = tileX; x < tileX2; x++ ) { - for ( y = tileY; y < tileY2; y++ ) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ( $img.size( ) === 0 ) { - /* same as refresh 3 */ - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] - (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] - ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - imageUrl = service.getUrl( { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - } ); - /* end same as refresh 3 */ - - serviceState.loadCount++; - //this._map._requestQueued(); - - if ( serviceState.reloadTiles && $img.size() > 0 ) { - $img.attr( "src", imageUrl ); - } else { - /* same as refresh 4 */ - var imgMarkup = ""; - - scaleContainer.append( imgMarkup ); - $img = scaleContainer.children(":last"); - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixelSize='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixelSize='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", imageUrl); - /* end same as refresh 4 */ - } - } - } - } - } - } - }, - - interactiveScale: function (map, service, center, pixelSize) { - var serviceState = $.data( service, "geoServiceState" ); - - if ( serviceState && service && ( service.visibility === undefined || service.visibility === "visible" ) ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight; - - - serviceContainer.children( ).each( function ( i ) { - var $scaleContainer = $(this), - scaleRatio = $scaleContainer.attr("data-pixelSize") / pixelSize; - - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var scaleOriginParts = $scaleContainer.data("scaleOrigin").split(","), - oldMapCoord = map._toMap([scaleOriginParts[0], scaleOriginParts[1]]), - newPixelPoint = map._toPixel(oldMapCoord, center, pixelSize); - - $scaleContainer.css( { - left: Math.round(newPixelPoint[0]) + "px", - top: Math.round(newPixelPoint[1]) + "px", - width: tileWidth * scaleRatio, - height: tileHeight * scaleRatio - } ); - - if ( $("body")[0].filters !== undefined ) { - $scaleContainer.children().each( function ( i ) { - $( this ).css( "filter", "progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11=" + scaleRatio + ",M22=" + scaleRatio + ",sizingmethod='auto expand')" ); - } ); - } - }); - } - }, - - refresh: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if ( serviceState && service && ( service.visibility === undefined || service.visibility === "visible" ) ) { - this._cancelUnloaded(map, service); - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - $serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - - tileX = Math.floor((bbox[0] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.floor((tilingScheme.origin[1] - bbox[3]) / (pixelSize * tileHeight)), - tileX2 = Math.ceil((bbox[2] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil((tilingScheme.origin[1] - bbox[1]) / (pixelSize * tileHeight)), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getTiledPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] - bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMaxY = tilingScheme.origin[1] - (fullYAtScale * tileHeight) * pixelSize, - - serviceLeft = Math.round((fullXMinX - bbox[0]) / pixelSize), - serviceTop = Math.round((bbox[3] - fullYMaxY) / pixelSize), - - scaleContainers = $serviceContainer.children().show(), - scaleContainer = scaleContainers.filter("[data-pixelSize='" + pixelSize + "']").appendTo($serviceContainer), - - opacity = (service.opacity === undefined ? 1 : service.opacity), - - x, y; - - if (serviceState.reloadTiles) { - scaleContainers.find("img").attr("data-dirty", "true"); - } - - if (!scaleContainer.size()) { - $serviceContainer.append("
                            "); - scaleContainer = $serviceContainer.children(":last").data("scaleOrigin", (serviceLeft % tileWidth) + "," + (serviceTop % tileHeight)); - } else { - scaleContainer.css({ - left: (serviceLeft % tileWidth) + "px", - top: (serviceTop % tileHeight) + "px" - }).data("scaleOrigin", (serviceLeft % tileWidth) + "," + (serviceTop % tileHeight)); - - scaleContainer.children().each(function (i) { - var - $img = $(this), - tile = $img.attr("data-tile").split(","); - - $img.css({ - left: Math.round(((parseInt(tile[0]) - fullXAtScale) * 100) + (serviceLeft - (serviceLeft % tileWidth)) / tileWidth * 100) + "%", - top: Math.round(((parseInt(tile[1]) - fullYAtScale) * 100) + (serviceTop - (serviceTop % tileHeight)) / tileHeight * 100) + "%" - }); - - if (opacity < 1) { - $img.fadeTo(0, opacity); - } - }); - } - - for (x = tileX; x < tileX2; x++) { - for (y = tileY; y < tileY2; y++) { - var - tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ($img.size() === 0 || serviceState.reloadTiles) { - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] - (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] - ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - imageUrl = service.getUrl({ - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }); - - serviceState.loadCount++; - //this._map._requestQueued(); - - if (serviceState.reloadTiles && $img.size() > 0) { - $img.attr("src", imageUrl); - } else { - var imgMarkup = ""; - - scaleContainer.append(imgMarkup); - $img = scaleContainer.children(":last"); - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - - if (serviceState.loadCount <= 0) { - $serviceContainer.children(":not([data-pixelSize='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - - if (serviceState.loadCount <= 0) { - $serviceContainer.children(":not([data-pixelSize='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", imageUrl); - } - } - } - } - - scaleContainers.find("[data-dirty]").remove(); - serviceState.reloadTiles = false; - } - }, - - resize: function (map, service) { - }, - - opacity: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find("img").stop(true).fadeTo("fast", service.opacity); - }, - - toggle: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.css("display", service.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - } - } - } - }; - })(); -})(jQuery); -(function ($, undefined) { - $.geo._serviceTypes.shingled = (function () { - return { - create: function (map, servicesContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0 - }; - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = service["class"] ? ' class="' + service["class"] + '"' : "", - scHtml = '
                            '; - - servicesContainer.append(scHtml); - - serviceState.serviceContainer = servicesContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, servicesContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactivePan: function (map, service, dx, dy) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - pixelSize = map._pixelSize, - scaleContainer = serviceContainer.children("[data-pixelSize='" + pixelSize + "']"), - panContainer = scaleContainer.children("div"); - - if ( !panContainer.length ) { - scaleContainer.children("img").wrap('
                            '); - panContainer = scaleContainer.children("div"); - } - - panContainer.css( { - left: function (index, value) { - return parseInt(value) + dx; - }, - top: function (index, value) { - return parseInt(value) + dy; - } - } ); - } - }, - - interactiveScale: function (map, service, center, pixelSize) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight]; - - serviceContainer.children().each(function (i) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.attr("data-pixelSize"), - ratio = scalePixelSize / pixelSize; - - $scaleContainer.css({ width: mapWidth * ratio, height: mapHeight * ratio }).children("img").each(function (i) { - var $img = $(this), - imgCenter = $img.data("center"), - x = (Math.round((imgCenter[0] - center[0]) / scalePixelSize) - halfWidth) * ratio, - y = (Math.round((center[1] - imgCenter[1]) / scalePixelSize) - halfHeight) * ratio; - - $img.css({ left: x + "px", top: y + "px" }); - }); - }); - } - }, - - refresh: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && service && (service.visibility === undefined || service.visibility === "visible")) { - this._cancelUnloaded(map, service); - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - scaleContainer = serviceContainer.children('[data-pixelSize="' + pixelSize + '"]'), - - opacity = (service.opacity === undefined ? 1 : service.opacity), - - $img; - - if ( !scaleContainer.size() ) { - serviceContainer.append('
                            '); - scaleContainer = serviceContainer.children(":last"); - } - - scaleContainer.children("img").each(function (i) { - var $thisimg = $(this), - imgCenter = $thisimg.data("center"), - center = map._getCenter(), - x = Math.round((imgCenter[0] - center[0]) / pixelSize) - halfWidth, - y = Math.round((center[1] - imgCenter[1]) / pixelSize) - halfHeight; - - $thisimg.css({ left: x + "px", top: y + "px" }); - }); - - if (opacity < 1) { - serviceContainer.find("img").attr("data-keepAlive", "0"); - } - - var imageUrl = service.getUrl({ - bbox: bbox, - width: mapWidth, - height: mapHeight, - zoom: map._getZoom(), - tile: null, - index: 0 - }); - - serviceState.loadCount++; - //this._map._requestQueued(); - - scaleContainer.append(''); - $img = scaleContainer.children(":last").data("center", map._getCenter()); - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - - if (serviceState.loadCount <= 0) { - serviceContainer.children(':not([data-pixelSize="' + pixelSize + '"])').remove(); - - var panContainer = serviceContainer.find('[data-pixelSize="' + pixelSize + '"]>div'); - if (panContainer.size() > 0) { - var panContainerPos = panContainer.position(); - - panContainer.children("img").each(function (i) { - var $thisimg = $(this), - x = panContainerPos.left + parseInt($thisimg.css("left")), - y = panContainerPos.top + parseInt($thisimg.css("top")); - - $thisimg.css({ left: x + "px", top: y + "px" }); - }).unwrap(); - - panContainer.remove(); - } - - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixelSize='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", imageUrl); - } - }, - - resize: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState && service && (service.visibility === undefined || service.visibility === "visible")) { - this._cancelUnloaded(map, service); - - var serviceState = shingledServicesState[service.id], - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - scaleContainer = serviceContainer.children(); - - scaleContainer.attr("data-pixelSize", "0"); - scaleContainer.css({ - left: halfWidth + 'px', - top: halfHeight + 'px' - }); - } - }, - - opacity: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.find("img").stop(true).fadeTo("fast", service.opacity); - }, - - toggle: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.css("display", service.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - } - } - } - } - })(); -})(jQuery); diff --git a/dist/jquery.geo-1.0a3.min.js b/dist/jquery.geo-1.0a3.min.js deleted file mode 100644 index c7bf3b2..0000000 --- a/dist/jquery.geo-1.0a3.min.js +++ /dev/null @@ -1,128 +0,0 @@ -document.createElement("canvas").getContext||function(){function e(){return this.context_||(this.context_=new s(this))}function r(h,n){var q=K.call(arguments,2);return function(){return h.apply(n,q.concat(K.call(arguments)))}}function p(h){h.namespaces.g_vml_||h.namespaces.add("g_vml_","urn:schemas-microsoft-com:vml","#default#VML");h.namespaces.g_o_||h.namespaces.add("g_o_","urn:schemas-microsoft-com:office:office","#default#VML");if(!h.styleSheets.ex_canvas_){h=h.createStyleSheet();h.owningElement.id= -"ex_canvas_";h.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function a(h){var n=h.srcElement;switch(h.propertyName){case "width":n.getContext().clearRect();n.style.width=n.attributes.width.nodeValue+"px";n.firstChild.style.width=n.clientWidth+"px";break;case "height":n.getContext().clearRect();n.style.height=n.attributes.height.nodeValue+"px";n.firstChild.style.height=n.clientHeight+"px"}}function c(h){h=h.srcElement;if(h.firstChild){h.firstChild.style.width= -h.clientWidth+"px";h.firstChild.style.height=h.clientHeight+"px"}}function b(){return[[1,0,0],[0,1,0],[0,0,1]]}function d(h,n){for(var q=b(),u=0;u<3;u++)for(var z=0;z<3;z++){for(var v=0,L=0;L<3;L++)v+=h[u][L]*n[L][z];q[u][z]=v}return q}function g(h,n){n.fillStyle=h.fillStyle;n.lineCap=h.lineCap;n.lineJoin=h.lineJoin;n.lineWidth=h.lineWidth;n.miterLimit=h.miterLimit;n.shadowBlur=h.shadowBlur;n.shadowColor=h.shadowColor;n.shadowOffsetX=h.shadowOffsetX;n.shadowOffsetY=h.shadowOffsetY;n.strokeStyle=h.strokeStyle; -n.globalAlpha=h.globalAlpha;n.font=h.font;n.textAlign=h.textAlign;n.textBaseline=h.textBaseline;n.arcScaleX_=h.arcScaleX_;n.arcScaleY_=h.arcScaleY_;n.lineScale_=h.lineScale_}function f(h){var n=h.indexOf("(",3),q=h.indexOf(")",n+1);n=h.substring(n+1,q).split(",");if(n.length!=4||h.charAt(3)!="a")n[3]=1;return n}function m(h,n,q){return Math.min(q,Math.max(n,h))}function l(h,n,q){q<0&&q++;q>1&&q--;return 6*q<1?h+(n-h)*6*q:2*q<1?n:3*q<2?h+(n-h)*(2/3-q)*6:h}function o(h){if(h in O)return O[h];var n, -q=1;h=String(h);if(h.charAt(0)=="#")n=h;else if(/^rgb/.test(h)){q=f(h);n="#";for(var u,z=0;z<3;z++){u=q[z].indexOf("%")!=-1?Math.floor(parseFloat(q[z])/100*255):+q[z];n+=F[m(u,0,255)]}q=+q[3]}else if(/^hsl/.test(h)){z=q=f(h);n=parseFloat(z[0])/360%360;n<0&&n++;u=m(parseFloat(z[1])/100,0,1);z=m(parseFloat(z[2])/100,0,1);if(u==0)u=z=n=z;else{var v=z<0.5?z*(1+u):z+u-z*u,L=2*z-v;u=l(L,v,n+1/3);z=l(L,v,n);n=l(L,v,n-1/3)}n="#"+F[Math.floor(u*255)]+F[Math.floor(z*255)]+F[Math.floor(n*255)];q=q[3]}else n= -h;return O[h]={color:n,alpha:q}}function s(h){this.m_=b();this.mStack_=[];this.aStack_=[];this.currentPath_=[];this.fillStyle=this.strokeStyle="#000";this.lineWidth=1;this.lineJoin="miter";this.lineCap="butt";this.miterLimit=D*1;this.globalAlpha=1;this.canvas=h;var n="width:"+h.clientWidth+"px;height:"+h.clientHeight+"px;overflow:hidden;position:absolute",q=h.ownerDocument.createElement("div");q.style.cssText=n;h.appendChild(q);n=q.cloneNode(false);n.style.backgroundColor="red";n.style.filter="alpha(opacity=0)"; -h.appendChild(n);this.element_=q;this.lineScale_=this.arcScaleY_=this.arcScaleX_=1}function x(h,n,q,u){h.currentPath_.push({type:"bezierCurveTo",cp1x:n.x,cp1y:n.y,cp2x:q.x,cp2y:q.y,x:u.x,y:u.y});h.currentX_=u.x;h.currentY_=u.y}function t(h,n,q){h=h.m_;return{x:D*(n*h[0][0]+q*h[1][0]+h[2][0])-J,y:D*(n*h[0][1]+q*h[1][1]+h[2][1])-J}}function A(h,n,q){if(isFinite(n[0][0])&&isFinite(n[0][1])&&isFinite(n[1][0])&&isFinite(n[1][1])&&isFinite(n[2][0])&&isFinite(n[2][1])){h.m_=n;if(q)h.lineScale_=E(G(n[0][0]* -n[1][1]-n[0][1]*n[1][0]))}}function B(h){this.code=this[h];this.message=h+": DOM Exception "+this.code}var C=Math,y=C.round,H=C.sin,I=C.cos,G=C.abs,E=C.sqrt,D=10,J=D/2;navigator.userAgent.match(/MSIE ([\d.]+)?/);var K=Array.prototype.slice;p(document);C={init:function(h){h=h||document;h.createElement("canvas");h.attachEvent("onreadystatechange",r(this.init_,this,h))},init_:function(h){h=h.getElementsByTagName("canvas");for(var n=0;nu.x)u.x=v.x;if(q.y==null||v.yu.y)u.y=v.y}}n.push(' ">');if(h){h=o(this.fillStyle);n.push('')}else{q=o(this.strokeStyle);h=q.color;q=q.alpha*this.globalAlpha;u=this.lineScale_*this.lineWidth;if(u<1)q*=u;n.push("')}n.push("");this.element_.insertAdjacentHTML("beforeEnd",n.join(""))};w.fill=function(){this.stroke(true)};w.closePath=function(){this.currentPath_.push({type:"close"})};w.save= -function(){var h={};g(this,h);this.aStack_.push(h);this.mStack_.push(this.m_);this.m_=d(b(),this.m_)};w.restore=function(){if(this.aStack_.length){g(this.aStack_.pop(),this);this.m_=this.mStack_.pop()}};w.translate=function(h,n){A(this,d([[1,0,0],[0,1,0],[h,n,1]],this.m_),false)};w.scale=function(h,n){this.arcScaleX_*=h;this.arcScaleY_*=n;A(this,d([[h,0,0],[0,n,0],[0,0,1]],this.m_),true)};w=B.prototype=Error();w.INDEX_SIZE_ERR=1;w.DOMSTRING_SIZE_ERR=2;w.HIERARCHY_REQUEST_ERR=3;w.WRONG_DOCUMENT_ERR= -4;w.INVALID_CHARACTER_ERR=5;w.NO_DATA_ALLOWED_ERR=6;w.NO_MODIFICATION_ALLOWED_ERR=7;w.NOT_FOUND_ERR=8;w.NOT_SUPPORTED_ERR=9;w.INUSE_ATTRIBUTE_ERR=10;w.INVALID_STATE_ERR=11;w.SYNTAX_ERR=12;w.INVALID_MODIFICATION_ERR=13;w.NAMESPACE_ERR=14;w.INVALID_ACCESS_ERR=15;w.VALIDATION_ERR=16;w.TYPE_MISMATCH_ERR=17;G_vmlCanvasManager=C;CanvasRenderingContext2D=s;DOMException=B}(); -(function(e){function r(a){var c=[].slice.call(arguments,1),b=0;a=e.event.fix(a||window.event);a.type="mousewheel";if(a.wheelDelta)b=a.wheelDelta/120;if(a.detail)b=-a.detail/3;c.unshift(a,b);return e.event.handle.apply(this,c)}var p=["DOMMouseScroll","mousewheel"];e.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=p.length;a;)this.addEventListener(p[--a],r,false);else this.onmousewheel=r},teardown:function(){if(this.removeEventListener)for(var a=p.length;a;)this.removeEventListener(p[--a], -r,false);else this.onmousewheel=null}};e.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery); -$.widget||function(e,r){var p=Array.prototype.slice,a=e.cleanData;e.cleanData=function(c){for(var b=0,d;(d=c[b])!=null;b++)e(d).triggerHandler("remove");a(c)};e.widget=function(c,b,d){var g=c.split(".")[0],f;c=c.split(".")[1];f=g+"-"+c;if(!d){d=b;b=e.Widget}e.expr[":"][f]=function(l){return!!e.data(l,c)};e[g]=e[g]||{};e[g][c]=e.extend(function(l,o){if(!this._createWidget)return new e[g][c](l,o);arguments.length&&this._createWidget(l,o)},e[g][c]);var m=new b;m.options=e.extend(true,{},m.options);e.each(d, -function(l,o){if(e.isFunction(o))d[l]=function(){var s=function(t){return b.prototype[t].apply(this,p.call(arguments,1))},x=function(t,A){return b.prototype[t].apply(this,A)};return function(){var t=this._super,A=this._superApply,B;this._super=s;this._superApply=x;B=o.apply(this,arguments);this._super=t;this._superApply=A;return B}}()});e[g][c].prototype=e.extend(true,m,{namespace:g,widgetName:c,widgetEventPrefix:c,widgetBaseClass:f},d);e.widget.bridge(c,e[g][c])};e.widget.bridge=function(c,b){e.fn[c]= -function(d){var g=typeof d==="string",f=p.call(arguments,1),m=this;d=!g&&f.length?e.extend.apply(null,[true,d].concat(f)):d;g?this.each(function(){var l=e.data(this,c);if(!l)return e.error("cannot call methods on "+c+" prior to initialization; attempted to call method '"+d+"'");if(!e.isFunction(l[d])||d.charAt(0)==="_")return e.error("no such method '"+d+"' for "+c+" widget instance");var o=l[d].apply(l,f);if(o!==l&&o!==r){m=o;return false}}):this.each(function(){var l=e.data(this,c);l?l.option(d|| -{})._init():b(d,this)});return m}};e.Widget=function(c,b){if(!this._createWidget)return new e[namespace][name](c,b);arguments.length&&this._createWidget(c,b)};e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"
                            ",options:{disabled:false},_createWidget:function(c,b){b=e(b||this.defaultElement||this)[0];this.element=e(b);this.options=e.extend(true,{},this.options,this._getCreateOptions(),c);this.bindings=e();this.hoverable=e();this.focusable=e();if(b!==this){e.data(b,this.widgetName, -this);this._bind({remove:"destroy"})}this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return e.metadata&&e.metadata.get(this.element[0])[this.widgetName]},_create:e.noop,_init:e.noop,destroy:function(){this._destroy();this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled");this.bindings.unbind("."+this.widgetName);this.hoverable.removeClass("ui-state-hover"); -this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(c,b){var d=c;if(arguments.length===0)return e.extend({},this.options);if(typeof c==="string"){if(b===r)return this.options[c];d={};d[c]=b}this._setOptions(d);return this},_setOptions:function(c){var b=this;e.each(c,function(d,g){b._setOption(d,g)});return this},_setOption:function(c,b){this.options[c]=b;if(c==="disabled"){this.widget().toggleClass(this.widgetBaseClass+"-disabled ui-state-disabled", -!!b).attr("aria-disabled",b);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus")}return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_bind:function(c,b){if(b){c=e(c);this.bindings=this.bindings.add(c)}else{b=c;c=this.element}var d=this;e.each(b,function(g,f){c.bind(g+"."+d.widgetName,function(){if(!(d.options.disabled===true||e(this).hasClass("ui-state-disabled")))return(typeof f=== -"string"?d[f]:f).apply(d,arguments)})})},_hoverable:function(c){this.hoverable=this.hoverable.add(c);this._bind(c,{mouseenter:function(b){e(b.currentTarget).addClass("ui-state-hover")},mouseleave:function(b){e(b.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(c){this.focusable=this.focusable.add(c);this._bind(c,{focusin:function(b){e(b.currentTarget).addClass("ui-state-focus")},focusout:function(b){e(b.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(c,b,d){var g= -this.options[c];b=e.Event(b);b.type=(c===this.widgetEventPrefix?c:this.widgetEventPrefix+c).toLowerCase();d=d||{};if(b.originalEvent){c=e.event.props.length;for(var f;c;){f=e.event.props[--c];b[f]=b.originalEvent[f]}}this.element.trigger(b,d);d=e.isArray(d)?[b].concat(d):[b,d];return!(e.isFunction(g)&&g.apply(this.element[0],d)===false||b.isDefaultPrevented())}}}(jQuery); -(function(e,r,p){var a=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY;e.geo={_allCoordinates:function(b){b=this._flatten(b);for(var d=0,g=[];d=d[2]&&b[3]>=d[3]},_bboxDisjoint:function(b,d){return d[0]>b[2]||d[2]b[3]||d[3]0){if(f/m>d){b=f/2;f=b/d}else{f=m/2;b=f*d}b=[g[0]-b,g[1]-f,g[0]+b,g[1]+f]}return e.geo.proj?e.geo.proj.toGeodetic(b):b},scaleBy:function(b,d,g){if(!g&&e.geo.proj)b=e.geo.proj.fromGeodetic(b);var f=this.center(b,true),m=(b[2]-b[0])*d/2;b=(b[3]-b[1])*d/2;b=[f[0]-m,f[1]-b,f[0]+m,f[1]+b];return!g&&e.geo.proj?e.geo.proj.toGeodetic(b):b},width:function(b,d){if(!d&&e.geo.proj)b=e.geo.proj.fromGeodetic(b);return b[2]-b[0]}, -bbox:function(b,d){if(b)if(b.bbox)result=!d&&e.geo.proj?e.geo.proj.fromGeodetic(b.bbox):b.bbox;else{result=[a,a,c,c];var g=this._allCoordinates(b),f=0;if(g.length==0)return p;if(e.geo.proj)g=e.geo.proj.fromGeodetic(g);for(;f0){f[0]=m[0][0];f[1]=m[0][1];return{type:"Point",coordinates:!d&&e.geo.proj?e.geo.proj.toGeodetic(f):f}}else break;g*=3;f[0]/=g;f[1]/=g;return{type:"Point",coordinates:!d&&e.geo.proj? -e.geo.proj.toGeodetic(f):f}}return p},contains:function(b,d){if(b.type!="Polygon")return false;switch(d.type){case "Point":return this._containsPolygonPoint(b.coordinates,d.coordinates);case "LineString":return this._containsPolygonLineString(b.coordinates,d.coordinates);case "Polygon":return this._containsPolygonLineString(b.coordinates,d.coordinates[0]);default:return false}},_containsPolygonPoint:function(b,d){if(b.length==0||b[0].length<4)return false;for(var g=0,f=b[0][0],m=1,l;md[0]&&g++}f=l}return g%2==1},_containsPolygonLineString:function(b,d){for(var g=0;g0){var f=b[0],m=d[0]-f[0],l=d[1]-f[1];if(b.length==1)return Math.sqrt(m*m+ -l*l);else for(var o=1;o=b)return m*m+l*l;return g*g+f*f-o*o/b},_distanceLineStringLineString:function(b,d){for(var g=a,f=0;f=2?{type:"Point",coordinates:[parseFloat(f[1]),parseFloat(f[2])]}:null}}}}(),proj:function(){return{fromGeodeticPos:function(b){if(!b)debugger; -return[6378137*b[0]*0.017453292519943295,6378137*Math.log(Math.tan(0.7853981633974483+b[1]*0.017453292519943295/2))]},fromGeodetic:function(b){var d=e.isArray(b[0]),g=this.fromGeodeticPos;if(!d&&b.length==4){d=g([b[0],b[1]]);b=g([b[2],b[3]]);return[d[0],d[1],b[0],b[1]]}else{var f=d&&e.isArray(b[0][0]),m=f&&e.isArray(b[0][0][0]),l=[],o,s,x;if(!m){if(!f){d||(b=[b]);b=[b]}b=[b]}for(o=0;o
                            ",b[0];);return a>6?a:!a}();e.widget("geo.geographics",{_$elem:r,_options:{},_trueCanvas:true,_width:0,_height:0,_$canvas:r,_context:r,options:{style:{borderRadius:"8px",color:"#7f0000",fillOpacity:0.2,height:"8px",opacity:1,strokeOpacity:1,strokeWidth:"2px",visibility:"visible",width:"8px"}},_create:function(){this._$elem=this.element;this._options=this.options; -this._$elem.css({display:"inline-block",overflow:"hidden",textAlign:"left"});this._$elem.css("position")=="static"&&this._$elem.css("position","relative");this._width=this._$elem.width();this._height=this._$elem.height();if(!(this._width&&this._height)){this._width=parseInt(this._$elem.css("width"));this._height=parseInt(this._$elem.css("height"))}if(document.createElement("canvas").getContext){this._$elem.append('');this._$canvas=this._$elem.children(":last");this._context=this._$canvas[0].getContext("2d")}else if(p<=8){this._trueCanvas=false;this._$elem.append('
                            ');this._$canvas=this._$elem.children(":last");G_vmlCanvasManager.initElement(this._$canvas[0]);this._context=this._$canvas[0].getContext("2d"); -this._$canvas.children().css({backgroundColor:"transparent",width:this._width,height:this._height})}},_setOption:function(a,c){if(a=="style")c=e.extend({},this._options.style,c);e.Widget.prototype._setOption.apply(this,arguments)},destroy:function(){e.Widget.prototype.destroy.apply(this,arguments);this._$elem.html("")},clear:function(){this._context.clearRect(0,0,this._width,this._height)},drawArc:function(a,c,b,d){d=this._getGraphicStyle(d);if(d.visibility!="hidden"&&d.opacity>0&&d.widthValue>0&& -d.heightValue>0){var g=Math.min(d.widthValue,d.heightValue)/2;c=c*Math.PI/180;b=b*Math.PI/180;this._context.save();this._context.translate(a[0],a[1]);d.widthValue>d.heightValue?this._context.scale(d.widthValue/d.heightValue,1):this._context.scale(1,d.heightValue/d.widthValue);this._context.beginPath();this._context.arc(0,0,g,c,b,false);this._trueCanvas&&this._context.restore();if(d.doFill){this._context.fillStyle=d.fill;this._context.globalAlpha=d.opacity*d.fillOpacity;this._context.fill()}if(d.doStroke){this._context.lineJoin= -"round";this._context.lineWidth=d.strokeWidthValue;this._context.strokeStyle=d.stroke;this._context.globalAlpha=d.opacity*d.strokeOpacity;this._context.stroke()}this._trueCanvas||this._context.restore()}},drawPoint:function(a,c){c=this._getGraphicStyle(c);if(c.widthValue==c.heightValue&&c.heightValue==c.borderRadiusValue)this.drawArc(a,0,360,c);else if(c.visibility!="hidden"&&c.opacity>0){c.borderRadiusValue=Math.min(Math.min(c.widthValue,c.heightValue)/2,c.borderRadiusValue);a[0]-=c.widthValue/2; -a[1]-=c.heightValue/2;this._context.beginPath();this._context.moveTo(a[0]+c.borderRadiusValue,a[1]);this._context.lineTo(a[0]+c.widthValue-c.borderRadiusValue,a[1]);this._context.quadraticCurveTo(a[0]+c.widthValue,a[1],a[0]+c.widthValue,a[1]+c.borderRadiusValue);this._context.lineTo(a[0]+c.widthValue,a[1]+c.heightValue-c.borderRadiusValue);this._context.quadraticCurveTo(a[0]+c.widthValue,a[1]+c.heightValue,a[0]+c.widthValue-c.borderRadiusValue,a[1]+c.heightValue);this._context.lineTo(a[0]+c.borderRadiusValue, -a[1]+c.heightValue);this._context.quadraticCurveTo(a[0],a[1]+c.heightValue,a[0],a[1]+c.heightValue-c.borderRadiusValue);this._context.lineTo(a[0],a[1]+c.borderRadiusValue);this._context.quadraticCurveTo(a[0],a[1],a[0]+c.borderRadiusValue,a[1]);this._context.closePath();if(c.doFill){this._context.fillStyle=c.fill;this._context.globalAlpha=c.opacity*c.fillOpacity;this._context.fill()}if(c.doStroke){this._context.lineJoin="round";this._context.lineWidth=c.strokeWidthValue;this._context.strokeStyle=c.stroke; -this._context.globalAlpha=c.opacity*c.strokeOpacity;this._context.stroke()}}},drawLineString:function(a,c){this._drawLines([a],false,c)},drawPolygon:function(a,c){this._drawLines(a,true,c)},drawBbox:function(a,c){this._drawLines([[[a[0],a[1]],[a[0],a[3]],[a[2],a[3]],[a[2],a[1]],[a[0],a[1]]]],true,c)},_getGraphicStyle:function(a){function c(b){b=parseInt(b);return+b+""===b?+b:b}a=e.extend({},this._options.style,a);a.borderRadiusValue=c(a.borderRadius);a.fill=a.fill||a.color;a.doFill=a.fill&&a.fillOpacity> -0;a.stroke=a.stroke||a.color;a.strokeWidthValue=c(a.strokeWidth);a.doStroke=a.stroke&&a.strokeOpacity>0&&a.strokeWidthValue>0;a.widthValue=c(a.width);a.heightValue=c(a.height);return a},_drawLines:function(a,c,b){if(!(!a||!a.length||a[0].length<2)){b=this._getGraphicStyle(b);var d,g;if(b.visibility!="hidden"&&b.opacity>0){this._context.beginPath();this._context.moveTo(a[0][0][0],a[0][0][1]);for(d=0;d
                            ",b[0];);return a>6?a:!a}();e.widget("geo.geomap",{_$elem:r,_created:false,_contentBounds:{},_$contentFrame:r,_$existingChildren:r,_$servicesContainer:r,_$drawContainer:r,_$shapesContainer:r,_$textContainer:r,_$textContent:r,_$eventTarget:r,_dpi:96,_currentServices:[],_center:r,_pixelSize:r,_centerMax:r,_pixelSizeMax:r,_wheelZoomFactor:1.18920711500273,_wheelTimeout:null, -_wheelLevel:0,_zoomFactor:2,_mouseDown:r,_inOp:r,_toolPan:r,_shiftZoom:r,_anchor:r,_current:r,_downDate:r,_moveDate:r,_clickDate:r,_lastMove:r,_lastDrag:r,_windowHandler:null,_resizeTimeout:null,_panning:r,_velocity:r,_friction:r,_supportTouch:r,_softDblClick:r,_isTap:r,_isDbltap:r,_drawTimeout:null,_drawPixels:[],_drawCoords:[],_graphicShapes:[],_initOptions:{},_options:{},options:e.extend({},{bbox:[-180,-85,180,85],bboxMax:[-180,-85,180,85],center:[0,0],cursors:{pan:"move",zoom:"crosshair",drawPoint:"crosshair", -drawLineString:"crosshair",drawPolygon:"crosshair"},drawStyle:{},shapeStyle:{},mode:"pan",services:[{"class":"osm",type:"tiled",getUrl:function(a){return"http://tile.openstreetmap.org/"+a.zoom+"/"+a.tile.column+"/"+a.tile.row+".png"},attr:"© OpenStreetMap & contributors, CC-BY-SA"}],tilingScheme:{tileWidth:256,tileHeight:256,levels:18,basePixelSize:156543.03392799935,origin:[-2.0037508342787E7,2.0037508342787E7]},zoom:0,pixelSize:0}),_createWidget:function(a,c){this._$elem=e(c);if(!this._$elem.is("[data-geo-service]")){this._$elem.attr("data-geo-map", -"data-geo-map");this._graphicShapes=[];this._initOptions=a||{};this._forcePosition(this._$elem);this._$elem.css("text-align","left");var b=this._findMapSize();this._contentBounds={x:parseInt(this._$elem.css("padding-left")),y:parseInt(this._$elem.css("padding-top")),width:b.width,height:b.height};this._createChildren();this._center=this._centerMax=[0,0];this.options.pixelSize=this._pixelSize=this._pixelSizeMax=156543.03392799935;this._mouseDown=this._inOp=this._toolPan=this._shiftZoom=this._panning= -this._isTap=this._isDbltap=false;this._anchor=this._current=this._lastMove=this._lastDrag=this._velocity=[0,0];this._friction=[0.8,0.8];this._downDate=this._moveDate=this._clickDate=0}e.Widget.prototype._createWidget.apply(this,arguments)},_create:function(){if(!this._$elem.is("[data-geo-service]")){this._options=this.options;this._softDblClick=(this._supportTouch="ontouchend"in document)||p==7;var a=this._supportTouch?"touchstart":"mousedown",c=this._supportTouch?"touchend touchcancel":"mouseup", -b=this._supportTouch?"touchmove":"mousemove";e(document).keydown(e.proxy(this._document_keydown,this));this._$eventTarget.dblclick(e.proxy(this._eventTarget_dblclick,this));this._$eventTarget.bind(a,e.proxy(this._eventTarget_touchstart,this));a=this._$eventTarget[0].setCapture?this._$eventTarget:e(document);a.bind(b,e.proxy(this._dragTarget_touchmove,this));a.bind(c,e.proxy(this._dragTarget_touchstop,this));this._$eventTarget.mousewheel(e.proxy(this._eventTarget_mousewheel,this));var d=this;this._windowHandler= -function(){d._resizeTimeout&&clearTimeout(d._resizeTimeout);this._resizeTimeout=setTimeout(function(){d._created&&d._$elem.geomap("resize")},500)};e(window).resize(this._windowHandler);this._$drawContainer.geographics({style:this._initOptions.drawStyle||{}});this._options.drawStyle=this._$drawContainer.geographics("option","style");this._$shapesContainer.geographics({style:this._initOptions.shapeStyle||{}});this._options.shapeStyle=this._$shapesContainer.geographics("option","style");if(this._initOptions){this._initOptions.bbox&& -this._setOption("bbox",this._initOptions.bbox,false);this._initOptions.center&&this._setOption("center",this._initOptions.center,false);this._initOptions.zoom&&this._setZoom(this._initOptions.zoom,false,false)}this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]);this._createServices();this._refresh();this._created=true}},_setOption:function(a,c,b){if(!(this._$elem.is("[data-geo-service]")||a=="pixelSize")){b=b===r||b;switch(a){case "bbox":if(e.geo.proj){c=e.geo.proj.fromGeodetic([[c[0], -c[1]],[c[2],c[3]]]);c=[c[0][0],c[0][1],c[1][0],c[1][1]]}this._setBbox(c,false,b);c=this._getBbox();if(e.geo.proj){c=e.geo.proj.toGeodetic([[c[0],c[1]],[c[2],c[3]]]);c=[c[0][0],c[0][1],c[1][0],c[1][1]]}break;case "center":this._setCenterAndSize(e.geo.proj?e.geo.proj.fromGeodetic([[c[0],c[1]]])[0]:c,this._pixelSize,false,b);break;case "drawStyle":if(this._$drawContainer){this._$drawContainer.geographics("option","style",c);c=this._$drawContainer.geographics("option","style")}break;case "shapeStyle":if(this._$shapesContainer){this._$shapesContainer.geographics("option", -"style",c);c=this._$shapesContainer.geographics("option","style")}break;case "mode":this._$drawContainer.geographics("clear");this._$eventTarget.css("cursor",this._options.cursors[c]);break;case "zoom":this._setZoom(c,false,b)}e.Widget.prototype._setOption.apply(this,arguments);switch(a){case "services":this._createServices();b&&this._refresh();break;case "shapeStyle":if(b){this._$shapesContainer.geographics("clear");this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes)}}}}, -destroy:function(){if(this._$elem.is("[data-geo-map]")){this._created=false;e(window).unbind("resize",this._windowHandler);for(var a=0;a=0||a<=1)for(var b=0;b
                            "); -this._$eventTarget=this._$contentFrame=this._$elem.children(":first");this._$contentFrame.append('
                            ');this._$servicesContainer=this._$contentFrame.children(":last");this._$contentFrame.append('
                            '); -this._$shapesContainer=this._$contentFrame.children(":last");this._$contentFrame.append('
                            ');this._$drawContainer=this._$contentFrame.children(":last");this._$contentFrame.append(''); -this._$textContainer=this._$contentFrame.children(":last");this._$textContent=this._$textContainer.children();this._$contentFrame.append(this._$existingChildren)},_createServices:function(){var a;for(a=0;a0){var a=this._options.mode,c=this._drawPixels;if(a=="drawPolygon")c=[c];this._$drawContainer.geographics(a,c)}},_resetDrawing:function(){this._drawPixels=[];this._drawCoords=[];this._$drawContainer.geographics("clear")}, -_refreshShapes:function(a,c,b,d,g){var f,m,l,o,s,x=this._getBbox(d,g),t=this;for(f=0;f0&&a.height>0);){a={width:c.width(),height:c.height()};if(a.width<=0||a.height<=0)a={width:parseInt(c.css("width")),height:parseInt(c.css("height"))};c=c.parent()}return a},_forcePosition:function(a){var c=a.css("position");c!="relative"&&c!="absolute"&&c!="fixed"&&a.css("position","relative")},_getTiledPixelSize:function(a){var c=this._options.tilingScheme; -if(c!=null){if(a===0)return c.pixelSizes!=null?c.pixelSizes[0]:c.basePixelSize;a=Math.round(a);a=Math.max(a,0);a=Math.min(a,(c.pixelSizes!=null?c.pixelSizes.length:c.levels)-1);return c.pixelSizes!=null?c.pixelSizes[a]:c.basePixelSize/Math.pow(2,a)}else return NaN},_getTiledZoom:function(a){var c=this._options.tilingScheme;if(c.pixelSizes!=null){a=Math.floor(a*1E3);for(var b=(c.pixelSizes!=null?c.pixelSizes.length:c.levels)-1;b>=0;b--)if(Math.floor(c.pixelSizes[b]*1E3)>=a)return b;return 0}else return Math.max(Math.round(Math.log(c.basePixelSize/ -a)/Math.log(2)),0)},_getZoomCenterAndSize:function(a,c,b){if(this._options.tilingScheme){c=this._getTiledZoom(this._pixelSize)+c;c=this._getTiledPixelSize(c)}else{c=Math.pow(b,-c);c=this._pixelSize*c}b=c/this._pixelSize;a=this._toMap(a);b=[(this._center[0]-a[0])*b,(this._center[1]-a[1])*b];return{pixelSize:c,center:[a[0]+b[0],a[1]+b[1]]}},_mouseWheelFinish:function(){this._wheelTimeout=null;if(this._wheelLevel!=0){var a=this._getZoomCenterAndSize(this._anchor,this._wheelLevel,this._wheelZoomFactor); -this._setCenterAndSize(a.center,a.pixelSize,true,true);this._wheelLevel=0}else this._refresh()},_panEnd:function(){this._velocity=[this._velocity[0]>0?Math.floor(this._velocity[0]*this._friction[0]):Math.ceil(this._velocity[0]*this._friction[0]),this._velocity[1]>0?Math.floor(this._velocity[1]*this._friction[1]):Math.ceil(this._velocity[1]*this._friction[1])];if(Math.abs(this._velocity[0])<4&&Math.abs(this._velocity[1])<4)this._panFinalize();else{this._current=[this._current[0]+this._velocity[0], -this._current[1]+this._velocity[1]];this._panMove();setTimeout(e.proxy(this._panEnd,this),30)}},_panFinalize:function(){if(this._panning){this._velocity=[0,0];var a=-(this._current[0]-this._anchor[0])*this._pixelSize,c=(this._current[1]-this._anchor[1])*this._pixelSize;this._$shapesContainer.css({left:0,top:0});this._setCenterAndSize([this._center[0]+a,this._center[1]+c],this._pixelSize,true,true);this._inOp=false;this._anchor=this._current;this._toolPan=this._panning=false;this._$eventTarget.css("cursor", -this._options.cursors[this._options.mode])}},_panMove:function(){var a=this._current[0]-this._lastDrag[0],c=this._current[1]-this._lastDrag[1],b=0,d;if(this._toolPan||a>3||a<-3||c>3||c<-3){if(!this._toolPan){this._toolPan=true;this._$eventTarget.css("cursor",this._options.cursors.pan)}if(this._mouseDown)this._velocity=[a,c];if(a!=0||c!=0){this._panning=true;this._lastDrag=this._current;for(b=0;b0&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes)}},_setCenterAndSize:function(a,c,b,d){if(this._pixelSize!=c){this._$shapesContainer.geographics("clear");for(var g=0;g0)this._drawPixels=this._toPixel(this._drawCoords);b&&this._trigger("bboxchange",window.event,{bbox:this._options.bbox});if(d){this._refresh();this._refreshDrawing()}},_toMap:function(a,c,b){var d=e.isArray(a[0]);d||(a=[a]);c=c||this._center; -b=b||this._pixelSize;var g=this._contentBounds.width,f=this._contentBounds.height,m=g/2*b;b=f/2*b;var l=[c[0]-m,c[1]-b,c[0]+m,c[1]+b],o=e.geo.width(l,true)/g,s=e.geo.height(l,true)/f,x=[];e.each(a,function(t){x[t]=[l[0]+this[0]*o,l[3]-this[1]*s]});return d?x:x[0]},_toPixel:function(a,c,b){var d=e.isArray(a[0]);d||(a=[a]);c=c||this._center;b=b||this._pixelSize;var g=this._contentBounds.width,f=this._contentBounds.height,m=g/2*b;b=f/2*b;var l=[c[0]-m,c[1]-b,c[0]+m,c[1]+b],o=e.geo.width(l,true),s=e.geo.height(l, -true),x=[];e.each(a,function(t){x[t]=[Math.round((this[0]-l[0])*g/o),Math.round((l[3]-this[1])*f/s)]});return d?x:x[0]},_zoomTo:function(a,c,b,d){c=c<0?0:c;var g=this._getTiledPixelSize(c);if(isNaN(g)){c=e.geo._scaleBy(this._getBboxMax(),1/Math.pow(this._zoomFactor,c),true);c=Math.max(e.geo.width(c,true)/this._contentBounds.width,e.geo.height(c,true)/this._contentBounds.height);this._setCenterAndSize(a,c,b,d)}else this._setCenterAndSize(a,g,b,d)},_document_keydown:function(a){var c=this._drawCoords.length; -if(c>0&&a.which==27)if(c<=2){this._resetDrawing();this._inOp=false}else{this._drawCoords[c-2]=e.merge([],this._drawCoords[c-1]);this._drawPixels[c-2]=e.merge([],this._drawPixels[c-1]);this._drawCoords.length--;this._drawPixels.length--;this._refreshDrawing()}},_eventTarget_dblclick_zoom:function(a){this._trigger("dblclick",a,{type:"Point",coordinates:this.toMap(this._current)});if(!a.isDefaultPrevented()){a=this._getZoomCenterAndSize(this._current,1,this._zoomFactor);this._setCenterAndSize(a.center, -a.pixelSize,true,true)}},_eventTarget_dblclick:function(a){this._panFinalize();if(this._drawTimeout){window.clearTimeout(this._drawTimeout);this._drawTimeout=null}e(a.currentTarget).offset();switch(this._options.mode){case "pan":case "drawPoint":this._eventTarget_dblclick_zoom(a);break;case "drawLineString":if(this._drawCoords.length>1&&!(this._drawCoords[0][0]==this._drawCoords[1][0]&&this._drawCoords[0][1]==this._drawCoords[1][1])){this._drawCoords.length--;this._trigger("shape",a,{type:"LineString", -coordinates:e.geo.proj?e.geo.proj.toGeodetic(this._drawCoords):this._drawCoords})}else this._eventTarget_dblclick_zoom(a);this._resetDrawing();break;case "drawPolygon":if(this._drawCoords.length>1&&!(this._drawCoords[0][0]==this._drawCoords[1][0]&&this._drawCoords[0][1]==this._drawCoords[1][1])){var c=this._drawCoords.length-1;if(c>2){this._drawCoords[c]=e.merge([],this._drawCoords[0]);this._trigger("shape",a,{type:"Polygon",coordinates:[e.geo.proj?e.geo.proj.toGeodetic(this._drawCoords):this._drawCoords]})}}else this._eventTarget_dblclick_zoom(a); -this._resetDrawing()}this._inOp=false},_eventTarget_touchstart:function(a){if(!(!this._supportTouch&&a.which!=1)){this._panFinalize();this._mouseWheelFinish();var c=e(a.currentTarget).offset();this._current=this._supportTouch?[a.originalEvent.changedTouches[0].pageX-c.left,a.originalEvent.changedTouches[0].pageY-c.top]:[a.pageX-c.left,a.pageY-c.top];if(this._softDblClick){c=e.now();if(c-this._downDate<750){if(this._isTap){var b=this._current[0]-this._anchor[0],d=this._current[1]-this._anchor[1];if(Math.sqrt(b* -b+d*d)>10)this._isTap=false;else this._current=this._anchor}this._isDbltap=this._isDbltap?false:this._isTap}else this._isDbltap=false;this._isTap=true;this._downDate=c}this._mouseDown=true;this._anchor=this._current;if(!this._inOp&&a.shiftKey){this._shiftZoom=true;this._$eventTarget.css("cursor",this._options.cursors.zoom)}else{this._inOp=true;switch(this._options.mode){case "pan":case "drawPoint":case "drawLineString":case "drawPolygon":this._lastDrag=this._current;a.currentTarget.setCapture&&a.currentTarget.setCapture()}}if(this._inOp){a.preventDefault(); -return false}}},_dragTarget_touchmove:function(a){var c=this._$eventTarget.offset(),b=this._drawCoords.length;c=this._supportTouch?[a.originalEvent.changedTouches[0].pageX-c.left,a.originalEvent.changedTouches[0].pageY-c.top]:[a.pageX-c.left,a.pageY-c.top];if(c[0]===this._lastMove[0]&&c[1]===this._lastMove[1])if(this._inOp){a.preventDefault();return false}if(this._softDblClick)this._isDbltap=this._isTap=false;if(this._mouseDown){this._current=c;this._moveDate=e.now()}switch(this._shiftZoom?"zoom": -this._options.mode){case "zoom":if(this._mouseDown){this._$drawContainer.geographics("clear");this._$drawContainer.geographics("drawBbox",[this._anchor[0],this._anchor[1],c[0],c[1]])}else this._trigger("move",a,{type:"Point",coordinates:this.toMap(c)});break;case "pan":case "drawPoint":this._mouseDown||this._toolPan?this._panMove():this._trigger("move",a,{type:"Point",coordinates:this.toMap(c)});break;case "drawLineString":case "drawPolygon":if(this._mouseDown||this._toolPan)this._panMove();else{if(b> -0){this._drawCoords[b-1]=this._toMap(c);this._drawPixels[b-1]=c;this._refreshDrawing()}this._trigger("move",a,{type:"Point",coordinates:this.toMap(c)})}}this._lastMove=c;if(this._inOp){a.preventDefault();return false}},_dragTarget_touchstop:function(a){!this._mouseDown&&p==7&&this._eventTarget_touchstart(a);var c=this._mouseDown,b=this._toolPan,d=this._$eventTarget.offset(),g=this._shiftZoom?"zoom":this._options.mode,f,m;f=this._supportTouch?[a.originalEvent.changedTouches[0].pageX-d.left,a.originalEvent.changedTouches[0].pageY- -d.top]:[a.pageX-d.left,a.pageY-d.top];d=f[0]-this._anchor[0];m=f[1]-this._anchor[1];this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]);this._shiftZoom=this._mouseDown=this._toolPan=false;document.releaseCapture&&document.releaseCapture();if(c){c=e.now();this._current=f;switch(g){case "zoom":if(d>0||m>0){b=this._pixelSize*6;g=this._toMap([[Math.min(this._anchor[0],f[0]),Math.max(this._anchor[1],f[1])],[Math.max(this._anchor[0],f[0]),Math.min(this._anchor[1],f[1])]]);g=[g[0][0], -g[0][1],g[1][0],g[1][1]];if(g[2]-g[0]100){this._trigger("click",a,{type:"Point",coordinates:this.toMap(f)});this._inOp=false}break;case "drawPoint":if(this._drawTimeout){window.clearTimeout(this._drawTimeout);this._drawTimeout=null}if(b)this._panFinalize();else if(c-this._clickDate>100){var l=this;this._drawTimeout= -setTimeout(function(){if(l._drawTimeout){l._trigger("shape",a,{type:"Point",coordinates:l.toMap(f)});l._inOp=false;l._drawTimeout=false}},250)}break;case "drawLineString":case "drawPolygon":if(b)this._panFinalize();else{b=this._drawCoords.length==0?0:this._drawCoords.length-1;this._drawCoords[b]=this._toMap(f);this._drawPixels[b]=f;if(b<2||!(this._drawCoords[b][0]==this._drawCoords[b-1][0]&&this._drawCoords[b][1]==this._drawCoords[b-1][1])){this._drawCoords[b+1]=this._toMap(f);this._drawPixels[b+ -1]=f}this._refreshDrawing()}}this._clickDate=c;if(this._softDblClick&&this._isDbltap){this._isDbltap=this._isTap=false;this._$eventTarget.trigger("dblclick",a)}}if(this._inOp){a.preventDefault();return false}},_eventTarget_mousewheel:function(a,c){a.preventDefault();this._panFinalize();if(this._mouseDown)return false;if(c!=0){if(this._wheelTimeout){window.clearTimeout(this._wheelTimeout);this._wheelTimeout=null}else{var b=e(a.currentTarget).offset();this._anchor=[a.pageX-b.left,a.pageY-b.top]}this._wheelLevel+= -c;b=this._getZoomCenterAndSize(this._anchor,this._wheelLevel,this._wheelZoomFactor);this._$shapesContainer.geographics("clear");for(i=0;i0&&this._graphicShapes.length<256&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,b.center,b.pixelSize);if(this._drawCoords.length> -0){this._drawPixels=this._toPixel(this._drawCoords,b.center,b.pixelSize);this._refreshDrawing()}var g=this;this._wheelTimeout=window.setTimeout(function(){g._mouseWheelFinish()},1E3)}return false}})})(jQuery); -(function(e,r){e.geo._serviceTypes.tiled=function(){return{create:function(p,a,c){p=e.data(c,"geoServiceState");if(!p){p={loadCount:0,reloadTiles:false};a.append('
                            ');p.serviceContainer=a.children(":last");e.data(c,"geoServiceState",p)}return p.serviceContainer}, -destroy:function(p,a,c){e.data(c,"geoServiceState").serviceContainer.remove();e.removeData(c,"geoServiceState")},interactivePan:function(p,a,c,b){var d=e.data(a,"geoServiceState");if(d){this._cancelUnloaded(p,a);d.serviceContainer.children().css({left:function(w,M){return parseInt(M)+c},top:function(w,M){return parseInt(M)+b}});if(a&&(a.visibility===r||a.visibility==="visible")){var g=p._pixelSize,f=d.serviceContainer,m=f.children("[data-pixelSize='"+g+"']"),l=p._getContentBounds(),o=p.options.tilingScheme, -s=o.tileWidth,x=o.tileHeight,t=l.width/2*g,A=l.height/2*g,B=m.position(),C=m.data("scaleOrigin").split(",");l=parseInt(C[0])-B.left;B=parseInt(C[1])-B.top;var y=p._getCenter();C=[y[0]+l*g,y[1]-B*g];var H=Math.floor((C[0]-t-o.origin[0])/(g*s));l=Math.floor((o.origin[1]-(C[1]+A))/(g*x));B=Math.ceil((C[0]+t-o.origin[0])/(g*s));C=Math.ceil((o.origin[1]-(C[1]-A))/(g*x));var I=p._getBboxMax(),G=p._getTiledPixelSize(0),E=G/g,D=Math.floor((I[0]-o.origin[0])/(G*s))*E;I=Math.floor((o.origin[1]-I[3])/(G*x))* -E;t=Math.round((o.origin[0]+D*s*g-(y[0]-t))/g);A=Math.round((y[1]+A-(o.origin[1]-I*x*g))/g);var J=a.opacity===r?1:a.opacity;for(y=H;y -0)E.attr("src",K);else{E="";m.append(E);E=m.children(":last");E.load(function(w){J<1?e(w.target).fadeTo(0,J):e(w.target).show();d.loadCount--;if(d.loadCount<=0){f.children(":not([data-pixelSize='"+ -g+"'])").remove();d.loadCount=0}}).error(function(w){e(w.target).remove();d.loadCount--;if(d.loadCount<=0){f.children(":not([data-pixelSize='"+g+"'])").remove();d.loadCount=0}}).attr("src",K)}}}}}},interactiveScale:function(p,a,c,b){var d=e.data(a,"geoServiceState");if(d&&a&&(a.visibility===r||a.visibility==="visible")){this._cancelUnloaded(p,a);a=p.options.tilingScheme;var g=a.tileWidth,f=a.tileHeight;d.serviceContainer.children().each(function(){var m=e(this),l=m.attr("data-pixelSize")/b;l=Math.round(l* -1E3)/1E3;var o=m.data("scaleOrigin").split(",");o=p._toMap([o[0],o[1]]);o=p._toPixel(o,c,b);m.css({left:Math.round(o[0])+"px",top:Math.round(o[1])+"px",width:g*l,height:f*l});e("body")[0].filters!==r&&m.children().each(function(){e(this).css("filter","progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11="+l+",M22="+l+",sizingmethod='auto expand')")})})}},refresh:function(p,a){var c=e.data(a,"geoServiceState");if(c&&a&&(a.visibility===r||a.visibility==="visible")){this._cancelUnloaded(p, -a);var b=p._getBbox(),d=p._pixelSize,g=c.serviceContainer;p._getContentBounds();var f=p.options.tilingScheme,m=f.tileWidth,l=f.tileHeight,o=Math.floor((b[0]-f.origin[0])/(d*m)),s=Math.floor((f.origin[1]-b[3])/(d*l)),x=Math.ceil((b[2]-f.origin[0])/(d*m)),t=Math.ceil((f.origin[1]-b[1])/(d*l)),A=p._getBboxMax(),B=p._getTiledPixelSize(0),C=B/d,y=Math.floor((A[0]-f.origin[0])/(B*m))*C,H=Math.floor((f.origin[1]-A[3])/(B*l))*C,I=Math.round((f.origin[0]+y*m*d-b[0])/d),G=Math.round((b[3]-(f.origin[1]-H*l* -d))/d);b=g.children().show();A=b.filter("[data-pixelSize='"+d+"']").appendTo(g);var E=a.opacity===r?1:a.opacity;c.reloadTiles&&b.find("img").attr("data-dirty","true");if(A.size()){A.css({left:I%m+"px",top:G%l+"px"}).data("scaleOrigin",I%m+","+G%l);A.children().each(function(){var F=e(this),w=F.attr("data-tile").split(",");F.css({left:Math.round((parseInt(w[0])-y)*100+(I-I%m)/m*100)+"%",top:Math.round((parseInt(w[1])-H)*100+(G-G%l)/l*100)+"%"});E<1&&F.fadeTo(0,E)})}else{g.append("
                            ");A=g.children(":last").data("scaleOrigin",I%m+","+G%l)}for(o=o;o0)D.attr("src",J);else{D="";A.append(D);D=A.children(":last");D.load(function(F){E<1?e(F.target).fadeTo(0, -E):e(F.target).show();c.loadCount--;if(c.loadCount<=0){g.children(":not([data-pixelSize='"+d+"'])").remove();c.loadCount=0}}).error(function(F){e(F.target).remove();c.loadCount--;if(c.loadCount<=0){g.children(":not([data-pixelSize='"+d+"'])").remove();c.loadCount=0}}).attr("src",J)}}}b.find("[data-dirty]").remove();c.reloadTiles=false}},resize:function(){},opacity:function(p,a){e.data(a,"geoServiceState").serviceContainer.find("img").stop(true).fadeTo("fast",a.opacity)},toggle:function(p,a){e.data(a, -"geoServiceState").serviceContainer.css("display",a.visibility==="visible"?"block":"none")},_cancelUnloaded:function(p,a){var c=e.data(a,"geoServiceState");if(c&&c.loadCount>0)for(c.serviceContainer.find("img:hidden").remove();c.loadCount>0;)c.loadCount--}}}()})(jQuery); -(function(e,r){e.geo._serviceTypes.shingled=function(){return{create:function(p,a,c){p=e.data(c,"geoServiceState");if(!p){p={loadCount:0};a.append('
                            ');p.serviceContainer=a.children(":last");e.data(c,"geoServiceState",p)}return p.serviceContainer}, -destroy:function(p,a,c){e.data(c,"geoServiceState").serviceContainer.remove();e.removeData(c,"geoServiceState")},interactivePan:function(p,a,c,b){var d=e.data(a,"geoServiceState");if(d){this._cancelUnloaded(p,a);p=d.serviceContainer.children("[data-pixelSize='"+p._pixelSize+"']");a=p.children("div");if(!a.length){p.children("img").wrap('
                            ');a=p.children("div")}a.css({left:function(g,f){return parseInt(f)+c},top:function(g, -f){return parseInt(f)+b}})}},interactiveScale:function(p,a,c,b){var d=e.data(a,"geoServiceState");if(d){this._cancelUnloaded(p,a);a=d.serviceContainer;p=p._getContentBounds();var g=p.width,f=p.height,m=g/2,l=f/2;a.children().each(function(){var o=e(this),s=o.attr("data-pixelSize"),x=s/b;o.css({width:g*x,height:f*x}).children("img").each(function(){var t=e(this),A=t.data("center");t.css({left:(Math.round((A[0]-c[0])/s)-m)*x+"px",top:(Math.round((c[1]-A[1])/s)-l)*x+"px"})})})}},refresh:function(p,a){var c= -e.data(a,"geoServiceState");if(c&&a&&(a.visibility===r||a.visibility==="visible")){this._cancelUnloaded(p,a);var b=p._getBbox(),d=p._pixelSize,g=c.serviceContainer,f=p._getContentBounds(),m=f.width,l=f.height,o=m/2,s=l/2;f=g.children('[data-pixelSize="'+d+'"]');var x=a.opacity===r?1:a.opacity;if(!f.size()){g.append('
                            ');f=g.children(":last")}f.children("img").each(function(){var t= -e(this),A=t.data("center"),B=p._getCenter();t.css({left:Math.round((A[0]-B[0])/d)-o+"px",top:Math.round((B[1]-A[1])/d)-s+"px"})});x<1&&g.find("img").attr("data-keepAlive","0");b=a.getUrl({bbox:b,width:m,height:l,zoom:p._getZoom(),tile:null,index:0});c.loadCount++;f.append(''); -f.children(":last").data("center",p._getCenter()).load(function(t){x<1?e(t.target).fadeTo(0,x):e(t.target).show();c.loadCount--;if(c.loadCount<=0){g.children(':not([data-pixelSize="'+d+'"])').remove();t=g.find('[data-pixelSize="'+d+'"]>div');if(t.size()>0){var A=t.position();t.children("img").each(function(){var B=e(this),C=A.left+parseInt(B.css("left")),y=A.top+parseInt(B.css("top"));B.css({left:C+"px",top:y+"px"})}).unwrap();t.remove()}c.loadCount=0}}).error(function(t){e(t.target).remove();c.loadCount--; -if(c.loadCount<=0){g.children(":not([data-pixelSize='"+d+"'])").remove();c.loadCount=0}}).attr("src",b)}},resize:function(p,a){var c=e.data(a,"geoServiceState");if(c&&a&&(a.visibility===r||a.visibility==="visible")){this._cancelUnloaded(p,a);c=shingledServicesState[a.id];var b=c.serviceContainer,d=p._getContentBounds();c=d.width/2;d=d.height/2;b=b.children();b.attr("data-pixelSize","0");b.css({left:c+"px",top:d+"px"})}},opacity:function(p,a){e.data(a,"geoServiceState").serviceContainer.find("img").stop(true).fadeTo("fast", -a.opacity)},toggle:function(p,a){e.data(a,"geoServiceState").serviceContainer.css("display",a.visibility==="visible"?"block":"none")},_cancelUnloaded:function(p,a){var c=e.data(a,"geoServiceState");if(c&&c.loadCount>0)for(c.serviceContainer.find("img:hidden").remove();c.loadCount>0;)c.loadCount--}}}()})(jQuery); diff --git a/dist/jquery.geo-1.0a4.js b/dist/jquery.geo-1.0a4.js deleted file mode 100644 index 3223253..0000000 --- a/dist/jquery.geo-1.0a4.js +++ /dev/null @@ -1,6233 +0,0 @@ -// excanvas -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/* - * AppGeo/geo - * (c) 2007-2011, Applied Geographics, Inc. All rights reserved. - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - */ - - -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -// Known Issues: -// -// * Patterns only support repeat. -// * Radial gradient are not implemented. The VML version of these look very -// different from the canvas one. -// * Clipping paths are not implemented. -// * Coordsize. The width and height attribute have higher priority than the -// width and height style values which isn't correct. -// * Painting mode isn't implemented. -// * Canvas width/height should is using content-box by default. IE in -// Quirks mode will draw the canvas using border-box. Either change your -// doctype to HTML5 -// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) -// or use Box Sizing Behavior from WebFX -// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) -// * Non uniform scaling does not correctly scale strokes. -// * Optimize. There is always room for speed improvements. - -// Only add this code if we do not already have a canvas implementation -if (!document.createElement('canvas').getContext) { - - (function () { - - // alias some functions to make (compiled) code shorter - var m = Math; - var mr = m.round; - var ms = m.sin; - var mc = m.cos; - var abs = m.abs; - var sqrt = m.sqrt; - - // this is used for sub pixel precision - var Z = 10; - var Z2 = Z / 2; - - var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; - - /** - * This funtion is assigned to the elements as element.getContext(). - * @this {HTMLElement} - * @return {CanvasRenderingContext2D_} - */ - function getContext() { - return this.context_ || - (this.context_ = new CanvasRenderingContext2D_(this)); - } - - var slice = Array.prototype.slice; - - /** - * Binds a function to an object. The returned function will always use the - * passed in {@code obj} as {@code this}. - * - * Example: - * - * g = bind(f, obj, a, b) - * g(c, d) // will do f.call(obj, a, b, c, d) - * - * @param {Function} f The function to bind the object to - * @param {Object} obj The object that should act as this when the function - * is called - * @param {*} var_args Rest arguments that will be used as the initial - * arguments when the function is called - * @return {Function} A new function that has bound this - */ - function bind(f, obj, var_args) { - var a = slice.call(arguments, 2); - return function () { - return f.apply(obj, a.concat(slice.call(arguments))); - }; - } - - function encodeHtmlAttribute(s) { - return String(s).replace(/&/g, '&').replace(/"/g, '"'); - } - - function addNamespace(doc, prefix, urn) { - if (!doc.namespaces[prefix]) { - doc.namespaces.add(prefix, urn, '#default#VML'); - } - } - - function addNamespacesAndStylesheet(doc) { - addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); - addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); - - // Setup default CSS. Only add one style sheet per document - if (!doc.styleSheets['ex_canvas_']) { - var ss = doc.createStyleSheet(); - ss.owningElement.id = 'ex_canvas_'; - ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + - // default size is 300x150 in Gecko and Opera - 'text-align:left;width:300px;height:150px}'; - } - } - - // Add namespaces and stylesheet at startup. - addNamespacesAndStylesheet(document); - - var G_vmlCanvasManager_ = { - init: function (opt_doc) { - var doc = opt_doc || document; - // Create a dummy element so that IE will allow canvas elements to be - // recognized. - doc.createElement('canvas'); - doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); - }, - - init_: function (doc) { - // find all canvas elements - var els = doc.getElementsByTagName('canvas'); - for (var i = 0; i < els.length; i++) { - this.initElement(els[i]); - } - }, - - /** - * Public initializes a canvas element so that it can be used as canvas - * element from now on. This is called automatically before the page is - * loaded but if you are creating elements using createElement you need to - * make sure this is called on the element. - * @param {HTMLElement} el The canvas element to initialize. - * @return {HTMLElement} the element that was created. - */ - initElement: function (el) { - if (!el.getContext) { - el.getContext = getContext; - - // Add namespaces and stylesheet to document of the element. - addNamespacesAndStylesheet(el.ownerDocument); - - // Remove fallback content. There is no way to hide text nodes so we - // just remove all childNodes. We could hide all elements and remove - // text nodes but who really cares about the fallback content. - el.innerHTML = ''; - - // do not use inline function because that will leak memory - el.attachEvent('onpropertychange', onPropertyChange); - el.attachEvent('onresize', onResize); - - var attrs = el.attributes; - if (attrs.width && attrs.width.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setWidth_(attrs.width.nodeValue); - el.style.width = attrs.width.nodeValue + 'px'; - } else { - el.width = el.clientWidth; - } - if (attrs.height && attrs.height.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setHeight_(attrs.height.nodeValue); - el.style.height = attrs.height.nodeValue + 'px'; - } else { - el.height = el.clientHeight; - } - //el.getContext().setCoordsize_() - } - return el; - } - }; - - function onPropertyChange(e) { - var el = e.srcElement; - - switch (e.propertyName) { - case 'width': - el.getContext().clearRect(); - el.style.width = el.attributes.width.nodeValue + 'px'; - // In IE8 this does not trigger onresize. - el.firstChild.style.width = el.clientWidth + 'px'; - break; - case 'height': - el.getContext().clearRect(); - el.style.height = el.attributes.height.nodeValue + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - break; - } - } - - function onResize(e) { - var el = e.srcElement; - if (el.firstChild) { - el.firstChild.style.width = el.clientWidth + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - } - } - - G_vmlCanvasManager_.init(); - - // precompute "00" to "FF" - var decToHex = []; - for (var i = 0; i < 16; i++) { - for (var j = 0; j < 16; j++) { - decToHex[i * 16 + j] = i.toString(16) + j.toString(16); - } - } - - function createMatrixIdentity() { - return [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1] - ]; - } - - function matrixMultiply(m1, m2) { - var result = createMatrixIdentity(); - - for (var x = 0; x < 3; x++) { - for (var y = 0; y < 3; y++) { - var sum = 0; - - for (var z = 0; z < 3; z++) { - sum += m1[x][z] * m2[z][y]; - } - - result[x][y] = sum; - } - } - return result; - } - - function copyState(o1, o2) { - o2.fillStyle = o1.fillStyle; - o2.lineCap = o1.lineCap; - o2.lineJoin = o1.lineJoin; - o2.lineWidth = o1.lineWidth; - o2.miterLimit = o1.miterLimit; - o2.shadowBlur = o1.shadowBlur; - o2.shadowColor = o1.shadowColor; - o2.shadowOffsetX = o1.shadowOffsetX; - o2.shadowOffsetY = o1.shadowOffsetY; - o2.strokeStyle = o1.strokeStyle; - o2.globalAlpha = o1.globalAlpha; - o2.font = o1.font; - o2.textAlign = o1.textAlign; - o2.textBaseline = o1.textBaseline; - o2.arcScaleX_ = o1.arcScaleX_; - o2.arcScaleY_ = o1.arcScaleY_; - o2.lineScale_ = o1.lineScale_; - } - - // var colorData = { - // aliceblue: '#F0F8FF', - // antiquewhite: '#FAEBD7', - // aquamarine: '#7FFFD4', - // azure: '#F0FFFF', - // beige: '#F5F5DC', - // bisque: '#FFE4C4', - // black: '#000000', - // blanchedalmond: '#FFEBCD', - // blueviolet: '#8A2BE2', - // brown: '#A52A2A', - // burlywood: '#DEB887', - // cadetblue: '#5F9EA0', - // chartreuse: '#7FFF00', - // chocolate: '#D2691E', - // coral: '#FF7F50', - // cornflowerblue: '#6495ED', - // cornsilk: '#FFF8DC', - // crimson: '#DC143C', - // cyan: '#00FFFF', - // darkblue: '#00008B', - // darkcyan: '#008B8B', - // darkgoldenrod: '#B8860B', - // darkgray: '#A9A9A9', - // darkgreen: '#006400', - // darkgrey: '#A9A9A9', - // darkkhaki: '#BDB76B', - // darkmagenta: '#8B008B', - // darkolivegreen: '#556B2F', - // darkorange: '#FF8C00', - // darkorchid: '#9932CC', - // darkred: '#8B0000', - // darksalmon: '#E9967A', - // darkseagreen: '#8FBC8F', - // darkslateblue: '#483D8B', - // darkslategray: '#2F4F4F', - // darkslategrey: '#2F4F4F', - // darkturquoise: '#00CED1', - // darkviolet: '#9400D3', - // deeppink: '#FF1493', - // deepskyblue: '#00BFFF', - // dimgray: '#696969', - // dimgrey: '#696969', - // dodgerblue: '#1E90FF', - // firebrick: '#B22222', - // floralwhite: '#FFFAF0', - // forestgreen: '#228B22', - // gainsboro: '#DCDCDC', - // ghostwhite: '#F8F8FF', - // gold: '#FFD700', - // goldenrod: '#DAA520', - // grey: '#808080', - // greenyellow: '#ADFF2F', - // honeydew: '#F0FFF0', - // hotpink: '#FF69B4', - // indianred: '#CD5C5C', - // indigo: '#4B0082', - // ivory: '#FFFFF0', - // khaki: '#F0E68C', - // lavender: '#E6E6FA', - // lavenderblush: '#FFF0F5', - // lawngreen: '#7CFC00', - // lemonchiffon: '#FFFACD', - // lightblue: '#ADD8E6', - // lightcoral: '#F08080', - // lightcyan: '#E0FFFF', - // lightgoldenrodyellow: '#FAFAD2', - // lightgreen: '#90EE90', - // lightgrey: '#D3D3D3', - // lightpink: '#FFB6C1', - // lightsalmon: '#FFA07A', - // lightseagreen: '#20B2AA', - // lightskyblue: '#87CEFA', - // lightslategray: '#778899', - // lightslategrey: '#778899', - // lightsteelblue: '#B0C4DE', - // lightyellow: '#FFFFE0', - // limegreen: '#32CD32', - // linen: '#FAF0E6', - // magenta: '#FF00FF', - // mediumaquamarine: '#66CDAA', - // mediumblue: '#0000CD', - // mediumorchid: '#BA55D3', - // mediumpurple: '#9370DB', - // mediumseagreen: '#3CB371', - // mediumslateblue: '#7B68EE', - // mediumspringgreen: '#00FA9A', - // mediumturquoise: '#48D1CC', - // mediumvioletred: '#C71585', - // midnightblue: '#191970', - // mintcream: '#F5FFFA', - // mistyrose: '#FFE4E1', - // moccasin: '#FFE4B5', - // navajowhite: '#FFDEAD', - // oldlace: '#FDF5E6', - // olivedrab: '#6B8E23', - // orange: '#FFA500', - // orangered: '#FF4500', - // orchid: '#DA70D6', - // palegoldenrod: '#EEE8AA', - // palegreen: '#98FB98', - // paleturquoise: '#AFEEEE', - // palevioletred: '#DB7093', - // papayawhip: '#FFEFD5', - // peachpuff: '#FFDAB9', - // peru: '#CD853F', - // pink: '#FFC0CB', - // plum: '#DDA0DD', - // powderblue: '#B0E0E6', - // rosybrown: '#BC8F8F', - // royalblue: '#4169E1', - // saddlebrown: '#8B4513', - // salmon: '#FA8072', - // sandybrown: '#F4A460', - // seagreen: '#2E8B57', - // seashell: '#FFF5EE', - // sienna: '#A0522D', - // skyblue: '#87CEEB', - // slateblue: '#6A5ACD', - // slategray: '#708090', - // slategrey: '#708090', - // snow: '#FFFAFA', - // springgreen: '#00FF7F', - // steelblue: '#4682B4', - // tan: '#D2B48C', - // thistle: '#D8BFD8', - // tomato: '#FF6347', - // turquoise: '#40E0D0', - // violet: '#EE82EE', - // wheat: '#F5DEB3', - // whitesmoke: '#F5F5F5', - // yellowgreen: '#9ACD32' - // }; - - - function getRgbHslContent(styleString) { - var start = styleString.indexOf('(', 3); - var end = styleString.indexOf(')', start + 1); - var parts = styleString.substring(start + 1, end).split(','); - // add alpha if needed - if (parts.length != 4 || styleString.charAt(3) != 'a') { - parts[3] = 1; - } - return parts; - } - - function percent(s) { - return parseFloat(s) / 100; - } - - function clamp(v, min, max) { - return Math.min(max, Math.max(min, v)); - } - - function hslToRgb(parts) { - var r, g, b, h, s, l; - h = parseFloat(parts[0]) / 360 % 360; - if (h < 0) - h++; - s = clamp(percent(parts[1]), 0, 1); - l = clamp(percent(parts[2]), 0, 1); - if (s == 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1 / 3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1 / 3); - } - - return '#' + decToHex[Math.floor(r * 255)] + - decToHex[Math.floor(g * 255)] + - decToHex[Math.floor(b * 255)]; - } - - function hueToRgb(m1, m2, h) { - if (h < 0) - h++; - if (h > 1) - h--; - - if (6 * h < 1) - return m1 + (m2 - m1) * 6 * h; - else if (2 * h < 1) - return m2; - else if (3 * h < 2) - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - else - return m1; - } - - var processStyleCache = {}; - - function processStyle(styleString) { - if (styleString in processStyleCache) { - return processStyleCache[styleString]; - } - - var str, alpha = 1; - - styleString = String(styleString); - if (styleString.charAt(0) == '#') { - str = styleString; - } else if (/^rgb/.test(styleString)) { - var parts = getRgbHslContent(styleString); - var str = '#', n; - for (var i = 0; i < 3; i++) { - if (parts[i].indexOf('%') != -1) { - n = Math.floor(percent(parts[i]) * 255); - } else { - n = +parts[i]; - } - str += decToHex[clamp(n, 0, 255)]; - } - alpha = +parts[3]; - } else if (/^hsl/.test(styleString)) { - var parts = getRgbHslContent(styleString); - str = hslToRgb(parts); - alpha = parts[3]; - } else { - str = /*colorData[styleString] ||*/styleString; - } - return processStyleCache[styleString] = { color: str, alpha: alpha }; - } - - var DEFAULT_STYLE = { - style: 'normal', - variant: 'normal', - weight: 'normal', - size: 10, - family: 'sans-serif' - }; - - // Internal text style cache - // var fontStyleCache = {}; - - // function processFontStyle(styleString) { - // if (fontStyleCache[styleString]) { - // return fontStyleCache[styleString]; - // } - - // var el = document.createElement('div'); - // var style = el.style; - // try { - // style.font = styleString; - // } catch (ex) { - // // Ignore failures to set to invalid font. - // } - - // return fontStyleCache[styleString] = { - // style: style.fontStyle || DEFAULT_STYLE.style, - // variant: style.fontVariant || DEFAULT_STYLE.variant, - // weight: style.fontWeight || DEFAULT_STYLE.weight, - // size: style.fontSize || DEFAULT_STYLE.size, - // family: style.fontFamily || DEFAULT_STYLE.family - // }; - // } - - // function getComputedStyle(style, element) { - // var computedStyle = {}; - - // for (var p in style) { - // computedStyle[p] = style[p]; - // } - - // // Compute the size - // var canvasFontSize = parseFloat(element.currentStyle.fontSize), - // fontSize = parseFloat(style.size); - - // if (typeof style.size == 'number') { - // computedStyle.size = style.size; - // } else if (style.size.indexOf('px') != -1) { - // computedStyle.size = fontSize; - // } else if (style.size.indexOf('em') != -1) { - // computedStyle.size = canvasFontSize * fontSize; - // } else if(style.size.indexOf('%') != -1) { - // computedStyle.size = (canvasFontSize / 100) * fontSize; - // } else if (style.size.indexOf('pt') != -1) { - // computedStyle.size = fontSize / .75; - // } else { - // computedStyle.size = canvasFontSize; - // } - - // // Different scaling between normal text and VML text. This was found using - // // trial and error to get the same size as non VML text. - // computedStyle.size *= 0.981; - - // return computedStyle; - // } - - // function buildStyle(style) { - // return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + - // style.size + 'px ' + style.family; - // } - - var lineCapMap = { - 'butt': 'flat', - 'round': 'round' - }; - - function processLineCap(lineCap) { - return lineCapMap[lineCap] || 'square'; - } - - /** - * This class implements CanvasRenderingContext2D interface as described by - * the WHATWG. - * @param {HTMLElement} canvasElement The element that the 2D context should - * be associated with - */ - function CanvasRenderingContext2D_(canvasElement) { - this.m_ = createMatrixIdentity(); - - this.mStack_ = []; - this.aStack_ = []; - this.currentPath_ = []; - - // Canvas context properties - this.strokeStyle = '#000'; - this.fillStyle = '#000'; - - this.lineWidth = 1; - this.lineJoin = 'miter'; - this.lineCap = 'butt'; - this.miterLimit = Z * 1; - this.globalAlpha = 1; - //this.font = '10px sans-serif'; - //this.textAlign = 'left'; - //this.textBaseline = 'alphabetic'; - this.canvas = canvasElement; - - var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + - canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; - var el = canvasElement.ownerDocument.createElement('div'); - el.style.cssText = cssText; - canvasElement.appendChild(el); - - var overlayEl = el.cloneNode(false); - // Use a non transparent background. - overlayEl.style.backgroundColor = 'red'; - overlayEl.style.filter = 'alpha(opacity=0)'; - canvasElement.appendChild(overlayEl); - - this.element_ = el; - this.arcScaleX_ = 1; - this.arcScaleY_ = 1; - this.lineScale_ = 1; - } - - var contextPrototype = CanvasRenderingContext2D_.prototype; - contextPrototype.clearRect = function () { - if (this.textMeasureEl_) { - this.textMeasureEl_.removeNode(true); - this.textMeasureEl_ = null; - } - this.element_.innerHTML = ''; - }; - - contextPrototype.beginPath = function () { - // TODO: Branch current matrix so that save/restore has no effect - // as per safari docs. - this.currentPath_ = []; - }; - - contextPrototype.moveTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'moveTo', x: p.x, y: p.y }); - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.lineTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'lineTo', x: p.x, y: p.y }); - - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY) { - var p = getCoords(this, aX, aY); - var cp1 = getCoords(this, aCP1x, aCP1y); - var cp2 = getCoords(this, aCP2x, aCP2y); - bezierCurveTo(this, cp1, cp2, p); - }; - - // Helper function that takes the already fixed cordinates. - function bezierCurveTo(self, cp1, cp2, p) { - self.currentPath_.push({ - type: 'bezierCurveTo', - cp1x: cp1.x, - cp1y: cp1.y, - cp2x: cp2.x, - cp2y: cp2.y, - x: p.x, - y: p.y - }); - self.currentX_ = p.x; - self.currentY_ = p.y; - } - - contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { - // the following is lifted almost directly from - // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes - - var cp = getCoords(this, aCPx, aCPy); - var p = getCoords(this, aX, aY); - - var cp1 = { - x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), - y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) - }; - var cp2 = { - x: cp1.x + (p.x - this.currentX_) / 3.0, - y: cp1.y + (p.y - this.currentY_) / 3.0 - }; - - bezierCurveTo(this, cp1, cp2, p); - }; - - contextPrototype.arc = function (aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise) { - aRadius *= Z; - var arcType = aClockwise ? 'at' : 'wa'; - - var xStart = aX + mc(aStartAngle) * aRadius - Z2; - var yStart = aY + ms(aStartAngle) * aRadius - Z2; - - var xEnd = aX + mc(aEndAngle) * aRadius - Z2; - var yEnd = aY + ms(aEndAngle) * aRadius - Z2; - - // IE won't render arches drawn counter clockwise if xStart == xEnd. - if (xStart == xEnd && !aClockwise) { - xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something - // that can be represented in binary - } - - var p = getCoords(this, aX, aY); - var pStart = getCoords(this, xStart, yStart); - var pEnd = getCoords(this, xEnd, yEnd); - - this.currentPath_.push({ type: arcType, - x: p.x, - y: p.y, - radius: aRadius, - xStart: pStart.x, - yStart: pStart.y, - xEnd: pEnd.x, - yEnd: pEnd.y - }); - - }; - - // contextPrototype.rect = function(aX, aY, aWidth, aHeight) { - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // }; - - // contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.stroke(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.fill(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { - // var gradient = new CanvasGradient_('gradient'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // return gradient; - // }; - - // contextPrototype.createRadialGradient = function(aX0, aY0, aR0, - // aX1, aY1, aR1) { - // var gradient = new CanvasGradient_('gradientradial'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.r0_ = aR0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // gradient.r1_ = aR1; - // return gradient; - // }; - - // contextPrototype.drawImage = function(image, var_args) { - // var dx, dy, dw, dh, sx, sy, sw, sh; - - // // to find the original width we overide the width and height - // var oldRuntimeWidth = image.runtimeStyle.width; - // var oldRuntimeHeight = image.runtimeStyle.height; - // image.runtimeStyle.width = 'auto'; - // image.runtimeStyle.height = 'auto'; - - // // get the original size - // var w = image.width; - // var h = image.height; - - // // and remove overides - // image.runtimeStyle.width = oldRuntimeWidth; - // image.runtimeStyle.height = oldRuntimeHeight; - - // if (arguments.length == 3) { - // dx = arguments[1]; - // dy = arguments[2]; - // sx = sy = 0; - // sw = dw = w; - // sh = dh = h; - // } else if (arguments.length == 5) { - // dx = arguments[1]; - // dy = arguments[2]; - // dw = arguments[3]; - // dh = arguments[4]; - // sx = sy = 0; - // sw = w; - // sh = h; - // } else if (arguments.length == 9) { - // sx = arguments[1]; - // sy = arguments[2]; - // sw = arguments[3]; - // sh = arguments[4]; - // dx = arguments[5]; - // dy = arguments[6]; - // dw = arguments[7]; - // dh = arguments[8]; - // } else { - // throw Error('Invalid number of arguments'); - // } - - // var d = getCoords(this, dx, dy); - - // var w2 = sw / 2; - // var h2 = sh / 2; - - // var vmlStr = []; - - // var W = 10; - // var H = 10; - - // // For some reason that I've now forgotten, using divs didn't work - // vmlStr.push(' ' , - // '', - // ''); - - // this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); - // }; - - contextPrototype.stroke = function (aFill) { - var lineStr = []; - var lineOpen = false; - - var W = 10; - var H = 10; - - lineStr.push(''); - - if (!aFill) { - appendStroke(this, lineStr); - } else { - appendFill(this, lineStr, min, max); - } - - lineStr.push(''); - - this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - }; - - function appendStroke(ctx, lineStr) { - var a = processStyle(ctx.strokeStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - var lineWidth = ctx.lineScale_ * ctx.lineWidth; - - // VML cannot correctly render a line if the width is less than 1px. - // In that case, we dilute the color to make the line look thinner. - if (lineWidth < 1) { - opacity *= lineWidth; - } - - lineStr.push( - '' - ); - } - - function appendFill(ctx, lineStr, min, max) { - var fillStyle = ctx.fillStyle; - var arcScaleX = ctx.arcScaleX_; - var arcScaleY = ctx.arcScaleY_; - var width = max.x - min.x; - var height = max.y - min.y; - // if (fillStyle instanceof CanvasGradient_) { - // // TODO: Gradients transformed with the transformation matrix. - // var angle = 0; - // var focus = {x: 0, y: 0}; - - // // additional offset - // var shift = 0; - // // scale factor for offset - // var expansion = 1; - - // if (fillStyle.type_ == 'gradient') { - // var x0 = fillStyle.x0_ / arcScaleX; - // var y0 = fillStyle.y0_ / arcScaleY; - // var x1 = fillStyle.x1_ / arcScaleX; - // var y1 = fillStyle.y1_ / arcScaleY; - // var p0 = getCoords(ctx, x0, y0); - // var p1 = getCoords(ctx, x1, y1); - // var dx = p1.x - p0.x; - // var dy = p1.y - p0.y; - // angle = Math.atan2(dx, dy) * 180 / Math.PI; - - // // The angle should be a non-negative number. - // if (angle < 0) { - // angle += 360; - // } - - // // Very small angles produce an unexpected result because they are - // // converted to a scientific notation string. - // if (angle < 1e-6) { - // angle = 0; - // } - // } else { - // var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); - // focus = { - // x: (p0.x - min.x) / width, - // y: (p0.y - min.y) / height - // }; - - // width /= arcScaleX * Z; - // height /= arcScaleY * Z; - // var dimension = m.max(width, height); - // shift = 2 * fillStyle.r0_ / dimension; - // expansion = 2 * fillStyle.r1_ / dimension - shift; - // } - - // // We need to sort the color stops in ascending order by offset, - // // otherwise IE won't interpret it correctly. - // var stops = fillStyle.colors_; - // stops.sort(function(cs1, cs2) { - // return cs1.offset - cs2.offset; - // }); - - // var length = stops.length; - // var color1 = stops[0].color; - // var color2 = stops[length - 1].color; - // var opacity1 = stops[0].alpha * ctx.globalAlpha; - // var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; - - // var colors = []; - // for (var i = 0; i < length; i++) { - // var stop = stops[i]; - // colors.push(stop.offset * expansion + shift + ' ' + stop.color); - // } - - // // When colors attribute is used, the meanings of opacity and o:opacity2 - // // are reversed. - // lineStr.push(''); - // } else if (fillStyle instanceof CanvasPattern_) { - // if (width && height) { - // var deltaLeft = -min.x; - // var deltaTop = -min.y; - // lineStr.push(''); - // } - // } else { - var a = processStyle(ctx.fillStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - lineStr.push(''); - // } - } - - contextPrototype.fill = function () { - this.stroke(true); - }; - - contextPrototype.closePath = function () { - this.currentPath_.push({ type: 'close' }); - }; - - function getCoords(ctx, aX, aY) { - var m = ctx.m_; - return { - x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, - y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 - }; - }; - - contextPrototype.save = function () { - var o = {}; - copyState(this, o); - this.aStack_.push(o); - this.mStack_.push(this.m_); - this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); - }; - - contextPrototype.restore = function () { - if (this.aStack_.length) { - copyState(this.aStack_.pop(), this); - this.m_ = this.mStack_.pop(); - } - }; - - function matrixIsFinite(m) { - return isFinite(m[0][0]) && isFinite(m[0][1]) && - isFinite(m[1][0]) && isFinite(m[1][1]) && - isFinite(m[2][0]) && isFinite(m[2][1]); - } - - function setM(ctx, m, updateLineScale) { - if (!matrixIsFinite(m)) { - return; - } - ctx.m_ = m; - - if (updateLineScale) { - // Get the line scale. - // Determinant of this.m_ means how much the area is enlarged by the - // transformation. So its square root can be used as a scale factor - // for width. - var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; - ctx.lineScale_ = sqrt(abs(det)); - } - } - - contextPrototype.translate = function (aX, aY) { - var m1 = [ - [1, 0, 0], - [0, 1, 0], - [aX, aY, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), false); - }; - - // contextPrototype.rotate = function(aRot) { - // var c = mc(aRot); - // var s = ms(aRot); - - // var m1 = [ - // [c, s, 0], - // [-s, c, 0], - // [0, 0, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), false); - // }; - - contextPrototype.scale = function (aX, aY) { - this.arcScaleX_ *= aX; - this.arcScaleY_ *= aY; - var m1 = [ - [aX, 0, 0], - [0, aY, 0], - [0, 0, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), true); - }; - - // contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { - // var m1 = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), true); - // }; - - // contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { - // var m = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, m, true); - // }; - - /** - * The text drawing function. - * The maxWidth argument isn't taken in account, since no browser supports - * it yet. - */ - // contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { - // var m = this.m_, - // delta = 1000, - // left = 0, - // right = delta, - // offset = {x: 0, y: 0}, - // lineStr = []; - - // var fontStyle = getComputedStyle(processFontStyle(this.font), - // this.element_); - - // var fontStyleString = buildStyle(fontStyle); - - // var elementStyle = this.element_.currentStyle; - // var textAlign = this.textAlign.toLowerCase(); - // switch (textAlign) { - // case 'left': - // case 'center': - // case 'right': - // break; - // case 'end': - // textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; - // break; - // case 'start': - // textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; - // break; - // default: - // textAlign = 'left'; - // } - - // // 1.75 is an arbitrary number, as there is no info about the text baseline - // switch (this.textBaseline) { - // case 'hanging': - // case 'top': - // offset.y = fontStyle.size / 1.75; - // break; - // case 'middle': - // break; - // default: - // case null: - // case 'alphabetic': - // case 'ideographic': - // case 'bottom': - // offset.y = -fontStyle.size / 2.25; - // break; - // } - - // switch(textAlign) { - // case 'right': - // left = delta; - // right = 0.05; - // break; - // case 'center': - // left = right = delta / 2; - // break; - // } - - // var d = getCoords(this, x + offset.x, y + offset.y); - - // lineStr.push(''); - - // if (stroke) { - // appendStroke(this, lineStr); - // } else { - // // TODO: Fix the min and max params. - // appendFill(this, lineStr, {x: -left, y: 0}, - // {x: right, y: fontStyle.size}); - // } - - // var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + - // m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; - - // var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); - - // lineStr.push('', - // '', - // ''); - - // this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - // }; - - // contextPrototype.fillText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, false); - // }; - - // contextPrototype.strokeText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, true); - // }; - - // contextPrototype.measureText = function(text) { - // if (!this.textMeasureEl_) { - // var s = ''; - // this.element_.insertAdjacentHTML('beforeEnd', s); - // this.textMeasureEl_ = this.element_.lastChild; - // } - // var doc = this.element_.ownerDocument; - // this.textMeasureEl_.innerHTML = ''; - // this.textMeasureEl_.style.font = this.font; - // // Don't use innerHTML or innerText because they allow markup/whitespace. - // this.textMeasureEl_.appendChild(doc.createTextNode(text)); - // return {width: this.textMeasureEl_.offsetWidth}; - // }; - - /******** STUBS ********/ - // contextPrototype.clip = function() { - // // TODO: Implement - // }; - - // contextPrototype.arcTo = function() { - // // TODO: Implement - // }; - - // contextPrototype.createPattern = function(image, repetition) { - // return new CanvasPattern_(image, repetition); - // }; - - // // Gradient / Pattern Stubs - // function CanvasGradient_(aType) { - // this.type_ = aType; - // this.x0_ = 0; - // this.y0_ = 0; - // this.r0_ = 0; - // this.x1_ = 0; - // this.y1_ = 0; - // this.r1_ = 0; - // this.colors_ = []; - // } - - // CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { - // aColor = processStyle(aColor); - // this.colors_.push({offset: aOffset, - // color: aColor.color, - // alpha: aColor.alpha}); - // }; - - // function CanvasPattern_(image, repetition) { - // assertImageIsValid(image); - // switch (repetition) { - // case 'repeat': - // case null: - // case '': - // this.repetition_ = 'repeat'; - // break - // case 'repeat-x': - // case 'repeat-y': - // case 'no-repeat': - // this.repetition_ = repetition; - // break; - // default: - // throwException('SYNTAX_ERR'); - // } - - // this.src_ = image.src; - // this.width_ = image.width; - // this.height_ = image.height; - // } - - function throwException(s) { - throw new DOMException_(s); - } - - // function assertImageIsValid(img) { - // if (!img || img.nodeType != 1 || img.tagName != 'IMG') { - // throwException('TYPE_MISMATCH_ERR'); - // } - // if (img.readyState != 'complete') { - // throwException('INVALID_STATE_ERR'); - // } - // } - - function DOMException_(s) { - this.code = this[s]; - this.message = s + ': DOM Exception ' + this.code; - } - var p = DOMException_.prototype = new Error; - p.INDEX_SIZE_ERR = 1; - p.DOMSTRING_SIZE_ERR = 2; - p.HIERARCHY_REQUEST_ERR = 3; - p.WRONG_DOCUMENT_ERR = 4; - p.INVALID_CHARACTER_ERR = 5; - p.NO_DATA_ALLOWED_ERR = 6; - p.NO_MODIFICATION_ALLOWED_ERR = 7; - p.NOT_FOUND_ERR = 8; - p.NOT_SUPPORTED_ERR = 9; - p.INUSE_ATTRIBUTE_ERR = 10; - p.INVALID_STATE_ERR = 11; - p.SYNTAX_ERR = 12; - p.INVALID_MODIFICATION_ERR = 13; - p.NAMESPACE_ERR = 14; - p.INVALID_ACCESS_ERR = 15; - p.VALIDATION_ERR = 16; - p.TYPE_MISMATCH_ERR = 17; - - // set up externs - G_vmlCanvasManager = G_vmlCanvasManager_; - CanvasRenderingContext2D = CanvasRenderingContext2D_; - //CanvasGradient = CanvasGradient_; - //CanvasPattern = CanvasPattern_; - DOMException = DOMException_; - })(); - -} // if -/*! - * jQuery UI Widget @VERSION - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ - -if ( ! $.widget ) { - -(function( $, undefined ) { - -// jQuery 1.4+ -if ( $.cleanData ) { - var _cleanData = $.cleanData; - $.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); - }; -} else { - var _remove = $.fn.remove; - $.fn.remove = function( selector, keepData ) { - return this.each(function() { - if ( !keepData ) { - if ( !selector || $.filter( selector, [ this ] ).length ) { - $( "*", this ).add( [ this ] ).each(function() { - try { - $( this ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - }); - } - } - return _remove.call( $(this), selector, keepData ); - }); - }; -} - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from -// $.each( basePrototype, function( key, val ) { -// if ( $.isPlainObject(val) ) { -// basePrototype[ key ] = $.extend( {}, val ); -// } -// }); - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = Array.prototype.slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - // prevent calls to internal methods - if ( isMethodCall && options.charAt( 0 ) === "_" ) { - return returnValue; - } - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ), - methodValue = instance && $.isFunction( instance[options] ) ? - instance[ options ].apply( instance, args ) : - instance; - // TODO: add this back in 1.9 and use $.error() (see #5972) -// if ( !instance ) { -// throw "cannot call methods on " + name + " prior to initialization; " + -// "attempted to call method '" + options + "'"; -// } -// if ( !$.isFunction( instance[options] ) ) { -// throw "no such method '" + options + "' for " + name + " widget instance"; -// } -// var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, name, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - // $.widget.bridge stores the plugin instance, but we do it anyway - // so that it's stored even before the _create function runs - $.data( element, this.widgetName, this ); - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - var self = this; - this.element.bind( "remove." + this.widgetName, function() { - self.destroy(); - }); - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: function() {}, - _init: function() {}, - - destroy: function() { - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - }, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - [ value ? "addClass" : "removeClass"]( - this.widgetBaseClass + "-disabled" + " " + - "ui-state-disabled" ) - .attr( "aria-disabled", value ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - - return !( $.isFunction(callback) && - callback.call( this.element[0], event, data ) === false || - event.isDefaultPrevented() ); - } -}; - -})( jQuery ); - -} - -/*! JsRender v1.0pre - (jsrender.js version: does not require jQuery): http://github.com/BorisMoore/jsrender */ -/* - * Optimized version of jQuery Templates, fosr rendering to string, using 'codeless' markup. - * - * Copyright 2011, Boris Moore - * Released under the MIT License. - */ -window.JsViews || window.jQuery && jQuery.views || (function( window, undefined ) { - -var $, _$, JsViews, viewsNs, tmplEncode, render, rTag, registerTags, registerHelpers, extend, - FALSE = false, TRUE = true, - jQuery = window.jQuery, document = window.document, - htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, - rPath = /^(true|false|null|[\d\.]+)|(\w+|\$(view|data|ctx|(\w+)))([\w\.]*)|((['"])(?:\\\1|.)*\7)$/g, - rParams = /(\$?[\w\.\[\]]+)(?:(\()|\s*(===|!==|==|!=|<|>|<=|>=)\s*|\s*(\=)\s*)?|(\,\s*)|\\?(\')|\\?(\")|(\))|(\s+)/g, - rNewLine = /\r?\n/g, - rUnescapeQuotes = /\\(['"])/g, - rEscapeQuotes = /\\?(['"])/g, - rBuildHash = /\x08([^\x08]+)\x08/g, - autoName = 0, - escapeMapForHtml = { - "&": "&", - "<": "<", - ">": ">" - }, - htmlSpecialChar = /[\x00"&'<>]/g, - slice = Array.prototype.slice; - -if ( jQuery ) { - - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is loaded, so make $ the jQuery object - $ = jQuery; - - $.fn.extend({ - // Use first wrapped element as template markup. - // Return string obtained by rendering the template against data. - render: function( data, context, parentView, path ) { - return render( data, this[0], context, parentView, path ); - }, - - // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template. - template: function( name, context ) { - return $.template( name, this[0], context ); - } - }); - -} else { - - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is not loaded. Make $ the JsViews object - - // Map over the $ in case of overwrite - _$ = window.$; - - window.JsViews = JsViews = window.$ = $ = { - extend: function( target, source ) { - var name; - for ( name in source ) { - target[ name ] = source[ name ]; - } - return target; - }, - isArray: Array.isArray || function( obj ) { - return Object.prototype.toString.call( obj ) === "[object Array]"; - }, - noConflict: function() { - if ( window.$ === JsViews ) { - window.$ = _$; - } - return JsViews; - } - }; -} - -extend = $.extend; - -//================= -// View constructor -//================= - -function View( context, path, parentView, data, template ) { - // Returns a view data structure for a new rendered instance of a template. - // The content field is a hierarchical array of strings and nested views. - - parentView = parentView || { viewsCount:0, ctx: viewsNs.helpers }; - - var parentContext = parentView && parentView.ctx; - - return { - jsViews: "v1.0pre", - path: path || "", - // inherit context from parentView, merged with new context. - itemNumber: ++parentView.viewsCount || 1, - viewsCount: 0, - tmpl: template, - data: data || parentView.data || {}, - // Set additional context on this view (which will modify the context inherited from the parent, and be inherited by child views) - ctx : context && context === parentContext - ? parentContext - : (parentContext ? extend( extend( {}, parentContext ), context ) : context||{}), - // If no jQuery, extend does not support chained copies - so limit to two parameters - parent: parentView - }; -} -extend( $, { - views: viewsNs = { - templates: {}, - tags: { - "if": function() { - var ifTag = this, - view = ifTag._view; - view.onElse = function( presenter, args ) { - var i = 0, - l = args.length; - while ( l && !args[ i++ ]) { - // Only render content if args.length === 0 (i.e. this is an else with no condition) or if a condition argument is truey - if ( i === l ) { - return ""; - } - } - view.onElse = undefined; // If condition satisfied, so won't run 'else'. - return render( view.data, presenter.tmpl, view.ctx, view); - }; - return view.onElse( this, arguments ); - }, - "else": function() { - var view = this._view; - return view.onElse ? view.onElse( this, arguments ) : ""; - }, - each: function() { - var i, - self = this, - result = "", - args = arguments, - l = args.length, - content = self.tmpl, - view = self._view; - for ( i = 0; i < l; i++ ) { - result += args[ i ] ? render( args[ i ], content, self.ctx || view.ctx, view, self._path, self._ctor ) : ""; - } - return l ? result - // If no data parameter, use the current $data from view, and render once - : result + render( view.data, content, view.ctx, view, self._path, self.tag ); - }, - "=": function( value ) { - return value; - }, - "*": function( value ) { - return value; - } - }, - helpers: { - not: function( value ) { - return !value; - } - }, - allowCode: FALSE, - debugMode: TRUE, - err: function( e ) { - return viewsNs.debugMode ? ("
                            Error: " + (e.message || e) + ". "): '""'; - }, - -//=============== -// setDelimiters -//=============== - - setDelimiters: function( openTag, closeTag ) { - // Set or modify the delimiter characters for tags: "{{" and "}}" - var firstCloseChar = closeTag.charAt( 0 ), - secondCloseChar = closeTag.charAt( 1 ); - openTag = "\\" + openTag.charAt( 0 ) + "\\" + openTag.charAt( 1 ); - closeTag = "\\" + firstCloseChar + "\\" + secondCloseChar; - - // Build regex with new delimiters - // {{ - rTag = openTag - // # tag (followed by space,! or }) or equals or code - + "(?:(?:(\\#)?(\\w+(?=[!\\s\\" + firstCloseChar + "]))" + "|(?:(\\=)|(\\*)))" - // params - + "\\s*((?:[^\\" + firstCloseChar + "]|\\" + firstCloseChar + "(?!\\" + secondCloseChar + "))*?)" - // encoding - + "(!(\\w*))?" - // closeBlock - + "|(?:\\/([\\w\\$\\.\\[\\]]+)))" - // }} - + closeTag; - - // Default rTag: # tag equals code params encoding closeBlock - // /\{\{(?:(?:(\#)?(\w+(?=[\s\}!]))|(?:(\=)|(\*)))((?:[^\}]|\}(?!\}))*?)(!(\w*))?|(?:\/([\w\$\.\[\]]+)))\}\}/g; - - rTag = new RegExp( rTag, "g" ); - }, - - -//=============== -// registerTags -//=============== - - // Register declarative tag. - registerTags: registerTags = function( name, tagFn ) { - var key; - if ( typeof name === "object" ) { - for ( key in name ) { - registerTags( key, name[ key ]); - } - } else { - // Simple single property case. - viewsNs.tags[ name ] = tagFn; - } - return this; - }, - -//=============== -// registerHelpers -//=============== - - // Register helper function for use in markup. - registerHelpers: registerHelpers = function( name, helper ) { - if ( typeof name === "object" ) { - // Object representation where property name is path and property value is value. - // TODO: We've discussed an "objectchange" event to capture all N property updates here. See TODO note above about propertyChanges. - var key; - for ( key in name ) { - registerHelpers( key, name[ key ]); - } - } else { - // Simple single property case. - viewsNs.helpers[ name ] = helper; - } - return this; - }, - -//=============== -// tmpl.encode -//=============== - - encode: function( encoding, text ) { - return text - ? ( tmplEncode[ encoding || "html" ] || tmplEncode.html)( text ) // HTML encoding is the default - : ""; - }, - - encoders: tmplEncode = { - "none": function( text ) { - return text; - }, - "html": function( text ) { - // HTML encoding helper: Replace < > & and ' and " by corresponding entities. - // Implementation, from Mike Samuel - return String( text ).replace( htmlSpecialChar, replacerForHtml ); - } - //TODO add URL encoding, and perhaps other encoding helpers... - }, - -//=============== -// renderTag -//=============== - - renderTag: function( tag, view, encode, content, tagProperties ) { - // This is a tag call, with arguments: "tag", view, encode, content, presenter [, params...] - var ret, ctx, name, - args = arguments, - presenters = viewsNs.presenters; - hash = tagProperties._hash, - tagFn = viewsNs.tags[ tag ]; - - if ( !tagFn ) { - return ""; - } - - content = content && view.tmpl.nested[ content - 1 ]; - tagProperties.tmpl = tagProperties.tmpl || content || undefined; - // Set the tmpl property to the content of the block tag, unless set as an override property on the tag - - if ( presenters && presenters[ tag ]) { - ctx = extend( extend( {}, tagProperties.ctx ), tagProperties ); - delete ctx.ctx; - delete ctx._path; - delete ctx.tmpl; - tagProperties.ctx = ctx; - tagProperties._ctor = tag + (hash ? "=" + hash.slice( 0, -1 ) : ""); - - tagProperties = extend( extend( {}, tagFn ), tagProperties ); - tagFn = viewsNs.tags.each; // Use each to render the layout template against the data - } - - tagProperties._encode = encode; - tagProperties._view = view; - ret = tagFn.apply( tagProperties, args.length > 5 ? slice.call( args, 5 ) : [view.data] ); - return ret || (ret === undefined ? "" : ret.toString()); // (If ret is the value 0 or false or null, will render to string) - } - }, - -//=============== -// render -//=============== - - render: render = function( data, tmpl, context, parentView, path, tagName ) { - // Render template against data as a tree of subviews (nested template), or as a string (top-level template). - // tagName parameter for internal use only. Used for rendering templates registered as tags (which may have associated presenter objects) - var i, l, dataItem, arrayView, content, result = ""; - - if ( arguments.length === 2 && data.jsViews ) { - parentView = data; - context = parentView.ctx; - data = parentView.data; - } - tmpl = $.template( tmpl ); - if ( !tmpl ) { - return ""; // Could throw... - } - - if ( $.isArray( data )) { - // Create a view item for the array, whose child views correspond to each data item. - arrayView = new View( context, path, parentView, data); - l = data.length; - for ( i = 0, l = data.length; i < l; i++ ) { - dataItem = data[ i ]; - content = dataItem ? tmpl( dataItem, new View( context, path, arrayView, dataItem, tmpl, this )) : ""; - result += viewsNs.activeViews ? "" + content + "" : content; - } - } else { - result += tmpl( data, new View( context, path, parentView, data, tmpl )); - } - - return viewsNs.activeViews - // If in activeView mode, include annotations - ? "" + result + "" - // else return just the string result - : result; - }, - -//=============== -// template -//=============== - - template: function( name, tmpl ) { - // Set: - // Use $.template( name, tmpl ) to cache a named template, - // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc. - // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration. - - // Get: - // Use $.template( name ) to access a cached template. - // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString ) - // will return the compiled template, without adding a name reference. - // If templateString is not a selector, $.template( templateString ) is equivalent - // to $.template( null, templateString ). To ensure a string is treated as a template, - // include an HTML element, an HTML comment, or a template comment tag. - - if (tmpl) { - // Compile template and associate with name - if ( "" + tmpl === tmpl ) { // type string - // This is an HTML string being passed directly in. - tmpl = compile( tmpl ); - } else if ( jQuery && tmpl instanceof $ ) { - tmpl = tmpl[0]; - } - if ( tmpl ) { - if ( jQuery && tmpl.nodeType ) { - // If this is a template block, use cached copy, or generate tmpl function and cache. - tmpl = $.data( tmpl, "tmpl" ) || $.data( tmpl, "tmpl", compile( tmpl.innerHTML )); - } - viewsNs.templates[ tmpl._name = tmpl._name || name || "_" + autoName++ ] = tmpl; - } - return tmpl; - } - // Return named compiled template - return name - ? "" + name !== name // not type string - ? (name._name - ? name // already compiled - : $.template( null, name )) - : viewsNs.templates[ name ] || - // If not in map, treat as a selector. (If integrated with core, use quickExpr.exec) - $.template( null, htmlExpr.test( name ) ? name : try$( name )) - : null; - } -}); - -viewsNs.setDelimiters( "{{", "}}" ); - -//================= -// compile template -//================= - -// Generate a reusable function that will serve to render a template against data -// (Compile AST then build template function) - -function parsePath( all, comp, object, viewDataCtx, viewProperty, path, string, quot ) { - return object - ? ((viewDataCtx - ? viewProperty - ? ("$view." + viewProperty) - : object - :("$data." + object) - ) + ( path || "" )) - : string || (comp || ""); -} - -function compile( markup ) { - var newNode, - loc = 0, - stack = [], - topNode = [], - content = topNode, - current = [,,topNode]; - - function pushPreceedingContent( shift ) { - shift -= loc; - if ( shift ) { - content.push( markup.substr( loc, shift ).replace( rNewLine,"\\n")); - } - } - - function parseTag( all, isBlock, tagName, equals, code, params, useEncode, encode, closeBlock, index ) { - // rTag : # tagName equals code params encode closeBlock - // /\{\{(?:(?:(\#)?(\w+(?=[\s\}!]))|(?:(\=)|(\*)))((?:[^\}]|\}(?!\}))*?)(!(\w*))?|(?:\/([\w\$\.\[\]]+)))\}\}/g; - - // Build abstract syntax tree: [ tagName, params, content, encode ] - var named, - hash = "", - parenDepth = 0, - quoted = FALSE, // boolean for string content in double qoutes - aposed = FALSE; // or in single qoutes - - function parseParams( all, path, paren, comp, eq, comma, apos, quot, rightParen, space, index ) { - // path paren eq comma apos quot rtPrn space - // /(\$?[\w\.\[\]]+)(?:(\()|(===)|(\=))?|(\,\s*)|\\?(\')|\\?(\")|(\))|(\s+)/g - - return aposed - // within single-quoted string - ? ( aposed = !apos, (aposed ? all : '"')) - : quoted - // within double-quoted string - ? ( quoted = !quot, (quoted ? all : '"')) - : comp - // comparison - ? ( path.replace( rPath, parsePath ) + comp) - : eq - // named param - ? parenDepth ? "" :( named = TRUE, '\b' + path + ':') - : paren - // function - ? (parenDepth++, path.replace( rPath, parsePath ) + '(') - : rightParen - // function - ? (parenDepth--, ")") - : path - // path - ? path.replace( rPath, parsePath ) - : comma - ? "," - : space - ? (parenDepth - ? "" - : named - ? ( named = FALSE, "\b") - : "," - ) - : (aposed = apos, quoted = quot, '"'); - } - - tagName = tagName || equals; - pushPreceedingContent( index ); - if ( code ) { - if ( viewsNs.allowCode ) { - content.push([ "*", params.replace( rUnescapeQuotes, "$1" )]); - } - } else if ( tagName ) { - if ( tagName === "else" ) { - current = stack.pop(); - content = current[ 2 ]; - isBlock = TRUE; - } - params = (params - ? (params + " ") - .replace( rParams, parseParams ) - .replace( rBuildHash, function( all, keyValue, index ) { - hash += keyValue + ","; - return ""; - }) - : ""); - params = params.slice( 0, -1 ); - newNode = [ - tagName, - useEncode ? encode || "none" : "", - isBlock && [], - "{" + hash + "_hash:'" + hash + "',_path:'" + params + "'}", - params - ]; - - if ( isBlock ) { - stack.push( current ); - current = newNode; - } - content.push( newNode ); - } else if ( closeBlock ) { - current = stack.pop(); - } - loc = index + all.length; // location marker - parsed up to here - if ( !current ) { - throw "Expected block tag"; - } - content = current[ 2 ]; - } - markup = markup.replace( rEscapeQuotes, "\\$1" ); - markup.replace( rTag, parseTag ); - pushPreceedingContent( markup.length ); - return buildTmplFunction( topNode ); -} - -// Build javascript compiled template function, from AST -function buildTmplFunction( nodes ) { - var ret, node, i, - nested = [], - l = nodes.length, - code = "try{var views=" - + (jQuery ? "jQuery" : "JsViews") - + '.views,tag=views.renderTag,enc=views.encode,html=views.encoders.html,$ctx=$view && $view.ctx,result=""+\n\n'; - - for ( i = 0; i < l; i++ ) { - node = nodes[ i ]; - if ( node[ 0 ] === "*" ) { - code = code.slice( 0, i ? -1 : -3 ) + ";" + node[ 1 ] + ( i + 1 < l ? "result+=" : "" ); - } else if ( "" + node === node ) { // type string - code += '"' + node + '"+'; - } else { - var tag = node[ 0 ], - encode = node[ 1 ], - content = node[ 2 ], - obj = node[ 3 ], - params = node[ 4 ], - paramsOrEmptyString = params + '||"")+'; - - if( content ) { - nested.push( buildTmplFunction( content )); - } - code += tag === "=" - ? (!encode || encode === "html" - ? "html(" + paramsOrEmptyString - : encode === "none" - ? ("(" + paramsOrEmptyString) - : ('enc("' + encode + '",' + paramsOrEmptyString) - ) - : 'tag("' + tag + '",$view,"' + ( encode || "" ) + '",' - + (content ? nested.length : '""') // For block tags, pass in the key (nested.length) to the nested content template - + "," + obj + (params ? "," : "") + params + ")+"; - } - } - ret = new Function( "$data, $view", code.slice( 0, -1) + ";return result;\n\n}catch(e){return views.err(e);}" ); - ret.nested = nested; - return ret; -} - -//========================== Private helper functions, used by code above ========================== - -function replacerForHtml( ch ) { - // Original code from Mike Samuel - return escapeMapForHtml[ ch ] - // Intentional assignment that caches the result of encoding ch. - || ( escapeMapForHtml[ ch ] = "&#" + ch.charCodeAt( 0 ) + ";" ); -} - -function try$( selector ) { - // If selector is valid, return jQuery object, otherwise return (invalid) selector string - try { - return $( selector ); - } catch( e) {} - return selector; -} -})( window ); -(function ($, window, undefined) { - var pos_oo = Number.POSITIVE_INFINITY, - neg_oo = Number.NEGATIVE_INFINITY; - - $.geo = { - // - // utility functions - // - - _allCoordinates: function (geom) { - // return array of all positions in all geometries of geom - // not in JTS - var geometries = this._flatten(geom), - curGeom = 0, - result = []; - - for (; curGeom < geometries.length; curGeom++) { - var coordinates = geometries[curGeom].coordinates, - isArray = coordinates && $.isArray(coordinates[0]), - isDblArray = isArray && $.isArray(coordinates[0][0]), - isTriArray = isDblArray && $.isArray(coordinates[0][0][0]), - i, j, k; - - if (!isTriArray) { - if (!isDblArray) { - if (!isArray) { - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - for (k = 0; k < coordinates[i][j].length; k++) { - result.push(coordinates[i][j][k]); - } - } - } - } - return result; - }, - - _isGeodetic: function( coords ) { - // returns true if the first coordinate it can find is geodetic - - while ( $.isArray( coords ) ) { - if ( coords.length > 1 && ! $.isArray( coords[ 0 ] ) ) { - return ( coords[ 0 ] >= -180 && coords[ 0 ] <= 180 && coords[ 1 ] >= -85 && coords[ 1 ] <= 85 ); - } else { - coords = coords[ 0 ]; - } - } - - return false; - }, - - // - // bbox functions - // - - center: function (bbox, _ignoreGeo /* Internal Use Only */) { - // Envelope.centre in JTS - // bbox only, use centroid for geom - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return wasGeodetic ? $.geo.proj.toGeodetic(center) : center; - }, - - expandBy: function (bbox, dx, dy, _ignoreGeo /* Internal Use Only */) { - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - bbox = [bbox[0] - dx, bbox[1] - dy, bbox[2] + dx, bbox[3] + dy]; - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - height: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[3] - bbox[1]; - }, - - _in: function(bbox1, bbox2) { - return bbox1[0] <= bbox2[0] && - bbox1[1] <= bbox2[1] && - bbox1[2] >= bbox2[2] && - bbox1[3] >= bbox2[3]; - }, - - _bboxDisjoint: function( bbox1, bbox2 ) { - return bbox2[ 0 ] > bbox1[ 2 ] || - bbox2[ 2 ] < bbox1[ 0 ] || - bbox2[ 1 ] > bbox1[ 3 ] || - bbox2[ 3 ] < bbox1[ 1 ]; - }, - - reaspect: function (bbox, ratio, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var width = this.width(bbox, true), - height = this.height(bbox, true), - center = this.center(bbox, true), - dx, dy; - - if (width != 0 && height != 0 && ratio > 0) { - if (width / height > ratio) { - dx = width / 2; - dy = dx / ratio; - } else { - dy = height / 2; - dx = dy * ratio; - } - - bbox = [center[0] - dx, center[1] - dy, center[0] + dx, center[1] + dy]; - } - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - recenter: function( bbox, center, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj ) { - if ( this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - if ( this._isGeodetic( center ) ) { - center = $.geo.proj.fromGeodetic(center); - } - } - - var halfWidth = ( bbox[ 2 ] - bbox[ 0 ] ) / 2, - halfHeight = ( bbox[ 3 ] - bbox[ 1 ] ) / 2; - - bbox = [ - center[ 0 ] - halfWidth, - center[ 1 ] - halfHeight, - center[ 0 ] + halfWidth, - center[ 1 ] + halfHeight - ]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - scaleBy: function ( bbox, scale, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var c = this.center(bbox, true), - dx = (bbox[2] - bbox[0]) * scale / 2, - dy = (bbox[3] - bbox[1]) * scale / 2; - - bbox = [c[0] - dx, c[1] - dy, c[0] + dx, c[1] + dy]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - width: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[2] - bbox[0]; - }, - - // - // geometry functions - // - - // bbox (Geometry.getEnvelope in JTS) - - bbox: function ( geom, _ignoreGeo /* Internal Use Only */ ) { - if ( !geom ) { - return undefined; - } else if ( geom.bbox ) { - result = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.bbox ) ) ? $.geo.proj.fromGeodetic( geom.bbox ) : geom.bbox; - } else { - result = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var coordinates = this._allCoordinates( geom ), - curCoord = 0; - - if ( coordinates.length == 0 ) { - return undefined; - } - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coordinates ) ) { - wasGeodetic = true; - coordinates = $.geo.proj.fromGeodetic( coordinates ); - } - - for ( ; curCoord < coordinates.length; curCoord++ ) { - result[0] = Math.min(coordinates[curCoord][0], result[0]); - result[1] = Math.min(coordinates[curCoord][1], result[1]); - result[2] = Math.max(coordinates[curCoord][0], result[2]); - result[3] = Math.max(coordinates[curCoord][1], result[3]); - } - } - - return wasGeodetic ? $.geo.proj.toGeodetic(result) : result; - }, - - // centroid - - centroid: function( geom, _ignoreGeo /* Internal Use Only */ ) { - switch (geom.type) { - case "Point": - return $.extend({}, geom); - - case "LineString": - case "Polygon": - var a = 0, - c = [0, 0], - coords = $.merge( [ ], geom.type == "Polygon" ? geom.coordinates[0] : geom.coordinates ), - i = 1, j, n; - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coords ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic(coords); - } - - //if (coords[0][0] != coords[coords.length - 1][0] || coords[0][1] != coords[coords.length - 1][1]) { - // coords.push(coords[0]); - //} - - for (; i <= coords.length; i++) { - j = i % coords.length; - n = (coords[i - 1][0] * coords[j][1]) - (coords[j][0] * coords[i - 1][1]); - a += n; - c[0] += (coords[i - 1][0] + coords[j][0]) * n; - c[1] += (coords[i - 1][1] + coords[j][1]) * n; - } - - if (a == 0) { - if (coords.length > 0) { - c[0] = coords[0][0]; - c[1] = coords[0][1]; - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } else { - return undefined; - } - } - - a *= 3; - c[0] /= a; - c[1] /= a; - - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } - return undefined; - }, - - // contains - - contains: function (geom1, geom2) { - if (geom1.type != "Polygon") { - return false; - } - - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1.coordinates, geom2.coordinates); - - case "LineString": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates); - - case "Polygon": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates[0]); - - default: - return false; - } - }, - - _containsPolygonPoint: function (polygonCoordinates, pointCoordinate) { - if (polygonCoordinates.length == 0 || polygonCoordinates[0].length < 4) { - return false; - } - - var rayCross = 0, - a = polygonCoordinates[0][0], - i = 1, - b, - x; - - for (; i < polygonCoordinates[0].length; i++) { - b = polygonCoordinates[0][i]; - - if ((a[1] <= pointCoordinate[1] && pointCoordinate[1] < b[1]) || (b[1] <= pointCoordinate[1] && pointCoordinate[1] < a[1]) && (pointCoordinate[0] < a[0] || pointCoordinate[0] < b[0])) { - x = a[0] + (b[0] - a[0]) * (pointCoordinate[1] - a[1]) / (b[1] - a[1]); - - if (x > pointCoordinate[0]) { - rayCross++; - } - } - - a = b; - } - - return rayCross % 2 == 1; - }, - - _containsPolygonLineString: function (polygonCoordinates, lineStringCoordinates) { - for (var i = 0; i < lineStringCoordinates.length; i++) { - if (!this._containsPolygonPoint(polygonCoordinates, lineStringCoordinates[i])) { - return false; - } - } - return true; - }, - - // distance - - distance: function ( geom1, geom2, _ignoreGeo /* Internal Use Only */ ) { - var geom1CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom1.coordinates ) ) ? $.geo.proj.fromGeodetic(geom1.coordinates) : geom1.coordinates, - geom2CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom2.coordinates ) ) ? $.geo.proj.fromGeodetic(geom2.coordinates) : geom2.coordinates; - - switch (geom1.type) { - case "Point": - switch (geom2.type) { - case "Point": - return this._distancePointPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "LineString": - return this._distanceLineStringPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "Polygon": - return this._containsPolygonPoint(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "LineString": - switch (geom2.type) { - case "Point": - return this._distanceLineStringPoint(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "LineString": - return this._distanceLineStringLineString(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "Polygon": - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "LineString": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected[0]) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected[0]); - default: - return undefined; - } - break; - } - }, - - _distancePointPoint: function (coordinate1, coordinate2) { - var dx = coordinate2[0] - coordinate1[0], - dy = coordinate2[1] - coordinate1[1]; - return Math.sqrt((dx * dx) + (dy * dy)); - }, - - _distanceLineStringPoint: function (lineStringCoordinates, pointCoordinate) { - var minDist = pos_oo; - - if (lineStringCoordinates.length > 0) { - var a = lineStringCoordinates[0], - - apx = pointCoordinate[0] - a[0], - apy = pointCoordinate[1] - a[1]; - - if (lineStringCoordinates.length == 1) { - return Math.sqrt(apx * apx + apy * apy); - } else { - for (var i = 1; i < lineStringCoordinates.length; i++) { - var b = lineStringCoordinates[i], - - abx = b[0] - a[0], - aby = b[1] - a[1], - bpx = pointCoordinate[0] - b[0], - bpy = pointCoordinate[1] - b[1], - - d = this._distanceSegmentPoint(abx, aby, apx, apy, bpx, bpy); - - if (d == 0) { - return 0; - } - - if (d < minDist) { - minDist = d; - } - - a = b; - apx = bpx; - apy = bpy; - } - } - } - - return Math.sqrt(minDist); - }, - - _distanceSegmentPoint: function (abx, aby, apx, apy, bpx, bpy) { - var dot1 = abx * apx + aby * apy; - - if (dot1 <= 0) { - return apx * apx + apy * apy; - } - - var dot2 = abx * abx + aby * aby; - - if (dot1 >= dot2) { - return bpx * bpx + bpy * bpy; - } - - return apx * apx + apy * apy - dot1 * dot1 / dot2; - }, - - _distanceLineStringLineString: function (lineStringCoordinates1, lineStringCoordinates2) { - var minDist = pos_oo; - for (var i = 0; i < lineStringCoordinates2.length; i++) { - minDist = Math.min(minDist, this._distanceLineStringPoint(lineStringCoordinates1, lineStringCoordinates2[i])); - } - return minDist; - }, - - // buffer - - _buffer: function( geom, distance, _ignoreGeo /* Internal Use Only */ ) { - var wasGeodetic = false, - coords = geom.coordinates; - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.coordinates ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic( geom.coordinates ); - } - - switch ( geom.type ) { - case "Point": - var resultCoords = [], - slices = 180, - i = 0, - a; - - for ( ; i <= slices; i++ ) { - a = ( i * 360 / slices ) * ( Math.PI / 180 ); - resultCoords.push( [ - coords[ 0 ] + Math.cos( a ) * distance, - coords[ 1 ] + Math.sin( a ) * distance - ] ); - } - - return { - type: "Polygon", - coordinates: [ ( wasGeodetic ? $.geo.proj.toGeodetic( resultCoords ) : resultCoords ) ] - }; - - break; - - default: - return undefined; - } - }, - - - // - // feature - // - - _flatten: function (geom) { - // return an array of all basic geometries - // not in JTS - var geometries = [], - curGeom = 0; - switch (geom.type) { - case "Feature": - $.merge(geometries, this._flatten(geom.geometry)); - break; - - case "FeatureCollection": - for (; curGeom < geom.features.length; curGeom++) { - $.merge(geometries, this._flatten(geom.features[curGeom].geometry)); - } - break; - - case "GeometryCollection": - for (; curGeom < geom.geometries.length; curGeom++) { - $.merge(geometries, this._flatten(geom.geometries[curGeom])); - } - break; - - default: - geometries[0] = geom; - break; - } - return geometries; - }, - - length: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - lineStringCoordinates, - i = 1, dx, dy; - - switch ( geom.type ) { - case "Point": - return 0; - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][0] - lineStringCoordinates[ i - 1 ][0]; - dy = lineStringCoordinates[ i ][1] - lineStringCoordinates[ i - 1 ][1]; - sum += Math.sqrt((dx * dx) + (dy * dy)); - } - - return sum; - } - - // return undefined; - }, - - area: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - polygonCoordinates, - i = 1, j; - - switch ( geom.type ) { - case "Point": - case "LineString": - return 0; - - case "Polygon": - polygonCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( polygonCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( polygonCoordinates ) ) { - polygonCoordinates = $.geo.proj.fromGeodetic( polygonCoordinates ); - } - - for ( ; i <= polygonCoordinates.length; i++) { - j = i % polygonCoordinates.length; - sum += ( polygonCoordinates[ i - 1 ][ 0 ] - polygonCoordinates[ j ][ 0 ] ) * ( polygonCoordinates[ i - 1 ][ 1 ] + polygonCoordinates[ j ][ 1 ] ) / 2; - } - - return Math.abs( sum ); - } - }, - - pointAlong: function( geom, percentage, _ignoreGeo /* Internal Use Only */ ) { - var totalLength = 0, - previousPercentageSum = 0, - percentageSum = 0, - remainderPercentageSum, - len, - lineStringCoordinates, - segmentLengths = [], - i = 1, dx, dy, - c, c0, c1, - wasGeodetic = false; - - switch ( geom.type ) { - case "Point": - return $.extend( { }, geom ); - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( percentage === 0 ) { - return { - type: "Point", - coordinates: [ lineStringCoordinates[ 0 ][ 0 ], lineStringCoordinates[ 0 ][ 1 ] ] - }; - } else if ( percentage === 1 ) { - i = lineStringCoordinates.length - 1; - return { - type: "Point", - coordinates: [ lineStringCoordinates[ i ][ 0 ], lineStringCoordinates[ i ][ 1 ] ] - }; - } else { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - wasGeodetic = true; - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][ 0 ] - lineStringCoordinates[ i - 1 ][ 0 ]; - dy = lineStringCoordinates[ i ][ 1 ] - lineStringCoordinates[ i - 1 ][ 1 ]; - len = Math.sqrt((dx * dx) + (dy * dy)); - segmentLengths.push( len ); - totalLength += len; - } - - for ( i = 0; i < segmentLengths.length && percentageSum < percentage; i++ ) { - previousPercentageSum = percentageSum; - percentageSum += ( segmentLengths[ i ] / totalLength ); - } - - remainderPercentageSum = percentage - previousPercentageSum; - - c0 = lineStringCoordinates[ i - 1 ]; - c1 = lineStringCoordinates[ i ]; - - c = [ - c0[ 0 ] + ( remainderPercentageSum * ( c1[ 0 ] - c0[ 0 ] ) ), - c0[ 1 ] + ( remainderPercentageSum * ( c1[ 1 ] - c0[ 1 ] ) ) - ]; - - return { - type: "Point", - coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c - }; - } - } - }, - - // - // WKT functions - // - - _WKT: (function () { - function pointToString(value) { - return "POINT " + pointToUntaggedString(value.coordinates); - } - - function pointToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - return "(" + coordinates.join(" ") + ")"; - } - } - - function lineStringToString(value) { - return "LINESTRING " + lineStringToUntaggedString(value.coordinates); - } - - function lineStringToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var points = [] - - for (var i = 0; i < coordinates.length; i++) { - points.push(coordinates[i].join(" ")); - } - - return "(" + points + ")"; - } - } - - function polygonToString(value) { - return "POLYGON " + polygonToUntaggedString(value.coordinates); - } - - function polygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMTPY"; - } else { - var lineStrings = []; - - for (var i = 0; i < coordinates.length; i++) { - lineStrings.push(lineStringToUntaggedString(coordinates[i])); - } - - return "(" + lineStrings + ")"; - } - } - - function multiPointToString(value) { - return "MULTIPOINT " + lineStringToUntaggedString(value.coordinates); - } - - function multiLineStringToString(value) { - return "MULTILINSTRING " + polygonToUntaggedString(value.coordinates); - } - - function multiPolygonToString(value) { - return "MULTIPOLYGON " + multiPolygonToUntaggedString(value.coordinates); - } - - function multiPolygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var polygons = []; - for (var i = 0; i < coordinates.length; i++) { - polygons.push(polygonToUntaggedString(coordinates[i])); - } - return "(" + polygons + ")"; - } - } - - function geometryCollectionToString(value) { - return "GEOMETRYCOLLECTION " + geometryCollectionToUntaggedString(value.geometries); - } - - function geometryCollectionToUntaggedString(geometries) { - if (!(geometries && geometries.length)) { - return "EMPTY"; - } else { - var geometryText = []; - for (var i = 0; i < geometries.length; i++) { - geometryText.push(stringify(geometries[i])); - } - return "(" + geometries + ")"; - } - } - - function stringify(value) { - if (!(value && value.type)) { - return ""; - } else { - switch (value.type) { - case "Point": - return pointToString(value); - - case "LineString": - return lineStringToString(value); - - case "Polygon": - return polygonToString(value); - - case "MultiPoint": - return multiPointToString(value); - - case "MultiLineString": - return multiLineStringToString(value); - - case "MultiPolygon": - return multiPolygonToString(value); - - case "GeometryCollection": - return geometryCollectionToString(value); - - default: - return ""; - } - } - } - - function pointParseUntagged(wkt) { - var pointString = wkt.match( /\(\s*([\d\.-]+)\s+([\d\.-]+)\s*\)/ ); - return pointString && pointString.length > 2 ? { - type: "Point", - coordinates: [ - parseFloat(pointString[1]), - parseFloat(pointString[2]) - ] - } : null; - } - - function lineStringParseUntagged(wkt) { - var lineString = wkt.match( /\s*\((.*)\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( lineString.length > 1 ) { - pointStrings = lineString[ 1 ].match( /[\d\.-]+\s+[\d\.-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.-]+)\s+([\d\.-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "LineString", - coordinates: coords - }; - } else { - return null - } - } - - function polygonParseUntagged(wkt) { - var polygon = wkt.match( /\s*\(\s*\((.*)\)\s*\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( polygon.length > 1 ) { - pointStrings = polygon[ 1 ].match( /[\d\.-]+\s+[\d\.-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.-]+)\s+([\d\.-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "Polygon", - coordinates: [ coords ] - }; - } else { - return null; - } - } - - function parse(wkt) { - wkt = $.trim(wkt); - - var typeIndex = wkt.indexOf( " " ), - untagged = wkt.substr( typeIndex + 1 ); - - switch (wkt.substr(0, typeIndex).toUpperCase()) { - case "POINT": - return pointParseUntagged( untagged ); - - case "LINESTRING": - return lineStringParseUntagged( untagged ); - - case "POLYGON": - return polygonParseUntagged( untagged ); - - default: - return null; - } - } - - return { - stringify: stringify, - - parse: parse - }; - })(), - - // - // projection functions - // - - proj: (function () { - var halfPi = 1.5707963267948966192, - quarterPi = 0.7853981633974483096, - radiansPerDegree = 0.0174532925199432958, - degreesPerRadian = 57.295779513082320877, - semiMajorAxis = 6378137; - - return { - fromGeodeticPos: function (coordinate) { - if (!coordinate) { - debugger; - } - return [ - semiMajorAxis * coordinate[ 0 ] * radiansPerDegree, - semiMajorAxis * Math.log(Math.tan(quarterPi + coordinate[ 1 ] * radiansPerDegree / 2)) - ]; - }, - - fromGeodetic: function ( coordinates ) { - if ( ! $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - fromGeodeticPos = this.fromGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length == 4) { - // bbox - var min = fromGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = fromGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = fromGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - }, - - toGeodeticPos: function (coordinate) { - return [ - (coordinate[ 0 ] / semiMajorAxis) * degreesPerRadian, - (halfPi - 2 * Math.atan(1 / Math.exp(coordinate[ 1 ] / semiMajorAxis))) * degreesPerRadian - ]; - }, - - toGeodetic: function (coordinates) { - if ( $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - toGeodeticPos = this.toGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length == 4) { - // bbox - var min = toGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = toGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ]; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = toGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - } - } - })(), - - // - // service types (defined in other files) - // - - _serviceTypes: {} - } -})(jQuery, this); -(function ($, undefined) { - - var _ieVersion = (function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - while (div.innerHTML = "", a[0]) { } - return v > 6 ? v : !v; - } ()); - - $.widget("geo.geographics", { - _$elem: undefined, - _options: {}, - _trueCanvas: true, - - _width: 0, - _height: 0, - - _$canvas: undefined, - _context: undefined, - _$labelsContainer: undefined, - - options: { - style: { - borderRadius: "8px", - color: "#7f0000", - //fill: undefined, - fillOpacity: .2, - height: "8px", - opacity: 1, - //stroke: undefined, - strokeOpacity: 1, - strokeWidth: "2px", - visibility: "visible", - width: "8px" - } - }, - - _create: function () { - this._$elem = this.element; - this._options = this.options; - - this._$elem.css({ display: "inline-block", overflow: "hidden", textAlign: "left" }); - - if (this._$elem.css("position") == "static") { - this._$elem.css("position", "relative"); - } - - this._$elem.addClass( "geo-graphics" ); - - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width")); - this._height = parseInt(this._$elem.css("height")); - } - - var posCss = 'position:absolute;left:0;top:0;margin:0;padding:0;', - sizeCss = 'width:' + this._width + 'px;height:' + this._height + 'px;', - sizeAttr = 'width="' + this._width + '" height="' + this._height + '"'; - - if (document.createElement('canvas').getContext) { - this._$elem.append(''); - this._$canvas = this._$elem.children(':last'); - this._context = this._$canvas[0].getContext("2d"); - } else if (_ieVersion <= 8) { - this._trueCanvas = false; - this._$elem.append( '
                            '); - this._$canvas = this._$elem.children(':last'); - - G_vmlCanvasManager.initElement(this._$canvas[0]); - this._context = this._$canvas[0].getContext("2d"); - this._$canvas.children().css({ backgroundColor: "transparent", width: this._width, height: this._height }); - } - - this._$elem.append('
                            '); - this._$labelsContainer = this._$elem.children(':last'); - }, - - _setOption: function (key, value) { - if (key == "style") { - value = $.extend({}, this._options.style, value); - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - destroy: function () { - $.Widget.prototype.destroy.apply(this, arguments); - this._$elem.html(""); - this._$elem.removeClass( "geo-graphics" ); - }, - - clear: function () { - this._context.clearRect(0, 0, this._width, this._height); - this._$labelsContainer.html(""); - }, - - drawArc: function (coordinates, startAngle, sweepAngle, style) { - style = this._getGraphicStyle(style); - - if (style.visibility != "hidden" && style.opacity > 0 && style.widthValue > 0 && style.heightValue > 0) { - var r = Math.min(style.widthValue, style.heightValue) / 2; - - startAngle = (startAngle * Math.PI / 180); - sweepAngle = (sweepAngle * Math.PI / 180); - - this._context.save(); - this._context.translate(coordinates[0], coordinates[1]); - if (style.widthValue > style.heightValue) { - this._context.scale(style.widthValue / style.heightValue, 1); - } else { - this._context.scale(1, style.heightValue / style.widthValue); - } - - this._context.beginPath(); - this._context.arc(0, 0, r, startAngle, sweepAngle, false); - - if (this._trueCanvas) { - this._context.restore(); - } - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - if (!this._trueCanvas) { - this._context.restore(); - } - } - }, - - drawPoint: function (coordinates, style) { - var style = this._getGraphicStyle(style); - if (style.widthValue == style.heightValue && style.heightValue == style.borderRadiusValue) { - this.drawArc(coordinates, 0, 360, style); - } else if (style.visibility != "hidden" && style.opacity > 0) { - style.borderRadiusValue = Math.min(Math.min(style.widthValue, style.heightValue) / 2, style.borderRadiusValue); - coordinates[0] -= style.widthValue / 2; - coordinates[1] -= style.heightValue / 2; - this._context.beginPath(); - this._context.moveTo(coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.lineTo(coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1]); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1], coordinates[0] + style.widthValue, coordinates[1] + style.borderRadiusValue); - this._context.lineTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue, coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.lineTo(coordinates[0] + style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1] + style.heightValue, coordinates[0], coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.lineTo(coordinates[0], coordinates[1] + style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1], coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.closePath(); - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - - this._context.stroke(); - } - } - }, - - drawLineString: function (coordinates, style) { - this._drawLines([coordinates], false, style); - }, - - drawPolygon: function (coordinates, style) { - this._drawLines(coordinates, true, style); - }, - - drawBbox: function (bbox, style) { - this._drawLines([[ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ]], true, style); - }, - - drawLabel: function( coordinates, label ) { - this._$labelsContainer.append( '
                            ' + label + '
                            '); - }, - - resize: function( ) { - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width")); - this._height = parseInt(this._$elem.css("height")); - } - - if ( this._trueCanvas ) { - this._$canvas[0].width = this._width; - this._$canvas[0].height = this._height; - } else { - } - - this._$labelsContainer.css( { - width: this._width, - height: this._height - } ); - }, - - _getGraphicStyle: function (style) { - function safeParse(value) { - value = parseInt(value); - return (+value + '') === value ? +value : value; - } - - style = $.extend({}, this._options.style, style); - style.borderRadiusValue = safeParse(style.borderRadius); - style.fill = style.fill || style.color; - style.doFill = style.fill && style.fillOpacity > 0; - style.stroke = style.stroke || style.color; - style.strokeWidthValue = safeParse(style.strokeWidth); - style.doStroke = style.stroke && style.strokeOpacity > 0 && style.strokeWidthValue > 0; - style.widthValue = safeParse(style.width); - style.heightValue = safeParse(style.height); - return style; - }, - - _drawLines: function (coordinates, close, style) { - if (!coordinates || !coordinates.length || coordinates[0].length < 2) { - return; - } - - var style = this._getGraphicStyle(style), - i, j; - - if (style.visibility != "hidden" && style.opacity > 0) { - this._context.beginPath(); - this._context.moveTo(coordinates[0][0][0], coordinates[0][0][1]); - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - this._context.lineTo(coordinates[i][j][0], coordinates[i][j][1]); - } - } - - if (close) { - this._context.closePath(); - } - - if (close && style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineCap = this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - } - } - }); - - -})(jQuery); - -(function ($, undefined) { - var _ieVersion = (function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - while (div.innerHTML = "", a[0]) { } - return v > 6 ? v : !v; - } ()), - - _defaultOptions = { - bbox: [-180, -85, 180, 85], - bboxMax: [-180, -85, 180, 85], - center: [0, 0], - cursors: { - "static": "default", - pan: "url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move", - zoom: "crosshair", - drawPoint: "crosshair", - drawLineString: "crosshair", - drawPolygon: "crosshair", - measureLength: "crosshair", - measureArea: "crosshair" - }, - measureLabels: { - length: "{{=length.toFixed( 2 )}} m", - area: "{{=area.toFixed( 2 )}} sq m" - }, - drawStyle: {}, - shapeStyle: {}, - mode: "pan", - pannable: true, - scroll: "default", - services: [ - { - "class": "osm", - type: "tiled", - src: function (view) { - return "http://tile.openstreetmap.org/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; - }, - attr: "© OpenStreetMap & contributors, CC-BY-SA" - } - ], - tilingScheme: { - tileWidth: 256, - tileHeight: 256, - levels: 18, - basePixelSize: 156543.03392799936, - origin: [-20037508.342787, 20037508.342787] - }, - axisLayout: "map", - zoom: 0, - pixelSize: 0 - }; - - $.widget("geo.geomap", { - // private widget members - _$elem: undefined, //< map div for maps, service div for services - _map: undefined, //< only defined in services - _created: false, - - _contentBounds: {}, - - _$resizeContainer: undefined, //< all elements that should match _contentBounds' size - - _$eventTarget: undefined, - _$contentFrame: undefined, - _$existingChildren: undefined, - _$attrList: undefined, - _$servicesContainer: undefined, - - _$panContainer: undefined, //< all non-service elements that move while panning - _$shapesContainer: undefined, - _$drawContainer: undefined, - _$measureContainer: undefined, - _$measureLabel: undefined, - - _dpi: 96, - - _currentServices: [], //< internal copy - - _center: undefined, - _pixelSize: undefined, - _centerMax: undefined, - _pixelSizeMax: undefined, - - _userGeodetic: true, - - _wheelTimeout: null, - _wheelLevel: 0, - - _zoomFactor: 2, //< determines what a zoom level means - - _fullZoomFactor: 2, //< interactiveScale factor needed to zoom a whole level - _partialZoomFactor: 1.18920711500273, //< interactiveScale factor needed to zoom a fraction of a level (the fourth root of 2) - - _mouseDown: undefined, - _inOp: undefined, - _toolPan: undefined, - _shiftZoom: undefined, - _anchor: undefined, - _current: undefined, - _downDate: undefined, - _moveDate: undefined, - _clickDate: undefined, - _lastMove: undefined, - _lastDrag: undefined, - - _windowHandler: null, - _resizeTimeout: null, - - _panning: undefined, - _velocity: undefined, - _friction: undefined, - - _supportTouch: undefined, - _softDblClick: undefined, - _isTap: undefined, - _isDbltap: undefined, - - _isMultiTouch: undefined, - _multiTouchAnchor: undefined, //< TouchList - _multiTouchAnchorBbox: undefined, //< bbox - _multiTouchCurrentBbox: undefined, //< bbox - - _drawTimeout: null, //< used in drawPoint mode so we don't send two shape events on dbltap - _drawPixels: [], //< an array of coordinate arrays for drawing lines & polygons, in pixel coordinates - _drawCoords: [], - - _graphicShapes: [], //< an array of objects containing style object refs & GeoJSON object refs - - _initOptions: {}, - - _options: {}, - - options: $.extend({}, _defaultOptions), - - _createWidget: function (options, element) { - this._$elem = $(element); - - if (this._$elem.is(".geo-service")) { - var $contentFrame = this._$elem.closest( ".geo-content-frame" ); - this._$elem.append('
                            '); - this._$shapesContainer = this._$elem.children(':last'); - this._graphicShapes = []; - $.Widget.prototype._createWidget.apply(this, arguments); - return; - } - - this._$elem.addClass("geo-map"); - - this._initOptions = options || {}; - - this._forcePosition(this._$elem); - - this._$elem.css("text-align", "left"); - - var size = this._findMapSize(); - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left")), - y: parseInt(this._$elem.css("padding-top")), - width: size["width"], - height: size["height"] - }; - - this._createChildren(); - - this._center = this._centerMax = [0, 0]; - - this.options["pixelSize"] = this._pixelSize = this._pixelSizeMax = 156543.03392799936; - - this._mouseDown = - this._inOp = - this._toolPan = - this._shiftZoom = - this._panning = - this._isTap = - this._isDbltap = false; - - this._anchor = [ 0, 0 ]; - this._current = [ 0, 0 ]; - this._lastMove = [ 0, 0 ]; - this._lastDrag = [ 0, 0 ]; - this._velocity = [ 0, 0 ]; - - this._friction = [.8, .8]; - - this._downDate = - this._moveDate = - this._clickDate = 0; - - this._drawPixels = []; - this._drawCoords = []; - this._graphicShapes = []; - - - $.Widget.prototype._createWidget.apply(this, arguments); - }, - - _create: function () { - this._options = this.options; - - if (this._$elem.is(".geo-service")) { - this._map = this._$elem.data( "geoMap" ); - this._$shapesContainer.geographics( ); - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - return; - } - - this._map = this; - - this._supportTouch = "ontouchend" in document; - this._softDblClick = this._supportTouch || _ieVersion == 7; - - var geomap = this, - touchStartEvent = this._supportTouch ? "touchstart" : "mousedown", - touchStopEvent = this._supportTouch ? "touchend touchcancel" : "mouseup", - touchMoveEvent = this._supportTouch ? "touchmove" : "mousemove"; - - $(document).keydown($.proxy(this._document_keydown, this)); - - this._$eventTarget.dblclick($.proxy(this._eventTarget_dblclick, this)); - - this._$eventTarget.bind(touchStartEvent, $.proxy(this._eventTarget_touchstart, this)); - - var dragTarget = (this._$eventTarget[0].setCapture) ? this._$eventTarget : $(document); - dragTarget.bind(touchMoveEvent, $.proxy(this._dragTarget_touchmove, this)); - dragTarget.bind(touchStopEvent, $.proxy(this._dragTarget_touchstop, this)); - - this._$eventTarget.mousewheel($.proxy(this._eventTarget_mousewheel, this)); - - this._windowHandler = function () { - if (geomap._resizeTimeout) { - clearTimeout(geomap._resizeTimeout); - } - geomap._resizeTimeout = setTimeout(function () { - if (geomap._created) { - geomap._$elem.geomap("resize"); - } - }, 500); - }; - - $(window).resize(this._windowHandler); - - this._$drawContainer.geographics({ style: this._initOptions.drawStyle || {} }); - this._options["drawStyle"] = this._$drawContainer.geographics("option", "style"); - - this._$shapesContainer.geographics( { style: this._initOptions.shapeStyle || { } } ); - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - - if (this._initOptions) { - if (this._initOptions.tilingScheme) { - this._setOption("tilingScheme", this._initOptions.tilingScheme, false); - } - if ( this._initOptions.services ) { - // jQuery UI Widget Factory merges user services with our default, we want to clobber the default - this._options[ "services" ] = $.merge( [ ], this._initOptions.services ); - } - if (this._initOptions.bbox) { - this._setOption("bbox", this._initOptions.bbox, false); - } - if (this._initOptions.center) { - this._setOption("center", this._initOptions.center, false); - } - if (this._initOptions.zoom !== undefined) { - this._setZoom(this._initOptions.zoom, false, false); - } - } - - $.template( "geoMeasureLength", this._options[ "measureLabels" ].length ); - $.template( "geoMeasureArea", this._options[ "measureLabels" ].area ); - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._createServices(); - this._refresh(); - - this._created = true; - }, - - _setOption: function (key, value, refresh) { - if ( key == "pixelSize" ) { - return; - } - - refresh = (refresh === undefined || refresh); - - if ( this._$elem.is( ".geo-map" ) ) { - this._panFinalize(); - } - - switch (key) { - case "bbox": - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - this._setBbox(value, false, refresh); - value = this._getBbox(); - break; - - case "center": - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - this._setCenterAndSize( value, this._pixelSize, false, refresh ); - break; - - case "measureLabels": - value = $.extend( this._options[ "measureLabels" ], value ); - $.template( "geoMeasureLength", value.length ); - $.template( "geoMeasureArea", value.area ); - break; - - case "drawStyle": - if (this._$drawContainer) { - this._$drawContainer.geographics("option", "style", value); - value = this._$drawContainer.geographics("option", "style"); - } - break; - - case "shapeStyle": - if (this._$shapesContainer) { - this._$shapesContainer.geographics("option", "style", value); - value = this._$shapesContainer.geographics("option", "style"); - } - break; - - case "mode": - this._resetDrawing( ); - this._$eventTarget.css("cursor", this._options["cursors"][value]); - break; - - case "zoom": - this._setZoom(value, false, refresh); - break; - } - - $.Widget.prototype._setOption.apply(this, arguments); - - switch ( key ) { - case "bbox": - case "center": - if ( this._userGeodetic ) { - this._options[ "bbox" ] = $.geo.proj.toGeodetic( this._options[ "bbox" ] ); - this._options[ "center" ] = $.geo.proj.toGeodetic( this._center ); - } - break; - - case "tilingScheme": - if ( value != null ) { - this._pixelSizeMax = this._getPixelSize( 0 ); - this._centerMax = [ - value.origin[ 0 ] + this._pixelSizeMax * value.tileWidth / 2, - value.origin[ 1 ] + this._pixelSizeMax * value.tileHeight / 2 - ]; - } - break; - - case "bboxMax": - this._pixelSizeMax = this._getPixelSize( 0 ); - - if ( $.geo.proj && $.geo._isGeodetic( value ) ) { - this._centerMax = $.geo.center( $.geo.proj.fromGeodetic( value ) ); - } else { - this._centerMax = $.geo.center( value ); - } - break; - - case "services": - this._createServices(); - if (refresh) { - this._refresh(); - } - break; - - case "shapeStyle": - if ( refresh ) { - this._$shapesContainer.geographics("clear"); - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - break; - } - }, - - destroy: function () { - if ( this._$elem.is(".geo-service") ) { - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - } else { - this._created = false; - - $(window).unbind("resize", this._windowHandler); - - for ( var i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._$drawContainer.geographics("destroy"); - this._$drawContainer = undefined; - - this._$existingChildren.detach(); - this._$elem.html(""); - this._$elem.append(this._$existingChildren); - this._$elem.removeClass("geo-map"); - } - - $.Widget.prototype.destroy.apply(this, arguments); - }, - - toMap: function (p) { - p = this._toMap(p); - return this._userGeodetic ? $.geo.proj.toGeodetic(p) : p; - }, - - toPixel: function ( p, _center /* Internal Use Only */, _pixelSize /* Internal Use Only */ ) { - return this._toPixel( $.geo.proj ? $.geo.proj.fromGeodetic( p ) : p, _center, _pixelSize ); - }, - - opacity: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "opacity", value, this._$elem ); - } else { - if ( value >= 0 || value <= 1 ) { - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - service.style.opacity = value; - $.geo[ "_serviceTypes" ][ service.type ].opacity( this, service ); - } - } - } - } - }, - - toggle: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "toggle", value, this._$elem ); - } else { - - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - if ( value === undefined ) { - // toggle visibility - value = ( service.style.visibility !== "visible" ); - } - - service.style.visibility = ( value ? "visible" : "hidden" ); - - service.serviceContainer.toggle( value ); - - if ( value ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service ); - } - } - } - } - }, - - zoom: function (numberOfLevels) { - if (numberOfLevels != null) { - this._setZoom(this._options["zoom"] + numberOfLevels, false, true); - } - }, - - refresh: function () { - this._refresh(); - }, - - resize: function () { - var size = this._findMapSize(), - dx = size["width"]/2 - this._contentBounds.width/2, - dy = size["height"]/2 - this._contentBounds.height/2, - i; - - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left")), - y: parseInt(this._$elem.css("padding-top")), - width: size["width"], - height: size["height"] - }; - - this._$resizeContainer.css( { - width: size["width"], - height: size["height"] - } ); - - for (i = 0; i < this._currentServices.length; i++) { - $.geo["_serviceTypes"][this._currentServices[i].type].resize(this, this._currentServices[i]); - } - - this._$elem.find( ".geo-graphics" ).css( { - width: size["width"], - height: size["height"] - }).geographics( "resize" ); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._setCenterAndSize(this._center, this._pixelSize, false, true); - }, - - append: function ( shape, style, label, refresh ) { - if ( shape && $.isPlainObject( shape ) ) { - var shapes, arg, i, realStyle, realLabel, realRefresh; - - if ( shape.type == "FeatureCollection" ) { - shapes = shape.features; - } else { - shapes = $.isArray( shape ) ? shape : [ shape ]; - } - - for ( i = 1; i < arguments.length; i++ ) { - arg = arguments[ i ]; - - if ( typeof arg === "object" ) { - realStyle = arg; - } else if ( typeof arg === "number" || typeof arg === "string" ) { - realLabel = arg; - } else if ( typeof arg === "boolean" ) { - realRefresh = arg; - } - } - - for ( i = 0; i < shapes.length; i++ ) { - if ( shapes[ i ].type != "Point" ) { - var bbox = $.geo.bbox( shapes[ i ] ); - if ( $.geo.proj && $.geo._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - $.data( shapes[ i ], "geoBbox", bbox ); - } - - this._graphicShapes.push( { - shape: shapes[ i ], - style: realStyle, - label: realLabel - } ); - } - - if ( realRefresh === undefined || realRefresh ) { - this._refresh( ); - } - } - }, - - empty: function ( refresh ) { - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - $.removeData( this._graphicShapes[ i ].shape, "geoBbox" ); - } - - this._graphicShapes = []; - - if ( refresh === undefined || refresh ) { - this._refresh(); - } - }, - - find: function ( selector, pixelTolerance ) { - var isPoint = $.isPlainObject( selector ), - searchPixel = isPoint ? this._map.toPixel( selector.coordinates ) : undefined, - mapTol = this._map._pixelSize * pixelTolerance, - result = [], - graphicShape, - geometries, - curGeom, - i = 0; - - for ( ; i < this._graphicShapes.length; i++ ) { - graphicShape = this._graphicShapes[ i ]; - - if ( isPoint ) { - if ( graphicShape.shape.type == "Point" ) { - if ( $.geo.distance( graphicShape.shape, selector ) <= mapTol ) { - result.push( graphicShape.shape ); - } - } else { - var bbox = $.data( graphicShape.shape, "geoBbox" ), - bboxPolygon = { - type: "Polygon", - coordinates: [ [ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ] ] - }, - projectedPoint = { - type: "Point", - coordinates: $.geo.proj && $.geo._isGeodetic( selector.coordinates ) ? $.geo.proj.fromGeodetic( selector.coordinates ) : selector.coordinates - }; - - if ( $.geo.distance( bboxPolygon, projectedPoint, true ) <= mapTol ) { - geometries = $.geo._flatten( graphicShape.shape ); - for ( curGeom = 0; curGeom < geometries.length; curGeom++ ) { - if ( $.geo.distance( geometries[ curGeom ], selector ) <= mapTol ) { - result.push( graphicShape.shape ); - break; - } - } - } - } - } else { - result.push( graphicShape.shape ); - } - } - - if ( this._$elem.is( ".geo-map" ) ) { - this._$elem.find( ".geo-service" ).each( function( ) { - result = $.merge( result, $( this ).geomap( "find", selector, pixelTolerance ) ); - } ); - } - - return result; - }, - - remove: function ( shape, refresh ) { - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - if ( this._graphicShapes[ i ].shape == shape ) { - $.removeData( shape, "geoBbox" ); - var rest = this._graphicShapes.slice( i + 1 ); - this._graphicShapes.length = i; - this._graphicShapes.push.apply( this._graphicShapes, rest ); - break; - } - } - - if ( refresh === undefined || refresh ) { - this._refresh(); - } - }, - - _getBbox: function (center, pixelSize) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - // calculate the internal bbox - var halfWidth = this._contentBounds[ "width" ] / 2 * pixelSize, - halfHeight = this._contentBounds[ "height" ] / 2 * pixelSize; - return [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - }, - - _setBbox: function (value, trigger, refresh) { - var center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2], - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height); - - if (this._options["tilingScheme"]) { - var zoom = this._getZoom( center, pixelSize ); - pixelSize = this._getPixelSize( zoom ); - } else { - if ( this._getZoom( center, pixelSize ) < 0 ) { - pixelSize = this._pixelSizeMax; - } - } - - this._setCenterAndSize(center, pixelSize, trigger, refresh); - }, - - _getBboxMax: function () { - // calculate the internal bboxMax - var halfWidth = this._contentBounds["width"] / 2 * this._pixelSizeMax, - halfHeight = this._contentBounds["height"] / 2 * this._pixelSizeMax; - return [this._centerMax[0] - halfWidth, this._centerMax[1] - halfHeight, this._centerMax[0] + halfWidth, this._centerMax[1] + halfHeight]; - }, - - _getCenter: function () { - return this._center; - }, - - _getContentBounds: function () { - return this._contentBounds; - }, - - _getServicesContainer: function () { - return this._$servicesContainer; - }, - - _getZoom: function ( center, pixelSize ) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - // calculate the internal zoom level, vs. public zoom property - var tilingScheme = this._options["tilingScheme"]; - if ( tilingScheme ) { - if ( tilingScheme.pixelSizes != null ) { - var roundedPixelSize = Math.floor(pixelSize * 1000), - levels = tilingScheme.pixelSizes.length, - i = levels - 1; - - for ( ; i >= 0; i-- ) { - if ( Math.floor( tilingScheme.pixelSizes[ i ] * 1000 ) >= roundedPixelSize ) { - return i; - } - } - - return 0; - } else { - return Math.max( Math.round( Math.log( tilingScheme.basePixelSize / pixelSize) / Math.log( 2 ) ), 0 ); - } - } else { - var ratio = this._contentBounds["width"] / this._contentBounds["height"], - bbox = $.geo.reaspect( this._getBbox( center, pixelSize ), ratio, true ), - bboxMax = $.geo.reaspect(this._getBboxMax(), ratio, true); - - return Math.max( Math.round( Math.log($.geo.width(bboxMax, true) / $.geo.width(bbox, true)) / Math.log(this._zoomFactor) ), 0 ); - } - }, - - _setZoom: function ( value, trigger, refresh ) { - value = Math.max( value, 0 ); - - this._setCenterAndSize( this._center, this._getPixelSize( value ), trigger, refresh ); - }, - - _createChildren: function () { - this._$existingChildren = this._$elem.children().detach(); - - this._forcePosition(this._$existingChildren); - - this._$existingChildren.css("-moz-user-select", "none"); - - var contentSizeCss = "width:" + this._contentBounds["width"] + "px; height:" + this._contentBounds["height"] + "px; margin:0; padding:0;", - contentPosCss = "position:absolute; left:0; top:0;"; - - this._$elem.prepend('
                            '); - this._$eventTarget = this._$contentFrame = this._$elem.children(':first'); - - this._$contentFrame.append('
                            '); - this._$servicesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                            '); - this._$shapesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append( '
                              ' ); - this._$attrList = this._$contentFrame.children( ":last" ); - - this._$contentFrame.append('
                              '); - this._$drawContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                              '); - this._$measureContainer = this._$contentFrame.children(':last'); - this._$measureLabel = this._$measureContainer.children(); - - this._$panContainer = $( [ this._$shapesContainer[ 0 ], this._$drawContainer[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$resizeContainer = $( [ this._$contentFrame[ 0 ], this._$servicesContainer[ 0 ], this._$eventTarget[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$contentFrame.append(this._$existingChildren); - - if ( ! $("#geo-measure-style").length ) { - $("head").prepend( '' ); - } - }, - - _createServices: function () { - var service, i; - - for ( i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap( "destroy" ); - $.geo[ "_serviceTypes" ][ this._currentServices[ i ].type ].destroy( this, this._$servicesContainer, this._currentServices[ i ] ); - } - - this._currentServices = [ ]; - this._$servicesContainer.html( "" ); - this._$attrList.html( "" ); - - for ( i = 0; i < this._options[ "services" ].length; i++ ) { - service = this._currentServices[ i ] = $.extend( { }, this._options[ "services" ][ i ] ); - - // default the service style property on our copy - service.style = $.extend( { - visibility: "visible", - opacity: 1 - }, service.style ); - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = 'class="geo-service ' + ( service["class"] ? service["class"] : '' ) + '"', - scHtml = '
                              ', - servicesContainer; - - this._$servicesContainer.append( scHtml ); - serviceContainer = this._$servicesContainer.children( ":last" ); - this._currentServices[ i ].serviceContainer = serviceContainer; - - $.geo[ "_serviceTypes" ][ service.type ].create( this, serviceContainer, service, i ); - - serviceContainer.data( "geoMap", this ).geomap(); - - if ( service.attr ) { - this._$attrList.append( '
                            • ' + service.attr + '
                            • ' ); - } - } - - this._$attrList.find( "a" ).css( { - position: "relative", - zIndex: 100 - } ); - }, - - _refreshDrawing: function ( ) { - this._$drawContainer.geographics("clear"); - - if ( this._drawPixels.length > 0 ) { - var mode = this._options[ "mode" ], - pixels = this._drawPixels, - coords = this._drawCoords, - label, - labelShape, - labelPixel, - widthOver, - heightOver; - - switch ( mode ) { - case "measureLength": - mode = "drawLineString"; - labelShape = { - type: "LineString", - coordinates: coords - }; - label = $.render( { length: $.geo.length( labelShape, true ) }, "geoMeasureLength" ); - labelPixel = $.merge( [], pixels[ pixels.length - 1 ] ); - break; - - case "measureArea": - mode = "drawPolygon"; - - labelShape = { - type: "Polygon", - coordinates: [ $.merge( [ ], coords ) ] - }; - labelShape.coordinates[ 0 ].push( coords[ 0 ] ); - - label = $.render( { area: $.geo.area( labelShape, true ) }, "geoMeasureArea" ); - labelPixel = $.merge( [], pixels[ pixels.length - 1 ] ); - pixels = [ pixels ]; - break; - - case "drawPolygon": - pixels = [ pixels ]; - break; - } - - this._$drawContainer.geographics( mode, pixels ); - - if ( label ) { - this._$measureLabel.html( label ); - - widthOver = this._contentBounds.width - ( this._$measureLabel.outerWidth( true ) + labelPixel[ 0 ] ); - heightOver = this._contentBounds.height - ( this._$measureLabel.outerHeight( true ) + labelPixel[ 1 ] ); - - if ( widthOver < 0 ) { - labelPixel[ 0 ] += widthOver; - } - - if ( heightOver < 0 ) { - labelPixel[ 1 ] += heightOver; - } - - this._$measureLabel.css( { - left: labelPixel[ 0 ], - top: labelPixel[ 1 ] - } ).show(); - } - } - }, - - _resetDrawing: function () { - this._drawPixels = []; - this._drawCoords = []; - this._$drawContainer.geographics("clear"); - this._$measureLabel.hide(); - }, - - _refreshShapes: function (geographics, shapes, styles, labels, center, pixelSize) { - var i, mgi, - shape, - shapeBbox, - style, - label, - hasLabel, - labelPixel, - bbox = this._map._getBbox(center, pixelSize); - - for (i = 0; i < shapes.length; i++) { - shape = shapes[i].shape || shapes[i]; - shape = shape.geometry || shape; - shapeBbox = $.data(shape, "geoBbox"); - - if ( shapeBbox && $.geo._bboxDisjoint( bbox, shapeBbox ) ) { - continue; - } - - style = $.isArray(styles) ? styles[i].style : styles; - label = $.isArray(labels) ? labels[i].label : labels; - hasLabel = ( label !== undefined ); - labelPixel = undefined; - - switch (shape.type) { - case "Point": - labelPixel = this._map.toPixel( shape.coordinates, center, pixelSize ); - this._$shapesContainer.geographics("drawPoint", labelPixel, style); - break; - case "LineString": - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.pointAlong( shape, .5 ).coordinates, center, pixelSize ); - } - break; - case "Polygon": - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiPoint": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPoint", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiLineString": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiPolygon": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - - case "GeometryCollection": - this._refreshShapes(geographics, shape.geometries, style, label, center, pixelSize); - break; - } - - if ( hasLabel && labelPixel ) { - this._$shapesContainer.geographics( "drawLabel", labelPixel, label ); - } - } - }, - - _findMapSize: function () { - // really, really attempt to find a size for this thing - // even if it's hidden (look at parents) - var size = { width: 0, height: 0 }, - sizeContainer = this._$elem; - - while (sizeContainer.size() && !(size["width"] > 0 && size["height"] > 0)) { - size = { width: sizeContainer.width(), height: sizeContainer.height() }; - if (size["width"] <= 0 || size["height"] <= 0) { - size = { width: parseInt(sizeContainer.css("width")), height: parseInt(sizeContainer.css("height")) }; - } - sizeContainer = sizeContainer.parent(); - } - return size; - }, - - _forcePosition: function (elem) { - var cssPosition = elem.css("position"); - if (cssPosition != "relative" && cssPosition != "absolute" && cssPosition != "fixed") { - elem.css("position", "relative"); - } - }, - - _getPixelSize: function ( zoom ) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme != null) { - if (zoom === 0) { - return tilingScheme.pixelSizes != null ? tilingScheme.pixelSizes[0] : tilingScheme.basePixelSize; - } - - zoom = Math.round(zoom); - zoom = Math.max(zoom, 0); - var levels = tilingScheme.pixelSizes != null ? tilingScheme.pixelSizes.length : tilingScheme.levels; - zoom = Math.min(zoom, levels - 1); - - if (tilingScheme.pixelSizes != null) { - return tilingScheme.pixelSizes[zoom]; - } else { - return tilingScheme.basePixelSize / Math.pow(2, zoom); - } - } else { - var bbox = $.geo.scaleBy( this._getBboxMax(), 1 / Math.pow( this._zoomFactor, zoom ), true ); - return Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - } - }, - - _getZoomCenterAndSize: function ( anchor, zoomDelta, full ) { - var zoomFactor = ( full ? this._fullZoomFactor : this._partialZoomFactor ), - scale = Math.pow( zoomFactor, -zoomDelta ), - pixelSize, - zoomLevel; - - if ( this._options[ "tilingScheme" ] ) { - zoomLevel = this._getZoom(this._center, this._pixelSize * scale); - pixelSize = this._getPixelSize(zoomLevel); - } else { - pixelSize = this._pixelSize * scale; - - if ( this._getZoom( this._center, pixelSize ) < 0 ) { - pixelSize = this._pixelSizeMax; - } - } - - var ratio = pixelSize / this._pixelSize, - anchorMapCoord = this._toMap(anchor), - centerDelta = [(this._center[0] - anchorMapCoord[0]) * ratio, (this._center[1] - anchorMapCoord[1]) * ratio], - scaleCenter = [anchorMapCoord[0] + centerDelta[0], anchorMapCoord[1] + centerDelta[1]]; - - return { pixelSize: pixelSize, center: scaleCenter }; - }, - - _mouseWheelFinish: function () { - this._wheelTimeout = null; - - if (this._wheelLevel != 0) { - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, this._wheelLevel, this._options[ "tilingScheme" ] != null ); - - this._setCenterAndSize(wheelCenterAndSize.center, wheelCenterAndSize.pixelSize, true, true); - - this._wheelLevel = 0; - } else { - this._refresh(); - } - }, - - _panEnd: function () { - this._velocity = [ - (this._velocity[0] > 0 ? Math.floor(this._velocity[0] * this._friction[0]) : Math.ceil(this._velocity[0] * this._friction[0])), - (this._velocity[1] > 0 ? Math.floor(this._velocity[1] * this._friction[1]) : Math.ceil(this._velocity[1] * this._friction[1])) - ]; - - if (Math.abs(this._velocity[0]) < 4 && Math.abs(this._velocity[1]) < 4) { - this._panFinalize(); - } else { - this._current = [ - this._current[0] + this._velocity[0], - this._current[1] + this._velocity[1] - ]; - - this._panMove(); - setTimeout($.proxy(this._panEnd, this), 30); - } - }, - - _panFinalize: function () { - if (this._panning) { - this._velocity = [0, 0]; - - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - image = this._options[ "axisLayout" ] === "image", - dxMap = -dx * this._pixelSize, - dyMap = ( image ? -1 : 1 ) * dy * this._pixelSize; - - this._$panContainer.css({ left: 0, top: 0 }); - - this._$servicesContainer.find( ".geo-shapes-container" ).css( { left: 0, top: 0 } ); - - this._setCenterAndSize([this._center[0] + dxMap, this._center[1] + dyMap], this._pixelSize, true, true); - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._inOp = false; - this._anchor = this._current; - this._mouseDown = this._toolPan = this._panning = false; - } - }, - - _panMove: function () { - if ( ! this._options[ "pannable" ] ) { - return; - } - - var dx = this._current[0] - this._lastDrag[0], - dy = this._current[1] - this._lastDrag[1], - i = 0, - service, - translateObj; - - if (this._toolPan || dx > 3 || dx < -3 || dy > 3 || dy < -3) { - if (!this._toolPan) { - this._toolPan = true; - this._$eventTarget.css("cursor", this._options["cursors"]["pan"]); - } - - if (this._mouseDown) { - this._velocity = [dx, dy]; - } - - if (dx != 0 || dy != 0) { - this._panning = true; - this._lastDrag = this._current; - - translateObj = { - left: function (index, value) { - return parseInt(value) + dx; - }, - top: function (index, value) { - return parseInt(value) + dy; - } - }; - - for ( i = 0; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo[ "_serviceTypes" ][ service.type ].interactivePan( this, service, dx, dy ); - - service.serviceContainer.find( ".geo-shapes-container" ).css( translateObj ); - } - - this._$panContainer.css( translateObj ); - - //this._refreshDrawing(); - } - } - }, - - _refresh: function () { - var service, - i = 0; - - if ( this._$elem.is( ".geo-map" ) ) { - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - - if ( !this._mouseDown && $.geo[ "_serviceTypes" ][ service.type ] !== null ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service ); - service.serviceContainer.geomap( "refresh" ); - } - } - } - - if ( this._$shapesContainer ) { - this._$shapesContainer.geographics( "clear" ); - if ( this._graphicShapes.length > 0 ) { - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - } - }, - - _setCenterAndSize: function (center, pixelSize, trigger, refresh) { - if ( ! $.isArray( center ) || center.length != 2 || typeof center[ 0 ] !== "number" || typeof center[ 1 ] !== "number" ) { - return; - } - - // the final call during any extent change - if (this._pixelSize != pixelSize) { - this._$elem.find( ".geo-shapes-container" ).geographics("clear"); - for (var i = 0; i < this._currentServices.length; i++) { - var service = this._currentServices[i]; - $.geo["_serviceTypes"][service.type].interactiveScale(this, service, center, pixelSize); - } - } - - this._center = $.merge( [ ], center ); - this._options["pixelSize"] = this._pixelSize = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox() ); - this._options["center"] = $.geo.proj.toGeodetic( this._center ); - } else { - this._options["bbox"] = this._getBbox(); - this._options["center"] = $.merge( [ ], center ); - } - - this._options["zoom"] = this._getZoom(); - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel(this._drawCoords); - } - - if (trigger) { - this._trigger("bboxchange", window.event, { bbox: $.merge( [ ], this._options["bbox"] ) }); - } - - if (refresh) { - this._refresh(); - this._refreshDrawing(); - } - }, - - _toMap: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - xRatio = $.geo.width(bbox, true) / width, - yRatio = $.geo.height(bbox, true) / height, - yOffset, - image = this._options[ "axisLayout" ] === "image", - result = [], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - yOffset = (p[ i ][ j ][ k ][1] * yRatio); - result[ i ][ j ][ k ] = [ - bbox[ 0 ] + ( p[ i ][ j ][ k ][ 0 ] * xRatio ), - image ? bbox[ 1 ] + yOffset : bbox[ 3 ] - yOffset - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _toPixel: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - bboxWidth = $.geo.width(bbox, true), - bboxHeight = $.geo.height(bbox, true), - image = this._options[ "axisLayout" ] === "image", - xRatio = width / bboxWidth, - yRatio = height / bboxHeight, - result = [ ], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = [ - Math.round( ( p[ i ][ j ][ k ][ 0 ] - bbox[ 0 ] ) * xRatio ), - Math.round( ( image ? p[ i ][ j ][ k ][ 1 ] - bbox[ 1 ] : bbox[ 3 ] - p[ i ][ j ][ k ][ 1 ] ) * yRatio ) - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _zoomTo: function (coord, zoom, trigger, refresh) { - zoom = zoom < 0 ? 0 : zoom; - - var pixelSize = this._getPixelSize( zoom ); - - this._setCenterAndSize( coord, pixelSize, trigger, refresh ); - }, - - _document_keydown: function (e) { - var len = this._drawCoords.length; - if (len > 0 && e.which == 27) { - if (len <= 2) { - this._resetDrawing(); - this._inOp = false; - } else { - this._drawCoords[len - 2] = $.merge( [], this._drawCoords[ len - 1 ] ); - this._drawPixels[len - 2] = $.merge( [], this._drawPixels[ len - 1 ] ); - - this._drawCoords.length--; - this._drawPixels.length--; - - this._refreshDrawing(); - } - } - }, - - _eventTarget_dblclick_zoom: function(e) { - this._trigger("dblclick", e, { type: "Point", coordinates: this.toMap(this._current) }); - if (!e.isDefaultPrevented()) { - var centerAndSize = this._getZoomCenterAndSize(this._current, 1, true ); - this._setCenterAndSize(centerAndSize.center, centerAndSize.pixelSize, true, true); - } - }, - - _eventTarget_dblclick: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - this._panFinalize(); - - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - var offset = $(e.currentTarget).offset(); - - switch (this._options["mode"]) { - case "drawLineString": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - this._drawCoords.length--; - this._trigger( "shape", e, { - type: "LineString", - coordinates: this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords - } ); - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "drawPolygon": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - var endIndex = this._drawCoords.length - 1; - if (endIndex > 2) { - this._drawCoords[endIndex] = $.merge( [], this._drawCoords[0] ); - this._trigger( "shape", e, { - type: "Polygon", - coordinates: [ this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords ] - } ); - } - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "measureLength": - case "measureArea": - this._resetDrawing(); - break; - - default: - this._eventTarget_dblclick_zoom(e); - break; - } - - this._inOp = false; - }, - - _eventTarget_touchstart: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if ( !this._supportTouch && e.which != 1 ) { - return; - } - - this._panFinalize(); - this._mouseWheelFinish(); - - var offset = $(e.currentTarget).offset(), - touches = e.originalEvent.changedTouches; - - if ( this._supportTouch ) { - this._multiTouchAnchor = $.merge( [ ], touches ); - - this._isMultiTouch = this._multiTouchAnchor.length > 1; - - if ( this._isMultiTouch ) { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - touches[1].pageX - offset.left, - touches[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ touches[0].pageX - offset.left, touches[0].pageY - offset.top ]; - } - } else { - this._current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - var downDate = $.now(); - if (downDate - this._downDate < 750) { - if (this._isTap) { - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance > 8) { - this._isTap = false; - } else { - this._current = $.merge( [ ], this._anchor ); - } - } - - if (this._isDbltap) { - this._isDbltap = false; - } else { - this._isDbltap = this._isTap; - } - } else { - this._isDbltap = false; - } - this._isTap = true; - this._downDate = downDate; - } - - this._mouseDown = true; - this._anchor = $.merge( [ ], this._current ); - - if (!this._inOp && e.shiftKey) { - this._shiftZoom = true; - this._$eventTarget.css("cursor", this._options["cursors"]["zoom"]); - } else if ( !this._isMultiTouch && this._options[ "pannable" ] ) { - this._inOp = true; - - switch (this._options["mode"]) { - case "zoom": - break; - - default: - this._lastDrag = this._current; - - if (e.currentTarget.setCapture) { - e.currentTarget.setCapture(); - } - - break; - } - } - - e.preventDefault(); - return false; - }, - - _dragTarget_touchmove: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - var offset = this._$eventTarget.offset(), - drawCoordsLen = this._drawCoords.length, - touches = e.originalEvent.changedTouches, - current, - service, - i = 0; - - if ( this._supportTouch ) { - if ( !this._isMultiTouch && touches[ 0 ].identifier !== this._multiTouchAnchor[ 0 ].identifier ) { - // switch to multitouch - this._mouseDown = false; - this._dragTarget_touchstop( e ); - - this._isMultiTouch = true; - - this._multiTouchAnchor.push( touches[ 0 ] ); - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._mouseDown = true; - this._anchor = this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - - return false; - } - - if ( this._isMultiTouch ) { - for ( ; i < touches.length; i++ ) { - if ( touches[ i ].identifier === this._multiTouchAnchor[ 0 ].identifier ) { - this._multiTouchCurrentBbox[ 0 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = touches[ i ].pageY - offset.top; - } else if ( touches[ i ].identifier === this._multiTouchAnchor[ 1 ].identifier ) { - this._multiTouchCurrentBbox[ 2 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = touches[ i ].pageY - offset.top; - } - } - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - var currentWidth = this._multiTouchCurrentBbox[ 2 ] - this._multiTouchCurrentBbox[ 0 ], - anchorWidth = this._multiTouchAnchorBbox[ 2 ] - this._multiTouchAnchorBbox[ 0 ], - ratioWidth = currentWidth / anchorWidth; - - this._wheelLevel = Math.abs( Math.floor( ( 1 - ratioWidth ) * 10 ) ); - if ( Math.abs( currentWidth ) < Math.abs( anchorWidth ) ) { - this._wheelLevel = - this._wheelLevel; - } - - var pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, this._wheelLevel, false ); - this._$elem.find( ".geo-shapes-container" ).geographics("clear"); - - for ( i = 0; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo[ "_serviceTypes" ][ service.type ].interactiveScale( this, service, pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - } - - if (this._graphicShapes.length > 0 && this._graphicShapes.length < 256) { - this._refreshShapes(this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes, pinchCenterAndSize.center, pinchCenterAndSize.pixelSize); - } - - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel(this._drawCoords, pinchCenterAndSize.center, pinchCenterAndSize.pixelSize); - this._refreshDrawing(); - } - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (current[0] === this._lastMove[0] && current[1] === this._lastMove[1]) { - if ( this._inOp ) { - e.preventDefault(); - return false; - } - } - - if ( _ieVersion == 7 ) { - this._isDbltap = this._isTap = false; - } - - if (this._mouseDown) { - this._current = current; - this._moveDate = $.now(); - } - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isDbltap = this._isTap = false; - return false; - } - - var mode = this._shiftZoom ? "zoom" : this._options["mode"]; - - switch (mode) { - case "zoom": - if ( this._mouseDown ) { - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawBbox", [ - this._anchor[ 0 ], - this._anchor[ 1 ], - current[ 0 ], - current[ 1 ] - ] ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (this._mouseDown || this._toolPan) { - this._panMove(); - } else { - if (drawCoordsLen > 0) { - this._drawCoords[drawCoordsLen - 1] = this._toMap(current); - this._drawPixels[drawCoordsLen - 1] = current; - - this._refreshDrawing(); - } - - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - default: - if (this._mouseDown || this._toolPan) { - this._panMove(); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - } - - this._lastMove = current; - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchstop: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if (!this._mouseDown && _ieVersion == 7) { - // ie7 doesn't appear to trigger dblclick on this._$eventTarget, - // we fake regular click here to cause soft dblclick - this._eventTarget_touchstart(e); - } - - var mouseWasDown = this._mouseDown, - wasToolPan = this._toolPan, - offset = this._$eventTarget.offset(), - mode = this._shiftZoom ? "zoom" : this._options["mode"], - current, i, clickDate, - dx, dy; - - if (this._supportTouch) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - if (this._isTap) { - var dx = current[0] - this._anchor[0], - dy = current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance <= 8) { - current = $.merge( [ ], this._anchor ); - } - } - } - - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._shiftZoom = this._mouseDown = this._toolPan = false; - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isMultiTouch = false; - - var pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, this._wheelLevel, false ); - - this._setCenterAndSize(pinchCenterAndSize.center, pinchCenterAndSize.pixelSize, true, true); - - this._wheelLevel = 0; - - return false; - } - - if (document.releaseCapture) { - document.releaseCapture(); - } - - if (mouseWasDown) { - clickDate = $.now(); - this._current = current; - - switch (mode) { - case "zoom": - if ( dx > 0 || dy > 0 ) { - var minSize = this._pixelSize * 6, - bboxCoords = this._toMap( [ [ - Math.min( this._anchor[ 0 ], current[ 0 ] ), - Math.max( this._anchor[ 1 ], current[ 1 ] ) - ], [ - Math.max( this._anchor[ 0 ], current[ 0 ] ), - Math.min( this._anchor[ 1 ], current[ 1 ] ) - ] - ] ), - bbox = [ - bboxCoords[0][0], - bboxCoords[0][1], - bboxCoords[1][0], - bboxCoords[1][1] - ]; - - if ( ( bbox[2] - bbox[0] ) < minSize && ( bbox[3] - bbox[1] ) < minSize ) { - bbox = $.geo.scaleBy( this._getBbox( $.geo.center( bbox, true ) ), .5, true ); - } - - this._setBbox(bbox, true, true); - } - - this._resetDrawing(); - break; - - case "drawPoint": - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - var geomap = this; - this._drawTimeout = setTimeout(function () { - if (geomap._drawTimeout) { - geomap._trigger("shape", e, { type: "Point", coordinates: geomap.toMap(current) }); - geomap._inOp = false; - geomap._drawTimeout = null; - } - }, 250); - } - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (wasToolPan) { - this._panFinalize(); - } else { - i = (this._drawCoords.length == 0 ? 0 : this._drawCoords.length - 1); - - this._drawCoords[i] = this._toMap(current); - this._drawPixels[i] = current; - - if (i < 2 || !(this._drawCoords[i][0] == this._drawCoords[i-1][0] && - this._drawCoords[i][1] == this._drawCoords[i-1][1])) { - this._drawCoords[i + 1] = this._toMap(current); - this._drawPixels[i + 1] = current; - } - - this._refreshDrawing(); - } - break; - - default: - if (wasToolPan) { - this._panEnd(); - } else { - if (clickDate - this._clickDate > 100) { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - this._inOp = false; - } - } - break; - } - - this._clickDate = clickDate; - - if (this._softDblClick && this._isDbltap) { - this._isDbltap = this._isTap = false; - this._$eventTarget.trigger("dblclick", e); - } - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _eventTarget_mousewheel: function (e, delta) { - if ( this._options[ "mode" ] === "static" || this._options[ "scroll" ] === "off" ) { - return; - } - - e.preventDefault(); - - this._panFinalize(); - - if ( this._mouseDown ) { - return false; - } - - if (delta != 0) { - if (this._wheelTimeout) { - window.clearTimeout(this._wheelTimeout); - this._wheelTimeout = null; - } else { - var offset = $(e.currentTarget).offset(); - this._anchor = [e.pageX - offset.left, e.pageY - offset.top]; - } - - this._wheelLevel += delta; - - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, this._wheelLevel, this._options[ "tilingScheme" ] != null ), - service, - i = 0; - - this._$elem.find( ".geo-shapes-container" ).geographics("clear"); - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo["_serviceTypes"][service.type].interactiveScale(this, service, wheelCenterAndSize.center, wheelCenterAndSize.pixelSize); - } - - if (this._graphicShapes.length > 0 && this._graphicShapes.length < 256) { - this._refreshShapes(this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes, wheelCenterAndSize.center, wheelCenterAndSize.pixelSize); - } - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel(this._drawCoords, wheelCenterAndSize.center, wheelCenterAndSize.pixelSize); - this._refreshDrawing(); - } - - var geomap = this; - this._wheelTimeout = window.setTimeout(function () { - geomap._mouseWheelFinish(); - }, 1000); - } - - return false; - } - } - ); -})(jQuery); - -(function ($, undefined) { - $.geo._serviceTypes.tiled = (function () { - return { - create: function (map, serviceContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0, - reloadTiles: false - }; - - var scHtml = '
                              '; - - serviceContainer.append(scHtml); - - serviceState.serviceContainer = serviceContainer.children( ":last" ); - - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactivePan: function ( map, service, dx, dy ) { - var serviceState = $.data( service, "geoServiceState" ); - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).css( "-moz-transition", "").css( { - webkitTransition: "", - transition: "", - left: function ( index, value ) { - return parseInt( value ) + dx; - }, - top: function ( index, value ) { - return parseInt( value ) + dy; - } - }); - - if ( service && service.style.visibility === "visible" ) { - var pixelSize = map._pixelSize, - - serviceObj = this, - serviceContainer = serviceState.serviceContainer, - scaleContainer = serviceContainer.children("[data-pixelSize='" + pixelSize + "']"), - - /* same as refresh 1 */ - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - image = map.options[ "axisLayout" ] === "image", - ySign = image ? +1 : -1, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - /* end same as refresh 1 */ - - halfWidth = mapWidth / 2 * pixelSize, - halfHeight = mapHeight / 2 * pixelSize, - - currentPosition = scaleContainer.position(), - scaleOriginParts = scaleContainer.data("scaleOrigin").split(","), - totalDx = parseInt(scaleOriginParts[0]) - currentPosition.left, - totalDy = parseInt(scaleOriginParts[1]) - currentPosition.top, - - mapCenterOriginal = map._getCenter(), - mapCenter = [ - mapCenterOriginal[0] + totalDx * pixelSize, - mapCenterOriginal[1] + ySign * totalDy * pixelSize - ], - - /* same as refresh 2 */ - tileX = Math.floor(((mapCenter[0] - halfWidth) - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.max( Math.floor(( image ? (mapCenter[1] - halfHeight) - tilingScheme.origin[1] : tilingScheme.origin[1] - (mapCenter[1] + halfHeight)) / (pixelSize * tileHeight)), 0 ), - tileX2 = Math.ceil(((mapCenter[0] + halfWidth) - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil(( image ? (mapCenter[1] + halfHeight) - tilingScheme.origin[1] : tilingScheme.origin[1] - (mapCenter[1] - halfHeight)) / (pixelSize * tileHeight)), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] + ySign * bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMinOrMaxY = tilingScheme.origin[1] + ySign * (fullYAtScale * tileHeight) * pixelSize, - /* end same as refresh 2 */ - - serviceLeft = Math.round((fullXMinX - (mapCenterOriginal[0] - halfWidth)) / pixelSize), - serviceTop = Math.round(( image ? fullYMinOrMaxY - (mapCenterOriginal[1] - halfHeight) : (mapCenterOriginal[1] + halfHeight) - fullYMinOrMaxY ) / pixelSize), - - opacity = service.style.opacity, - - x, y; - - for ( x = tileX; x < tileX2; x++ ) { - for ( y = tileY; y < tileY2; y++ ) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ( $img.size( ) === 0 ) { - /* same as refresh 3 */ - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] + ySign * (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] + ySign * ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - urlProp = ( service.hasOwnProperty("src") ? "src" : "getUrl" ), - urlArgs = { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl; - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - $.template( "geoSrc", service[ urlProp ] ); - imageUrl = $.render( urlArgs, "geoSrc" ); - } - /* end same as refresh 3 */ - - serviceState.loadCount++; - //this._map._requestQueued(); - - if ( serviceState.reloadTiles && $img.size() > 0 ) { - $img.attr( "src", imageUrl ); - } else { - /* same as refresh 4 */ - var imgMarkup = ""; - - scaleContainer.append( imgMarkup ); - $img = scaleContainer.children(":last"); - } - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, serviceState, serviceContainer, opacity ); - } else { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, serviceState, serviceContainer, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - } ); - } - - /* end same as refresh 4 */ - } - } - } - } - } - }, - - interactiveScale: function (map, service, center, pixelSize) { - var serviceState = $.data( service, "geoServiceState" ); - - if ( serviceState && service && service.style.visibility === "visible" ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight; - - - serviceContainer.children( ).each( function ( i ) { - var $scaleContainer = $(this), - scaleRatio = $scaleContainer.attr("data-pixelSize") / pixelSize, - transitionCss = ""; //"width .25s ease-in, height .25s ease-in, left .25s ease-in, top .25s ease-in"; - - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - - var scaleOriginParts = $scaleContainer.data("scaleOrigin").split(","), - oldMapCoord = map._toMap([scaleOriginParts[0], scaleOriginParts[1]]), - newPixelPoint = map._toPixel(oldMapCoord, center, pixelSize); - - $scaleContainer.css( "-moz-transition", transitionCss ).css( { - webkitTransition: transitionCss, - transition: transitionCss, - left: Math.round(newPixelPoint[0]) + "px", - top: Math.round(newPixelPoint[1]) + "px", - width: tileWidth * scaleRatio, - height: tileHeight * scaleRatio - } ); - - if ( $("body")[0].filters !== undefined ) { - $scaleContainer.children().each( function ( i ) { - $( this ).css( "filter", "progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11=" + scaleRatio + ",M22=" + scaleRatio + ",sizingmethod='auto expand')" ); - } ); - } - }); - } - }, - - refresh: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - this._cancelUnloaded(map, service); - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - $serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - image = map.options[ "axisLayout" ] === "image", - ySign = image ? +1 : -1, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - - tileX = Math.floor((bbox[0] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.max( Math.floor( ( image ? bbox[1] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 3 ] ) / (pixelSize * tileHeight) ), 0 ), - tileX2 = Math.ceil((bbox[2] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil( ( image ? bbox[3] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 1 ] ) / (pixelSize * tileHeight) ), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] + ySign * bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMinOrMaxY = tilingScheme.origin[1] + ySign * (fullYAtScale * tileHeight) * pixelSize, - - serviceLeft = Math.round((fullXMinX - bbox[0]) / pixelSize), - serviceTop = Math.round( ( image ? fullYMinOrMaxY - bbox[1] : bbox[3] - fullYMinOrMaxY ) / pixelSize), - - scaleContainers = $serviceContainer.children().show(), - scaleContainer = scaleContainers.filter("[data-pixelSize='" + pixelSize + "']").appendTo($serviceContainer), - - opacity = service.style.opacity, - - x, y; - - if (serviceState.reloadTiles) { - scaleContainers.find("img").attr("data-dirty", "true"); - } - - if (!scaleContainer.size()) { - $serviceContainer.append("
                              "); - scaleContainer = $serviceContainer.children(":last").data("scaleOrigin", (serviceLeft % tileWidth) + "," + (serviceTop % tileHeight)); - } else { - scaleContainer.css({ - left: (serviceLeft % tileWidth) + "px", - top: (serviceTop % tileHeight) + "px" - }).data("scaleOrigin", (serviceLeft % tileWidth) + "," + (serviceTop % tileHeight)); - - scaleContainer.children().each(function (i) { - var - $img = $(this), - tile = $img.attr("data-tile").split(","); - - $img.css({ - left: Math.round(((parseInt(tile[0]) - fullXAtScale) * 100) + (serviceLeft - (serviceLeft % tileWidth)) / tileWidth * 100) + "%", - top: Math.round(((parseInt(tile[1]) - fullYAtScale) * 100) + (serviceTop - (serviceTop % tileHeight)) / tileHeight * 100) + "%" - }); - - if (opacity < 1) { - $img.fadeTo(0, opacity); - } - }); - } - - for (x = tileX; x < tileX2; x++) { - for (y = tileY; y < tileY2; y++) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ($img.size() === 0 || serviceState.reloadTiles) { - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] + ySign * (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] + ySign * ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - urlProp = ( service.hasOwnProperty( "src" ) ? "src" : "getUrl" ), - urlArgs = { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl; - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - $.template( "geoSrc", service[ urlProp ] ); - imageUrl = $.render( urlArgs, "geoSrc" ); - } - - serviceState.loadCount++; - //this._map._requestQueued(); - - if (serviceState.reloadTiles && $img.size() > 0) { - $img.attr("src", imageUrl); - } else { - var imgMarkup = ""; - - scaleContainer.append(imgMarkup); - $img = scaleContainer.children(":last"); - } - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, serviceState, $serviceContainer, opacity ); - } else { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, serviceState, $serviceContainer, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - } ); - } - } - } - } - - scaleContainers.find("[data-dirty]").remove(); - serviceState.reloadTiles = false; - } - }, - - resize: function (map, service) { - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.css( "display", service.style.visibility === "visible" ? "block" : "none" ); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - } - } - }, - - _loadImage: function ( $img, url, pixelSize, serviceState, serviceContainer, opacity ) { - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixelSize='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixelSize='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - })(); -})(jQuery); -(function ($, undefined) { - $.geo._serviceTypes.shingled = (function () { - return { - create: function (map, serviceContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0 - }; - - var scHtml = '
                              '; - - serviceContainer.append(scHtml); - - serviceState.serviceContainer = serviceContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactivePan: function (map, service, dx, dy) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - pixelSize = map._pixelSize, - scaleContainer = serviceContainer.children("[data-pixelSize='" + pixelSize + "']"), - panContainer = scaleContainer.children("div"); - - if ( !panContainer.length ) { - scaleContainer.children("img").wrap('
                              '); - panContainer = scaleContainer.children("div"); - } - - panContainer.css( { - left: function (index, value) { - return parseInt(value) + dx; - }, - top: function (index, value) { - return parseInt(value) + dy; - } - } ); - - // until pan/zoom rewrite, remove all containers not in this scale - serviceContainer.children(":not([data-pixelSize='" + pixelSize + "'])").remove(); - } - }, - - interactiveScale: function (map, service, center, pixelSize) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight]; - - serviceContainer.children().each(function (i) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.attr("data-pixelSize"), - ratio = scalePixelSize / pixelSize; - - $scaleContainer.css( { - width: mapWidth * ratio, - height: mapHeight * ratio } ).children("img").each(function (i) { - var $img = $(this), - imgCenter = $img.data("center"), - x = (Math.round((imgCenter[0] - center[0]) / scalePixelSize) - halfWidth) * ratio, - y = (Math.round((center[1] - imgCenter[1]) / scalePixelSize) - halfHeight) * ratio; - - $img.css({ left: x + "px", top: y + "px" }); - }); - }); - } - }, - - refresh: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - this._cancelUnloaded(map, service); - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - scaleContainer = serviceContainer.children('[data-pixelSize="' + pixelSize + '"]'), - - opacity = service.style.opacity, - - $img; - - if ( !scaleContainer.size() ) { - serviceContainer.append('
                              '); - scaleContainer = serviceContainer.children(":last"); - } - - scaleContainer.children("img").each(function (i) { - var $thisimg = $(this), - imgCenter = $thisimg.data("center"), - center = map._getCenter(), - x = Math.round((imgCenter[0] - center[0]) / pixelSize) - halfWidth, - y = Math.round((center[1] - imgCenter[1]) / pixelSize) - halfHeight; - - $thisimg.css({ left: x + "px", top: y + "px" }); - }); - - if (opacity < 1) { - serviceContainer.find("img").attr("data-keepAlive", "0"); - } - - var urlProp = ( service.hasOwnProperty("src") ? "src" : "getUrl" ), - urlArgs = { - bbox: bbox, - width: mapWidth, - height: mapHeight, - zoom: map._getZoom(), - tile: null, - index: 0 - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl; - - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - $.template( "geoSrc", service[ urlProp ] ); - imageUrl = $.render( urlArgs, "geoSrc" ); - } - - serviceState.loadCount++; - //this._map._requestQueued(); - - scaleContainer.append(''); - $img = scaleContainer.children(":last").data("center", map._getCenter()); - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, serviceState, serviceContainer, opacity ); - } else { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, serviceState, serviceContainer, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - } ); - } - - } - }, - - resize: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState && service && service.style.visibility === "visible" ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - scaleContainer = serviceContainer.children(); - - scaleContainer.attr("data-pixelSize", "0"); - scaleContainer.css({ - left: halfWidth + 'px', - top: halfHeight + 'px' - }); - } - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.css("display", service.style.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - } - } - }, - - _loadImage: function ( $img, url, pixelSize, serviceState, serviceContainer, opacity ) { - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - - if (serviceState.loadCount <= 0) { - serviceContainer.children(':not([data-pixelSize="' + pixelSize + '"])').remove(); - - var panContainer = serviceContainer.find('[data-pixelSize="' + pixelSize + '"]>div'); - if (panContainer.size() > 0) { - var panContainerPos = panContainer.position(); - - panContainer.children("img").each(function (i) { - var $thisimg = $(this), - x = panContainerPos.left + parseInt($thisimg.css("left")), - y = panContainerPos.top + parseInt($thisimg.css("top")); - - $thisimg.css({ left: x + "px", top: y + "px" }); - }).unwrap(); - - panContainer.remove(); - } - - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixelSize='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - } - })(); -})(jQuery); -/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) - * Licensed under the MIT License (LICENSE.txt). - * - * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. - * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. - * Thanks to: Seamus Leahy for adding deltaX and deltaY - * - * Version: 3.0.6 - * - * Requires: 1.2.2+ - */ - -(function($) { - -var types = ['DOMMouseScroll', 'mousewheel']; - -if ($.event.fixHooks) { - for ( var i=types.length; i; ) { - $.event.fixHooks[ types[--i] ] = $.event.mouseHooks; - } -} - -$.event.special.mousewheel = { - setup: function() { - if ( this.addEventListener ) { - for ( var i=types.length; i; ) { - this.addEventListener( types[--i], handler, false ); - } - } else { - this.onmousewheel = handler; - } - }, - - teardown: function() { - if ( this.removeEventListener ) { - for ( var i=types.length; i; ) { - this.removeEventListener( types[--i], handler, false ); - } - } else { - this.onmousewheel = null; - } - } -}; - -$.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); - }, - - unmousewheel: function(fn) { - return this.unbind("mousewheel", fn); - } -}); - - -function handler(event) { - var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0; - event = $.event.fix(orgEvent); - event.type = "mousewheel"; - - // Old school scrollwheel delta - if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; } - if ( orgEvent.detail ) { delta = -orgEvent.detail/3; } - - // New school multidimensional scroll (touchpads) deltas - deltaY = delta; - - // Gecko - if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { - deltaY = 0; - deltaX = -1*delta; - } - - // Webkit - if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; } - if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; } - - // Add event and delta to the front of the arguments - args.unshift(event, delta, deltaX, deltaY); - - return ($.event.dispatch || $.event.handle).apply(this, args); -} - -})(jQuery); diff --git a/dist/jquery.geo-1.0a4.min.js b/dist/jquery.geo-1.0a4.min.js deleted file mode 100644 index 8696f1e..0000000 --- a/dist/jquery.geo-1.0a4.min.js +++ /dev/null @@ -1,171 +0,0 @@ -document.createElement("canvas").getContext||function(){function g(){return this.context_||(this.context_=new t(this))}function q(p,h){var o=G.call(arguments,2);return function(){return p.apply(h,o.concat(G.call(arguments)))}}function r(p){p.namespaces.g_vml_||p.namespaces.add("g_vml_","urn:schemas-microsoft-com:vml","#default#VML");p.namespaces.g_o_||p.namespaces.add("g_o_","urn:schemas-microsoft-com:office:office","#default#VML");if(!p.styleSheets.ex_canvas_){p=p.createStyleSheet();p.owningElement.id= -"ex_canvas_";p.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function b(p){var h=p.srcElement;switch(p.propertyName){case "width":h.getContext().clearRect();h.style.width=h.attributes.width.nodeValue+"px";h.firstChild.style.width=h.clientWidth+"px";break;case "height":h.getContext().clearRect();h.style.height=h.attributes.height.nodeValue+"px";h.firstChild.style.height=h.clientHeight+"px"}}function c(p){p=p.srcElement;if(p.firstChild){p.firstChild.style.width= -p.clientWidth+"px";p.firstChild.style.height=p.clientHeight+"px"}}function a(){return[[1,0,0],[0,1,0],[0,0,1]]}function d(p,h){for(var o=a(),s=0;s<3;s++)for(var x=0;x<3;x++){for(var v=0,A=0;A<3;A++)v+=p[s][A]*h[A][x];o[s][x]=v}return o}function f(p,h){h.fillStyle=p.fillStyle;h.lineCap=p.lineCap;h.lineJoin=p.lineJoin;h.lineWidth=p.lineWidth;h.miterLimit=p.miterLimit;h.shadowBlur=p.shadowBlur;h.shadowColor=p.shadowColor;h.shadowOffsetX=p.shadowOffsetX;h.shadowOffsetY=p.shadowOffsetY;h.strokeStyle=p.strokeStyle; -h.globalAlpha=p.globalAlpha;h.font=p.font;h.textAlign=p.textAlign;h.textBaseline=p.textBaseline;h.arcScaleX_=p.arcScaleX_;h.arcScaleY_=p.arcScaleY_;h.lineScale_=p.lineScale_}function e(p){var h=p.indexOf("(",3),o=p.indexOf(")",h+1);h=p.substring(h+1,o).split(",");if(h.length!=4||p.charAt(3)!="a")h[3]=1;return h}function l(p,h,o){return Math.min(o,Math.max(h,p))}function m(p,h,o){o<0&&o++;o>1&&o--;return 6*o<1?p+(h-p)*6*o:2*o<1?h:3*o<2?p+(h-p)*(2/3-o)*6:p}function n(p){if(p in R)return R[p];var h, -o=1;p=String(p);if(p.charAt(0)=="#")h=p;else if(/^rgb/.test(p)){o=e(p);h="#";for(var s,x=0;x<3;x++){s=o[x].indexOf("%")!=-1?Math.floor(parseFloat(o[x])/100*255):+o[x];h+=M[l(s,0,255)]}o=+o[3]}else if(/^hsl/.test(p)){x=o=e(p);h=parseFloat(x[0])/360%360;h<0&&h++;s=l(parseFloat(x[1])/100,0,1);x=l(parseFloat(x[2])/100,0,1);if(s==0)s=x=h=x;else{var v=x<0.5?x*(1+s):x+s-x*s,A=2*x-v;s=m(A,v,h+1/3);x=m(A,v,h);h=m(A,v,h-1/3)}h="#"+M[Math.floor(s*255)]+M[Math.floor(x*255)]+M[Math.floor(h*255)];o=o[3]}else h= -p;return R[p]={color:h,alpha:o}}function t(p){this.m_=a();this.mStack_=[];this.aStack_=[];this.currentPath_=[];this.fillStyle=this.strokeStyle="#000";this.lineWidth=1;this.lineJoin="miter";this.lineCap="butt";this.miterLimit=H*1;this.globalAlpha=1;this.canvas=p;var h="width:"+p.clientWidth+"px;height:"+p.clientHeight+"px;overflow:hidden;position:absolute",o=p.ownerDocument.createElement("div");o.style.cssText=h;p.appendChild(o);h=o.cloneNode(false);h.style.backgroundColor="red";h.style.filter="alpha(opacity=0)"; -p.appendChild(h);this.element_=o;this.lineScale_=this.arcScaleY_=this.arcScaleX_=1}function u(p,h,o,s){p.currentPath_.push({type:"bezierCurveTo",cp1x:h.x,cp1y:h.y,cp2x:o.x,cp2y:o.y,x:s.x,y:s.y});p.currentX_=s.x;p.currentY_=s.y}function w(p,h,o){p=p.m_;return{x:H*(h*p[0][0]+o*p[1][0]+p[2][0])-C,y:H*(h*p[0][1]+o*p[1][1]+p[2][1])-C}}function B(p,h,o){if(isFinite(h[0][0])&&isFinite(h[0][1])&&isFinite(h[1][0])&&isFinite(h[1][1])&&isFinite(h[2][0])&&isFinite(h[2][1])){p.m_=h;if(o)p.lineScale_=P(J(h[0][0]* -h[1][1]-h[0][1]*h[1][0]))}}function I(p){this.code=this[p];this.message=p+": DOM Exception "+this.code}var F=Math,y=F.round,K=F.sin,D=F.cos,J=F.abs,P=F.sqrt,H=10,C=H/2;navigator.userAgent.match(/MSIE ([\d.]+)?/);var G=Array.prototype.slice;r(document);F={init:function(p){p=p||document;p.createElement("canvas");p.attachEvent("onreadystatechange",q(this.init_,this,p))},init_:function(p){p=p.getElementsByTagName("canvas");for(var h=0;hs.x)s.x=v.x;if(o.y==null||v.ys.y)s.y=v.y}}h.push(' ">');if(p){p=n(this.fillStyle);h.push('')}else{o=n(this.strokeStyle);p=o.color;o=o.alpha*this.globalAlpha;s=this.lineScale_*this.lineWidth;if(s<1)o*=s;h.push("')}h.push("");this.element_.insertAdjacentHTML("beforeEnd",h.join(""))};z.fill=function(){this.stroke(true)};z.closePath=function(){this.currentPath_.push({type:"close"})};z.save= -function(){var p={};f(this,p);this.aStack_.push(p);this.mStack_.push(this.m_);this.m_=d(a(),this.m_)};z.restore=function(){if(this.aStack_.length){f(this.aStack_.pop(),this);this.m_=this.mStack_.pop()}};z.translate=function(p,h){B(this,d([[1,0,0],[0,1,0],[p,h,1]],this.m_),false)};z.scale=function(p,h){this.arcScaleX_*=p;this.arcScaleY_*=h;B(this,d([[p,0,0],[0,h,0],[0,0,1]],this.m_),true)};z=I.prototype=Error();z.INDEX_SIZE_ERR=1;z.DOMSTRING_SIZE_ERR=2;z.HIERARCHY_REQUEST_ERR=3;z.WRONG_DOCUMENT_ERR= -4;z.INVALID_CHARACTER_ERR=5;z.NO_DATA_ALLOWED_ERR=6;z.NO_MODIFICATION_ALLOWED_ERR=7;z.NOT_FOUND_ERR=8;z.NOT_SUPPORTED_ERR=9;z.INUSE_ATTRIBUTE_ERR=10;z.INVALID_STATE_ERR=11;z.SYNTAX_ERR=12;z.INVALID_MODIFICATION_ERR=13;z.NAMESPACE_ERR=14;z.INVALID_ACCESS_ERR=15;z.VALIDATION_ERR=16;z.TYPE_MISMATCH_ERR=17;G_vmlCanvasManager=F;CanvasRenderingContext2D=t;DOMException=I}(); -$.widget||function(g,q){if(g.cleanData){var r=g.cleanData;g.cleanData=function(c){for(var a=0,d;(d=c[a])!=null;a++)try{g(d).triggerHandler("remove")}catch(f){}r(c)}}else{var b=g.fn.remove;g.fn.remove=function(c,a){return this.each(function(){if(!a)if(!c||g.filter(c,[this]).length)g("*",this).add([this]).each(function(){try{g(this).triggerHandler("remove")}catch(d){}});return b.call(g(this),c,a)})}}g.widget=function(c,a,d){var f=c.split(".")[0],e;c=c.split(".")[1];e=f+"-"+c;if(!d){d=a;a=g.Widget}g.expr[":"][e]= -function(l){return!!g.data(l,c)};g[f]=g[f]||{};g[f][c]=function(l,m){arguments.length&&this._createWidget(l,m)};a=new a;a.options=g.extend(true,{},a.options);g[f][c].prototype=g.extend(true,a,{namespace:f,widgetName:c,widgetEventPrefix:g[f][c].prototype.widgetEventPrefix||c,widgetBaseClass:e},d);g.widget.bridge(c,g[f][c])};g.widget.bridge=function(c,a){g.fn[c]=function(d){var f=typeof d==="string",e=Array.prototype.slice.call(arguments,1),l=this;d=!f&&e.length?g.extend.apply(null,[true,d].concat(e)): -d;if(f&&d.charAt(0)==="_")return l;f?this.each(function(){var m=g.data(this,c),n=m&&g.isFunction(m[d])?m[d].apply(m,e):m;if(n!==m&&n!==q){l=n;return false}}):this.each(function(){var m=g.data(this,c);m?m.option(d||{})._init():g.data(this,c,new a(d,this))});return l}};g.Widget=function(c,a){arguments.length&&this._createWidget(c,a)};g.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(c,a){g.data(a,this.widgetName,this);this.element=g(a);this.options= -g.extend(true,{},this.options,this._getCreateOptions(),c);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return g.metadata&&g.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+ -"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(c,a){var d=c;if(arguments.length===0)return g.extend({},this.options);if(typeof c==="string"){if(a===q)return this.options[c];d={};d[c]=a}this._setOptions(d);return this},_setOptions:function(c){var a=this;g.each(c,function(d,f){a._setOption(d,f)});return this},_setOption:function(c,a){this.options[c]=a;if(c==="disabled")this.widget()[a?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled", -a);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(c,a,d){var f,e=this.options[c];d=d||{};a=g.Event(a);a.type=(c===this.widgetEventPrefix?c:this.widgetEventPrefix+c).toLowerCase();a.target=this.element[0];if(c=a.originalEvent)for(f in c)f in a||(a[f]=c[f]);this.element.trigger(a,d);return!(g.isFunction(e)&&e.call(this.element[0],a,d)===false||a.isDefaultPrevented())}}}(jQuery); -window.JsViews||window.jQuery&&jQuery.views||function(g,q){function r(h,o,s,x,v){var A=(s=s||{viewsCount:0,ctx:n.helpers})&&s.ctx;return{jsViews:"v1.0pre",path:o||"",itemNumber:++s.viewsCount||1,viewsCount:0,tmpl:v,data:x||s.data||{},ctx:h&&h===A?A:A?F(F({},A),h):h||{},parent:s}}function b(h,o,s,x,v,A,E){return s?(x?v?"$view."+v:s:"$data."+s)+(A||""):E||o||""}function c(h){function o(O){O-=x;O&&E.push(h.substr(x,O).replace(C,"\\n"))}var s,x=0,v=[],A=[],E=A,N=[,,A];h=h.replace(M,"\\$1");h.replace(w, -function(O,S,Q,ga,ha,T,ia,ja,ka,ca){function la(Z,V,ma,da,na,oa,ea,fa,pa,qa){return W?(W=!ea,W?Z:'"'):X?(X=!fa,X?Z:'"'):da?V.replace(P,b)+da:na?Y?"":(aa=K,"\u0008"+V+":"):ma?(Y++,V.replace(P,b)+"("):pa?(Y--,")"):V?V.replace(P,b):oa?",":qa?Y?"":aa?(aa=y,"\u0008"):",":(W=ea,X=fa,'"')}var aa,ba="",Y=0,X=y,W=y;Q=Q||ga;o(ca);if(ha)n.allowCode&&E.push(["*",T.replace(G,"$1")]);else if(Q){if(Q==="else"){N=v.pop();E=N[2];S=K}T=T?(T+" ").replace(H,la).replace(z,function(Z,V){ba+=V+",";return""}):"";T=T.slice(0, --1);s=[Q,ia?ja||"none":"",S&&[],"{"+ba+"_hash:'"+ba+"',_path:'"+T+"'}",T];if(S){v.push(N);N=s}E.push(s)}else if(ka)N=v.pop();x=ca+O.length;if(!N)throw"Expected block tag";E=N[2]});o(h.length);return a(A)}function a(h){var o,s,x=[],v=h.length,A="try{var views="+(D?"jQuery":"JsViews")+'.views,tag=views.renderTag,enc=views.encode,html=views.encoders.html,$ctx=$view && $view.ctx,result=""+\n\n';for(s=0;s)[^>]*$|\{\{\! /,P=/^(true|false|null|[\d\.]+)|(\w+|\$(view|data|ctx|(\w+)))([\w\.]*)|((['"])(?:\\\1|.)*\7)$/g,H=/(\$?[\w\.\[\]]+)(?:(\()|\s*(===|!==|==|!=|<|>|<=|>=)\s*|\s*(\=)\s*)?|(\,\s*)|\\?(\')|\\?(\")|(\))|(\s+)/g,C=/\r?\n/g,G=/\\(['"])/g,M=/\\?(['"])/g,z=/\x08([^\x08]+)\x08/g,L=0,R={"&":"&","<":"<",">":">"},U=/[\x00"&'<>]/g,p=Array.prototype.slice;if(D){e=D;e.fn.extend({render:function(h,o,s,x){return u(h,this[0],o,s,x)},template:function(h,o){return e.template(h, -this[0],o)}})}else{l=g.$;g.JsViews=m=g.$=e={extend:function(h,o){for(var s in o)h[s]=o[s];return h},isArray:Array.isArray||function(h){return Object.prototype.toString.call(h)==="[object Array]"},noConflict:function(){if(g.$===m)g.$=l;return m}}}F=e.extend;F(e,{views:n={templates:{},tags:{"if":function(){var h=this._view;h.onElse=function(o,s){for(var x=0,v=s.length;v&&!s[x++];)if(x===v)return"";h.onElse=q;return u(h.data,o.tmpl,h.ctx,h)};return h.onElse(this,arguments)},"else":function(){var h=this._view; -return h.onElse?h.onElse(this,arguments):""},each:function(){var h,o="",s=arguments,x=s.length,v=this.tmpl,A=this._view;for(h=0;hError: "+(h.message||h)+". ":'""'},setDelimiters:function(h,o){var s=o.charAt(0), -x=o.charAt(1);h="\\"+h.charAt(0)+"\\"+h.charAt(1);o="\\"+s+"\\"+x;w=h+"(?:(?:(\\#)?(\\w+(?=[!\\s\\"+s+"]))|(?:(\\=)|(\\*)))\\s*((?:[^\\"+s+"]|\\"+s+"(?!\\"+x+"))*?)(!(\\w*))?|(?:\\/([\\w\\$\\.\\[\\]]+)))"+o;w=RegExp(w,"g")},registerTags:B=function(h,o){var s;if(typeof h==="object")for(s in h)B(s,h[s]);else n.tags[h]=o;return this},registerHelpers:I=function(h,o){if(typeof h==="object")for(var s in h)I(s,h[s]);else n.helpers[h]=o;return this},encode:function(h,o){return o?(t[h||"html"]||t.html)(o): -""},encoders:t={none:function(h){return h},html:function(h){return String(h).replace(U,d)}},renderTag:function(h,o,s,x,v){var A,E;A=arguments;E=n.presenters;hash=v._hash;tagFn=n.tags[h];if(!tagFn)return"";x=x&&o.tmpl.nested[x-1];v.tmpl=v.tmpl||x||q;if(E&&E[h]){E=F(F({},v.ctx),v);delete E.ctx;delete E._path;delete E.tmpl;v.ctx=E;v._ctor=h+(hash?"="+hash.slice(0,-1):"");v=F(F({},tagFn),v);tagFn=n.tags.each}v._encode=s;v._view=o;return(A=tagFn.apply(v,A.length>5?p.call(A,5):[o.data]))||(A===q?"":A.toString())}}, -render:u=function(h,o,s,x,v,A){var E,N,O,S,Q="";if(arguments.length===2&&h.jsViews){x=h;s=x.ctx;h=x.data}o=e.template(o);if(!o)return"";if(e.isArray(h)){S=new r(s,v,x,h);E=0;for(N=h.length;E"+O+""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ); - - $.widget("geo.geographics", { - _$elem: undefined, - _options: {}, - _trueCanvas: true, - - _width: 0, - _height: 0, - - _$canvas: undefined, - _context: undefined, - - _blitcanvas: undefined, - _blitcontext: undefined, - - _$labelsContainer: undefined, - - options: { - style: { - borderRadius: "8px", - color: "#7f0000", - //fill: undefined, - fillOpacity: 0.2, - height: "8px", - opacity: 1, - //stroke: undefined, - strokeOpacity: 1, - strokeWidth: "2px", - visibility: "visible", - width: "8px" - } - }, - - _create: function () { - this._$elem = this.element; - this._options = this.options; - - this._$elem.css({ display: "inline-block", overflow: "hidden", textAlign: "left" }); - - if (this._$elem.css("position") == "static") { - this._$elem.css("position", "relative"); - } - - this._$elem.addClass( "geo-graphics" ); - - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - var posCss = 'position:absolute;left:0;top:0;margin:0;padding:0;', - sizeCss = 'width:' + this._width + 'px;height:' + this._height + 'px;', - sizeAttr = 'width="' + this._width + '" height="' + this._height + '"'; - - if (document.createElement('canvas').getContext) { - this._$elem.append(''); - this._$canvas = this._$elem.children(':last'); - this._context = this._$canvas[0].getContext("2d"); - - this._blitcanvas = document.createElement( "canvas" ); - this._blitcanvas.width = this._width; - this._blitcanvas.height = this._height; - this._blitcontext = this._blitcanvas.getContext("2d"); - } else if (_ieVersion <= 8) { - this._trueCanvas = false; - this._$elem.append( '
                              '); - this._$canvas = this._$elem.children(':last'); - - G_vmlCanvasManager.initElement(this._$canvas[0]); - this._context = this._$canvas[0].getContext("2d"); - this._$canvas.children().css({ backgroundColor: "transparent", width: this._width, height: this._height }); - } - - this._$elem.append('
                              '); - this._$labelsContainer = this._$elem.children(':last'); - }, - - _setOption: function (key, value) { - if (key == "style") { - value = $.extend({}, this._options.style, value); - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - destroy: function () { - $.Widget.prototype.destroy.apply(this, arguments); - this._$elem.html(""); - this._$elem.removeClass( "geo-graphics" ); - }, - - clear: function () { - this._context.clearRect(0, 0, this._width, this._height); - this._$labelsContainer.html(""); - }, - - drawArc: function (coordinates, startAngle, sweepAngle, style) { - style = this._getGraphicStyle(style); - - if (style.visibility != "hidden" && style.opacity > 0 && style.widthValue > 0 && style.heightValue > 0) { - var r = Math.min(style.widthValue, style.heightValue) / 2; - - startAngle = (startAngle * Math.PI / 180); - sweepAngle = (sweepAngle * Math.PI / 180); - - this._context.save(); - this._context.translate(coordinates[0], coordinates[1]); - if (style.widthValue > style.heightValue) { - this._context.scale(style.widthValue / style.heightValue, 1); - } else { - this._context.scale(1, style.heightValue / style.widthValue); - } - - this._context.beginPath(); - this._context.arc(0, 0, r, startAngle, sweepAngle, false); - - if (this._trueCanvas) { - this._context.restore(); - } - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - if (!this._trueCanvas) { - this._context.restore(); - } - } - }, - - drawPoint: function (coordinates, style) { - style = this._getGraphicStyle(style); - if (style.widthValue == style.heightValue && style.heightValue == style.borderRadiusValue) { - this.drawArc(coordinates, 0, 360, style); - } else if (style.visibility != "hidden" && style.opacity > 0) { - style.borderRadiusValue = Math.min(Math.min(style.widthValue, style.heightValue) / 2, style.borderRadiusValue); - coordinates[0] -= style.widthValue / 2; - coordinates[1] -= style.heightValue / 2; - this._context.beginPath(); - this._context.moveTo(coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.lineTo(coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1]); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1], coordinates[0] + style.widthValue, coordinates[1] + style.borderRadiusValue); - this._context.lineTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue, coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.lineTo(coordinates[0] + style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1] + style.heightValue, coordinates[0], coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.lineTo(coordinates[0], coordinates[1] + style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1], coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.closePath(); - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - - this._context.stroke(); - } - } - }, - - drawLineString: function (coordinates, style) { - this._drawLines([coordinates], false, style); - }, - - drawPolygon: function (coordinates, style) { - if ( !this._trueCanvas || coordinates.length == 1 ) { - // either we don't have fancy rendering or there's no need for it (no holes) - this._drawLines( coordinates, true, style ); - } else { - if ( !coordinates || !coordinates.length || coordinates[ 0 ].length < 3 ) { - // this is not a Polygon or it doesn't have a proper outer ring - return; - } - - style = this._getGraphicStyle(style); - - var pixelBbox, i, j; - - if ( style.visibility != "hidden" && style.opacity > 0 ) { - this._blitcontext.clearRect(0, 0, this._width, this._height); - - if ( style.doFill ) { - if ( coordinates.length > 1 ) { - // stencil inner rings - this._blitcontext.globalCompositeOperation = "source-out"; - this._blitcontext.globalAlpha = 1; - - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.fill( ); - } - } - } - - // path outer ring - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ 0 ][ 0 ][ 0 ], coordinates[ 0 ][ 0 ][ 1 ] ); - - pixelBbox = [ coordinates[ 0 ][ 0 ][ 0 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 0 ] + style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] + style.strokeWidthValue ]; - - for ( i = 1; i < coordinates[ 0 ].length - 1; i++ ) { - this._blitcontext.lineTo( coordinates[ 0 ][ i ][ 0 ], coordinates[ 0 ][ i ][ 1 ] ); - - pixelBbox[ 0 ] = Math.min( coordinates[ 0 ][ i ][ 0 ] - style.strokeWidthValue, pixelBbox[ 0 ] ); - pixelBbox[ 1 ] = Math.min( coordinates[ 0 ][ i ][ 1 ] - style.strokeWidthValue, pixelBbox[ 1 ] ); - pixelBbox[ 2 ] = Math.max( coordinates[ 0 ][ i ][ 0 ] + style.strokeWidthValue, pixelBbox[ 2 ] ); - pixelBbox[ 3 ] = Math.max( coordinates[ 0 ][ i ][ 1 ] + style.strokeWidthValue, pixelBbox[ 3 ] ); - } - - this._blitcontext.closePath(); - - this._blitcontext.globalCompositeOperation = "source-out"; - if ( style.doFill ) { - // fill outer ring - this._blitcontext.fillStyle = style.fill; - this._blitcontext.globalAlpha = style.opacity * style.fillOpacity; - this._blitcontext.fill( ); - } - - this._blitcontext.globalCompositeOperation = "source-over"; - if ( style.doStroke ) { - // stroke outer ring - this._blitcontext.lineCap = this._blitcontext.lineJoin = "round"; - this._blitcontext.lineWidth = style.strokeWidthValue; - this._blitcontext.strokeStyle = style.stroke; - - this._blitcontext.globalAlpha = style.opacity * style.strokeOpacity; - this._blitcontext.stroke( ); - - if ( coordinates.length > 1 ) { - // stroke inner rings - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.stroke( ); - } - } - } - - // blit - pixelBbox[ 0 ] = Math.min( Math.max( pixelBbox[ 0 ], 0), this._width ); - pixelBbox[ 1 ] = Math.min( Math.max( pixelBbox[ 1 ], 0), this._height ); - pixelBbox[ 2 ] = Math.min( Math.max( pixelBbox[ 2 ], 0), this._width ); - pixelBbox[ 3 ] = Math.min( Math.max( pixelBbox[ 3 ], 0), this._height ); - - if ( pixelBbox[ 0 ] !== pixelBbox[ 2 ] && pixelBbox[ 1 ] !== pixelBbox[ 3 ] ) { - this._context.drawImage(this._blitcanvas, pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ], pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ] ); - } - } - } - }, - - drawBbox: function (bbox, style) { - this._drawLines([[ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ]], true, style); - }, - - drawLabel: function( coordinates, label ) { - this._$labelsContainer.append( '
                              ' + label + '
                              '); - }, - - resize: function( ) { - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - if ( this._trueCanvas ) { - this._$canvas[0].width = this._width; - this._$canvas[0].height = this._height; - } else { - } - - this._$labelsContainer.css( { - width: this._width, - height: this._height - } ); - }, - - _getGraphicStyle: function (style) { - function safeParse(value) { - value = parseInt(value, 10); - return (+value + '') === value ? +value : value; - } - - style = $.extend({}, this._options.style, style); - style.borderRadiusValue = safeParse(style.borderRadius); - style.fill = style.fill || style.color; - style.doFill = style.fill && style.fillOpacity > 0; - style.stroke = style.stroke || style.color; - style.strokeWidthValue = safeParse(style.strokeWidth); - style.doStroke = style.stroke && style.strokeOpacity > 0 && style.strokeWidthValue > 0; - style.widthValue = safeParse(style.width); - style.heightValue = safeParse(style.height); - return style; - }, - - _drawLines: function (coordinates, close, style) { - if (!coordinates || !coordinates.length || coordinates[0].length < 2) { - return; - } - - var i, j; - style = this._getGraphicStyle(style); - - if (style.visibility != "hidden" && style.opacity > 0) { - this._context.beginPath(); - - for (i = 0; i < coordinates.length; i++) { - this._context.moveTo(coordinates[i][0][0], coordinates[i][0][1]); - for (j = 1; j < coordinates[i].length; j++) { - this._context.lineTo(coordinates[i][j][0], coordinates[i][j][1]); - } - } - - if (close) { - this._context.closePath(); - } - - if (close && style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineCap = this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - } - } - }); -}(jQuery)); - - -(function ($, undefined) { - var _widgetIdSeed = 0, - _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ), - - _defaultOptions = { - bbox: [-180, -85, 180, 85], - bboxMax: [-180, -85, 180, 85], - center: [0, 0], - cursors: { - "static": "default", - pan: "url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move", - zoom: "crosshair", - dragBox: "crosshair", - dragCircle: "crosshair", - drawPoint: "crosshair", - drawLineString: "crosshair", - drawPolygon: "crosshair", - measureLength: "crosshair", - measureArea: "crosshair" - }, - measureLabels: { - length: "{{:length.toFixed( 2 )}} m", - area: "{{:area.toFixed( 2 )}} sq m" - }, - drawStyle: {}, - shapeStyle: {}, - mode: "pan", - pannable: true, - scroll: "default", - shift: "default", - services: [ - { - "class": "osm", - type: "tiled", - src: function (view) { - return "http://otile" + ((view.index % 4) + 1) + ".mqcdn.com/tiles/1.0.0/osm/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; - }, - attr: "Tiles Courtesy of MapQuest " - } - ], - tilingScheme: { - tileWidth: 256, - tileHeight: 256, - levels: 18, - basePixelSize: 156543.03392799936, - origin: [-20037508.342787, 20037508.342787] - }, - axisLayout: "map", - zoom: 0, - zoomMin: 0, - zoomMax: Number.POSITIVE_INFINITY, - pixelSize: 0 - }; - - $.widget("geo.geomap", { - // private widget members - _$elem: undefined, //< map div for maps, service div for services - _map: undefined, //< only defined in services - _created: false, - _createdGraphics: false, - _widgetId: 0, - _tmplLengthId: "", - _tmplAreaId: "", - - _contentBounds: {}, - - _$resizeContainer: undefined, //< all elements that should match _contentBounds' size - - _$eventTarget: undefined, - _$contentFrame: undefined, - _$existingChildren: undefined, - _$attrList: undefined, - _$servicesContainer: undefined, - _$shapesContainers: undefined, //< all shapesContainer divs (map only) - - _$panContainer: undefined, //< all non-service elements that move while panning - _$shapesContainer: undefined, //< just "our" shapesContainer div (map & service) - _$drawContainer: undefined, - _$measureContainer: undefined, - _$measureLabel: undefined, - - _dpi: 96, - - _currentServices: [], //< internal copy - - _center: undefined, - _pixelSize: undefined, - _centerMax: undefined, - _pixelSizeMax: undefined, - - _userGeodetic: true, - - _centerInteractive: undefined, - _pixelSizeInteractive: undefined, - _timeoutInteractive: null, - _triggerInteractive: false, - - _loadCount: 0, - - _wheelTimeout: null, - _wheelLevel: 0, - - _zoomFactor: 2, //< determines what a zoom level means - - _fullZoomFactor: 2, //< interactiveScale factor needed to zoom a whole level - _partialZoomFactor: 1.18920711500273, //< interactiveScale factor needed to zoom a fraction of a level (the fourth root of 2) - - _mouseDown: undefined, - _inOp: undefined, - _toolPan: undefined, - _shiftDown: undefined, - _anchor: undefined, - _current: undefined, - _downDate: undefined, - _moveDate: undefined, - _clickDate: undefined, - _lastMove: undefined, - _lastDrag: undefined, - - _windowHandler: null, - _resizeTimeout: null, - - _panning: undefined, - _velocity: undefined, - _friction: undefined, - - _supportTouch: undefined, - _softDblClick: undefined, - _isTap: undefined, - _isDbltap: undefined, - - _isMultiTouch: undefined, - _multiTouchAnchor: [], //< TouchList - _multiTouchAnchorBbox: undefined, //< bbox - _multiTouchCurrentBbox: undefined, //< bbox - - _drawTimeout: null, //< used in drawPoint mode so we don't send two shape events on dbltap - _drawPixels: [], //< an array of coordinate arrays for drawing lines & polygons, in pixel coordinates - _drawCoords: [], - - _graphicShapes: [], //< an array of objects containing style object refs & GeoJSON object refs - - _initOptions: {}, - - _options: {}, - - options: $.extend({}, _defaultOptions), - - _createWidget: function (options, element) { - this._$elem = $(element); - - if (this._$elem.is(".geo-service")) { - this._graphicShapes = []; - $.Widget.prototype._createWidget.apply(this, arguments); - return; - } - - this._widgetId = _widgetIdSeed++; - this._tmplLengthId = "geoMeasureLength" + this._widgetId; - this._tmplAreaId = "geoMeasureArea" + this._widgetId; - - this._$elem.addClass("geo-map").css( { - webkitTransform: "translateZ(0)" - } ); - - - this._initOptions = options || {}; - - this._forcePosition(this._$elem); - - this._$elem.css("text-align", "left"); - - var size = this._findMapSize(); - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._createChildren(); - - this._center = [ 0, 0 ]; - this._centerMax = [ 0, 0 ]; - this._centerInteractive = [ 0, 0 ]; - - this.options["pixelSize"] = this._pixelSize = this._pixelSizeMax = 156543.03392799936; - - this._mouseDown = - this._inOp = - this._toolPan = - this._shiftDown = - this._panning = - this._isTap = - this._isDbltap = false; - - this._anchor = [ 0, 0 ]; - this._current = [ 0, 0 ]; - this._lastMove = [ 0, 0 ]; - this._lastDrag = [ 0, 0 ]; - this._velocity = [ 0, 0 ]; - - this._friction = [0.8, 0.8]; - - this._downDate = - this._moveDate = - this._clickDate = 0; - - this._drawPixels = []; - this._drawCoords = []; - this._graphicShapes = []; - - - $.Widget.prototype._createWidget.apply(this, arguments); - }, - - _create: function () { - this._options = this.options; - - if (this._$elem.is(".geo-service")) { - this._map = this._$elem.data( "geoMap" ); - this._$elem.data( "geoService", this ); - return; - } - - this._map = this; - - this._supportTouch = "ontouchend" in document; - this._softDblClick = this._supportTouch || _ieVersion == 7; - - var geomap = this, - touchStartEvent = this._supportTouch ? "touchstart" : "mousedown", - touchStopEvent = this._supportTouch ? "touchend touchcancel" : "mouseup", - touchMoveEvent = this._supportTouch ? "touchmove" : "mousemove"; - - $(document).keydown($.proxy(this._document_keydown, this)); - - this._$eventTarget.dblclick($.proxy(this._eventTarget_dblclick, this)); - - this._$eventTarget.bind(touchStartEvent, $.proxy(this._eventTarget_touchstart, this)); - - var dragTarget = (this._$eventTarget[0].setCapture) ? this._$eventTarget : $(document); - dragTarget.bind(touchMoveEvent, $.proxy(this._dragTarget_touchmove, this)); - dragTarget.bind(touchStopEvent, $.proxy(this._dragTarget_touchstop, this)); - - this._$eventTarget.mousewheel($.proxy(this._eventTarget_mousewheel, this)); - - this._windowHandler = function () { - if (geomap._resizeTimeout) { - clearTimeout(geomap._resizeTimeout); - } - geomap._resizeTimeout = setTimeout(function () { - if (geomap._created) { - geomap._$elem.geomap( "resize", true ); - } - }, 500); - }; - - $(window).resize(this._windowHandler); - - this._$drawContainer.geographics({ style: this._initOptions.drawStyle || {} }); - this._options["drawStyle"] = this._$drawContainer.geographics("option", "style"); - - this._$shapesContainer.geographics( { style: this._initOptions.shapeStyle || { } } ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - - if (this._initOptions) { - // always init tilingScheme right away, even if it's null - if ( this._initOptions.tilingScheme !== undefined ) { - this._setOption("tilingScheme", this._initOptions.tilingScheme || null, false); - } - - if ( this._initOptions.services ) { - // jQuery UI Widget Factory merges user services with our default, we want to clobber the default - this._options[ "services" ] = $.merge( [ ], this._initOptions.services ); - } - if (this._initOptions.bboxMax) { - this._setOption("bboxMax", this._initOptions.bboxMax, false); - this._setOption("bbox", this._initOptions.bboxMax, false); - } - if (this._initOptions.zoomMin !== undefined) { - this._setOption("zoomMin", this._initOptions.zoomMin, false); - } - if (this._initOptions.zoomMax !== undefined) { - this._setOption("zoomMax", this._initOptions.zoomMax, false); - } - if (this._initOptions.bbox) { - this._setOption("bbox", this._initOptions.bbox, false); - } - if (this._initOptions.center) { - this._setOption("center", this._initOptions.center, false); - } - if (this._initOptions.zoom !== undefined) { - this._setOption("zoom", this._initOptions.zoom, false); - } - } - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._createServices(); - this._refresh(); - - this._created = true; - }, - - _setOption: function (key, value, refresh) { - if ( key == "pixelSize" ) { - return; - } - - refresh = (refresh === undefined || refresh); - - if ( this._$elem.is( ".geo-map" ) ) { - this._panFinalize(); - } - - var center, pixelSize, bbox, zoom; - - switch (key) { - case "bbox": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2]; - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height); - - // clamp to zoom - zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( center, pixelSize ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( center, pixelSize, false, refresh ); - } - - value = this._getBbox( center, pixelSize ); - break; - - case "bboxMax": - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - break; - - case "center": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( value, this._pixelSizeInteractive ); - this._interactiveTransform( ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( value, this._pixelSize, false, refresh ); - } - break; - - case "measureLabels": - value = $.extend( this._options[ "measureLabels" ], value ); - - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - break; - - case "drawStyle": - if (this._$drawContainer) { - this._$drawContainer.geographics("option", "style", value); - value = this._$drawContainer.geographics("option", "style"); - } - break; - - case "shapeStyle": - if ( this._$elem.is( ".geo-service" ) && !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("option", "style", value); - value = this._$shapesContainer.geographics("option", "style"); - } - break; - - case "mode": - this._resetDrawing( ); - this._$eventTarget.css("cursor", this._options["cursors"][value]); - break; - - case "zoom": - if ( this._created ) { - this._setZoom(value, false, refresh); - } else { - value = Math.max( value, 0 ); - this._setCenterAndSize( this._center, this._getPixelSize( value ), false, refresh ); - } - break; - } - - $.Widget.prototype._setOption.apply(this, arguments); - - switch ( key ) { - case "bbox": - case "center": - if ( this._userGeodetic ) { - this._options[ "bbox" ] = $.geo.proj.toGeodetic( this._options[ "bbox" ] ); - this._options[ "center" ] = $.geo.proj.toGeodetic( this._center ); - } - break; - - case "tilingScheme": - if ( value !== null ) { - this._pixelSizeMax = this._getPixelSize( 0 ); - this._centerMax = [ - value.origin[ 0 ] + this._pixelSizeMax * value.tileWidth / 2, - value.origin[ 1 ] + this._pixelSizeMax * value.tileHeight / 2 - ]; - } - break; - - case "bboxMax": - if ( $.geo.proj && $.geo._isGeodetic( value ) ) { - bbox = $.geo.proj.fromGeodetic( value ); - } else { - bbox = value; - } - - this._centerMax = $.geo.center( bbox ); - this._pixelSizeMax = Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - break; - - case "services": - this._createServices(); - if (refresh) { - this._refresh(); - } - break; - - case "shapeStyle": - if ( refresh && this._createdGraphics ) { - this._$shapesContainer.geographics("clear"); - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - break; - } - }, - - destroy: function () { - if ( this._$elem.is(".geo-service") ) { - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - } - } else { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - - this._created = false; - - $(window).unbind("resize", this._windowHandler); - - for ( var i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - - this._$drawContainer.geographics("destroy"); - this._$drawContainer = undefined; - - this._$existingChildren.detach(); - this._$elem.html(""); - this._$elem.append(this._$existingChildren); - this._$elem.removeClass("geo-map"); - } - - $.Widget.prototype.destroy.apply(this, arguments); - }, - - toMap: function (p) { - p = this._toMap(p); - return this._userGeodetic ? $.geo.proj.toGeodetic(p) : p; - }, - - toPixel: function ( p, _center /* Internal Use Only */, _pixelSize /* Internal Use Only */ ) { - return this._toPixel( $.geo.proj ? $.geo.proj.fromGeodetic( p ) : p, _center, _pixelSize ); - }, - - opacity: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "opacity", value, this._$elem ); - } else { - if ( value >= 0 || value <= 1 ) { - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - service.style.opacity = value; - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - $.geo[ "_serviceTypes" ][ service.type ].opacity( this, service ); - } - } - } - } - }, - - toggle: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "toggle", value, this._$elem ); - } else { - - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - if ( value === undefined ) { - // toggle visibility - value = ( service.style.visibility !== "visible" ); - } - - service.style.visibility = ( value ? "visible" : "hidden" ); - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - service.serviceContainer.toggle( value ); - - if ( value ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service ); - } - } - } - } - }, - - zoom: function (numberOfLevels) { - if (numberOfLevels !== null) { - this._setZoom(this._options["zoom"] + numberOfLevels, false, true); - } - }, - - refresh: function ( force, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "refresh", force, this._$elem ); - } else { - this._refresh( force, _serviceContainer ); - } - }, - - resize: function ( _trigger /* Internal Use Only */ ) { - var size = this._findMapSize(), - dx = size["width"]/2 - this._contentBounds.width/2, - dy = size["height"]/2 - this._contentBounds.height/2, - i; - - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._$resizeContainer.css( { - width: size["width"], - height: size["height"] - } ); - - for (i = 0; i < this._currentServices.length; i++) { - $.geo["_serviceTypes"][this._currentServices[i].type].resize(this, this._currentServices[i]); - } - - this._$elem.find( ".geo-graphics" ).css( { - width: size["width"], - height: size["height"] - }).geographics( "resize" ); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._setCenterAndSize(this._center, this._pixelSize, _trigger, true); - }, - - append: function ( shape, style, label, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - if ( !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - var shapes, arg, i, realStyle, realLabel, realRefresh; - - if ( $.isArray( shape ) ) { - shapes = shape; - } else if ( shape.type == "FeatureCollection" ) { - shapes = shape.features; - } else { - shapes = [ shape ]; - } - - for ( i = 1; i < arguments.length; i++ ) { - arg = arguments[ i ]; - - if ( typeof arg === "object" ) { - realStyle = arg; - } else if ( typeof arg === "number" || typeof arg === "string" ) { - realLabel = arg; - } else if ( typeof arg === "boolean" ) { - realRefresh = arg; - } - } - - for ( i = 0; i < shapes.length; i++ ) { - if ( shapes[ i ].type != "Point" ) { - var bbox = $.geo.bbox( shapes[ i ] ); - if ( $.geo.proj && $.geo._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - $.data( shapes[ i ], "geoBbox", bbox ); - } - - this._graphicShapes.push( { - shape: shapes[ i ], - style: realStyle, - label: realLabel - } ); - } - - if ( realRefresh === undefined || realRefresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - } - } - }, - - empty: function ( refresh ) { - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - $.removeData( this._graphicShapes[ i ].shape, "geoBbox" ); - } - - this._graphicShapes = []; - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - } - }, - - find: function ( selector, pixelTolerance ) { - var isPoint = $.isPlainObject( selector ), - searchPixel = isPoint ? this._map.toPixel( selector.coordinates ) : undefined, - mapTol = this._map._pixelSize * pixelTolerance, - result = [], - graphicShape, - geometries, - curGeom, - i = 0; - - for ( ; i < this._graphicShapes.length; i++ ) { - graphicShape = this._graphicShapes[ i ]; - - if ( isPoint ) { - if ( graphicShape.shape.type == "Point" ) { - if ( $.geo.distance( graphicShape.shape, selector ) <= mapTol ) { - result.push( graphicShape.shape ); - } - } else { - var bbox = $.data( graphicShape.shape, "geoBbox" ), - bboxPolygon = { - type: "Polygon", - coordinates: [ [ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ] ] - }, - projectedPoint = { - type: "Point", - coordinates: $.geo.proj && $.geo._isGeodetic( selector.coordinates ) ? $.geo.proj.fromGeodetic( selector.coordinates ) : selector.coordinates - }; - - if ( $.geo.distance( bboxPolygon, projectedPoint, true ) <= mapTol ) { - geometries = $.geo._flatten( graphicShape.shape ); - for ( curGeom = 0; curGeom < geometries.length; curGeom++ ) { - if ( $.geo.distance( geometries[ curGeom ], selector ) <= mapTol ) { - result.push( graphicShape.shape ); - break; - } - } - } - } - } else { - result.push( graphicShape.shape ); - } - } - - if ( this._$elem.is( ".geo-map" ) ) { - this._$elem.find( ".geo-service" ).each( function( ) { - result = $.merge( result, $( this ).geomap( "find", selector, pixelTolerance ) ); - } ); - } - - return result; - }, - - remove: function ( shape, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - var shapes = $.isArray( shape ) ? shape : [ shape ], - rest; - - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - if ( $.inArray( this._graphicShapes[ i ].shape, shapes ) >= 0 ) { - $.removeData( shape, "geoBbox" ); - rest = this._graphicShapes.slice( i + 1 ); - this._graphicShapes.length = i; - this._graphicShapes.push.apply( this._graphicShapes, rest ); - i--; - } - } - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - } - } - }, - - _getBbox: function (center, pixelSize) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - // calculate the internal bbox - var halfWidth = this._contentBounds[ "width" ] / 2 * pixelSize, - halfHeight = this._contentBounds[ "height" ] / 2 * pixelSize; - return [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - }, - - _setBbox: function (value, trigger, refresh) { - var center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2], - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height), - zoom = this._getZoom( center, pixelSize ); - - // clamp to zoom - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._setInteractiveCenterAndSize( center, pixelSize ); - this._interactiveTransform( ); - }, - - _getBboxMax: function () { - // calculate the internal bboxMax - var halfWidth = this._contentBounds["width"] / 2 * this._pixelSizeMax, - halfHeight = this._contentBounds["height"] / 2 * this._pixelSizeMax; - return [this._centerMax[0] - halfWidth, this._centerMax[1] - halfHeight, this._centerMax[0] + halfWidth, this._centerMax[1] + halfHeight]; - }, - - _getCenter: function () { - return this._center; - }, - - _getContentBounds: function () { - return this._contentBounds; - }, - - _getServicesContainer: function () { - return this._$servicesContainer; - }, - - _getZoom: function ( center, pixelSize ) { - // calculate the internal zoom level, vs. public zoom property - // this does not take zoomMin or zoomMax into account - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var tilingScheme = this._options["tilingScheme"]; - if ( tilingScheme ) { - if ( tilingScheme.pixelSizes ) { - var roundedPixelSize = Math.floor(pixelSize * 1000), - levels = tilingScheme.pixelSizes.length, - i = levels - 1; - - for ( ; i >= 0; i-- ) { - if ( Math.floor( tilingScheme.pixelSizes[ i ] * 1000 ) >= roundedPixelSize ) { - return i; - } - } - - return 0; - } else { - return Math.round( Math.log( tilingScheme.basePixelSize / pixelSize) / Math.log( 2 ) ); - } - } else { - var ratio = this._contentBounds["width"] / this._contentBounds["height"], - bbox = $.geo.reaspect( this._getBbox( center, pixelSize ), ratio, true ), - bboxMax = $.geo.reaspect(this._getBboxMax(), ratio, true); - - return Math.round( Math.log($.geo.width(bboxMax, true) / $.geo.width(bbox, true)) / Math.log(this._zoomFactor) ); - } - }, - - _setZoom: function ( value, trigger, refresh ) { - // set the map widget's zoom, taking zoomMin and zoomMax into account - this._clearInteractiveTimeout( ); - - value = Math.min( Math.max( value, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ); - this._setInteractiveCenterAndSize( this._centerInteractive, this._getPixelSize( value ) ); - this._interactiveTransform( ); - - this._setInteractiveTimeout( trigger ); - }, - - _createChildren: function () { - this._$existingChildren = this._$elem.children(); - - this._forcePosition(this._$existingChildren); - - this._$existingChildren.detach().css( { - mozUserSelect: "none" - } ); - - - var contentSizeCss = "width:" + this._contentBounds["width"] + "px; height:" + this._contentBounds["height"] + "px; margin:0; padding:0;", - contentPosCss = "position:absolute; left:0; top:0;"; - - this._$elem.prepend('
                              '); - this._$eventTarget = this._$contentFrame = this._$elem.children(':first'); - - this._$contentFrame.append('
                              '); - this._$servicesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                              '); - this._$shapesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append( '
                                ' ); - this._$attrList = this._$contentFrame.children( ":last" ); - - this._$contentFrame.append('
                                '); - this._$drawContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                                '); - this._$measureContainer = this._$contentFrame.children(':last'); - this._$measureLabel = this._$measureContainer.children(); - - this._$panContainer = $( [ this._$shapesContainer[ 0 ], this._$drawContainer[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$resizeContainer = $( [ this._$contentFrame[ 0 ], this._$servicesContainer[ 0 ], this._$eventTarget[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$contentFrame.append(this._$existingChildren); - - if ( ! $("#geo-measure-style").length ) { - $("head").prepend( '' ); - } - }, - - _createServices: function () { - var service, i; - - for ( i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap( "destroy" ); - $.geo[ "_serviceTypes" ][ this._currentServices[ i ].type ].destroy( this, this._$servicesContainer, this._currentServices[ i ] ); - } - - this._currentServices = [ ]; - this._$servicesContainer.html( "" ); - this._$attrList.html( "" ); - - for ( i = 0; i < this._options[ "services" ].length; i++ ) { - service = this._currentServices[ i ] = $.extend( { }, this._options[ "services" ][ i ] ); - - // keep a reference to the original - service.serviceObject = this._options[ "services" ][ i ]; - - // default the service style property on our copy - service.style = $.extend( { - visibility: "visible", - opacity: 1 - }, service.style ); - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = 'class="geo-service ' + ( service["class"] ? service["class"] : '' ) + '"', - scHtml = '
                                ', - servicesContainer; - - this._$servicesContainer.append( scHtml ); - serviceContainer = this._$servicesContainer.children( ":last" ); - service.serviceContainer = serviceContainer; - - $.geo[ "_serviceTypes" ][ service.type ].create( this, serviceContainer, service, i ); - - serviceContainer.data( "geoMap", this ).geomap(); - - if ( service.attr ) { - this._$attrList.append( '
                              • ' + service.attr + '
                              • ' ); - } - } - - // start with our map-level shapesContainer - this._$shapesContainers = this._$shapesContainer; - - this._$attrList.find( "a" ).css( { - position: "relative", - zIndex: 100 - } ); - }, - - _createServiceGraphics: function( ) { - // only called in the context of a service-level geomap - var $contentFrame = this._$elem.closest( ".geo-content-frame" ); - this._$elem.append('
                                '); - this._$shapesContainer = this._$elem.children(':last'); - - this._map._$shapesContainers = this._map._$shapesContainers.add( this._$shapesContainer ); - - this._$shapesContainer.geographics( ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - }, - - _refreshDrawing: function ( ) { - this._$drawContainer.geographics("clear"); - - if ( this._drawPixels.length > 0 ) { - var mode = this._options[ "mode" ], - pixels = this._drawPixels, - coords = this._drawCoords, - label, - labelShape, - labelPixel, - widthOver, - heightOver; - - switch ( mode ) { - case "measureLength": - mode = "drawLineString"; - labelShape = { - type: "LineString", - coordinates: coords - }; - label = $.render[ this._tmplLengthId ]( { length: $.geo.length( labelShape, true ) } ); - labelPixel = $.merge( [], pixels[ pixels.length - 1 ] ); - break; - - case "measureArea": - mode = "drawPolygon"; - - labelShape = { - type: "Polygon", - coordinates: [ $.merge( [ ], coords ) ] - }; - labelShape.coordinates[ 0 ].push( coords[ 0 ] ); - - label = $.render[ this._tmplAreaId ]( { area: $.geo.area( labelShape, true ) } ); - labelPixel = this._toPixel( $.geo.centroid( labelShape ).coordinates ); - pixels = [ pixels ]; - break; - - case "drawPolygon": - pixels = [ pixels ]; - break; - } - - this._$drawContainer.geographics( mode, pixels ); - - if ( label ) { - this._$measureLabel.html( label ); - - widthOver = this._contentBounds.width - ( this._$measureLabel.outerWidth( true ) + labelPixel[ 0 ] ); - heightOver = this._contentBounds.height - ( this._$measureLabel.outerHeight( true ) + labelPixel[ 1 ] ); - - if ( widthOver < 0 ) { - labelPixel[ 0 ] += widthOver; - } - - if ( heightOver < 0 ) { - labelPixel[ 1 ] += heightOver; - } - - this._$measureLabel.css( { - left: Math.max( labelPixel[ 0 ], 0 ), - top: Math.max( labelPixel[ 1 ], 0 ) - } ).show(); - } - } - }, - - _resetDrawing: function () { - this._drawPixels = []; - this._drawCoords = []; - this._$drawContainer.geographics("clear"); - this._$measureLabel.hide(); - }, - - _refreshShapes: function (geographics, shapes, styles, labels, center, pixelSize) { - var i, mgi, - shape, - shapeBbox, - style, - label, - hasLabel, - labelPixel, - bbox = this._map._getBbox(center, pixelSize); - - for (i = 0; i < shapes.length; i++) { - shape = shapes[i].shape || shapes[i]; - shape = shape.geometry || shape; - shapeBbox = $.data(shape, "geoBbox"); - - if ( shapeBbox && $.geo._bboxDisjoint( bbox, shapeBbox ) ) { - continue; - } - - style = $.isArray(styles) ? styles[i].style : styles; - label = $.isArray(labels) ? labels[i].label : labels; - hasLabel = ( label !== undefined ); - labelPixel = undefined; - - switch (shape.type) { - case "Point": - labelPixel = this._map.toPixel( shape.coordinates, center, pixelSize ); - this._$shapesContainer.geographics("drawPoint", labelPixel, style); - break; - case "LineString": - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.pointAlong( shape, 0.5 ).coordinates, center, pixelSize ); - } - break; - case "Polygon": - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiPoint": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPoint", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiLineString": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiPolygon": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - - case "GeometryCollection": - this._refreshShapes(geographics, shape.geometries, style, label, center, pixelSize); - break; - } - - if ( hasLabel && labelPixel ) { - this._$shapesContainer.geographics( "drawLabel", labelPixel, label ); - } - } - }, - - _findMapSize: function () { - // really, really attempt to find a size for this thing - // even if it's hidden (look at parents) - var size = { width: 0, height: 0 }, - sizeContainer = this._$elem; - - while (sizeContainer.size() && !(size["width"] > 0 && size["height"] > 0)) { - size = { width: sizeContainer.width(), height: sizeContainer.height() }; - if (size["width"] <= 0 || size["height"] <= 0) { - size = { width: parseInt(sizeContainer.css("width"), 10), height: parseInt(sizeContainer.css("height"), 10) }; - } - sizeContainer = sizeContainer.parent(); - } - return size; - }, - - _forcePosition: function (elem) { - var cssPosition = elem.css("position"); - if (cssPosition != "relative" && cssPosition != "absolute" && cssPosition != "fixed") { - elem.css("position", "relative"); - } - }, - - _getPixelSize: function ( zoom ) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme !== null) { - if (zoom === 0) { - return tilingScheme.pixelSizes ? tilingScheme.pixelSizes[0] : tilingScheme.basePixelSize; - } - - zoom = Math.round(zoom); - zoom = Math.max(zoom, 0); - var levels = tilingScheme.pixelSizes ? tilingScheme.pixelSizes.length : tilingScheme.levels; - zoom = Math.min(zoom, levels - 1); - - if ( tilingScheme.pixelSizes ) { - return tilingScheme.pixelSizes[zoom]; - } else { - return tilingScheme.basePixelSize / Math.pow(2, zoom); - } - } else { - var bbox = $.geo.scaleBy( this._getBboxMax(), 1 / Math.pow( this._zoomFactor, zoom ), true ); - return Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - } - }, - - _getZoomCenterAndSize: function ( anchor, zoomDelta, full ) { - var zoomFactor = ( full ? this._fullZoomFactor : this._partialZoomFactor ), - scale = Math.pow( zoomFactor, -zoomDelta ), - pixelSize = this._pixelSizeInteractive * scale, - zoom = this._getZoom(this._centerInteractive, pixelSize); - - // clamp to zoom - if ( full && this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoomDelta < 0 && zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._pixelSizeInteractive; - } else if ( zoomDelta > 0 && zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._pixelSizeInteractive; - } - } - - var ratio = pixelSize / this._pixelSizeInteractive, - anchorMapCoord = this._toMap( anchor, this._centerInteractive, this._pixelSizeInteractive ), - centerDelta = [(this._centerInteractive[0] - anchorMapCoord[0]) * ratio, (this._centerInteractive[1] - anchorMapCoord[1]) * ratio], - scaleCenter = [anchorMapCoord[0] + centerDelta[0], anchorMapCoord[1] + centerDelta[1]]; - - return { pixelSize: pixelSize, center: scaleCenter }; - }, - - _mouseWheelFinish: function ( refresh ) { - this._wheelTimeout = null; - - if (this._wheelLevel !== 0) { - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, this._wheelLevel, this._options[ "tilingScheme" ] !== null ); - - this._wheelLevel = 0; - } else if ( refresh ) { - this._refresh(); - } - }, - - _panFinalize: function () { - if (this._panning) { - this._velocity = [0, 0]; - - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - image = this._options[ "axisLayout" ] === "image", - dxMap = -dx * this._pixelSize, - dyMap = ( image ? -1 : 1 ) * dy * this._pixelSize; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._inOp = false; - this._anchor = this._current; - this._mouseDown = this._toolPan = this._panning = false; - } - }, - - _panMove: function () { - if ( ! this._options[ "pannable" ] ) { - return; - } - - var dx = this._current[0] - this._lastDrag[0], - dy = this._current[1] - this._lastDrag[1], - i = 0, - service, - translateObj; - - if (this._toolPan || dx > 3 || dx < -3 || dy > 3 || dy < -3) { - if (!this._toolPan) { - this._toolPan = true; - this._$eventTarget.css("cursor", this._options["cursors"]["pan"]); - } - - if (this._mouseDown) { - this._velocity = [dx, dy]; - } - - if (dx !== 0 || dy !== 0) { - this._panning = true; - this._lastDrag = this._current; - - this._centerInteractive[ 0 ] -= ( dx * this._pixelSizeInteractive ); - this._centerInteractive[ 1 ] += ( ( this._options[ "axisLayout" ] === "image" ? -1 : 1 ) * dy * this._pixelSizeInteractive ); - this._setInteractiveCenterAndSize( this._centerInteractive, this._pixelSizeInteractive ); - this._interactiveTransform( ); - } - } - }, - - _clearInteractiveTimeout: function() { - if ( this._timeoutInteractive ) { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - return true; - } else { - this._centerInteractive[ 0 ] = this._center[ 0 ]; - this._centerInteractive[ 1 ] = this._center[ 1 ]; - this._pixelSizeInteractive = this._pixelSize; - return false; - } - }, - - _interactiveTransform: function( ) { - if ( this._$shapesContainers ) { - this._$shapesContainers.geographics("clear"); - } - - for ( var i = 0; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo[ "_serviceTypes" ][ service.type ].interactiveTransform( this, service, this._centerInteractive, this._pixelSizeInteractive ); - } - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel( this._drawCoords, this._centerInteractive, this._pixelSizeInteractive ); - this._refreshDrawing(); - } - }, - - _setInteractiveTimeout: function( trigger ) { - var geomap = this; - - function interactiveTimeoutCallback( ) { - if ( geomap._isMultiTouch ) { - geomap._timeoutInteractive = setTimeout( interactiveTimeoutCallback, 128 ); - } else if ( geomap._created && geomap._timeoutInteractive ) { - geomap._setCenterAndSize( geomap._centerInteractive, geomap._pixelSizeInteractive, geomap._triggerInteractive, true ); - geomap._timeoutInteractive = null; - geomap._triggerInteractive = false; - } - } - - this._timeoutInteractive = setTimeout( interactiveTimeoutCallback, 128 ); - this._triggerInteractive |= trigger; - }, - - _refresh: function ( force, _serviceContainer ) { - var service, - geoService, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service, force ); - geoService = service.serviceContainer.data( "geoService" ); - - if ( geoService._createdGraphics ) { - geoService._$shapesContainer.geographics( "clear" ); - if ( geoService._graphicShapes.length > 0 ) { - geoService._refreshShapes( geoService._$shapesContainer, geoService._graphicShapes, geoService._graphicShapes, geoService._graphicShapes ); - } - } - } - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics( "clear" ); - if ( this._graphicShapes.length > 0 ) { - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - } - }, - - _setInteractiveCenterAndSize: function ( center, pixelSize ) { - // set the temporary (interactive) center & size - // also, update the public-facing options - // this does not take zoomMin or zoomMax into account - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - this._pixelSizeInteractive = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox( center, pixelSize ) ); - this._options["center"] = $.geo.proj.toGeodetic( center ); - } else { - this._options["bbox"] = this._getBbox( center, pixelSize ); - this._options["center"][ 0 ] = center[ 0 ]; - this._options["center"][ 1 ] = center[ 1 ]; - } - - this._options["pixelSize"] = pixelSize; - this._options["zoom"] = this._getZoom( center, pixelSize ); - }, - - _setCenterAndSize: function (center, pixelSize, trigger, refresh) { - if ( ! $.isArray( center ) || center.length != 2 || typeof center[ 0 ] !== "number" || typeof center[ 1 ] !== "number" ) { - return; - } - - // the final call during any extent change - // only called by timeoutInteractive & resize - // clamp to zoom - var zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._center[ 0 ] = center[ 0 ]; - this._center[ 1 ] = center[ 1 ]; - this._options["pixelSize"] = this._pixelSize = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox() ); - this._options["center"] = $.geo.proj.toGeodetic( this._center ); - } else { - this._options["bbox"] = this._getBbox(); - this._options["center"] = $.merge( [ ], center ); - } - - this._options["zoom"] = zoom; - - if (trigger) { - this._trigger("bboxchange", window.event, { bbox: $.merge( [ ], this._options["bbox"] ) }); - } - - if (refresh) { - this._refresh(); - this._refreshDrawing(); - } - }, - - _requestQueued: function ( ) { - if ( this._loadCount === 0 ) { - this._trigger( "loadstart", window.event ); - } - this._loadCount++; - }, - - _requestComplete: function ( ) { - this._loadCount--; - if ( this._loadCount <= 0 ) { - this._loadCount = 0; - this._trigger( "loadend", window.event ); - } - }, - - _toMap: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - xRatio = $.geo.width(bbox, true) / width, - yRatio = $.geo.height(bbox, true) / height, - yOffset, - image = this._options[ "axisLayout" ] === "image", - result = [], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - yOffset = (p[ i ][ j ][ k ][1] * yRatio); - result[ i ][ j ][ k ] = [ - bbox[ 0 ] + ( p[ i ][ j ][ k ][ 0 ] * xRatio ), - image ? bbox[ 1 ] + yOffset : bbox[ 3 ] - yOffset - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _toPixel: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - bboxWidth = $.geo.width(bbox, true), - bboxHeight = $.geo.height(bbox, true), - image = this._options[ "axisLayout" ] === "image", - xRatio = width / bboxWidth, - yRatio = height / bboxHeight, - result = [ ], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = [ - Math.round( ( p[ i ][ j ][ k ][ 0 ] - bbox[ 0 ] ) * xRatio ), - Math.round( ( image ? p[ i ][ j ][ k ][ 1 ] - bbox[ 1 ] : bbox[ 3 ] - p[ i ][ j ][ k ][ 1 ] ) * yRatio ) - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _document_keydown: function (e) { - var len = this._drawCoords.length; - if (len > 0 && e.which == 27) { - if (len <= 2) { - this._resetDrawing(); - this._inOp = false; - } else { - this._drawCoords[len - 2] = $.merge( [], this._drawCoords[ len - 1 ] ); - this._drawPixels[len - 2] = $.merge( [], this._drawPixels[ len - 1 ] ); - - this._drawCoords.length--; - this._drawPixels.length--; - - this._refreshDrawing(); - } - } - }, - - _eventTarget_dblclick_zoom: function(e) { - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - this._trigger("dblclick", e, { type: "Point", coordinates: this._toMap(this._current, this._centerInteractive, this._pixelSizeInteractive ) }); - - if (!e.isDefaultPrevented()) { - var centerAndSize = this._getZoomCenterAndSize(this._current, 1, true ); - - this._setInteractiveCenterAndSize( centerAndSize.center, centerAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - }, - - _eventTarget_dblclick: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - var offset = $(e.currentTarget).offset(); - - switch (this._options["mode"]) { - case "drawLineString": - case "measureLength": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - this._drawCoords.length--; - this._trigger( "shape", e, { - type: "LineString", - coordinates: this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords - } ); - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "drawPolygon": - case "measureArea": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - var endIndex = this._drawCoords.length - 1; - if (endIndex > 2) { - this._drawCoords[endIndex] = $.merge( [], this._drawCoords[0] ); - this._trigger( "shape", e, { - type: "Polygon", - coordinates: [ this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords ] - } ); - } - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - default: - this._eventTarget_dblclick_zoom(e); - break; - } - - this._inOp = false; - }, - - _eventTarget_touchstart: function (e) { - var mode = this._options[ "mode" ], - shift = this._options[ "shift" ]; - - if ( mode === "static" ) { - return; - } - - if ( !this._supportTouch && e.which != 1 ) { - return; - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var offset = $(e.currentTarget).offset(), - touches = e.originalEvent.changedTouches; - - if ( this._supportTouch ) { - this._multiTouchAnchor = $.merge( [ ], touches ); - - this._isMultiTouch = this._multiTouchAnchor.length > 1; - - if ( this._isMultiTouch ) { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - touches[1].pageX - offset.left, - touches[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ touches[0].pageX - offset.left, touches[0].pageY - offset.top ]; - } - } else { - this._current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - var downDate = $.now(); - if (downDate - this._downDate < 750) { - if (this._isTap) { - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance > 8) { - this._isTap = false; - } else { - this._current = $.merge( [ ], this._anchor ); - } - } - - if (this._isDbltap) { - this._isDbltap = false; - } else { - this._isDbltap = this._isTap; - } - } else { - this._isDbltap = false; - } - this._isTap = true; - this._downDate = downDate; - } - - this._mouseDown = true; - this._anchor = $.merge( [ ], this._current ); - - if (!this._inOp && e.shiftKey && shift !== "off") { - this._shiftDown = true; - this._$eventTarget.css( "cursor", this._options[ "cursors" ][ shift === "default" ? "zoom" : shift ] ); - } else if ( !this._isMultiTouch && ( this._options[ "pannable" ] || mode === "dragBox" || mode === "dragCircle" ) ) { - this._inOp = true; - - if ( mode !== "zoom" && mode !== "dragBox" && mode !== "dragCircle" ) { - this._lastDrag = this._current; - - if (e.currentTarget.setCapture) { - e.currentTarget.setCapture(); - } - } - } - - e.preventDefault(); - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - }, - - _dragTarget_touchmove: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - var doInteractiveTimeout = false; - if ( this._mouseDown ) { - doInteractiveTimeout = this._clearInteractiveTimeout( ); - } - - var offset = this._$eventTarget.offset(), - drawCoordsLen = this._drawCoords.length, - touches = e.originalEvent.changedTouches, - current, - service, - i = 0; - - if ( this._supportTouch ) { - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 && touches[ 0 ].identifier !== this._multiTouchAnchor[ 0 ].identifier ) { - // switch to multitouch - this._mouseDown = false; - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( touches[ 0 ] ); - - - - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._mouseDown = true; - this._anchor = this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - if ( this._isMultiTouch ) { - - for ( ; i < touches.length; i++ ) { - if ( touches[ i ].identifier === this._multiTouchAnchor[ 0 ].identifier ) { - this._multiTouchCurrentBbox[ 0 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = touches[ i ].pageY - offset.top; - } else if ( touches[ i ].identifier === this._multiTouchAnchor[ 1 ].identifier ) { - this._multiTouchCurrentBbox[ 2 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = touches[ i ].pageY - offset.top; - } - } - - var anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ), - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - var wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - var delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - var pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (current[0] === this._lastMove[0] && current[1] === this._lastMove[1]) { - if ( this._inOp ) { - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - } - - if ( _ieVersion == 7 ) { - this._isDbltap = this._isTap = false; - } - - if (this._mouseDown) { - this._current = current; - this._moveDate = $.now(); - } - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - var shift = this._options[ "shift" ], - mode = this._shiftDown ? ( shift === "default" ? "zoom" : shift ) : this._options["mode"], - dx, dy, circleSize; - - switch (mode) { - case "zoom": - case "dragBox": - if ( this._mouseDown ) { - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawBbox", [ - this._anchor[ 0 ], - this._anchor[ 1 ], - current[ 0 ], - current[ 1 ] - ] ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "dragCircle": - if ( this._mouseDown ) { - dx = current[ 0 ] - this._anchor[ 0 ]; - dy = current[ 1 ] - this._anchor[ 1 ]; - circleSize = Math.sqrt( ( dx * dx) + ( dy * dy ) ) * 2; - //circleSize = Math.max( Math.abs( current[ 0 ] - this._anchor[ 0 ] ), Math.abs( current[ 1 ] - this._anchor[ 1 ] ) ) * 2; - - // not part of _refreshDrawing - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawArc", this._anchor, 0, 360, { - width: circleSize, - height: circleSize - } ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - if (drawCoordsLen > 0) { - this._drawCoords[drawCoordsLen - 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[drawCoordsLen - 1] = current; - - this._refreshDrawing(); - } - - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - default: - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - } - - this._lastMove = current; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchstop: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if ( !this._mouseDown ) { - if ( _ieVersion == 7 ) { - // ie7 doesn't appear to trigger dblclick on this._$eventTarget, - // we fake regular click here to cause soft dblclick - this._eventTarget_touchstart(e); - } else { - // Chrome & Firefox trigger a rogue mouseup event when doing a dblclick maximize in Windows(/Linux?) - // ignore it - return false; - } - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var mouseWasDown = this._mouseDown, - wasToolPan = this._toolPan, - offset = this._$eventTarget.offset(), - shift = this._options[ "shift" ], - mode = this._shiftDown ? ( shift === "default" ? "zoom" : shift ) : this._options["mode"], - current, i, clickDate, - dx, dy, - coordBuffer, - triggerShape; - - - if (this._supportTouch) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - this._multiTouchAnchor = []; - this._inOp = false; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - if (this._isTap) { - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - if (Math.sqrt((dx * dx) + (dy * dy)) <= 8) { - current = $.merge( [ ], this._anchor ); - } - } - } - - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._shiftDown = this._mouseDown = this._toolPan = false; - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isMultiTouch = false; - - this._wheelLevel = 0; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return; - } - - if (document.releaseCapture) { - document.releaseCapture(); - } - - if (mouseWasDown) { - clickDate = $.now(); - this._current = current; - - switch ( mode ) { - case "zoom": - case "dragBox": - if ( dx !== 0 || dy !== 0 ) { - var minSize = this._pixelSize * 6, - bboxCoords = this._toMap( [ [ - Math.min( this._anchor[ 0 ], current[ 0 ] ), - Math.max( this._anchor[ 1 ], current[ 1 ] ) - ], [ - Math.max( this._anchor[ 0 ], current[ 0 ] ), - Math.min( this._anchor[ 1 ], current[ 1 ] ) - ] - ] ), - bbox = [ - bboxCoords[0][0], - bboxCoords[0][1], - bboxCoords[1][0], - bboxCoords[1][1] - ]; - - if ( mode === "zoom" ) { - if ( ( bbox[2] - bbox[0] ) < minSize && ( bbox[3] - bbox[1] ) < minSize ) { - bbox = $.geo.scaleBy( this._getBbox( $.geo.center( bbox, true ) ), 0.5, true ); - } - - this._setBbox(bbox, true, true); - doInteractiveTimeout = true; - } else { - triggerShape = $.geo.polygonize( bbox, true ); - triggerShape.bbox = bbox; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - this._trigger( "shape", e, triggerShape ); - } - } else { - if ( mode === "dragBox" ) { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - } - - this._resetDrawing(); - break; - - case "dragCircle": - if ( dx !== 0 || dy !== 0 ) { - var image = this._options[ "axisLayout" ] === "image", - d = Math.sqrt( ( dx * dx) + ( dy * dy ) ), - n = 180, - a; - - this._drawPixels.length = n + 1; - - for ( i = 0; i < n; i++ ) { - a = ( i * 360 / n ) * ( Math.PI / 180 ); - this._drawPixels[ i ] = [ - this._anchor[ 0 ] + Math.cos( a ) * d, - this._anchor[ 1 ] + Math.sin( a ) * d - ]; - } - - this._drawPixels[ n ] = [ - this._drawPixels[ 0 ][ 0 ], - this._drawPixels[ 0 ][ 1 ] - ]; - - // using coordBuffer for bbox coords - coordBuffer = this._toMap( [ - [ this._anchor[ 0 ] - d, this._anchor[ 1 ] + ( image ? -d : d ) ], - [ this._anchor[ 0 ] + d, this._anchor[ 1 ] + ( image ? d : -d ) ] - ] ); - - triggerShape = { - type: "Polygon", - coordinates: [ this._toMap( this._drawPixels ) ], - bbox: [ coordBuffer[ 0 ][ 0 ], coordBuffer[ 0 ][ 1 ], coordBuffer[ 1 ][ 0 ], coordBuffer[ 1 ][ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - - this._resetDrawing(); - } else { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - break; - - case "drawPoint": - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - var geomap = this; - this._drawTimeout = setTimeout(function () { - if (geomap._drawTimeout) { - geomap._trigger("shape", e, { type: "Point", coordinates: geomap.toMap(current) }); - geomap._inOp = false; - geomap._drawTimeout = null; - } - }, 250); - } - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (wasToolPan) { - this._panFinalize(); - } else { - i = (this._drawCoords.length === 0 ? 0 : this._drawCoords.length - 1); - - this._drawCoords[i] = this._toMap(current); - this._drawPixels[i] = current; - - if (i < 2 || !(this._drawCoords[i][0] == this._drawCoords[i-1][0] && - this._drawCoords[i][1] == this._drawCoords[i-1][1])) { - this._drawCoords[i + 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[i + 1] = current; - } - - this._refreshDrawing(); - } - break; - - default: - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - this._inOp = false; - } - } - break; - } - - this._clickDate = clickDate; - - if (this._softDblClick && this._isDbltap) { - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - this._$eventTarget.trigger("dblclick", e); - return false; - } - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _eventTarget_mousewheel: function (e, delta) { - if ( this._options[ "mode" ] === "static" || this._options[ "scroll" ] === "off" ) { - return; - } - - e.preventDefault(); - - if ( this._mouseDown ) { - return false; - } - - if (delta !== 0) { - this._clearInteractiveTimeout( ); - - if ( delta > 0 ) { - delta = Math.ceil( delta ); - } else { - delta = Math.floor( delta ); - } - - var offset = $(e.currentTarget).offset(); - this._anchor = [e.pageX - offset.left, e.pageY - offset.top]; - - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, this._options[ "tilingScheme" ] !== null ), - service, - i = 0; - - this._setInteractiveCenterAndSize( wheelCenterAndSize.center, wheelCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - this._setInteractiveTimeout( true ); - } - - return false; - } - } - ); -}(jQuery)); - - -(function ($, undefined) { - $.geo._serviceTypes.tiled = (function () { - return { - create: function (map, serviceContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0, - reloadTiles: false - }; - - var scHtml = '
                                '; - - serviceContainer.append(scHtml); - - serviceState.serviceContainer = serviceContainer.children( ":last" ); - - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - //console.log( "tiled.interactiveTransform( " + center.join( ", " ) + ", " + pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ), - tilingScheme = map.options[ "tilingScheme" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( i ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data("pixelSize"), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapCoord = $scaleContainer.data("scaleOrigin"), - newPixelPoint = map._toPixel(oldMapCoord, center, pixelSize); - - $scaleContainer.css( { - left: Math.round(newPixelPoint[0]) + "px", - top: Math.round(newPixelPoint[1]) + "px", - width: tilingScheme.tileWidth * scaleRatio, - height: tilingScheme.tileHeight * scaleRatio - } ); - - /* - if ( $("body")[0].filters !== undefined ) { - $scaleContainer.children().each( function ( i ) { - $( this ).css( "filter", "progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11=" + scaleRatio + ",M22=" + scaleRatio + ",sizingmethod='auto expand')" ); - } ); - } - */ - } - }); - } - }, - - refresh: function (map, service, force) { - //console.log( "tiled.refresh( " + map._center.join( ", " ) + ", " + map._pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ); - - this._cancelUnloaded(map, service); - - if ( serviceState && force ) { - // if hidden atm, we want to make sure we reload this service after it becomes visible - serviceState.reloadTiles = true; - } - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - $serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - image = map.options[ "axisLayout" ] === "image", - ySign = image ? +1 : -1, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - - tileX = Math.floor((bbox[0] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.max( Math.floor( ( image ? bbox[1] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 3 ] ) / (pixelSize * tileHeight) ), 0 ), - tileX2 = Math.ceil((bbox[2] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil( ( image ? bbox[3] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 1 ] ) / (pixelSize * tileHeight) ), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] + ySign * bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMinOrMaxY = tilingScheme.origin[1] + ySign * (fullYAtScale * tileHeight) * pixelSize, - - serviceLeft = Math.round((fullXMinX - bbox[0]) / pixelSize), - serviceTop = Math.round( ( image ? fullYMinOrMaxY - bbox[1] : bbox[3] - fullYMinOrMaxY ) / pixelSize), - - scaleContainers = $serviceContainer.children().show(), - scaleContainer = scaleContainers.filter("[data-pixel-size='" + pixelSize + "']").appendTo($serviceContainer), - - opacity = service.style.opacity, - - x, y, - - loadImageDeferredDone = function( url ) { - // when a Deferred call is done, add the image to the map - // a reference to the correct img element is on the Deferred object itself - serviceObj._loadImage( $.data( this, "img" ), url, pixelSize, map, serviceState, opacity ); - }, - - loadImageDeferredFail = function( ) { - $.data( this, "img" ).remove( ); - serviceState.loadCount--; - map._requestComplete(); - }; - - if (serviceState.reloadTiles) { - scaleContainers.find("img").attr("data-dirty", "true"); - } - - if (!scaleContainer.size()) { - $serviceContainer.append("
                                "); - scaleContainer = $serviceContainer.children(":last").data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - } else { - scaleContainer.css({ - left: (serviceLeft % tileWidth) + "px", - top: (serviceTop % tileHeight) + "px" - }).data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - - scaleContainer.children().each(function (i) { - var - $img = $(this), - tile = $img.attr("data-tile").split(","); - - $img.css({ - left: Math.round(((parseInt(tile[0], 10) - fullXAtScale) * 100) + (serviceLeft - (serviceLeft % tileWidth)) / tileWidth * 100) + "%", - top: Math.round(((parseInt(tile[1], 10) - fullYAtScale) * 100) + (serviceTop - (serviceTop % tileHeight)) / tileHeight * 100) + "%" - }); - - if (opacity < 1) { - $img.fadeTo(0, opacity); - } - }); - } - - for (x = tileX; x < tileX2; x++) { - for (y = tileY; y < tileY2; y++) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ($img.size() === 0 || serviceState.reloadTiles) { - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] + ySign * (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] + ySign * ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - urlProp = ( service.hasOwnProperty( "src" ) ? "src" : "getUrl" ), - urlArgs = { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl; - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - $.templates( "geoSrc", service[ urlProp ] ); - imageUrl = $.render[ "geoSrc" ]( urlArgs ); - } - - serviceState.loadCount++; - map._requestQueued(); - - if (serviceState.reloadTiles && $img.size() > 0) { - $img.attr("src", imageUrl); - } else { - var imgMarkup = ""; - - scaleContainer.append(imgMarkup); - $img = scaleContainer.children(":last"); - } - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl ) { - // assume Deferred - $.data( imageUrl, "img", $img ); - imageUrl.done( loadImageDeferredDone ).fail( loadImageDeferredFail ); - } else { - $img.remove( ); - } - } - } - } - - scaleContainers.find("[data-dirty]").remove(); - serviceState.reloadTiles = false; - } - }, - - resize: function (map, service) { - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.css( "display", service.style.visibility === "visible" ? "block" : "none" ); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery)); - -(function ($, undefined) { - $.geo._serviceTypes.shingled = (function () { - return { - create: function (map, serviceContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0 - }; - - var scHtml = '
                                '; - - serviceContainer.append(scHtml); - - serviceState.serviceContainer = serviceContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - var serviceState = $.data( service, "geoServiceState" ), - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds[ "width" ], - mapHeight = contentBounds[ "height" ], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - bbox = [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( i ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data( "pixelSize" ), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin, center, pixelSize ); - - $scaleContainer.css( { - left: Math.round( newPixelPoint[ 0 ] ), - top: Math.round( newPixelPoint[ 1 ] ), - width: mapWidth * scaleRatio, - height: mapHeight * scaleRatio - } ); - - - // #newpanzoom - /* - .children("img").each(function (i) { - var $img = $(this), - imgCenter = $img.data("center"), - x = (Math.round((imgCenter[0] - center[0]) / scalePixelSize) - halfWidth) * scaleRatio, - y = (Math.round((center[1] - imgCenter[1]) / scalePixelSize) - halfHeight) * scaleRatio; - - $img.css({ left: x + "px", top: y + "px" }); - }); - */ - } - }); - } - }, - - refresh: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - this._cancelUnloaded(map, service); - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainer = serviceContainer.children('[data-pixel-size="' + pixelSize + '"]'), - - opacity = service.style.opacity, - - $img; - - if (opacity < 1) { - serviceContainer.find("img").attr("data-keep-alive", "0"); - } - - if ( !scaleContainer.size() ) { - serviceContainer.append('
                                '); - scaleContainer = serviceContainer.children(":last"); - } - - var urlProp = ( service.hasOwnProperty("src") ? "src" : "getUrl" ), - urlArgs = { - bbox: bbox, - width: mapWidth, - height: mapHeight, - zoom: map._getZoom(), - tile: null, - index: 0 - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl, - imagePos = scaleContainer.position( ); - - imagePos.left = - ( imagePos.left ); - imagePos.top = - ( imagePos.top ); - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - $.templates( "geoSrc", service[ urlProp ] ); - imageUrl = $.render[ "geoSrc" ]( urlArgs ); - } - - serviceState.loadCount++; - map._requestQueued(); - - scaleContainer.append(''); - $img = scaleContainer.children(":last").data("center", map._center); - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, map, serviceState, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - map._requestComplete(); - } ); - } - - } - }, - - resize: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState && service && service.style.visibility === "visible" ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainers = serviceContainer.children(); - - scaleContainers.attr("data-pixel-size", "0"); - - scaleContainers.each( function ( i ) { - var $scaleContainer = $(this), - position = $scaleContainer.position( ); - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin ); - - $scaleContainer.css( { - left: position.left + ( mapWidth - $scaleContainer.width( ) ) / 2, - top: position.top + ( mapHeight - $scaleContainer.height( ) ) / 2 - } ); - - } ); - - - /* - scaleContainer.css({ - left: halfWidth + 'px', - top: halfHeight + 'px' - }); - */ - } - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.css("display", service.style.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - // #newpanzoom - serviceContainer.children(':not([data-pixel-size="' + pixelSize + '"])').remove(); - - serviceContainer.find( "img[data-keep-alive]" ).remove( ); - - serviceState.loadCount = 0; - } - }).error(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery)); diff --git a/dist/jquery.geo-1.0b1.1.min.js b/dist/jquery.geo-1.0b1.1.min.js deleted file mode 100644 index 8f92661..0000000 --- a/dist/jquery.geo-1.0b1.1.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery Geo - v1.0b1.1 - 2012-08-24 - * http://jquerygeo.com - * Copyright (c) 2012 Ryan Westphal/Applied Geographics, Inc.; Licensed MIT, GPL */ -document.createElement("canvas").getContext||function(){function j(){return this.context_||(this.context_=new I(this))}function l(a,b,c){var d=k.call(arguments,2);return function(){return a.apply(b,d.concat(k.call(arguments)))}}function m(a){return String(a).replace(/&/g,"&").replace(/"/g,""")}function n(a,b,c){a.namespaces[b]||a.namespaces.add(b,c,"#default#VML")}function o(a){n(a,"g_vml_","urn:schemas-microsoft-com:vml"),n(a,"g_o_","urn:schemas-microsoft-com:office:office");if(!a.styleSheets.ex_canvas_){var b=a.createStyleSheet();b.owningElement.id="ex_canvas_",b.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function q(a){var b=a.srcElement;switch(a.propertyName){case"width":b.getContext().clearRect(),b.style.width=b.attributes.width.nodeValue+"px",b.firstChild.style.width=b.clientWidth+"px";break;case"height":b.getContext().clearRect(),b.style.height=b.attributes.height.nodeValue+"px",b.firstChild.style.height=b.clientHeight+"px"}}function r(a){var b=a.srcElement;b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px",b.firstChild.style.height=b.clientHeight+"px")}function v(){return[[1,0,0],[0,1,0],[0,0,1]]}function w(a,b){var c=v();for(var d=0;d<3;d++)for(var e=0;e<3;e++){var f=0;for(var g=0;g<3;g++)f+=a[d][g]*b[g][e];c[d][e]=f}return c}function x(a,b){b.fillStyle=a.fillStyle,b.lineCap=a.lineCap,b.lineJoin=a.lineJoin,b.lineWidth=a.lineWidth,b.miterLimit=a.miterLimit,b.shadowBlur=a.shadowBlur,b.shadowColor=a.shadowColor,b.shadowOffsetX=a.shadowOffsetX,b.shadowOffsetY=a.shadowOffsetY,b.strokeStyle=a.strokeStyle,b.globalAlpha=a.globalAlpha,b.font=a.font,b.textAlign=a.textAlign,b.textBaseline=a.textBaseline,b.arcScaleX_=a.arcScaleX_,b.arcScaleY_=a.arcScaleY_,b.lineScale_=a.lineScale_}function y(a){var b=a.indexOf("(",3),c=a.indexOf(")",b+1),d=a.substring(b+1,c).split(",");if(d.length!=4||a.charAt(3)!="a")d[3]=1;return d}function z(a){return parseFloat(a)/100}function A(a,b,c){return Math.min(c,Math.max(b,a))}function B(a){var b,c,d,e,f,g;e=parseFloat(a[0])/360%360,e<0&&e++,f=A(z(a[1]),0,1),g=A(z(a[2]),0,1);if(f==0)b=c=d=g;else{var h=g<.5?g*(1+f):g+f-g*f,i=2*g-h;b=C(i,h,e+1/3),c=C(i,h,e),d=C(i,h,e-1/3)}return"#"+s[Math.floor(b*255)]+s[Math.floor(c*255)]+s[Math.floor(d*255)]}function C(a,b,c){return c<0&&c++,c>1&&c--,6*c<1?a+(b-a)*6*c:2*c<1?b:3*c<2?a+(b-a)*(2/3-c)*6:a}function E(a){if(a in D)return D[a];var b,c=1;a=String(a);if(a.charAt(0)=="#")b=a;else if(/^rgb/.test(a)){var d=y(a),b="#",e;for(var f=0;f<3;f++)d[f].indexOf("%")!=-1?e=Math.floor(z(d[f])*255):e=+d[f],b+=s[A(e,0,255)];c=+d[3]}else if(/^hsl/.test(a)){var d=y(a);b=B(d),c=d[3]}else b=a;return D[a]={color:b,alpha:c}}function H(a){return G[a]||"square"}function I(a){this.m_=v(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.strokeStyle="#000",this.fillStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=g*1,this.globalAlpha=1,this.canvas=a;var b="width:"+a.clientWidth+"px;height:"+a.clientHeight+"px;overflow:hidden;position:absolute",c=a.ownerDocument.createElement("div");c.style.cssText=b,a.appendChild(c);var d=c.cloneNode(!1);d.style.backgroundColor="red",d.style.filter="alpha(opacity=0)",a.appendChild(d),this.element_=c,this.arcScaleX_=1,this.arcScaleY_=1,this.lineScale_=1}function K(a,b,c,d){a.currentPath_.push({type:"bezierCurveTo",cp1x:b.x,cp1y:b.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y}),a.currentX_=d.x,a.currentY_=d.y}function L(a,b){var c=E(a.strokeStyle),d=c.color,e=c.alpha*a.globalAlpha,f=a.lineScale_*a.lineWidth;f<1&&(e*=f),b.push("')}function M(a,b,c,d){var e=a.fillStyle,f=a.arcScaleX_,g=a.arcScaleY_,h=d.x-c.x,i=d.y-c.y,j=E(a.fillStyle),k=j.color,l=j.alpha*a.globalAlpha;b.push('')}function N(a,b,c){var d=a.m_;return{x:g*(b*d[0][0]+c*d[1][0]+d[2][0])-h,y:g*(b*d[0][1]+c*d[1][1]+d[2][1])-h}}function O(a){return isFinite(a[0][0])&&isFinite(a[0][1])&&isFinite(a[1][0])&&isFinite(a[1][1])&&isFinite(a[2][0])&&isFinite(a[2][1])}function P(a,b,c){if(!O(b))return;a.m_=b;if(c){var d=b[0][0]*b[1][1]-b[0][1]*b[1][0];a.lineScale_=f(e(d))}}function Q(a){throw new R(a)}function R(a){this.code=this[a],this.message=a+": DOM Exception "+this.code}var a=Math,b=a.round,c=a.sin,d=a.cos,e=a.abs,f=a.sqrt,g=10,h=g/2,i=+navigator.userAgent.match(/MSIE ([\d.]+)?/)[1],k=Array.prototype.slice;o(document);var p={init:function(a){var b=a||document;b.createElement("canvas"),b.attachEvent("onreadystatechange",l(this.init_,this,b))},init_:function(a){var b=a.getElementsByTagName("canvas");for(var c=0;cj.x)j.x=l.x;if(i.y==null||l.yj.y)j.y=l.y}}c.push(' ">'),a?M(this,c,i,j):L(this,c),c.push(""),this.element_.insertAdjacentHTML("beforeEnd",c.join(""))},J.fill=function(){this.stroke(!0)},J.closePath=function(){this.currentPath_.push({type:"close"})},J.save=function(){var a={};x(this,a),this.aStack_.push(a),this.mStack_.push(this.m_),this.m_=w(v(),this.m_)},J.restore=function(){this.aStack_.length&&(x(this.aStack_.pop(),this),this.m_=this.mStack_.pop())},J.translate=function(a,b){var c=[[1,0,0],[0,1,0],[a,b,1]];P(this,w(c,this.m_),!1)},J.scale=function(a,b){this.arcScaleX_*=a,this.arcScaleY_*=b;var c=[[a,0,0],[0,b,0],[0,0,1]];P(this,w(c,this.m_),!0)};var S=R.prototype=new Error;S.INDEX_SIZE_ERR=1,S.DOMSTRING_SIZE_ERR=2,S.HIERARCHY_REQUEST_ERR=3,S.WRONG_DOCUMENT_ERR=4,S.INVALID_CHARACTER_ERR=5,S.NO_DATA_ALLOWED_ERR=6,S.NO_MODIFICATION_ALLOWED_ERR=7,S.NOT_FOUND_ERR=8,S.NOT_SUPPORTED_ERR=9,S.INUSE_ATTRIBUTE_ERR=10,S.INVALID_STATE_ERR=11,S.SYNTAX_ERR=12,S.INVALID_MODIFICATION_ERR=13,S.NAMESPACE_ERR=14,S.INVALID_ACCESS_ERR=15,S.VALIDATION_ERR=16,S.TYPE_MISMATCH_ERR=17,G_vmlCanvasManager=p,CanvasRenderingContext2D=I,DOMException=R}(),this.jsviews||this.jQuery&&jQuery.views||function(a,b){function A(a,b){var c="\\"+a.charAt(0),d="\\"+a.charAt(1),g="\\"+b.charAt(0),h="\\"+b.charAt(1);return z.rTag=e=d+"(?:(?:(\\w+(?=[\\/\\s"+g+"]))|(?:(\\w+)?(:)|(>)|(\\*)))"+"\\s*((?:[^"+g+"]|"+g+"(?!"+h+"))*?)"+"(\\/)?|(?:\\/(\\w+)))"+g,e=new RegExp(c+e+h,"g"),f=new RegExp("<.*>|"+a+".*"+b),this}function B(a){var c=this,d=c.tmpl.helpers||{};return a=(c.ctx[a]!==b?c.ctx:d[a]!==b?d:I[a]!==b?I:{})[a],typeof a!="function"?a:function(){return a.apply(c,arguments)}}function C(a,b,c){var d=b.tmpl.converters;return a=d&&d[a]||J[a],a?a.call(b,c):c}function D(a,c,d,e,f){f.props=f.props||{};var h,i=f.props.tmpl,k=c.tmpl.tags,l=c.tmpl.templates,m=arguments,n=k&&k[a]||H[a];return n?(e=e&&c.tmpl.tmpls[e-1],i=i||e||b,f.tmpl=""+i===i?l&&l[i]||G[i]||G(i):i,f.isTag=j,f.converter=d,f.view=c,f.renderContent=K,c.ctx&&g(f.ctx,c.ctx),h=n.apply(f,m.length>5?x.call(m,5):[]),h||(h==b?"":h.toString())):""}function E(a,c,e,f,g,h){var i=e.views,j={tmpl:g,path:c,parent:e,data:f,ctx:a,views:d.isArray(f)?[]:{},hlp:B};return d.isArray(i)?i.splice(j.index=h!==b?h:i.length,0,j):i[j.index="_"+r++]=j,j}function F(a,c,d,e,f){var g,i;if(d&&typeof d=="object"&&!d.nodeType){for(g in d)c(g,d[g]);return a}if(!d||e===b)f&&(e=f(b,e||d));else if(""+d===d)if(e===null)delete c[d];else if(e=f?f(d,e):e)c[d]=e;return(i=h.onStoreItem)&&i(c,d,e,f),e}function G(a,b){return F(this,G,a,b,O)}function H(a,b){return F(this,H,a,b)}function I(a,b){return F(this,I,a,b)}function J(a,b){return F(this,J,a,b)}function K(a,c,e,f,k){var l,m,n,o,p,q,r,s,t,u,v={},w=k===j,x=this,y="";x.isTag?(t=x.tmpl,c=c||x.ctx,e=e||x.view,f=f||x.path,k=k||x.index,v=x.props):t=x.jquery&&x[0]||x,e=e||z.topView,s=e.ctx,u=t.layout,a===e&&(a=e.data,u=j),c=c&&c===s?s:s?(s=g({},s),c)?g(s,c):s:c||{},v.link===i&&(c.link=i),t.fn||(t=G[t]||G(t)),p=c.link&&h.onRenderItem,q=c.link&&h.onRenderItems;if(t){if(d.isArray(a)&&!u){o=w?e:k!==b&&e||E(c,f,e,a,t,k);for(l=0,m=a.length;l-1,i+=(t===":"?u==="html"?(l=j,"e("+w):u?(r=j,'c("'+u+'",view,'+w):(m=j,"((v="+w+')!=u?v:""'):(k=j,'t("'+t+'",view,"'+(u||"")+'",'+(F?B.length:'""')+","+x+(w?",":"")+w))+")+");return i=new Function("data, view, j, b, u",v+(m?"v,":"")+(k?"t=j.tag,":"")+(r?"c=j.convert,":"")+(l?"e=j.converters.html,":"")+"ret; try{\n\n"+(A.debug?"debugger;":"")+(z?"ret=":"return ")+i.slice(0,-1)+";\n\n"+(z?"return ret;":"")+"}catch(e){return j.err(e);}"),b&&(b.fn=i,b.useVw=r||s||k),i}function N(a,b){function h(a,h,k,m,n,o,p,q,r,s,t,u,v,w,x,y){function z(a,c,d,e,f,g,h){if(c){var i=(d?'view.hlp("'+d+'")':e?"view":"data")+(h?(f?"."+f:d?"":e?"":"."+c)+(g||""):(h=d?"":e?f||"":c,""));return b&&r!=="("&&(i="b("+i+',"'+h+'")'),i+(h?"."+h:"")}return a}n=n||"",k=k||h||t,m=m||q,r=r||x||"",n=n||"";if(o)L();else return g?(g=!u,g?a:'"'):f?(f=!v,f?a:'"'):(k?(e++,k):"")+(y?e?"":c?(c=i,"\b"):",":p?(e&&L(),c=j,"\b"+m+":"):m?m.replace(l,z)+(r?(d[++e]=j,r):n):n?a:w?(d[e--]=i,w)+(r?(d[++e]=j,r):""):s?(d[e]||L(),","):h?"":(g=u,f=v,'"'))}var c,d={},e=0,f=i,g=i;return a=(a+" ").replace(m,h),a}function O(a,c,d,e){function n(b){if(""+b===b||b.nodeType>0)return i=b.nodeType>0?b:!f.test(b)&&k&&k(b)[0],i&&i.type&&(b=G[i.getAttribute(u)],b||(a=a||"_"+s++,i.setAttribute(u,a),b=O(a,i.innerHTML,d,e),G[a]=b)),b}var h,i,j,l,m;h=n(c),e=e||(c.markup?c:{}),e.name=a,l=e.templates,!h&&c.markup&&(h=n(c.markup))&&h.fn&&(h.debug!==c.debug||h.allowCode!==c.allowCode)&&(h=h.markup);if(h!==b){a&&!d&&(y[a]=function(){return c.render.apply(c,arguments)}),h.fn||c.fn?h.fn&&(a&&a!==h.name?c=g(g({},h),e):c=h):(c=P(h,e,d,0),M(h,c));for(j in l)m=l[j],m.name!==j&&(l[j]=O(j,m,c));return c}}function P(a,b,c,d){function e(a){c[a]&&(f[a]=g(g({},c[a]),b[a]))}b=b||{};var f={markup:a,tmpls:[],links:[],render:K};return c&&(c.templates&&(f.templates=g(g({},c.templates),b.templates)),f.parent=c,f.name=c.name+"["+d+"]",f.index=d),g(f,b),c&&(e("templates"),e("tags"),e("helpers"),e("converters")),f}function Q(a){return t[a]||(t[a]="&#"+a.charCodeAt(0)+";")}var c="v1.0pre",d,e,f,g,h={},i=!1,j=!0,k=a.jQuery,l=/^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g,m=/(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,n=/\r?\n/g,o=/\\(['"])/g,p=/\\?(['"])/g,q=/\x08(~)?([^\x08]+)\x08/g,r=0,s=0,t={"&":"&","<":"<",">":">"},u="data-jsv-tmpl",v="var j=j||"+(k?"jQuery.":"js")+"views,",w=/[\x00"&'<>]/g,x=Array.prototype.slice,y={},z={jsviews:c,sub:h,debugMode:j,err:function(a){return z.debugMode?"
                                Error: "+(a.message||a)+". ":'""'},tmplFn:M,render:y,templates:G,tags:H,helpers:I,converters:J,View:E,convert:C,delimiters:A,tag:D};k?(d=k,d.templates=G,d.render=y,d.views=z,d.fn.render=K):(d=a.jsviews=z,d.extend=function(a,b){var c;a=a||{};for(c in b)a[c]=b[c];return a},d.isArray=Array&&Array.isArray||function(a){return Object.prototype.toString.call(a)==="[object Array]"}),g=d.extend,z.topView={views:{},tmpl:{},hlp:B,ctx:z.helpers},H({"if":function(){var a=this,c=a.view;return c.onElse=function(a,d){var e=0,f=d.length;while(f&&!d[e++])if(e===f)return"";return c.onElse=b,a.path="",a.renderContent(c)},c.onElse(this,arguments)},"else":function(){var a=this.view;return a.onElse?a.onElse(this,arguments):""},"for":function(){var a,b=this,c="",d=arguments,e=d.length;b.props.layout&&(b.tmpl.layout=j);for(a=0;a1&&!a.isArray(b[0]))return b[0]>=-180&&b[0]<=180&&b[1]>=-85&&b[1]<=85;b=b[0]}return!1},center:function(b,c){var d=!1;!c&&a.geo.proj&&this._isGeodetic(b)&&(d=!0,b=a.geo.proj.fromGeodetic(b));var e=[(b[0]+b[2])/2,(b[1]+b[3])/2];return d?a.geo.proj.toGeodetic(e):e},expandBy:function(b,c,d,e){var f=!1;return!e&&a.geo.proj&&this._isGeodetic(b)&&(f=!0,b=a.geo.proj.fromGeodetic(b)),b=[b[0]-c,b[1]-d,b[2]+c,b[3]+d],f?a.geo.proj.toGeodetic(b):b},height:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[3]-b[1]},_in:function(a,b){return a[0]<=b[0]&&a[1]<=b[1]&&a[2]>=b[2]&&a[3]>=b[3]},_bboxDisjoint:function(a,b){return b[0]>a[2]||b[2]a[3]||b[3]0&&(f/g>c?(i=f/2,j=i/c):(j=g/2,i=j*c),b=[h[0]-i,h[1]-j,h[0]+i,h[1]+j]),e?a.geo.proj.toGeodetic(b):b},recenter:function(b,c,d){var e=!1;!d&&a.geo.proj&&(this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b)),this._isGeodetic(c)&&(c=a.geo.proj.fromGeodetic(c)));var f=(b[2]-b[0])/2,g=(b[3]-b[1])/2;return b=[c[0]-f,c[1]-g,c[0]+f,c[1]+g],e?a.geo.proj.toGeodetic(b):b},scaleBy:function(b,c,d){var e=!1;!d&&a.geo.proj&&this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b));var f=this.center(b,!0),g=(b[2]-b[0])*c/2,h=(b[3]-b[1])*c/2;return b=[f[0]-g,f[1]-h,f[0]+g,f[1]+h],e?a.geo.proj.toGeodetic(b):b},width:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[2]-b[0]},bbox:function(b,f){var g,h=!1;if(!b)return c;if(b.bbox)g=!f&&a.geo.proj&&this._isGeodetic(b.bbox)?a.geo.proj.fromGeodetic(b.bbox):b.bbox;else{g=[d,d,e,e];var i=this._allCoordinates(b),j=0;if(i.length===0)return c;!f&&a.geo.proj&&this._isGeodetic(i)&&(h=!0,i=a.geo.proj.fromGeodetic(i));for(;j0?(h[0]=Math.min(Math.max(i[0][0],m[0]),m[2]),h[1]=Math.min(Math.max(i[0][1],m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(h):h}):c;return g*=3,h[0]=Math.min(Math.max(h[0]/g,m[0]),m[2]),h[1]=Math.min(Math.max(h[1]/g,m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(h):h}}return c},contains:function(a,b){if(a.type!="Polygon")return!1;switch(b.type){case"Point":return this._containsPolygonPoint(a.coordinates,b.coordinates);case"LineString":return this._containsPolygonLineString(a.coordinates,b.coordinates);case"Polygon":return this._containsPolygonLineString(a.coordinates,b.coordinates[0]);default:return!1}},_containsPolygonPoint:function(a,b){if(a.length===0||a[0].length<4)return!1;var c=0,d=a[0][0],e=1,f,g;for(;eb[0]&&c++;d=f}return c%2==1},_containsPolygonLineString:function(a,b){for(var c=0;c0){var e=a[0],f=b[0]-e[0],g=b[1]-e[1];if(a.length==1)return Math.sqrt(f*f+g*g);for(var h=1;h=h?e*e+f*f:c*c+d*d-g*g/h},_distanceLineStringLineString:function(a,b){var c=d;for(var e=0;e2?{type:"Point",coordinates:[parseFloat(b[1]),parseFloat(b[2])]}:null}function p(a){var b=a.match(/\s*\((.*)\)/),c=[],d,e,f=0;if(b&&b.length>1){d=b[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);for(;f1){d=b[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);for(;f0){for(;f
                                ";while(c[0]);return a>6?a:!a}();a.widget("geo.geographics",{_$elem:b,_options:{},_trueCanvas:!0,_width:0,_height:0,_$canvas:b,_context:b,_blitcanvas:b,_blitcontext:b,_$labelsContainer:b,options:{style:{borderRadius:"8px",color:"#7f0000",fillOpacity:.2,height:"8px",opacity:1,strokeOpacity:1,strokeWidth:"2px",visibility:"visible",width:"8px"}},_create:function(){this._$elem=this.element,this._options=this.options,this._$elem.css({display:"inline-block",overflow:"hidden",textAlign:"left"}),this._$elem.css("position")=="static"&&this._$elem.css("position","relative"),this._$elem.addClass("geo-graphics"),this._width=this._$elem.width(),this._height=this._$elem.height();if(!this._width||!this._height)this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10);var a="position:absolute;left:0;top:0;margin:0;padding:0;",b="width:"+this._width+"px;height:"+this._height+"px;",d='width="'+this._width+'" height="'+this._height+'"';document.createElement("canvas").getContext?(this._$elem.append("'),this._$canvas=this._$elem.children(":last"),this._context=this._$canvas[0].getContext("2d"),this._blitcanvas=document.createElement("canvas"),this._blitcanvas.width=this._width,this._blitcanvas.height=this._height,this._blitcontext=this._blitcanvas.getContext("2d")):c<=8&&(this._trueCanvas=!1,this._$elem.append("
                                '),this._$canvas=this._$elem.children(":last"),G_vmlCanvasManager.initElement(this._$canvas[0]),this._context=this._$canvas[0].getContext("2d"),this._$canvas.children().css({backgroundColor:"transparent",width:this._width,height:this._height})),this._$elem.append('
                                '),this._$labelsContainer=this._$elem.children(":last")},_setOption:function(b,c){b=="style"&&(c=a.extend({},this._options.style,c)),a.Widget.prototype._setOption.apply(this,arguments)},destroy:function(){a.Widget.prototype.destroy.apply(this,arguments),this._$elem.html(""),this._$elem.removeClass("geo-graphics")},clear:function(){this._context.clearRect(0,0,this._width,this._height),this._$labelsContainer.html("")},drawArc:function(a,b,c,d){d=this._getGraphicStyle(d);if(d.visibility!="hidden"&&d.opacity>0&&d.widthValue>0&&d.heightValue>0){var e=Math.min(d.widthValue,d.heightValue)/2;b=b*Math.PI/180,c=c*Math.PI/180,this._context.save(),this._context.translate(a[0],a[1]),d.widthValue>d.heightValue?this._context.scale(d.widthValue/d.heightValue,1):this._context.scale(1,d.heightValue/d.widthValue),this._context.beginPath(),this._context.arc(0,0,e,b,c,!1),this._trueCanvas&&this._context.restore(),d.doFill&&(this._context.fillStyle=d.fill,this._context.globalAlpha=d.opacity*d.fillOpacity,this._context.fill()),d.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=d.strokeWidthValue,this._context.strokeStyle=d.stroke,this._context.globalAlpha=d.opacity*d.strokeOpacity,this._context.stroke()),this._trueCanvas||this._context.restore()}},drawPoint:function(a,b){b=this._getGraphicStyle(b),b.widthValue==b.heightValue&&b.heightValue==b.borderRadiusValue?this.drawArc(a,0,360,b):b.visibility!="hidden"&&b.opacity>0&&(b.borderRadiusValue=Math.min(Math.min(b.widthValue,b.heightValue)/2,b.borderRadiusValue),a[0]-=b.widthValue/2,a[1]-=b.heightValue/2,this._context.beginPath(),this._context.moveTo(a[0]+b.borderRadiusValue,a[1]),this._context.lineTo(a[0]+b.widthValue-b.borderRadiusValue,a[1]),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1],a[0]+b.widthValue,a[1]+b.borderRadiusValue),this._context.lineTo(a[0]+b.widthValue,a[1]+b.heightValue-b.borderRadiusValue),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1]+b.heightValue,a[0]+b.widthValue-b.borderRadiusValue,a[1]+b.heightValue),this._context.lineTo(a[0]+b.borderRadiusValue,a[1]+b.heightValue),this._context.quadraticCurveTo(a[0],a[1]+b.heightValue,a[0],a[1]+b.heightValue-b.borderRadiusValue),this._context.lineTo(a[0],a[1]+b.borderRadiusValue),this._context.quadraticCurveTo(a[0],a[1],a[0]+b.borderRadiusValue,a[1]),this._context.closePath(),b.doFill&&(this._context.fillStyle=b.fill,this._context.globalAlpha=b.opacity*b.fillOpacity,this._context.fill()),b.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=b.strokeWidthValue,this._context.strokeStyle=b.stroke,this._context.globalAlpha=b.opacity*b.strokeOpacity,this._context.stroke()))},drawLineString:function(a,b){this._drawLines([a],!1,b)},drawPolygon:function(a,b){if(!this._trueCanvas||a.length==1)this._drawLines(a,!0,b);else{if(!a||!a.length||a[0].length<3)return;b=this._getGraphicStyle(b);var c,d,e;if(b.visibility!="hidden"&&b.opacity>0){this._blitcontext.clearRect(0,0,this._width,this._height);if(b.doFill&&a.length>1){this._blitcontext.globalCompositeOperation="source-out",this._blitcontext.globalAlpha=1;for(d=1;d1)for(d=1;d'+b+"
                                ")},resize:function(){this._width=this._$elem.width(),this._height=this._$elem.height();if(!this._width||!this._height)this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10);this._trueCanvas&&(this._$canvas[0].width=this._width,this._$canvas[0].height=this._height),this._$labelsContainer.css({width:this._width,height:this._height})},_getGraphicStyle:function(b){function c(a){return a=parseInt(a,10),+a+""===a?+a:a}return b=a.extend({},this._options.style,b),b.borderRadiusValue=c(b.borderRadius),b.fill=b.fill||b.color,b.doFill=b.fill&&b.fillOpacity>0,b.stroke=b.stroke||b.color,b.strokeWidthValue=c(b.strokeWidth),b.doStroke=b.stroke&&b.strokeOpacity>0&&b.strokeWidthValue>0,b.widthValue=c(b.width),b.heightValue=c(b.height),b},_drawLines:function(a,b,c){if(!a||!a.length||a[0].length<2)return;var d,e;c=this._getGraphicStyle(c);if(c.visibility!="hidden"&&c.opacity>0){this._context.beginPath();for(d=0;d
                                ";while(c[0]);return a>6?a:!a}(),e={bbox:[-180,-85,180,85],bboxMax:[-180,-85,180,85],center:[0,0],cursors:{"static":"default",pan:"url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move",zoom:"crosshair",dragBox:"crosshair",dragCircle:"crosshair",drawPoint:"crosshair",drawLineString:"crosshair",drawPolygon:"crosshair",measureLength:"crosshair",measureArea:"crosshair"},measureLabels:{length:"{{:length.toFixed( 2 )}} m",area:"{{:area.toFixed( 2 )}} sq m"},drawStyle:{},shapeStyle:{},mode:"pan",pannable:!0,scroll:"default",shift:"default",services:[{"class":"osm",type:"tiled",src:function(a){return"http://otile"+(a.index%4+1)+".mqcdn.com/tiles/1.0.0/osm/"+a.zoom+"/"+a.tile.column+"/"+a.tile.row+".png"},attr:"Tiles Courtesy of MapQuest "}],tilingScheme:{tileWidth:256,tileHeight:256,levels:18,basePixelSize:156543.03392799935,origin:[-20037508.342787,20037508.342787]},axisLayout:"map",zoom:0,zoomMin:0,zoomMax:Number.POSITIVE_INFINITY,pixelSize:0};a.widget("geo.geomap",{_$elem:b,_map:b,_created:!1,_createdGraphics:!1,_widgetId:0,_tmplLengthId:"",_tmplAreaId:"",_contentBounds:{},_$resizeContainer:b,_$eventTarget:b,_$contentFrame:b,_$existingChildren:b,_$attrList:b,_$servicesContainer:b,_$shapesContainers:b,_$panContainer:b,_$shapesContainer:b,_$drawContainer:b,_$measureContainer:b,_$measureLabel:b,_dpi:96,_currentServices:[],_center:b,_pixelSize:b,_centerMax:b,_pixelSizeMax:b,_userGeodetic:!0,_centerInteractive:b,_pixelSizeInteractive:b,_timeoutInteractive:null,_triggerInteractive:!1,_loadCount:0,_wheelTimeout:null,_wheelLevel:0,_zoomFactor:2,_fullZoomFactor:2,_partialZoomFactor:1.18920711500273,_mouseDown:b,_inOp:b,_toolPan:b,_shiftDown:b,_anchor:b,_current:b,_downDate:b,_moveDate:b,_clickDate:b,_lastMove:b,_lastDrag:b,_windowHandler:null,_resizeTimeout:null,_panning:b,_velocity:b,_friction:b,_supportTouch:b,_softDblClick:b,_isTap:b,_isDbltap:b,_isMultiTouch:b,_multiTouchAnchor:[],_multiTouchAnchorBbox:b,_multiTouchCurrentBbox:b,_drawTimeout:null,_drawPixels:[],_drawCoords:[],_graphicShapes:[],_initOptions:{},_options:{},options:a.extend({},e),_createWidget:function(b,d){this._$elem=a(d);if(this._$elem.is(".geo-service")){this._graphicShapes=[],a.Widget.prototype._createWidget.apply(this,arguments);return}this._widgetId=c++,this._tmplLengthId="geoMeasureLength"+this._widgetId,this._tmplAreaId="geoMeasureArea"+this._widgetId,this._$elem.addClass("geo-map").css({webkitTransform:"translateZ(0)"}),this._initOptions=b||{},this._forcePosition(this._$elem),this._$elem.css("text-align","left");var e=this._findMapSize();this._contentBounds={x:parseInt(this._$elem.css("padding-left"),10),y:parseInt(this._$elem.css("padding-top"),10),width:e.width,height:e.height},this._createChildren(),this._center=[0,0],this._centerMax=[0,0],this._centerInteractive=[0,0],this.options.pixelSize=this._pixelSize=this._pixelSizeMax=156543.03392799935,this._mouseDown=this._inOp=this._toolPan=this._shiftDown=this._panning=this._isTap=this._isDbltap=!1,this._anchor=[0,0],this._current=[0,0],this._lastMove=[0,0],this._lastDrag=[0,0],this._velocity=[0,0],this._friction=[.8,.8],this._downDate=this._moveDate=this._clickDate=0,this._drawPixels=[],this._drawCoords=[],this._graphicShapes=[],a.Widget.prototype._createWidget.apply(this,arguments)},_create:function(){this._options=this.options;if(this._$elem.is(".geo-service")){this._map=this._$elem.data("geoMap"),this._$elem.data("geoService",this);return}this._map=this,this._supportTouch="ontouchend"in document,this._softDblClick=this._supportTouch||d==7;var c=this,e=this._supportTouch?"touchstart":"mousedown",f=this._supportTouch?"touchend touchcancel":"mouseup",g=this._supportTouch?"touchmove":"mousemove";a(document).keydown(a.proxy(this._document_keydown,this)),this._$eventTarget.dblclick(a.proxy(this._eventTarget_dblclick,this)),this._$eventTarget.bind(e,a.proxy(this._eventTarget_touchstart,this));var h=this._$eventTarget[0].setCapture?this._$eventTarget:a(document);h.bind(g,a.proxy(this._dragTarget_touchmove,this)),h.bind(f,a.proxy(this._dragTarget_touchstop,this)),this._$eventTarget.mousewheel(a.proxy(this._eventTarget_mousewheel,this)),this._windowHandler=function(){c._resizeTimeout&&clearTimeout(c._resizeTimeout),c._resizeTimeout=setTimeout(function(){c._created&&c._$elem.geomap("resize",!0)},500)},a(window).resize(this._windowHandler),this._$drawContainer.geographics({style:this._initOptions.drawStyle||{}}),this._options.drawStyle=this._$drawContainer.geographics("option","style"),this._$shapesContainer.geographics({style:this._initOptions.shapeStyle||{}}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style"),this._initOptions&&(this._initOptions.tilingScheme!==b&&this._setOption("tilingScheme",this._initOptions.tilingScheme||null,!1),this._initOptions.services&&(this._options.services=a.merge([],this._initOptions.services)),this._initOptions.bboxMax&&(this._setOption("bboxMax",this._initOptions.bboxMax,!1),this._setOption("bbox",this._initOptions.bboxMax,!1)),this._initOptions.zoomMin!==b&&this._setOption("zoomMin",this._initOptions.zoomMin,!1),this._initOptions.zoomMax!==b&&this._setOption("zoomMax",this._initOptions.zoomMax,!1),this._initOptions.bbox&&this._setOption("bbox",this._initOptions.bbox,!1),this._initOptions.center&&this._setOption("center",this._initOptions.center,!1),this._initOptions.zoom!==b&&this._setOption("zoom",this._initOptions.zoom,!1)),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area),this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._createServices(),this._refresh(),this._created=!0},_setOption:function(c,d,e){if(c=="pixelSize")return;e=e===b||e,this._$elem.is(".geo-map")&&this._panFinalize();var f,g,h,i;switch(c){case"bbox":this._created&&this._clearInteractiveTimeout(),this._userGeodetic=a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),f=[d[0]+(d[2]-d[0])/2,d[1]+(d[3]-d[1])/2],g=Math.max(a.geo.width(d,!0)/this._contentBounds.width,a.geo.height(d,!0)/this._contentBounds.height),i=this._getZoom(f,g),this._options.tilingScheme?g=this._getPixelSize(Math.min(Math.max(i,this._options.zoomMin),this._options.zoomMax)):ithis._options.zoomMax&&(g=this._getPixelSize(this._options.zoomMax)),this._created?(this._setInteractiveCenterAndSize(f,g),this._setInteractiveTimeout(!1)):this._setCenterAndSize(f,g,!1,e),d=this._getBbox(f,g);break;case"bboxMax":this._userGeodetic=a.geo.proj&&a.geo._isGeodetic(d);break;case"center":this._created&&this._clearInteractiveTimeout(),this._userGeodetic=a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),this._created?(this._setInteractiveCenterAndSize(d,this._pixelSizeInteractive),this._interactiveTransform(),this._setInteractiveTimeout(!1)):this._setCenterAndSize(d,this._pixelSize,!1,e);break;case"measureLabels":d=a.extend(this._options.measureLabels,d),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area);break;case"drawStyle":this._$drawContainer&&(this._$drawContainer.geographics("option","style",d),d=this._$drawContainer.geographics("option","style"));break;case"shapeStyle":this._$elem.is(".geo-service")&&!this._createdGraphics&&this._createServiceGraphics(),this._createdGraphics&&(this._$shapesContainer.geographics("option","style",d),d=this._$shapesContainer.geographics("option","style"));break;case"mode":this._resetDrawing(),this._$eventTarget.css("cursor",this._options.cursors[d]);break;case"zoom":this._created?this._setZoom(d,!1,e):(d=Math.max(d,0),this._setCenterAndSize(this._center,this._getPixelSize(d),!1,e))}a.Widget.prototype._setOption.apply(this,arguments);switch(c){case"bbox":case"center":this._userGeodetic&&(this._options.bbox=a.geo.proj.toGeodetic(this._options.bbox),this._options.center=a.geo.proj.toGeodetic(this._center));break;case"tilingScheme":d!==null&&(this._pixelSizeMax=this._getPixelSize(0),this._centerMax=[d.origin[0]+this._pixelSizeMax*d.tileWidth/2,d.origin[1]+this._pixelSizeMax*d.tileHeight/2]);break;case"bboxMax":a.geo.proj&&a.geo._isGeodetic(d)?h=a.geo.proj.fromGeodetic(d):h=d,this._centerMax=a.geo.center(h),this._pixelSizeMax=Math.max(a.geo.width(h,!0)/this._contentBounds.width,a.geo.height(h,!0)/this._contentBounds.height);break;case"services":this._createServices(),e&&this._refresh();break;case"shapeStyle":e&&this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))}},destroy:function(){if(this._$elem.is(".geo-service"))this._createdGraphics&&(this._$shapesContainer.geographics("destroy"),this._$shapesContainer=b,this._createdGraphics=!1);else{clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,this._created=!1,a(window).unbind("resize",this._windowHandler);for(var c=0;c=0||b<=1)for(var d=0;d0)){this._createdGraphics||this._createServiceGraphics();var g,h,i,j,k,l;a.isArray(c)?g=c:c.type=="FeatureCollection"?g=c.features:g=[c];for(i=1;i0)){var e=a.isArray(c)?c:[c],f;for(var g=0;g=0&&(a.removeData(c,"geoBbox"),f=this._graphicShapes.slice(g+1),this._graphicShapes.length=g,this._graphicShapes.push.apply(this._graphicShapes,f),g--);if(d===b||d)this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh()}},_getBbox:function(a,b){a=a||this._center,b=b||this._pixelSize;var c=this._contentBounds.width/2*b,d=this._contentBounds.height/2*b;return[a[0]-c,a[1]-d,a[0]+c,a[1]+d]},_setBbox:function(b,c,d){var e=[b[0]+(b[2]-b[0])/2,b[1]+(b[3]-b[1])/2],f=Math.max(a.geo.width(b,!0)/this._contentBounds.width,a.geo.height(b,!0)/this._contentBounds.height),g=this._getZoom(e,f);this._options.tilingScheme?f=this._getPixelSize(Math.min(Math.max(g,this._options.zoomMin),this._options.zoomMax)):gthis._options.zoomMax&&(f=this._getPixelSize(this._options.zoomMax)),this._setInteractiveCenterAndSize(e,f),this._interactiveTransform()},_getBboxMax:function(){var a=this._contentBounds.width/2*this._pixelSizeMax,b=this._contentBounds.height/2*this._pixelSizeMax;return[this._centerMax[0]-a,this._centerMax[1]-b,this._centerMax[0]+a,this._centerMax[1]+b]},_getCenter:function(){return this._center},_getContentBounds:function(){return this._contentBounds},_getServicesContainer:function(){return this._$servicesContainer},_getZoom:function(b,c){b=b||this._center,c=c||this._pixelSize;var d=this._options.tilingScheme;if(d){if(d.pixelSizes){var e=Math.floor(c*1e3),f=d.pixelSizes.length,g=f-1;for(;g>=0;g--)if(Math.floor(d.pixelSizes[g]*1e3)>=e)return g;return 0}return Math.round(Math.log(d.basePixelSize/c)/Math.log(2))}var h=this._contentBounds.width/this._contentBounds.height,i=a.geo.reaspect(this._getBbox(b,c),h,!0),j=a.geo.reaspect(this._getBboxMax(),h,!0);return Math.round(Math.log(a.geo.width(j,!0)/a.geo.width(i,!0))/Math.log(this._zoomFactor))},_setZoom:function(a,b,c){this._clearInteractiveTimeout(),a=Math.min(Math.max(a,this._options.zoomMin),this._options.zoomMax),this._setInteractiveCenterAndSize(this._centerInteractive,this._getPixelSize(a)),this._interactiveTransform(),this._setInteractiveTimeout(b)},_createChildren:function(){this._$existingChildren=this._$elem.children(),this._forcePosition(this._$existingChildren),this._$existingChildren.detach().css({mozUserSelect:"none"});var b="width:"+this._contentBounds.width+"px; height:"+this._contentBounds.height+"px; margin:0; padding:0;",c="position:absolute; left:0; top:0;";this._$elem.prepend('
                                '),this._$eventTarget=this._$contentFrame=this._$elem.children(":first"),this._$contentFrame.append('
                                '),this._$servicesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                                '),this._$shapesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                                  '),this._$attrList=this._$contentFrame.children(":last"),this._$contentFrame.append('
                                  '),this._$drawContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                                  '),this._$measureContainer=this._$contentFrame.children(":last"),this._$measureLabel=this._$measureContainer.children(),this._$panContainer=a([this._$shapesContainer[0],this._$drawContainer[0],this._$measureContainer[0]]),this._$resizeContainer=a([this._$contentFrame[0],this._$servicesContainer[0],this._$eventTarget[0],this._$measureContainer[0]]),this._$contentFrame.append(this._$existingChildren),a("#geo-measure-style").length||a("head").prepend('")},_createServices:function(){var b,c;for(c=0;c',g;this._$servicesContainer.append(f),serviceContainer=this._$servicesContainer.children(":last"),b.serviceContainer=serviceContainer,a.geo._serviceTypes[b.type].create(this,serviceContainer,b,c),serviceContainer.data("geoMap",this).geomap(),b.attr&&this._$attrList.append("
                                • "+b.attr+"
                                • ")}this._$shapesContainers=this._$shapesContainer,this._$attrList.find("a").css({position:"relative",zIndex:100})},_createServiceGraphics:function(){var a=this._$elem.closest(".geo-content-frame");this._$elem.append('
                                  '),this._$shapesContainer=this._$elem.children(":last"),this._map._$shapesContainers=this._map._$shapesContainers.add(this._$shapesContainer),this._$shapesContainer.geographics(),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style")},_refreshDrawing:function(){this._$drawContainer.geographics("clear");if(this._drawPixels.length>0){var b=this._options.mode,c=this._drawPixels,d=this._drawCoords,e,f,g,h,i;switch(b){case"measureLength":b="drawLineString",f={type:"LineString",coordinates:d},e=a.render[this._tmplLengthId]({length:a.geo.length(f,!0)}),g=a.merge([],c[c.length-1]);break;case"measureArea":b="drawPolygon",f={type:"Polygon",coordinates:[a.merge([],d)]},f.coordinates[0].push(d[0]),e=a.render[this._tmplAreaId]({area:a.geo.area(f,!0)}),g=this._toPixel(a.geo.centroid(f).coordinates),c=[c];break;case"drawPolygon":c=[c]}this._$drawContainer.geographics(b,c),e&&(this._$measureLabel.html(e),h=this._contentBounds.width-(this._$measureLabel.outerWidth(!0)+g[0]),i=this._contentBounds.height-(this._$measureLabel.outerHeight(!0)+g[1]),h<0&&(g[0]+=h),i<0&&(g[1]+=i),this._$measureLabel.css({left:Math.max(g[0],0),top:Math.max(g[1],0)}).show())}},_resetDrawing:function(){this._drawPixels=[],this._drawCoords=[],this._$drawContainer.geographics("clear"),this._$measureLabel.hide()},_refreshShapes:function(c,d,e,f,g,h){var i,j,k,l,m,n,o,p,q=this._map._getBbox(g,h);for(i=0;i0&&a.height>0)){a={width:b.width(),height:b.height()};if(a.width<=0||a.height<=0)a={width:parseInt(b.css("width"),10),height:parseInt(b.css("height"),10)};b=b.parent()}return a},_forcePosition:function(a){var b=a.css("position");b!="relative"&&b!="absolute"&&b!="fixed"&&a.css("position","relative")},_getPixelSize:function(b){var c=this._options.tilingScheme;if(c!==null){if(b===0)return c.pixelSizes?c.pixelSizes[0]:c.basePixelSize;b=Math.round(b),b=Math.max(b,0);var d=c.pixelSizes?c.pixelSizes.length:c.levels;return b=Math.min(b,d-1),c.pixelSizes?c.pixelSizes[b]:c.basePixelSize/Math.pow(2,b)}var e=a.geo.scaleBy(this._getBboxMax(),1/Math.pow(this._zoomFactor,b),!0);return Math.max(a.geo.width(e,!0)/this._contentBounds.width,a.geo.height(e,!0)/this._contentBounds.height)},_getZoomCenterAndSize:function(a,b,c){var d=c?this._fullZoomFactor:this._partialZoomFactor,e=Math.pow(d,-b),f=this._pixelSizeInteractive*e,g=this._getZoom(this._centerInteractive,f);c&&this._options.tilingScheme?f=this._getPixelSize(Math.min(Math.max(g,this._options.zoomMin),this._options.zoomMax)):b<0&&g0&&g>this._options.zoomMax&&(f=this._pixelSizeInteractive);var h=f/this._pixelSizeInteractive,i=this._toMap(a,this._centerInteractive,this._pixelSizeInteractive),j=[(this._centerInteractive[0]-i[0])*h,(this._centerInteractive[1]-i[1])*h],k=[i[0]+j[0],i[1]+j[1]];return{pixelSize:f,center:k}},_mouseWheelFinish:function(a){this._wheelTimeout=null;if(this._wheelLevel!==0){var b=this._getZoomCenterAndSize(this._anchor,this._wheelLevel,this._options.tilingScheme!==null);this._wheelLevel=0}else a&&this._refresh()},_panFinalize:function(){if(this._panning){this._velocity=[0,0];var a=this._current[0]-this._anchor[0],b=this._current[1]-this._anchor[1],c=this._options.axisLayout==="image",d=-a*this._pixelSize,e=(c?-1:1)*b*this._pixelSize;this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._inOp=!1,this._anchor=this._current,this._mouseDown=this._toolPan=this._panning=!1}},_panMove:function(){if(!this._options.pannable)return;var a=this._current[0]-this._lastDrag[0],b=this._current[1]-this._lastDrag[1],c=0,d,e;if(this._toolPan||a>3||a<-3||b>3||b<-3){this._toolPan||(this._toolPan=!0,this._$eventTarget.css("cursor",this._options.cursors.pan)),this._mouseDown&&(this._velocity=[a,b]);if(a!==0||b!==0)this._panning=!0,this._lastDrag=this._current,this._centerInteractive[0]-=a*this._pixelSizeInteractive,this._centerInteractive[1]+=(this._options.axisLayout==="image"?-1:1)*b*this._pixelSizeInteractive,this._setInteractiveCenterAndSize(this._centerInteractive,this._pixelSizeInteractive),this._interactiveTransform()}},_clearInteractiveTimeout:function(){return this._timeoutInteractive?(clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,!0):(this._centerInteractive[0]=this._center[0],this._centerInteractive[1]=this._center[1],this._pixelSizeInteractive=this._pixelSize,!1)},_interactiveTransform:function(){this._$shapesContainers&&this._$shapesContainers.geographics("clear");for(var b=0;b0&&(this._drawPixels=this._toPixel(this._drawCoords,this._centerInteractive,this._pixelSizeInteractive),this._refreshDrawing())},_setInteractiveTimeout:function(a){function c(){b._isMultiTouch?b._timeoutInteractive=setTimeout(c,128):b._created&&b._timeoutInteractive&&(b._setCenterAndSize(b._centerInteractive,b._pixelSizeInteractive,b._triggerInteractive,!0),b._timeoutInteractive=null,b._triggerInteractive=!1)}var b=this;this._timeoutInteractive=setTimeout(c,128),this._triggerInteractive|=a},_refresh:function(b,c){var d,e,f=0;for(;f0&&e._refreshShapes(e._$shapesContainer,e._graphicShapes,e._graphicShapes,e._graphicShapes))}this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._graphicShapes.length>0&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))},_setInteractiveCenterAndSize:function(b,c){this._centerInteractive[0]=b[0],this._centerInteractive[1]=b[1],this._pixelSizeInteractive=c,this._userGeodetic?(this._options.bbox=a.geo.proj.toGeodetic(this._getBbox(b,c)),this._options.center=a.geo.proj.toGeodetic(b)):(this._options.bbox=this._getBbox(b,c),this._options.center[0]=b[0],this._options.center[1]=b[1]),this._options.pixelSize=c,this._options.zoom=this._getZoom(b,c)},_setCenterAndSize:function(b,c,d,e){if(!a.isArray(b)||b.length!=2||typeof b[0]!="number"||typeof b[1]!="number")return;var f=this._getZoom(b,c);this._options.tilingScheme?this._pixelSizeInteractive=c=this._getPixelSize(Math.min(Math.max(f,this._options.zoomMin),this._options.zoomMax)):fthis._options.zoomMax&&(this._pixelSizeInteractive=c=this._getPixelSize(this._options.zoomMax)),this._center[0]=b[0],this._center[1]=b[1],this._options.pixelSize=this._pixelSize=c,this._userGeodetic?(this._options.bbox=a.geo.proj.toGeodetic(this._getBbox()),this._options.center=a.geo.proj.toGeodetic(this._center)):(this._options.bbox=this._getBbox(),this._options.center=a.merge([],b)),this._options.zoom=f,d&&this._trigger("bboxchange",window.event,{bbox:a.merge([],this._options.bbox)}),e&&(this._refresh(),this._refreshDrawing())},_requestQueued:function(){this._loadCount===0&&this._trigger("loadstart",window.event),this._loadCount++},_requestComplete:function(){this._loadCount--,this._loadCount<=0&&(this._loadCount=0,this._trigger("loadend",window.event))},_toMap:function(b,c,d){c=c||this._center,d=d||this._pixelSize;var e=a.isArray(b[0]),f=e&&a.isArray(b[0][0]),g=f&&a.isArray(b[0][0][0]),h=this._contentBounds.width,i=this._contentBounds.height,j=h/2*d,k=i/2*d,l=[c[0]-j,c[1]-k,c[0]+j,c[1]+k],m=a.geo.width(l,!0)/h,n=a.geo.height(l,!0)/i,o,p=this._options.axisLayout==="image",q=[],r,s,t;g||(f||(e||(b=[b]),b=[b]),b=[b]);for(r=0;r0&&b.which==27&&(c<=2?(this._resetDrawing(),this._inOp=!1):(this._drawCoords[c-2]=a.merge([],this._drawCoords[c-1]),this._drawPixels[c-2]=a.merge([],this._drawPixels[c-1]),this._drawCoords.length--,this._drawPixels.length--,this._refreshDrawing()))},_eventTarget_dblclick_zoom:function(a){var b=this._clearInteractiveTimeout();this._trigger("dblclick",a,{type:"Point",coordinates:this._toMap(this._current,this._centerInteractive,this._pixelSizeInteractive)});if(!a.isDefaultPrevented()){var c=this._getZoomCenterAndSize(this._current,1,!0);this._setInteractiveCenterAndSize(c.center,c.pixelSize),this._interactiveTransform(),b=!0}b&&this._setInteractiveTimeout(!0)},_eventTarget_dblclick:function(b){if(this._options.mode==="static")return;this._drawTimeout&&(window.clearTimeout(this._drawTimeout),this._drawTimeout=null);var c=a(b.currentTarget).offset();switch(this._options.mode){case"drawLineString":case"measureLength":this._drawCoords.length>1&&(this._drawCoords[0][0]!=this._drawCoords[1][0]||this._drawCoords[0][1]!=this._drawCoords[1][1])?(this._drawCoords.length--,this._trigger("shape",b,{type:"LineString",coordinates:this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords})):this._eventTarget_dblclick_zoom(b),this._resetDrawing();break;case"drawPolygon":case"measureArea":if(this._drawCoords.length>1&&(this._drawCoords[0][0]!=this._drawCoords[1][0]||this._drawCoords[0][1]!=this._drawCoords[1][1])){var d=this._drawCoords.length-1;d>2&&(this._drawCoords[d]=a.merge([],this._drawCoords[0]),this._trigger("shape",b,{type:"Polygon",coordinates:[this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords]}))}else this._eventTarget_dblclick_zoom(b);this._resetDrawing();break;default:this._eventTarget_dblclick_zoom(b)}this._inOp=!1},_eventTarget_touchstart:function(b){var c=this._options.mode,d=this._options.shift;if(c==="static")return;if(!this._supportTouch&&b.which!=1)return;var e=this._clearInteractiveTimeout(),f=a(b.currentTarget).offset(),g=b.originalEvent.changedTouches;this._supportTouch?(this._multiTouchAnchor=a.merge([],g),this._isMultiTouch=this._multiTouchAnchor.length>1,this._isMultiTouch?(this._multiTouchCurrentBbox=[g[0].pageX-f.left,g[0].pageY-f.top,g[1].pageX-f.left,g[1].pageY-f.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._current=a.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchCurrentBbox=[g[0].pageX-f.left,g[0].pageY-f.top,NaN,NaN],this._current=[g[0].pageX-f.left,g[0].pageY-f.top])):this._current=[b.pageX-f.left,b.pageY-f.top];if(this._softDblClick){var h=a.now();if(h-this._downDate<750){if(this._isTap){var i=this._current[0]-this._anchor[0],j=this._current[1]-this._anchor[1],k=Math.sqrt(i*i+j*j);k>8?this._isTap=!1:this._current=a.merge([],this._anchor)}this._isDbltap?this._isDbltap=!1:this._isDbltap=this._isTap}else this._isDbltap=!1;this._isTap=!0,this._downDate=h}return this._mouseDown=!0,this._anchor=a.merge([],this._current),!this._inOp&&b.shiftKey&&d!=="off"?(this._shiftDown=!0,this._$eventTarget.css("cursor",this._options.cursors[d==="default"?"zoom":d])):!this._isMultiTouch&&(this._options.pannable||c==="dragBox"||c==="dragCircle")&&(this._inOp=!0,c!=="zoom"&&c!=="dragBox"&&c!=="dragCircle"&&(this._lastDrag=this._current,b.currentTarget.setCapture&&b.currentTarget.setCapture())),b.preventDefault(),e&&this._setInteractiveTimeout(!0),!1},_dragTarget_touchmove:function(b){if(this._options.mode==="static")return;var c=!1;this._mouseDown&&(c=this._clearInteractiveTimeout());var e=this._$eventTarget.offset(),f=this._drawCoords.length,g=b.originalEvent.changedTouches,h,i,j=0;if(this._supportTouch){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&g[0].identifier!==this._multiTouchAnchor[0].identifier)return this._mouseDown=!1,this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(g[0]),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-e.left,this._multiTouchAnchor[1].pageY-e.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._mouseDown=!0,this._anchor=this._current=a.geo.center(this._multiTouchCurrentBbox,!0),c&&this._setInteractiveTimeout(!0),!1;if(this._isMultiTouch){for(;j0?m*=5:m*=10;var n=m-this._wheelLevel;this._wheelLevel=m;var o=this._getZoomCenterAndSize(this._anchor,n,!1);this._setInteractiveCenterAndSize(o.center,o.pixelSize),this._interactiveTransform(),c=!0,h=a.geo.center(this._multiTouchCurrentBbox,!0)}else h=[b.originalEvent.changedTouches[0].pageX-e.left,b.originalEvent.changedTouches[0].pageY-e.top]}else h=[b.pageX-e.left,b.pageY-e.top];if(h[0]===this._lastMove[0]&&h[1]===this._lastMove[1]&&this._inOp)return b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1;d==7&&(this._isDbltap=this._isTap=!1),this._mouseDown&&(this._current=h,this._moveDate=a.now());if(this._isMultiTouch)return b.preventDefault(),this._isDbltap=this._isTap=!1,c&&this._setInteractiveTimeout(!0),!1;var p=this._options.shift,q=this._shiftDown?p==="default"?"zoom":p:this._options.mode,r,s,t;switch(q){case"zoom":case"dragBox":this._mouseDown?(this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawBbox",[this._anchor[0],this._anchor[1],h[0],h[1]])):this._trigger("move",b,{type:"Point",coordinates:this.toMap(h)});break;case"dragCircle":this._mouseDown?(r=h[0]-this._anchor[0],s=h[1]-this._anchor[1],t=Math.sqrt(r*r+s*s)*2,this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawArc",this._anchor,0,360,{width:t,height:t})):this._trigger("move",b,{type:"Point",coordinates:this.toMap(h)});break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":this._mouseDown||this._toolPan?(this._panMove(),c=!0):(f>0&&(this._drawCoords[f-1]=this._toMap(h,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[f-1]=h,this._refreshDrawing()),this._trigger("move",b,{type:"Point",coordinates:this.toMap(h)}));break;default:this._mouseDown||this._toolPan?(this._panMove(),c=!0):this._trigger("move",b,{type:"Point",coordinates:this.toMap(h)})}this._lastMove=h,c&&this._setInteractiveTimeout(!0);if(this._inOp)return b.preventDefault(),!1},_dragTarget_touchstop:function(b){if(this._options.mode==="static")return;if(!this._mouseDown)if(d==7)this._eventTarget_touchstart(b);else return!1;var c=this._clearInteractiveTimeout(),e=this._mouseDown,f=this._toolPan,g=this._$eventTarget.offset(),h=this._options.shift,i=this._shiftDown?h==="default"?"zoom":h:this._options.mode,j,k,l,m,n,o,p;this._supportTouch?(j=[b.originalEvent.changedTouches[0].pageX-g.left,b.originalEvent.changedTouches[0].pageY-g.top],this._multiTouchAnchor=[],this._inOp=!1):j=[b.pageX-g.left,b.pageY-g.top],this._softDblClick&&this._isTap&&(m=j[0]-this._anchor[0],n=j[1]-this._anchor[1],Math.sqrt(m*m+n*n)<=8&&(j=a.merge([],this._anchor))),m=j[0]-this._anchor[0],n=j[1]-this._anchor[1],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._shiftDown=this._mouseDown=this._toolPan=!1;if(this._isMultiTouch){b.preventDefault(),this._isMultiTouch=!1,this._wheelLevel=0,c&&this._setInteractiveTimeout(!0);return}document.releaseCapture&&document.releaseCapture();if(e){l=a.now(),this._current=j;switch(i){case"zoom":case"dragBox":if(m!==0||n!==0){var q=this._pixelSize*6,r=this._toMap([[Math.min(this._anchor[0],j[0]),Math.max(this._anchor[1],j[1])],[Math.max(this._anchor[0],j[0]),Math.min(this._anchor[1],j[1])]]),s=[r[0][0],r[0][1],r[1][0],r[1][1]];i==="zoom"?(s[2]-s[0]100){var x=this;this._drawTimeout=setTimeout(function(){x._drawTimeout&&(x._trigger("shape",b,{type:"Point",coordinates:x.toMap(j)}),x._inOp=!1,x._drawTimeout=null)},250)}break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":if(f)this._panFinalize();else{k=this._drawCoords.length===0?0:this._drawCoords.length-1,this._drawCoords[k]=this._toMap(j),this._drawPixels[k]=j;if(k<2||this._drawCoords[k][0]!=this._drawCoords[k-1][0]||this._drawCoords[k][1]!=this._drawCoords[k-1][1])this._drawCoords[k+1]=this._toMap(j,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[k+1]=j;this._refreshDrawing()}break;default:f?this._panFinalize():l-this._clickDate>100&&(this._trigger("click",b,{type:"Point",coordinates:this.toMap(j)}),this._inOp=!1)}this._clickDate=l;if(this._softDblClick&&this._isDbltap)return this._isDbltap=this._isTap=!1,c&&this._setInteractiveTimeout(!0),this._$eventTarget.trigger("dblclick",b),!1}c&&this._setInteractiveTimeout(!0);if(this._inOp)return b.preventDefault(),!1},_eventTarget_mousewheel:function(b,c){if(this._options.mode==="static"||this._options.scroll==="off")return;b.preventDefault();if(this._mouseDown)return!1;if(c!==0){this._clearInteractiveTimeout(),c>0?c=Math.ceil(c):c=Math.floor(c);var d=a(b.currentTarget).offset();this._anchor=[b.pageX-d.left,b.pageY-d.top];var e=this._getZoomCenterAndSize(this._anchor,c,this._options.tilingScheme!==null),f,g=0;this._setInteractiveCenterAndSize(e.center,e.pixelSize),this._interactiveTransform(),this._setInteractiveTimeout(!0)}return!1}})}(jQuery),function(a,b){a.geo._serviceTypes.tiled=function(){return{create:function(b,c,d,e){var f=a.data(d,"geoServiceState");if(!f){f={loadCount:0,reloadTiles:!1};var g='
                                  ';c.append(g),f.serviceContainer=c.children(":last"),a.data(d,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b.options.tilingScheme;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(c){var f=a(this),h=f.data("pixelSize"),i=h/e;if(h>0){i=Math.round(i*1e3)/1e3;var j=f.data("scaleOrigin"),k=b._toPixel(j,d,e);f.css({left:Math.round(k[0])+"px",top:Math.round(k[1])+"px",width:g.tileWidth*i,height:g.tileHeight*i})}}))},refresh:function(b,c,d){var e=a.data(c,"geoServiceState");this._cancelUnloaded(b,c),e&&d&&(e.reloadTiles=!0);if(e&&c&&c.style.visibility==="visible"&&!e.serviceContainer.is(":hidden")){var f=b._getBbox(),g=b._pixelSize,h=this,i=e.serviceContainer,j=b._getContentBounds(),k=j.width,l=j.height,m=b.options.axisLayout==="image",n=m?1:-1,o=b.options.tilingScheme,p=o.tileWidth,q=o.tileHeight,r=Math.floor((f[0]-o.origin[0])/(g*p)),s=Math.max(Math.floor((m?f[1]-o.origin[1]:o.origin[1]-f[3])/(g*q)),0),t=Math.ceil((f[2]-o.origin[0])/(g*p)),u=Math.ceil((m?f[3]-o.origin[1]:o.origin[1]-f[1])/(g*q)),v=b._getBboxMax(),w=b._getPixelSize(0),x=w/g,y=Math.floor((v[0]-o.origin[0])/(w*p))*x,z=Math.floor((o.origin[1]+n*v[3])/(w*q))*x,A=o.origin[0]+y*p*g,B=o.origin[1]+n*z*q*g,C=Math.round((A-f[0])/g),D=Math.round((m?B-f[1]:f[3]-B)/g),E=i.children().show(),F=E.filter("[data-pixel-size='"+g+"']").appendTo(i),G=c.style.opacity,H,I,J=function(c){h._loadImage(a.data(this,"img"),c,g,b,e,G)},K=function(){a.data(this,"img").remove(),e.loadCount--,b._requestComplete()};e.reloadTiles&&E.find("img").attr("data-dirty","true"),F.size()?(F.css({left:C%p+"px",top:D%q+"px"}).data("scaleOrigin",b._toMap([C%p,D%q])),F.children().each(function(b){var c=a(this),d=c.attr("data-tile").split(",");c.css({left:Math.round((parseInt(d[0],10)-y)*100+(C-C%p)/p*100)+"%",top:Math.round((parseInt(d[1],10)-z)*100+(D-D%q)/q*100)+"%"}),G<1&&c.fadeTo(0,G)})):(i.append("
                                  "),F=i.children(":last").data("scaleOrigin",b._toMap([C%p,D%q])));for(H=r;H0)M.attr("src",T);else{var U="",F.append(U),M=F.children(":last")}typeof T=="string"?h._loadImage(M,T,g,b,e,G):T?(a.data(T,"img",M),T.done(J).fail(K)):M.remove()}}E.find("[data-dirty]").remove(),e.reloadTiles=!1}},resize:function(a,b){},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display",c.style.visibility==="visible"?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0){d.serviceContainer.find("img:hidden").remove();while(d.loadCount>0)d.loadCount--,b._requestComplete()}},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){g<1?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).error(function(b){a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).attr("src",c)}}}()}(jQuery),function(a,b){a.geo._serviceTypes.shingled=function(){return{create:function(b,c,d,e){var f=a.data(d,"geoServiceState");if(!f){f={loadCount:0};var g='
                                  ';c.append(g),f.serviceContainer=c.children(":last"),a.data(d,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b._getContentBounds(),h=g.width,i=g.height,j=h/2,k=i/2,l=[d[0]-j,d[1]-k,d[0]+j,d[1]+k];f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(c){var f=a(this),g=f.data("pixelSize"),j=g/e;if(g>0){j=Math.round(j*1e3)/1e3;var k=f.data("origin"),l=b._toPixel(k,d,e);f.css({left:Math.round(l[0]),top:Math.round(l[1]),width:h*j,height:i*j})}}))},refresh:function(b,c){var d=a.data(c,"geoServiceState");this._cancelUnloaded(b,c);if(d&&c&&c.style.visibility==="visible"&&!d.serviceContainer.is(":hidden")){var e=b._getBbox(),f=b._pixelSize,g=this,h=d.serviceContainer,i=b._getContentBounds(),j=i.width,k=i.height,l=h.children('[data-pixel-size="'+f+'"]'),m=c.style.opacity,n;m<1&&h.find("img").attr("data-keep-alive","0"),l.size()||(h.append('
                                  '),l=h.children(":last"));var o=c.hasOwnProperty("src")?"src":"getUrl",p={bbox:e,width:j,height:k,zoom:b._getZoom(),tile:null,index:0},q=a.isFunction(c[o]),r,s=l.position();s.left=-s.left,s.top=-s.top,q?r=c[o](p):(a.templates("geoSrc",c[o]),r=a.render.geoSrc(p)),d.loadCount++,b._requestQueued(),l.append(''),n=l.children(":last").data("center",b._center),typeof r=="string"?g._loadImage(n,r,f,b,d,m):r.done(function(a){g._loadImage(n,a,f,b,d,m)}).fail(function(){n.remove(),d.loadCount--,b._requestComplete()})}},resize:function(b,c){var d=a.data(c,"geoServiceState");if(d&&c&&c.style.visibility==="visible"){this._cancelUnloaded(b,c);var e=d.serviceContainer,f=b._getContentBounds(),g=f.width,h=f.height,i=e.children();i.attr("data-pixel-size","0"),i.each(function(c){var d=a(this),e=d.position(),f=d.data("origin"),i=b._toPixel(f);d.css({left:e.left+(g-d.width())/2,top:e.top+(h-d.height())/2})})}},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display",c.style.visibility==="visible"?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0){d.serviceContainer.find("img:hidden").remove();while(d.loadCount>0)d.loadCount--,b._requestComplete()}},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){if(!a.contains(document.body,b.target.jquery?b.target[0]:b.target))return;g<1?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(':not([data-pixel-size="'+d+'"])').remove(),h.find("img[data-keep-alive]").remove(),f.loadCount=0)}).error(function(b){if(!a.contains(document.body,b.target.jquery?b.target[0]:b.target))return;a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).attr("src",c)}}}()}(jQuery); \ No newline at end of file diff --git a/dist/jquery.geo-1.0b1.5.js b/dist/jquery.geo-1.0b1.5.js deleted file mode 100644 index 6490a12..0000000 --- a/dist/jquery.geo-1.0b1.5.js +++ /dev/null @@ -1,7224 +0,0 @@ -/*! jQuery Geo - v1.0b1.5 - 2013-01-17 - * http://jquerygeo.com - * Copyright (c) 2013 Ryan Westphal/Applied Geographics, Inc.; Licensed MIT, GPL */ - -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -// Known Issues: -// -// * Patterns only support repeat. -// * Radial gradient are not implemented. The VML version of these look very -// different from the canvas one. -// * Clipping paths are not implemented. -// * Coordsize. The width and height attribute have higher priority than the -// width and height style values which isn't correct. -// * Painting mode isn't implemented. -// * Canvas width/height should is using content-box by default. IE in -// Quirks mode will draw the canvas using border-box. Either change your -// doctype to HTML5 -// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) -// or use Box Sizing Behavior from WebFX -// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) -// * Non uniform scaling does not correctly scale strokes. -// * Optimize. There is always room for speed improvements. - -// Only add this code if we do not already have a canvas implementation -if (!document.createElement('canvas').getContext) { - - (function () { - - // alias some functions to make (compiled) code shorter - var m = Math; - var mr = m.round; - var ms = m.sin; - var mc = m.cos; - var abs = m.abs; - var sqrt = m.sqrt; - - // this is used for sub pixel precision - var Z = 10; - var Z2 = Z / 2; - - var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; - - /** - * This funtion is assigned to the elements as element.getContext(). - * @this {HTMLElement} - * @return {CanvasRenderingContext2D_} - */ - function getContext() { - return this.context_ || - (this.context_ = new CanvasRenderingContext2D_(this)); - } - - var slice = Array.prototype.slice; - - /** - * Binds a function to an object. The returned function will always use the - * passed in {@code obj} as {@code this}. - * - * Example: - * - * g = bind(f, obj, a, b) - * g(c, d) // will do f.call(obj, a, b, c, d) - * - * @param {Function} f The function to bind the object to - * @param {Object} obj The object that should act as this when the function - * is called - * @param {*} var_args Rest arguments that will be used as the initial - * arguments when the function is called - * @return {Function} A new function that has bound this - */ - function bind(f, obj, var_args) { - var a = slice.call(arguments, 2); - return function () { - return f.apply(obj, a.concat(slice.call(arguments))); - }; - } - - function encodeHtmlAttribute(s) { - return String(s).replace(/&/g, '&').replace(/"/g, '"'); - } - - function addNamespace(doc, prefix, urn) { - if (!doc.namespaces[prefix]) { - doc.namespaces.add(prefix, urn, '#default#VML'); - } - } - - function addNamespacesAndStylesheet(doc) { - addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); - addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); - - // Setup default CSS. Only add one style sheet per document - if (!doc.styleSheets['ex_canvas_']) { - var ss = doc.createStyleSheet(); - ss.owningElement.id = 'ex_canvas_'; - ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + - // default size is 300x150 in Gecko and Opera - 'text-align:left;width:300px;height:150px}'; - } - } - - // Add namespaces and stylesheet at startup. - addNamespacesAndStylesheet(document); - - var G_vmlCanvasManager_ = { - init: function (opt_doc) { - var doc = opt_doc || document; - // Create a dummy element so that IE will allow canvas elements to be - // recognized. - doc.createElement('canvas'); - doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); - }, - - init_: function (doc) { - // find all canvas elements - var els = doc.getElementsByTagName('canvas'); - for (var i = 0; i < els.length; i++) { - this.initElement(els[i]); - } - }, - - /** - * Public initializes a canvas element so that it can be used as canvas - * element from now on. This is called automatically before the page is - * loaded but if you are creating elements using createElement you need to - * make sure this is called on the element. - * @param {HTMLElement} el The canvas element to initialize. - * @return {HTMLElement} the element that was created. - */ - initElement: function (el) { - if (!el.getContext) { - el.getContext = getContext; - - // Add namespaces and stylesheet to document of the element. - addNamespacesAndStylesheet(el.ownerDocument); - - // Remove fallback content. There is no way to hide text nodes so we - // just remove all childNodes. We could hide all elements and remove - // text nodes but who really cares about the fallback content. - el.innerHTML = ''; - - // do not use inline function because that will leak memory - el.attachEvent('onpropertychange', onPropertyChange); - el.attachEvent('onresize', onResize); - - var attrs = el.attributes; - if (attrs.width && attrs.width.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setWidth_(attrs.width.nodeValue); - el.style.width = attrs.width.nodeValue + 'px'; - } else { - el.width = el.clientWidth; - } - if (attrs.height && attrs.height.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setHeight_(attrs.height.nodeValue); - el.style.height = attrs.height.nodeValue + 'px'; - } else { - el.height = el.clientHeight; - } - //el.getContext().setCoordsize_() - } - return el; - } - }; - - function onPropertyChange(e) { - var el = e.srcElement; - - switch (e.propertyName) { - case 'width': - el.getContext().clearRect(); - el.style.width = el.attributes.width.nodeValue + 'px'; - // In IE8 this does not trigger onresize. - el.firstChild.style.width = el.clientWidth + 'px'; - break; - case 'height': - el.getContext().clearRect(); - el.style.height = el.attributes.height.nodeValue + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - break; - } - } - - function onResize(e) { - var el = e.srcElement; - if (el.firstChild) { - el.firstChild.style.width = el.clientWidth + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - } - } - - G_vmlCanvasManager_.init(); - - // precompute "00" to "FF" - var decToHex = []; - for (var i = 0; i < 16; i++) { - for (var j = 0; j < 16; j++) { - decToHex[i * 16 + j] = i.toString(16) + j.toString(16); - } - } - - function createMatrixIdentity() { - return [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1] - ]; - } - - function matrixMultiply(m1, m2) { - var result = createMatrixIdentity(); - - for (var x = 0; x < 3; x++) { - for (var y = 0; y < 3; y++) { - var sum = 0; - - for (var z = 0; z < 3; z++) { - sum += m1[x][z] * m2[z][y]; - } - - result[x][y] = sum; - } - } - return result; - } - - function copyState(o1, o2) { - o2.fillStyle = o1.fillStyle; - o2.lineCap = o1.lineCap; - o2.lineJoin = o1.lineJoin; - o2.lineWidth = o1.lineWidth; - o2.miterLimit = o1.miterLimit; - o2.shadowBlur = o1.shadowBlur; - o2.shadowColor = o1.shadowColor; - o2.shadowOffsetX = o1.shadowOffsetX; - o2.shadowOffsetY = o1.shadowOffsetY; - o2.strokeStyle = o1.strokeStyle; - o2.globalAlpha = o1.globalAlpha; - o2.font = o1.font; - o2.textAlign = o1.textAlign; - o2.textBaseline = o1.textBaseline; - o2.arcScaleX_ = o1.arcScaleX_; - o2.arcScaleY_ = o1.arcScaleY_; - o2.lineScale_ = o1.lineScale_; - } - - // var colorData = { - // aliceblue: '#F0F8FF', - // antiquewhite: '#FAEBD7', - // aquamarine: '#7FFFD4', - // azure: '#F0FFFF', - // beige: '#F5F5DC', - // bisque: '#FFE4C4', - // black: '#000000', - // blanchedalmond: '#FFEBCD', - // blueviolet: '#8A2BE2', - // brown: '#A52A2A', - // burlywood: '#DEB887', - // cadetblue: '#5F9EA0', - // chartreuse: '#7FFF00', - // chocolate: '#D2691E', - // coral: '#FF7F50', - // cornflowerblue: '#6495ED', - // cornsilk: '#FFF8DC', - // crimson: '#DC143C', - // cyan: '#00FFFF', - // darkblue: '#00008B', - // darkcyan: '#008B8B', - // darkgoldenrod: '#B8860B', - // darkgray: '#A9A9A9', - // darkgreen: '#006400', - // darkgrey: '#A9A9A9', - // darkkhaki: '#BDB76B', - // darkmagenta: '#8B008B', - // darkolivegreen: '#556B2F', - // darkorange: '#FF8C00', - // darkorchid: '#9932CC', - // darkred: '#8B0000', - // darksalmon: '#E9967A', - // darkseagreen: '#8FBC8F', - // darkslateblue: '#483D8B', - // darkslategray: '#2F4F4F', - // darkslategrey: '#2F4F4F', - // darkturquoise: '#00CED1', - // darkviolet: '#9400D3', - // deeppink: '#FF1493', - // deepskyblue: '#00BFFF', - // dimgray: '#696969', - // dimgrey: '#696969', - // dodgerblue: '#1E90FF', - // firebrick: '#B22222', - // floralwhite: '#FFFAF0', - // forestgreen: '#228B22', - // gainsboro: '#DCDCDC', - // ghostwhite: '#F8F8FF', - // gold: '#FFD700', - // goldenrod: '#DAA520', - // grey: '#808080', - // greenyellow: '#ADFF2F', - // honeydew: '#F0FFF0', - // hotpink: '#FF69B4', - // indianred: '#CD5C5C', - // indigo: '#4B0082', - // ivory: '#FFFFF0', - // khaki: '#F0E68C', - // lavender: '#E6E6FA', - // lavenderblush: '#FFF0F5', - // lawngreen: '#7CFC00', - // lemonchiffon: '#FFFACD', - // lightblue: '#ADD8E6', - // lightcoral: '#F08080', - // lightcyan: '#E0FFFF', - // lightgoldenrodyellow: '#FAFAD2', - // lightgreen: '#90EE90', - // lightgrey: '#D3D3D3', - // lightpink: '#FFB6C1', - // lightsalmon: '#FFA07A', - // lightseagreen: '#20B2AA', - // lightskyblue: '#87CEFA', - // lightslategray: '#778899', - // lightslategrey: '#778899', - // lightsteelblue: '#B0C4DE', - // lightyellow: '#FFFFE0', - // limegreen: '#32CD32', - // linen: '#FAF0E6', - // magenta: '#FF00FF', - // mediumaquamarine: '#66CDAA', - // mediumblue: '#0000CD', - // mediumorchid: '#BA55D3', - // mediumpurple: '#9370DB', - // mediumseagreen: '#3CB371', - // mediumslateblue: '#7B68EE', - // mediumspringgreen: '#00FA9A', - // mediumturquoise: '#48D1CC', - // mediumvioletred: '#C71585', - // midnightblue: '#191970', - // mintcream: '#F5FFFA', - // mistyrose: '#FFE4E1', - // moccasin: '#FFE4B5', - // navajowhite: '#FFDEAD', - // oldlace: '#FDF5E6', - // olivedrab: '#6B8E23', - // orange: '#FFA500', - // orangered: '#FF4500', - // orchid: '#DA70D6', - // palegoldenrod: '#EEE8AA', - // palegreen: '#98FB98', - // paleturquoise: '#AFEEEE', - // palevioletred: '#DB7093', - // papayawhip: '#FFEFD5', - // peachpuff: '#FFDAB9', - // peru: '#CD853F', - // pink: '#FFC0CB', - // plum: '#DDA0DD', - // powderblue: '#B0E0E6', - // rosybrown: '#BC8F8F', - // royalblue: '#4169E1', - // saddlebrown: '#8B4513', - // salmon: '#FA8072', - // sandybrown: '#F4A460', - // seagreen: '#2E8B57', - // seashell: '#FFF5EE', - // sienna: '#A0522D', - // skyblue: '#87CEEB', - // slateblue: '#6A5ACD', - // slategray: '#708090', - // slategrey: '#708090', - // snow: '#FFFAFA', - // springgreen: '#00FF7F', - // steelblue: '#4682B4', - // tan: '#D2B48C', - // thistle: '#D8BFD8', - // tomato: '#FF6347', - // turquoise: '#40E0D0', - // violet: '#EE82EE', - // wheat: '#F5DEB3', - // whitesmoke: '#F5F5F5', - // yellowgreen: '#9ACD32' - // }; - - - function getRgbHslContent(styleString) { - var start = styleString.indexOf('(', 3); - var end = styleString.indexOf(')', start + 1); - var parts = styleString.substring(start + 1, end).split(','); - // add alpha if needed - if (parts.length != 4 || styleString.charAt(3) != 'a') { - parts[3] = 1; - } - return parts; - } - - function percent(s) { - return parseFloat(s) / 100; - } - - function clamp(v, min, max) { - return Math.min(max, Math.max(min, v)); - } - - function hslToRgb(parts) { - var r, g, b, h, s, l; - h = parseFloat(parts[0]) / 360 % 360; - if (h < 0) - h++; - s = clamp(percent(parts[1]), 0, 1); - l = clamp(percent(parts[2]), 0, 1); - if (s == 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1 / 3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1 / 3); - } - - return '#' + decToHex[Math.floor(r * 255)] + - decToHex[Math.floor(g * 255)] + - decToHex[Math.floor(b * 255)]; - } - - function hueToRgb(m1, m2, h) { - if (h < 0) - h++; - if (h > 1) - h--; - - if (6 * h < 1) - return m1 + (m2 - m1) * 6 * h; - else if (2 * h < 1) - return m2; - else if (3 * h < 2) - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - else - return m1; - } - - var processStyleCache = {}; - - function processStyle(styleString) { - if (styleString in processStyleCache) { - return processStyleCache[styleString]; - } - - var str, alpha = 1; - - styleString = String(styleString); - if (styleString.charAt(0) == '#') { - str = styleString; - } else if (/^rgb/.test(styleString)) { - var parts = getRgbHslContent(styleString); - var str = '#', n; - for (var i = 0; i < 3; i++) { - if (parts[i].indexOf('%') != -1) { - n = Math.floor(percent(parts[i]) * 255); - } else { - n = +parts[i]; - } - str += decToHex[clamp(n, 0, 255)]; - } - alpha = +parts[3]; - } else if (/^hsl/.test(styleString)) { - var parts = getRgbHslContent(styleString); - str = hslToRgb(parts); - alpha = parts[3]; - } else { - str = /*colorData[styleString] ||*/styleString; - } - return processStyleCache[styleString] = { color: str, alpha: alpha }; - } - - var DEFAULT_STYLE = { - style: 'normal', - variant: 'normal', - weight: 'normal', - size: 10, - family: 'sans-serif' - }; - - // Internal text style cache - // var fontStyleCache = {}; - - // function processFontStyle(styleString) { - // if (fontStyleCache[styleString]) { - // return fontStyleCache[styleString]; - // } - - // var el = document.createElement('div'); - // var style = el.style; - // try { - // style.font = styleString; - // } catch (ex) { - // // Ignore failures to set to invalid font. - // } - - // return fontStyleCache[styleString] = { - // style: style.fontStyle || DEFAULT_STYLE.style, - // variant: style.fontVariant || DEFAULT_STYLE.variant, - // weight: style.fontWeight || DEFAULT_STYLE.weight, - // size: style.fontSize || DEFAULT_STYLE.size, - // family: style.fontFamily || DEFAULT_STYLE.family - // }; - // } - - // function getComputedStyle(style, element) { - // var computedStyle = {}; - - // for (var p in style) { - // computedStyle[p] = style[p]; - // } - - // // Compute the size - // var canvasFontSize = parseFloat(element.currentStyle.fontSize), - // fontSize = parseFloat(style.size); - - // if (typeof style.size == 'number') { - // computedStyle.size = style.size; - // } else if (style.size.indexOf('px') != -1) { - // computedStyle.size = fontSize; - // } else if (style.size.indexOf('em') != -1) { - // computedStyle.size = canvasFontSize * fontSize; - // } else if(style.size.indexOf('%') != -1) { - // computedStyle.size = (canvasFontSize / 100) * fontSize; - // } else if (style.size.indexOf('pt') != -1) { - // computedStyle.size = fontSize / .75; - // } else { - // computedStyle.size = canvasFontSize; - // } - - // // Different scaling between normal text and VML text. This was found using - // // trial and error to get the same size as non VML text. - // computedStyle.size *= 0.981; - - // return computedStyle; - // } - - // function buildStyle(style) { - // return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + - // style.size + 'px ' + style.family; - // } - - var lineCapMap = { - 'butt': 'flat', - 'round': 'round' - }; - - function processLineCap(lineCap) { - return lineCapMap[lineCap] || 'square'; - } - - /** - * This class implements CanvasRenderingContext2D interface as described by - * the WHATWG. - * @param {HTMLElement} canvasElement The element that the 2D context should - * be associated with - */ - function CanvasRenderingContext2D_(canvasElement) { - this.m_ = createMatrixIdentity(); - - this.mStack_ = []; - this.aStack_ = []; - this.currentPath_ = []; - - // Canvas context properties - this.strokeStyle = '#000'; - this.fillStyle = '#000'; - - this.lineWidth = 1; - this.lineJoin = 'miter'; - this.lineCap = 'butt'; - this.miterLimit = Z * 1; - this.globalAlpha = 1; - //this.font = '10px sans-serif'; - //this.textAlign = 'left'; - //this.textBaseline = 'alphabetic'; - this.canvas = canvasElement; - - var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + - canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; - var el = canvasElement.ownerDocument.createElement('div'); - el.style.cssText = cssText; - canvasElement.appendChild(el); - - var overlayEl = el.cloneNode(false); - // Use a non transparent background. - overlayEl.style.backgroundColor = 'red'; - overlayEl.style.filter = 'alpha(opacity=0)'; - canvasElement.appendChild(overlayEl); - - this.element_ = el; - this.arcScaleX_ = 1; - this.arcScaleY_ = 1; - this.lineScale_ = 1; - } - - var contextPrototype = CanvasRenderingContext2D_.prototype; - contextPrototype.clearRect = function () { - if (this.textMeasureEl_) { - this.textMeasureEl_.removeNode(true); - this.textMeasureEl_ = null; - } - this.element_.innerHTML = ''; - }; - - contextPrototype.beginPath = function () { - // TODO: Branch current matrix so that save/restore has no effect - // as per safari docs. - this.currentPath_ = []; - }; - - contextPrototype.moveTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'moveTo', x: p.x, y: p.y }); - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.lineTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'lineTo', x: p.x, y: p.y }); - - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY) { - var p = getCoords(this, aX, aY); - var cp1 = getCoords(this, aCP1x, aCP1y); - var cp2 = getCoords(this, aCP2x, aCP2y); - bezierCurveTo(this, cp1, cp2, p); - }; - - // Helper function that takes the already fixed cordinates. - function bezierCurveTo(self, cp1, cp2, p) { - self.currentPath_.push({ - type: 'bezierCurveTo', - cp1x: cp1.x, - cp1y: cp1.y, - cp2x: cp2.x, - cp2y: cp2.y, - x: p.x, - y: p.y - }); - self.currentX_ = p.x; - self.currentY_ = p.y; - } - - contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { - // the following is lifted almost directly from - // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes - - var cp = getCoords(this, aCPx, aCPy); - var p = getCoords(this, aX, aY); - - var cp1 = { - x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), - y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) - }; - var cp2 = { - x: cp1.x + (p.x - this.currentX_) / 3.0, - y: cp1.y + (p.y - this.currentY_) / 3.0 - }; - - bezierCurveTo(this, cp1, cp2, p); - }; - - contextPrototype.arc = function (aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise) { - aRadius *= Z; - var arcType = aClockwise ? 'at' : 'wa'; - - var xStart = aX + mc(aStartAngle) * aRadius - Z2; - var yStart = aY + ms(aStartAngle) * aRadius - Z2; - - var xEnd = aX + mc(aEndAngle) * aRadius - Z2; - var yEnd = aY + ms(aEndAngle) * aRadius - Z2; - - // IE won't render arches drawn counter clockwise if xStart == xEnd. - if (xStart == xEnd && !aClockwise) { - xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something - // that can be represented in binary - } - - var p = getCoords(this, aX, aY); - var pStart = getCoords(this, xStart, yStart); - var pEnd = getCoords(this, xEnd, yEnd); - - this.currentPath_.push({ type: arcType, - x: p.x, - y: p.y, - radius: aRadius, - xStart: pStart.x, - yStart: pStart.y, - xEnd: pEnd.x, - yEnd: pEnd.y - }); - - }; - - // contextPrototype.rect = function(aX, aY, aWidth, aHeight) { - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // }; - - // contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.stroke(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.fill(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { - // var gradient = new CanvasGradient_('gradient'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // return gradient; - // }; - - // contextPrototype.createRadialGradient = function(aX0, aY0, aR0, - // aX1, aY1, aR1) { - // var gradient = new CanvasGradient_('gradientradial'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.r0_ = aR0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // gradient.r1_ = aR1; - // return gradient; - // }; - - // contextPrototype.drawImage = function(image, var_args) { - // var dx, dy, dw, dh, sx, sy, sw, sh; - - // // to find the original width we overide the width and height - // var oldRuntimeWidth = image.runtimeStyle.width; - // var oldRuntimeHeight = image.runtimeStyle.height; - // image.runtimeStyle.width = 'auto'; - // image.runtimeStyle.height = 'auto'; - - // // get the original size - // var w = image.width; - // var h = image.height; - - // // and remove overides - // image.runtimeStyle.width = oldRuntimeWidth; - // image.runtimeStyle.height = oldRuntimeHeight; - - // if (arguments.length == 3) { - // dx = arguments[1]; - // dy = arguments[2]; - // sx = sy = 0; - // sw = dw = w; - // sh = dh = h; - // } else if (arguments.length == 5) { - // dx = arguments[1]; - // dy = arguments[2]; - // dw = arguments[3]; - // dh = arguments[4]; - // sx = sy = 0; - // sw = w; - // sh = h; - // } else if (arguments.length == 9) { - // sx = arguments[1]; - // sy = arguments[2]; - // sw = arguments[3]; - // sh = arguments[4]; - // dx = arguments[5]; - // dy = arguments[6]; - // dw = arguments[7]; - // dh = arguments[8]; - // } else { - // throw Error('Invalid number of arguments'); - // } - - // var d = getCoords(this, dx, dy); - - // var w2 = sw / 2; - // var h2 = sh / 2; - - // var vmlStr = []; - - // var W = 10; - // var H = 10; - - // // For some reason that I've now forgotten, using divs didn't work - // vmlStr.push(' ' , - // '', - // ''); - - // this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); - // }; - - contextPrototype.stroke = function (aFill) { - var lineStr = []; - var lineOpen = false; - - var W = 10; - var H = 10; - - lineStr.push(''); - - if (!aFill) { - appendStroke(this, lineStr); - } else { - appendFill(this, lineStr, min, max); - } - - lineStr.push(''); - - this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - }; - - function appendStroke(ctx, lineStr) { - var a = processStyle(ctx.strokeStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - var lineWidth = ctx.lineScale_ * ctx.lineWidth; - - // VML cannot correctly render a line if the width is less than 1px. - // In that case, we dilute the color to make the line look thinner. - if (lineWidth < 1) { - opacity *= lineWidth; - } - - lineStr.push( - '' - ); - } - - function appendFill(ctx, lineStr, min, max) { - var fillStyle = ctx.fillStyle; - var arcScaleX = ctx.arcScaleX_; - var arcScaleY = ctx.arcScaleY_; - var width = max.x - min.x; - var height = max.y - min.y; - // if (fillStyle instanceof CanvasGradient_) { - // // TODO: Gradients transformed with the transformation matrix. - // var angle = 0; - // var focus = {x: 0, y: 0}; - - // // additional offset - // var shift = 0; - // // scale factor for offset - // var expansion = 1; - - // if (fillStyle.type_ == 'gradient') { - // var x0 = fillStyle.x0_ / arcScaleX; - // var y0 = fillStyle.y0_ / arcScaleY; - // var x1 = fillStyle.x1_ / arcScaleX; - // var y1 = fillStyle.y1_ / arcScaleY; - // var p0 = getCoords(ctx, x0, y0); - // var p1 = getCoords(ctx, x1, y1); - // var dx = p1.x - p0.x; - // var dy = p1.y - p0.y; - // angle = Math.atan2(dx, dy) * 180 / Math.PI; - - // // The angle should be a non-negative number. - // if (angle < 0) { - // angle += 360; - // } - - // // Very small angles produce an unexpected result because they are - // // converted to a scientific notation string. - // if (angle < 1e-6) { - // angle = 0; - // } - // } else { - // var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); - // focus = { - // x: (p0.x - min.x) / width, - // y: (p0.y - min.y) / height - // }; - - // width /= arcScaleX * Z; - // height /= arcScaleY * Z; - // var dimension = m.max(width, height); - // shift = 2 * fillStyle.r0_ / dimension; - // expansion = 2 * fillStyle.r1_ / dimension - shift; - // } - - // // We need to sort the color stops in ascending order by offset, - // // otherwise IE won't interpret it correctly. - // var stops = fillStyle.colors_; - // stops.sort(function(cs1, cs2) { - // return cs1.offset - cs2.offset; - // }); - - // var length = stops.length; - // var color1 = stops[0].color; - // var color2 = stops[length - 1].color; - // var opacity1 = stops[0].alpha * ctx.globalAlpha; - // var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; - - // var colors = []; - // for (var i = 0; i < length; i++) { - // var stop = stops[i]; - // colors.push(stop.offset * expansion + shift + ' ' + stop.color); - // } - - // // When colors attribute is used, the meanings of opacity and o:opacity2 - // // are reversed. - // lineStr.push(''); - // } else if (fillStyle instanceof CanvasPattern_) { - // if (width && height) { - // var deltaLeft = -min.x; - // var deltaTop = -min.y; - // lineStr.push(''); - // } - // } else { - var a = processStyle(ctx.fillStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - lineStr.push(''); - // } - } - - contextPrototype.fill = function () { - this.stroke(true); - }; - - contextPrototype.closePath = function () { - this.currentPath_.push({ type: 'close' }); - }; - - function getCoords(ctx, aX, aY) { - var m = ctx.m_; - return { - x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, - y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 - }; - }; - - contextPrototype.save = function () { - var o = {}; - copyState(this, o); - this.aStack_.push(o); - this.mStack_.push(this.m_); - this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); - }; - - contextPrototype.restore = function () { - if (this.aStack_.length) { - copyState(this.aStack_.pop(), this); - this.m_ = this.mStack_.pop(); - } - }; - - function matrixIsFinite(m) { - return isFinite(m[0][0]) && isFinite(m[0][1]) && - isFinite(m[1][0]) && isFinite(m[1][1]) && - isFinite(m[2][0]) && isFinite(m[2][1]); - } - - function setM(ctx, m, updateLineScale) { - if (!matrixIsFinite(m)) { - return; - } - ctx.m_ = m; - - if (updateLineScale) { - // Get the line scale. - // Determinant of this.m_ means how much the area is enlarged by the - // transformation. So its square root can be used as a scale factor - // for width. - var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; - ctx.lineScale_ = sqrt(abs(det)); - } - } - - contextPrototype.translate = function (aX, aY) { - var m1 = [ - [1, 0, 0], - [0, 1, 0], - [aX, aY, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), false); - }; - - // contextPrototype.rotate = function(aRot) { - // var c = mc(aRot); - // var s = ms(aRot); - - // var m1 = [ - // [c, s, 0], - // [-s, c, 0], - // [0, 0, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), false); - // }; - - contextPrototype.scale = function (aX, aY) { - this.arcScaleX_ *= aX; - this.arcScaleY_ *= aY; - var m1 = [ - [aX, 0, 0], - [0, aY, 0], - [0, 0, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), true); - }; - - // contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { - // var m1 = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), true); - // }; - - // contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { - // var m = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, m, true); - // }; - - /** - * The text drawing function. - * The maxWidth argument isn't taken in account, since no browser supports - * it yet. - */ - // contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { - // var m = this.m_, - // delta = 1000, - // left = 0, - // right = delta, - // offset = {x: 0, y: 0}, - // lineStr = []; - - // var fontStyle = getComputedStyle(processFontStyle(this.font), - // this.element_); - - // var fontStyleString = buildStyle(fontStyle); - - // var elementStyle = this.element_.currentStyle; - // var textAlign = this.textAlign.toLowerCase(); - // switch (textAlign) { - // case 'left': - // case 'center': - // case 'right': - // break; - // case 'end': - // textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; - // break; - // case 'start': - // textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; - // break; - // default: - // textAlign = 'left'; - // } - - // // 1.75 is an arbitrary number, as there is no info about the text baseline - // switch (this.textBaseline) { - // case 'hanging': - // case 'top': - // offset.y = fontStyle.size / 1.75; - // break; - // case 'middle': - // break; - // default: - // case null: - // case 'alphabetic': - // case 'ideographic': - // case 'bottom': - // offset.y = -fontStyle.size / 2.25; - // break; - // } - - // switch(textAlign) { - // case 'right': - // left = delta; - // right = 0.05; - // break; - // case 'center': - // left = right = delta / 2; - // break; - // } - - // var d = getCoords(this, x + offset.x, y + offset.y); - - // lineStr.push(''); - - // if (stroke) { - // appendStroke(this, lineStr); - // } else { - // // TODO: Fix the min and max params. - // appendFill(this, lineStr, {x: -left, y: 0}, - // {x: right, y: fontStyle.size}); - // } - - // var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + - // m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; - - // var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); - - // lineStr.push('', - // '', - // ''); - - // this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - // }; - - // contextPrototype.fillText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, false); - // }; - - // contextPrototype.strokeText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, true); - // }; - - // contextPrototype.measureText = function(text) { - // if (!this.textMeasureEl_) { - // var s = ''; - // this.element_.insertAdjacentHTML('beforeEnd', s); - // this.textMeasureEl_ = this.element_.lastChild; - // } - // var doc = this.element_.ownerDocument; - // this.textMeasureEl_.innerHTML = ''; - // this.textMeasureEl_.style.font = this.font; - // // Don't use innerHTML or innerText because they allow markup/whitespace. - // this.textMeasureEl_.appendChild(doc.createTextNode(text)); - // return {width: this.textMeasureEl_.offsetWidth}; - // }; - - /******** STUBS ********/ - // contextPrototype.clip = function() { - // // TODO: Implement - // }; - - // contextPrototype.arcTo = function() { - // // TODO: Implement - // }; - - // contextPrototype.createPattern = function(image, repetition) { - // return new CanvasPattern_(image, repetition); - // }; - - // // Gradient / Pattern Stubs - // function CanvasGradient_(aType) { - // this.type_ = aType; - // this.x0_ = 0; - // this.y0_ = 0; - // this.r0_ = 0; - // this.x1_ = 0; - // this.y1_ = 0; - // this.r1_ = 0; - // this.colors_ = []; - // } - - // CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { - // aColor = processStyle(aColor); - // this.colors_.push({offset: aOffset, - // color: aColor.color, - // alpha: aColor.alpha}); - // }; - - // function CanvasPattern_(image, repetition) { - // assertImageIsValid(image); - // switch (repetition) { - // case 'repeat': - // case null: - // case '': - // this.repetition_ = 'repeat'; - // break - // case 'repeat-x': - // case 'repeat-y': - // case 'no-repeat': - // this.repetition_ = repetition; - // break; - // default: - // throwException('SYNTAX_ERR'); - // } - - // this.src_ = image.src; - // this.width_ = image.width; - // this.height_ = image.height; - // } - - function throwException(s) { - throw new DOMException_(s); - } - - // function assertImageIsValid(img) { - // if (!img || img.nodeType != 1 || img.tagName != 'IMG') { - // throwException('TYPE_MISMATCH_ERR'); - // } - // if (img.readyState != 'complete') { - // throwException('INVALID_STATE_ERR'); - // } - // } - - function DOMException_(s) { - this.code = this[s]; - this.message = s + ': DOM Exception ' + this.code; - } - var p = DOMException_.prototype = new Error; - p.INDEX_SIZE_ERR = 1; - p.DOMSTRING_SIZE_ERR = 2; - p.HIERARCHY_REQUEST_ERR = 3; - p.WRONG_DOCUMENT_ERR = 4; - p.INVALID_CHARACTER_ERR = 5; - p.NO_DATA_ALLOWED_ERR = 6; - p.NO_MODIFICATION_ALLOWED_ERR = 7; - p.NOT_FOUND_ERR = 8; - p.NOT_SUPPORTED_ERR = 9; - p.INUSE_ATTRIBUTE_ERR = 10; - p.INVALID_STATE_ERR = 11; - p.SYNTAX_ERR = 12; - p.INVALID_MODIFICATION_ERR = 13; - p.NAMESPACE_ERR = 14; - p.INVALID_ACCESS_ERR = 15; - p.VALIDATION_ERR = 16; - p.TYPE_MISMATCH_ERR = 17; - - // set up externs - G_vmlCanvasManager = G_vmlCanvasManager_; - CanvasRenderingContext2D = CanvasRenderingContext2D_; - //CanvasGradient = CanvasGradient_; - //CanvasPattern = CanvasPattern_; - DOMException = DOMException_; - })(); - -} // if - -/*! JsRender v1.0pre: http://github.com/BorisMoore/jsrender */ -/* - * Optimized version of jQuery Templates, for rendering to string. - * Does not require jQuery, or HTML DOM - * Integrates with JsViews (http://github.com/BorisMoore/jsviews) - * Copyright 2012, Boris Moore - * Released under the MIT License. - */ -// informal pre beta commit counter: 3 - -this.jsviews || this.jQuery && jQuery.views || (function( window, undefined ) { - -//========================== Top-level vars ========================== - -var versionNumber = "v1.0pre", - - $, rTag, rTmplString, extend, - sub = {}, - FALSE = false, TRUE = true, - jQuery = window.jQuery, - - rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // nil object helper view viewProperty pathTokens leafToken string - - rParams = /(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - - rNewLine = /\r?\n/g, - rUnescapeQuotes = /\\(['"])/g, - rEscapeQuotes = /\\?(['"])/g, - rBuildHash = /\x08(~)?([^\x08]+)\x08/g, - - autoViewKey = 0, - autoTmplName = 0, - escapeMapForHtml = { - "&": "&", - "<": "<", - ">": ">" - }, - tmplAttr = "data-jsv-tmpl", - fnDeclStr = "var j=j||" + (jQuery ? "jQuery." : "js") + "views,", - htmlSpecialChar = /[\x00"&'<>]/g, - slice = Array.prototype.slice, - - render = {}, - - // jsviews object ($.views if jQuery is loaded) - jsv = { - jsviews: versionNumber, - sub: sub, // subscription, e.g. JsViews integration - debugMode: TRUE, - err: function( e ) { - return jsv.debugMode ? ("
                                  Error: " + (e.message || e) + ". ") : '""'; - }, - tmplFn: tmplFn, - render: render, - templates: templates, - tags: tags, - helpers: helpers, - converters: converters, - View: View, - convert: convert, - delimiters: setDelimiters, - tag: renderTag - }; - -//========================== Top-level functions ========================== - -//=================== -// jsviews.delimiters -//=================== - -function setDelimiters( openChars, closeChars ) { - // Set the tag opening and closing delimiters. Default is "{{" and "}}" - // openChar, closeChars: opening and closing strings, each with two characters - var firstOpenChar = "\\" + openChars.charAt( 0 ), // Escape the characters - since they could be regex special characters - secondOpenChar = "\\" + openChars.charAt( 1 ), - firstCloseChar = "\\" + closeChars.charAt( 0 ), - secondCloseChar = "\\" + closeChars.charAt( 1 ); - // Build regex with new delimiters - jsv.rTag = rTag // make rTag available to JsViews (or other components) for parsing binding expressions - = secondOpenChar - // tag (followed by / space or }) or colon or html or code - + "(?:(?:(\\w+(?=[\\/\\s" + firstCloseChar + "]))|(?:(\\w+)?(:)|(>)|(\\*)))" - // params - + "\\s*((?:[^" + firstCloseChar + "]|" + firstCloseChar + "(?!" + secondCloseChar + "))*?)" - // slash or closeBlock - + "(\\/)?|(?:\\/(\\w+)))" - // }} - + firstCloseChar; - - // Default rTag: tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/\s\}]))|(?:(\w+)?(:)|(>)|(\*)))\s*((?:[^}]|}(?!\}))*?)(\/)?|(?:\/(\w+)))}} - - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - rTag = new RegExp( firstOpenChar + rTag + secondCloseChar, "g" ); - rTmplString = new RegExp( "<.*>|" + openChars + ".*" + closeChars ); - return this; -} - -//================= -// View.hlp -//================= - -function getHelper( helper ) { - // Helper method called as view.hlp() from compiled template, for helper functions or template parameters ~foo - var view = this, - tmplHelpers = view.tmpl.helpers || {}; - helper = (view.ctx[ helper ] !== undefined ? view.ctx : tmplHelpers[ helper ] !== undefined ? tmplHelpers : helpers[ helper ] !== undefined ? helpers : {})[ helper ]; - return typeof helper !== "function" ? helper : function() { - return helper.apply(view, arguments); - }; -} - -//================= -// jsviews.convert -//================= - -function convert( converter, view, text ) { - var tmplConverters = view.tmpl.converters; - converter = tmplConverters && tmplConverters[ converter ] || converters[ converter ]; - return converter ? converter.call( view, text ) : text; -} - -//================= -// jsviews.tag -//================= - -function renderTag( tag, parentView, converter, content, tagObject ) { - // Called from within compiled template function, to render a nested tag - // Returns the rendered tag - tagObject.props = tagObject.props || {}; - var ret, - tmpl = tagObject.props.tmpl, - tmplTags = parentView.tmpl.tags, - nestedTemplates = parentView.tmpl.templates, - args = arguments, - tagFn = tmplTags && tmplTags[ tag ] || tags[ tag ]; - - if ( !tagFn ) { - return ""; - } - // Set the tmpl property to the content of the block tag, unless set as an override property on the tag - content = content && parentView.tmpl.tmpls[ content - 1 ]; - tmpl = tmpl || content || undefined; - tagObject.tmpl = - "" + tmpl === tmpl // if a string - ? nestedTemplates && nestedTemplates[ tmpl ] || templates[ tmpl ] || templates( tmpl ) - : tmpl; - - tagObject.isTag = TRUE; - tagObject.converter = converter; - tagObject.view = parentView; - tagObject.renderContent = renderContent; - if ( parentView.ctx ) { - extend( tagObject.ctx, parentView.ctx); - } - - ret = tagFn.apply( tagObject, args.length > 5 ? slice.call( args, 5 ) : [] ); - return ret || ( ret == undefined ? "" : ret.toString()); // (If ret is the value 0 or false, will render to string) -} - -//================= -// View constructor -//================= - -function View( context, path, parentView, data, template, index ) { - // Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded) - var views = parentView.views, -// TODO: add this, as part of smart re-linking on existing content ($.link method), or remove completely -// self = parentView.views[ index ]; -// if ( !self ) { ... } - self = { - tmpl: template, - path: path, - parent: parentView, - data: data, - ctx: context, - views: $.isArray( data ) ? [] : {}, - hlp: getHelper - }; - - if ( $.isArray( views )) { - views.splice( - self.index = index !== undefined - ? index - : views.length, 0, self - ); - } else { - views[ self.index = "_" + autoViewKey++ ] = self; - } - return self; -} - -//================= -// Registration -//================= - -function addToStore( self, store, name, item, process ) { - // Add item to named store such as templates, helpers, converters... - var key, onStore; - if ( name && typeof name === "object" && !name.nodeType ) { - // If name is a map, iterate over map and call store for key - for ( key in name ) { - store( key, name[ key ]); - } - return self; - } - if ( !name || item === undefined ) { - if ( process ) { - item = process( undefined, item || name ); - } - } else if ( "" + name === name ) { // name must be a string - if ( item === null ) { - // If item is null, delete this entry - delete store[name]; - } else if ( item = process ? process( name, item ) : item ) { - store[ name ] = item; - } - } - if ( onStore = sub.onStoreItem ) { - // e.g. JsViews integration - onStore( store, name, item, process ); - } - return item; -} - -function templates( name, tmpl ) { - // Register templates - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, templates, name, tmpl, compile ); -} - -function tags( name, tagFn ) { - // Register template tags - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, tags, name, tagFn ); -} - -function helpers( name, helperFn ) { - // Register helper functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.helpers( name, helperFn ) or $.view.helpers({ name: helperFn, ... }) to add additional helpers to the registered helpers collection. - // Getter: Use var helperFn = $.views.helpers( name ) or $.views.helpers[name] or $.views.helpers.name to return the function. - // Remove: Use $.view.helpers( name, null ) to remove a registered helper function from $.view.helpers. - // Within a template, access the helper using the syntax: {{... ~myHelper(...) ...}}. - return addToStore( this, helpers, name, helperFn ); -} - -function converters( name, converterFn ) { - // Register converter functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.converters( name, converterFn ) or $.view.converters({ name: converterFn, ... }) to add additional converters to the registered converters collection. - // Getter: Use var converterFn = $.views.converters( name ) or $.views.converters[name] or $.views.converters.name to return the converter function. - // Remove: Use $.view.converters( name, null ) to remove a registered converter from $.view.converters. - // Within a template, access the converter using the syntax: {{myConverter:...}}. - return addToStore( this, converters, name, converterFn ); -} - -//================= -// renderContent -//================= - -function renderContent( data, context, parentView, path, index ) { - // Render template against data as a tree of subviews (nested template), or as a string (top-level template). - // tagName parameter for internal use only. Used for rendering templates registered as tags (which may have associated presenter objects) - var i, l, dataItem, newView, itemWrap, itemsWrap, itemResult, parentContext, tmpl, layout, - props = {}, - swapContent = index === TRUE, - self = this, - result = ""; - - if ( self.isTag ) { - // This is a call from renderTag - tmpl = self.tmpl; - context = context || self.ctx; - parentView = parentView || self.view; - path = path || self.path; - index = index || self.index; - props = self.props; - } else { - tmpl = self.jquery && self[0] // This is a call $.fn.render - || self; // This is a call from tmpl.render - } - parentView = parentView || jsv.topView; - parentContext = parentView.ctx; - layout = tmpl.layout; - if ( data === parentView ) { - // Inherit the data from the parent view. - // This may be the contents of an {{if}} block - data = parentView.data; - layout = TRUE; - } - - // Set additional context on views created here, (as modified context inherited from the parent, and be inherited by child views) - // Note: If no jQuery, extend does not support chained copies - so limit extend() to two parameters - context = (context && context === parentContext) - ? parentContext - : (parentContext - // if parentContext, make copy - ? ((parentContext = extend( {}, parentContext ), context) - // If context, merge context with copied parentContext - ? extend( parentContext, context ) - : parentContext) - // if no parentContext, use context, or default to {} - : context || {}); - - if ( props.link === FALSE ) { - // Override inherited value of link by an explicit setting in props: link=false - // The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect. - context.link = FALSE; - } - if ( !tmpl.fn ) { - tmpl = templates[ tmpl ] || templates( tmpl ); - } - itemWrap = context.link && sub.onRenderItem; - itemsWrap = context.link && sub.onRenderItems; - - if ( tmpl ) { - if ( $.isArray( data ) && !layout ) { - // Create a view for the array, whose child views correspond to each data item. - // (Note: if index and parentView are passed in along with parent view, treat as - // insert -e.g. from view.addViews - so parentView is already the view item for array) - newView = swapContent ? parentView : (index !== undefined && parentView) || View( context, path, parentView, data, tmpl, index ); - - for ( i = 0, l = data.length; i < l; i++ ) { - // Create a view for each data item. - dataItem = data[ i ]; - itemResult = tmpl.fn( dataItem, View( context, path, newView, dataItem, tmpl, (index||0) + i ), jsv ); - result += itemWrap ? itemWrap( itemResult, props ) : itemResult; - } - } else { - // Create a view for singleton data object. - newView = swapContent ? parentView : View( context, path, parentView, data, tmpl, index ); - result += (data || layout) ? tmpl.fn( data, newView, jsv ) : ""; - } - parentView.topKey = newView.index; - return itemsWrap ? itemsWrap( result, path, newView.index, tmpl, props ) : result; - } - return ""; // No tmpl. Could throw... -} - -//=========================== -// Build and compile template -//=========================== - -// Generate a reusable function that will serve to render a template against data -// (Compile AST then build template function) - -function syntaxError() { - throw "Syntax error"; -} - -function tmplFn( markup, tmpl, bind ) { - // Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes - // Used for compiling templates, and also by JsViews to build functions for data link expressions - var newNode, node, i, l, code, hasTag, hasEncoder, getsValue, hasConverter, hasViewPath, tag, converter, params, hash, nestedTmpl, allowCode, - tmplOptions = tmpl ? { - allowCode: allowCode = tmpl.allowCode, - debug: tmpl.debug - } : {}, - nested = tmpl && tmpl.tmpls, - astTop = [], - loc = 0, - stack = [], - content = astTop, - current = [,,,astTop], - nestedIndex = 0; - - //==== nested functions ==== - function pushPreceedingContent( shift ) { - shift -= loc; - if ( shift ) { - content.push( markup.substr( loc, shift ).replace( rNewLine, "\\n" )); - } - } - - function parseTag( all, tagName, converter, colon, html, code, params, slash, closeBlock, index ) { - // tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(?:(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - // Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, contentMarkup ] - if ( html ) { - colon = ":"; - converter = "html"; - } - var hash = "", - passedCtx = "", - block = !slash && !colon; // Block tag if not self-closing and not {{:}} or {{>}} (special case) - - //==== nested helper function ==== - - tagName = tagName || colon; - pushPreceedingContent( index ); - loc = index + all.length; // location marker - parsed up to here - if ( code ) { - if ( allowCode ) { - content.push([ "*", params.replace( rUnescapeQuotes, "$1" ) ]); - } - } else if ( tagName ) { - if ( tagName === "else" ) { - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - content = current[ 3 ]; - block = TRUE; - } - params = (params - ? parseParams( params, bind ) - .replace( rBuildHash, function( all, isCtx, keyValue ) { - if ( isCtx ) { - passedCtx += keyValue + ","; - } else { - hash += keyValue + ","; - } - return ""; - }) - : ""); - hash = hash.slice( 0, -1 ); - params = params.slice( 0, -1 ); - newNode = [ - tagName, - converter || "", - params, - block && [], - "{" + (hash ? ("props:{" + hash + "},"): "") + "path:'" + params + "'" + (passedCtx ? ",ctx:{" + passedCtx.slice( 0, -1 ) + "}" : "") + "}" - ]; - if ( block ) { - stack.push( current ); - current = newNode; - current[ 5 ] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag - } - content.push( newNode ); - } else if ( closeBlock ) { - //if ( closeBlock !== current[ 0 ]) { - // throw "unmatched close tag: /" + closeBlock + ". Expected /" + current[ 0 ]; - //} - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - } - if ( !current ) { - throw "Expected block tag"; - } - content = current[ 3 ]; - } - //==== /end of nested functions ==== - - markup = markup.replace( rEscapeQuotes, "\\$1" ); - - // Build the AST (abstract syntax tree) under astTop - markup.replace( rTag, parseTag ); - - pushPreceedingContent( markup.length ); - - // Use the AST (astTop) to build the template function - l = astTop.length; - code = (l ? "" : '"";'); - - for ( i = 0; i < l; i++ ) { - // AST nodes: [ tagName, converter, params, content, hash, contentMarkup ] - node = astTop[ i ]; - if ( node[ 0 ] === "*" ) { - code = code.slice( 0, i ? -1 : -3 ) + ";" + node[ 1 ] + (i + 1 < l ? "ret+=" : ""); - } else if ( "" + node === node ) { // type string - code += '"' + node + '"+'; - } else { - tag = node[ 0 ]; - converter = node[ 1 ]; - params = node[ 2 ]; - content = node[ 3 ]; - hash = node[ 4 ]; - markup = node[ 5 ]; - if ( content ) { - // Create template object for nested template - nestedTmpl = TmplObject( markup, tmplOptions, tmpl, nestedIndex++ ); - // Compile to AST and then to compiled function - tmplFn( markup, nestedTmpl); - nested.push( nestedTmpl ); - } - hasViewPath = hasViewPath || hash.indexOf( "view" ) > -1; - code += (tag === ":" - ? (converter === "html" - ? (hasEncoder = TRUE, "e(" + params) - : converter - ? (hasConverter = TRUE, 'c("' + converter + '",view,' + params) - : (getsValue = TRUE, "((v=" + params + ')!=u?v:""') - ) - : (hasTag = TRUE, 't("' + tag + '",view,"' + (converter || "") + '",' - + (content ? nested.length : '""') // For block tags, pass in the key (nested.length) to the nested content template - + "," + hash + (params ? "," : "") + params)) - + ")+"; - } - } - code = new Function( "data, view, j, b, u", fnDeclStr - + (getsValue ? "v," : "") - + (hasTag ? "t=j.tag," : "") - + (hasConverter ? "c=j.convert," : "") - + (hasEncoder ? "e=j.converters.html," : "") - + "ret; try{\n\n" - + (tmplOptions.debug ? "debugger;" : "") - + (allowCode ? 'ret=' : 'return ') - + code.slice( 0, -1 ) + ";\n\n" - + (allowCode ? "return ret;" : "") - + "}catch(e){return j.err(e);}" - ); - - // Include only the var references that are needed in the code - if ( tmpl ) { - tmpl.fn = code; - tmpl.useVw = hasConverter || hasViewPath || hasTag; - } - return code; -} - -function parseParams( params, bind ) { - var named, - fnCall = {}, - parenDepth = 0, - quoted = FALSE, // boolean for string content in double quotes - aposed = FALSE; // or in single quotes - - function parseTokens( all, lftPrn0, lftPrn, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, prn2, space ) { - // rParams = /(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn path operator err eq path2 prn comma lftPrn3 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - operator = operator || ""; - lftPrn = lftPrn || lftPrn0 || lftPrn2; - path = path || path2; - prn = prn || prn2 || ""; - operator = operator || ""; - - function parsePath( all, object, helper, view, viewProperty, pathTokens, leafToken ) { - // rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // object helper view viewProperty pathTokens leafToken string - if ( object ) { - var ret = (helper - ? 'view.hlp("' + helper + '")' - : view - ? "view" - : "data") - + (leafToken - ? (viewProperty - ? "." + viewProperty - : helper - ? "" - : (view ? "" : "." + object) - ) + (pathTokens || "") - : (leafToken = helper ? "" : view ? viewProperty || "" : object, "")); - - if ( bind && prn !== "(" ) { - ret = "b(" + ret + ',"' + leafToken + '")'; - } - return ret + (leafToken ? "." + leafToken : ""); - } - return all; - } - - if ( err ) { - syntaxError(); - } else { - return (aposed - // within single-quoted string - ? (aposed = !apos, (aposed ? all : '"')) - : quoted - // within double-quoted string - ? (quoted = !quot, (quoted ? all : '"')) - : - ( - (lftPrn - ? (parenDepth++, lftPrn) - : "") - + (space - ? (parenDepth - ? "" - : named - ? (named = FALSE, "\b") - : "," - ) - : eq - // named param - ? (parenDepth && syntaxError(), named = TRUE, '\b' + path + ':') - : path - // path - ? (path.replace( rPath, parsePath ) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : operator) - ) - : operator - ? all - : rtPrn - // function - ? ((fnCall[ parenDepth-- ] = FALSE, rtPrn) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : "") - ) - : comma - ? (fnCall[ parenDepth ] || syntaxError(), ",") // We don't allow top-level literal arrays or objects - : lftPrn0 - ? "" - : (aposed = apos, quoted = quot, '"') - )) - ); - } - } - params = (params + " " ).replace( rParams, parseTokens ); - return params; -} - -function compile( name, tmpl, parent, options ) { - // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object - // options is the set of template properties, c - var tmplOrMarkup, elem, key, nested, nestedItem; - - //==== nested functions ==== - function tmplOrMarkupFromStr( value ) { - // If value is of type string - treat as selector, or name of compiled template - // Return the template object, if already compiled, or the markup string - - if ( ("" + value === value) || value.nodeType > 0 ) { - // If selector is valid and returns at least one element, get first element - elem = value.nodeType > 0 ? value : !rTmplString.test( value ) && jQuery && jQuery( value )[0]; - if ( elem && elem.type ) { - // It is a script element - // Create a name for data linking if none provided - value = templates[ elem.getAttribute( tmplAttr )]; - if ( !value ) { - // Not already compiled and cached, so compile and cache the name - name = name || "_" + autoTmplName++; - elem.setAttribute( tmplAttr, name ); - value = compile( name, elem.innerHTML, parent, options ); // Use tmpl as options - templates[ name ] = value; - } - } - return value; - } - // If value is not a string or dom element, return undefined - } - - //==== Compile the template ==== - tmplOrMarkup = tmplOrMarkupFromStr( tmpl ); - - // If tmpl is a template object, use it for options - options = options || (tmpl.markup ? tmpl : {}); - options.name = name; - nested = options.templates; - - // If tmpl is not a markup string or a selector string, then it must be a template object - // In that case, get it from the markup property of the object - if ( !tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr( tmpl.markup ))) { - if ( tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode )) { - // if the string references a compiled template object, but the debug or allowCode props are different, need to recompile - tmplOrMarkup = tmplOrMarkup.markup; - } - } - if ( tmplOrMarkup !== undefined ) { - if ( name && !parent ) { - render[ name ] = function() { - return tmpl.render.apply( tmpl, arguments ); - }; - } - if ( tmplOrMarkup.fn || tmpl.fn ) { - // tmpl is already compiled, so use it, or if different name is provided, clone it - if ( tmplOrMarkup.fn ) { - if ( name && name !== tmplOrMarkup.name ) { - tmpl = extend( extend( {}, tmplOrMarkup ), options); - } else { - tmpl = tmplOrMarkup; - } - } - } else { - // tmplOrMarkup is a markup string, not a compiled template - // Create template object - tmpl = TmplObject( tmplOrMarkup, options, parent, 0 ); - // Compile to AST and then to compiled function - tmplFn( tmplOrMarkup, tmpl ); - } - for ( key in nested ) { - // compile nested template declarations - nestedItem = nested[ key ]; - if ( nestedItem.name !== key ) { - nested[ key ] = compile( key, nestedItem, tmpl ); - } - } - return tmpl; - } -} -//==== /end of function compile ==== - -function TmplObject( markup, options, parent, index ) { - // Template object constructor - - // nested helper function - function extendStore( storeName ) { - if ( parent[ storeName ]) { - // Include parent items except if overridden by item of same name in options - tmpl[ storeName ] = extend( extend( {}, parent[ storeName ] ), options[ storeName ] ); - } - } - - options = options || {}; - var tmpl = { - markup: markup, - tmpls: [], - links: [], - render: renderContent - }; - if ( parent ) { - if ( parent.templates ) { - tmpl.templates = extend( extend( {}, parent.templates ), options.templates ); - } - tmpl.parent = parent; - tmpl.name = parent.name + "[" + index + "]"; - tmpl.index = index; - } - - extend( tmpl, options ); - if ( parent ) { - extendStore( "templates" ); - extendStore( "tags" ); - extendStore( "helpers" ); - extendStore( "converters" ); - } - return tmpl; -} - -//========================== Initialize ========================== - -if ( jQuery ) { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is loaded, so make $ the jQuery object - $ = jQuery; - $.templates = templates; - $.render = render; - $.views = jsv; - $.fn.render = renderContent; - -} else { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is not loaded. - - $ = window.jsviews = jsv; - $.extend = function( target, source ) { - var name; - target = target || {}; - for ( name in source ) { - target[ name ] = source[ name ]; - } - return target; - }; - - $.isArray = Array && Array.isArray || function( obj ) { - return Object.prototype.toString.call( obj ) === "[object Array]"; - }; -} - -extend = $.extend; - -jsv.topView = { views: {}, tmpl: {}, hlp: getHelper, ctx: jsv.helpers }; - -function replacerForHtml( ch ) { - // Original code from Mike Samuel - return escapeMapForHtml[ ch ] - // Intentional assignment that caches the result of encoding ch. - || (escapeMapForHtml[ ch ] = "&#" + ch.charCodeAt( 0 ) + ";"); -} - -//========================== Register tags ========================== - -tags({ - "if": function() { - var ifTag = this, - view = ifTag.view; - - view.onElse = function( tagObject, args ) { - var i = 0, - l = args.length; - - while ( l && !args[ i++ ]) { - // Only render content if args.length === 0 (i.e. this is an else with no condition) or if a condition argument is truey - if ( i === l ) { - return ""; - } - } - view.onElse = undefined; // If condition satisfied, so won't run 'else'. - tagObject.path = ""; - return tagObject.renderContent( view ); - // Test is satisfied, so render content, while remaining in current data context - // By passing the view, we inherit data context from the parent view, and the content is treated as a layout template - // (so if the data is an array, it will not iterate over the data - }; - return view.onElse( this, arguments ); - }, - "else": function() { - var view = this.view; - return view.onElse ? view.onElse( this, arguments ) : ""; - }, - "for": function() { - var i, - self = this, - result = "", - args = arguments, - l = args.length; - if ( self.props.layout ) { - self.tmpl.layout = TRUE; - } - for ( i = 0; i < l; i++ ) { - result += self.renderContent( args[ i ]); - } - return result; - }, - "=": function( value ) { - return value; - }, - "*": function( value ) { - return value; - } -}); - -//========================== Register global helpers ========================== - -// helpers({ // Global helper functions -// // TODO add any useful built-in helper functions -// }); - -//========================== Register converters ========================== - -converters({ - html: function( text ) { - // HTML encoding helper: Replace < > & and ' and " by corresponding entities. - // inspired by Mike Samuel - return text != undefined ? String( text ).replace( htmlSpecialChar, replacerForHtml ) : ""; - } -}); - -//========================== Define default delimiters ========================== -setDelimiters( "{{", "}}" ); - -})( this ); - -/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) - * Licensed under the MIT License (LICENSE.txt). - * - * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. - * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. - * Thanks to: Seamus Leahy for adding deltaX and deltaY - * - * Version: 3.0.6 - * - * Requires: 1.2.2+ - */ - -(function($) { - -var types = ['DOMMouseScroll', 'mousewheel']; - -if ($.event.fixHooks) { - for ( var i=types.length; i; ) { - $.event.fixHooks[ types[--i] ] = $.event.mouseHooks; - } -} - -$.event.special.mousewheel = { - setup: function() { - if ( this.addEventListener ) { - for ( var i=types.length; i; ) { - this.addEventListener( types[--i], handler, false ); - } - } else { - this.onmousewheel = handler; - } - }, - - teardown: function() { - if ( this.removeEventListener ) { - for ( var i=types.length; i; ) { - this.removeEventListener( types[--i], handler, false ); - } - } else { - this.onmousewheel = null; - } - } -}; - -$.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); - }, - - unmousewheel: function(fn) { - return this.unbind("mousewheel", fn); - } -}); - - -function handler(event) { - var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0; - event = $.event.fix(orgEvent); - event.type = "mousewheel"; - - // Old school scrollwheel delta - if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; } - if ( orgEvent.detail ) { delta = -orgEvent.detail/3; } - - // New school multidimensional scroll (touchpads) deltas - deltaY = delta; - - // Gecko - if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { - deltaY = 0; - deltaX = -1*delta; - } - - // Webkit - if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; } - if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; } - - // Add event and delta to the front of the arguments - args.unshift(event, delta, deltaX, deltaY); - - return ($.event.dispatch || $.event.handle).apply(this, args); -} - -})(jQuery); - -/*! - * jQuery UI Widget 1.8.18 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ - -if ( ! $.widget ) { - -(function( $, undefined ) { - -// jQuery 1.4+ -if ( $.cleanData ) { - var _cleanData = $.cleanData; - $.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); - }; -} else { - var _remove = $.fn.remove; - $.fn.remove = function( selector, keepData ) { - return this.each(function() { - if ( !keepData ) { - if ( !selector || $.filter( selector, [ this ] ).length ) { - $( "*", this ).add( [ this ] ).each(function() { - try { - $( this ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - }); - } - } - return _remove.call( $(this), selector, keepData ); - }); - }; -} - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from -// $.each( basePrototype, function( key, val ) { -// if ( $.isPlainObject(val) ) { -// basePrototype[ key ] = $.extend( {}, val ); -// } -// }); - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = Array.prototype.slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - // prevent calls to internal methods - if ( isMethodCall && options.charAt( 0 ) === "_" ) { - return returnValue; - } - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ), - methodValue = instance && $.isFunction( instance[options] ) ? - instance[ options ].apply( instance, args ) : - instance; - // TODO: add this back in 1.9 and use $.error() (see #5972) -// if ( !instance ) { -// throw "cannot call methods on " + name + " prior to initialization; " + -// "attempted to call method '" + options + "'"; -// } -// if ( !$.isFunction( instance[options] ) ) { -// throw "no such method '" + options + "' for " + name + " widget instance"; -// } -// var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, name, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - // $.widget.bridge stores the plugin instance, but we do it anyway - // so that it's stored even before the _create function runs - $.data( element, this.widgetName, this ); - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - var self = this; - this.element.bind( "remove." + this.widgetName, function() { - self.destroy(); - }); - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: function() {}, - _init: function() {}, - - destroy: function() { - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - }, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - [ value ? "addClass" : "removeClass"]( - this.widgetBaseClass + "-disabled" + " " + - "ui-state-disabled" ) - .attr( "aria-disabled", value ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - - return !( $.isFunction(callback) && - callback.call( this.element[0], event, data ) === false || - event.isDefaultPrevented() ); - } -}; - -})( jQuery ); - -}; - - -(function ($, window, undefined) { - var pos_oo = Number.POSITIVE_INFINITY, - neg_oo = Number.NEGATIVE_INFINITY; - - $.geo = { - // - // utility functions - // - - _allCoordinates: function (geom) { - // return array of all positions in all geometries of geom - // not in JTS - var geometries = this._flatten(geom), - curGeom = 0, - result = []; - - for (; curGeom < geometries.length; curGeom++) { - var coordinates = geometries[curGeom].coordinates, - isArray = coordinates && $.isArray(coordinates[0]), - isDblArray = isArray && $.isArray(coordinates[0][0]), - isTriArray = isDblArray && $.isArray(coordinates[0][0][0]), - i, j, k; - - if (!isTriArray) { - if (!isDblArray) { - if (!isArray) { - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - for (k = 0; k < coordinates[i][j].length; k++) { - result.push(coordinates[i][j][k]); - } - } - } - } - return result; - }, - - _isGeodetic: function( coords ) { - // returns true if the first coordinate it can find is geodetic - - while ( $.isArray( coords ) ) { - if ( coords.length > 1 && ! $.isArray( coords[ 0 ] ) ) { - return ( coords[ 0 ] >= -180 && coords[ 0 ] <= 180 && coords[ 1 ] >= -85 && coords[ 1 ] <= 85 ); - } else { - coords = coords[ 0 ]; - } - } - - return false; - }, - - // - // bbox functions - // - - center: function (bbox, _ignoreGeo /* Internal Use Only */) { - // Envelope.centre in JTS - // bbox only, use centroid for geom - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return wasGeodetic ? $.geo.proj.toGeodetic(center) : center; - }, - - expandBy: function (bbox, dx, dy, _ignoreGeo /* Internal Use Only */) { - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - bbox = [bbox[0] - dx, bbox[1] - dy, bbox[2] + dx, bbox[3] + dy]; - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - height: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[3] - bbox[1]; - }, - - _in: function(bbox1, bbox2) { - return bbox1[0] <= bbox2[0] && - bbox1[1] <= bbox2[1] && - bbox1[2] >= bbox2[2] && - bbox1[3] >= bbox2[3]; - }, - - _bboxDisjoint: function( bbox1, bbox2 ) { - return bbox2[ 0 ] > bbox1[ 2 ] || - bbox2[ 2 ] < bbox1[ 0 ] || - bbox2[ 1 ] > bbox1[ 3 ] || - bbox2[ 3 ] < bbox1[ 1 ]; - }, - - include: function( bbox, value, _ignoreGeo /* Internal Use Only */ ) { - // similar to Envelope.expandToInclude in JTS - if ( !value || !$.isArray( value ) ) { - return bbox; - } - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox || value ) ) { - wasGeodetic = true; - } - - if ( !bbox ) { - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - } else if ( wasGeodetic ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - - if ( value.length === 2 ) { - value = [ value[ 0 ], value[ 1 ], value[ 0 ], value[ 1 ] ]; - } - - value = $.geo.proj.fromGeodetic( value ); - - bbox[0] = Math.min( value[ 0 ], bbox[ 0 ] ); - bbox[1] = Math.min( value[ 1 ], bbox[ 1 ] ); - bbox[2] = Math.max( value[ 2 ], bbox[ 2 ] ); - bbox[3] = Math.max( value[ 3 ], bbox[ 3 ] ); - - return wasGeodetic ? $.geo.proj.toGeodetic( bbox ) : bbox; - }, - - polygonize: function( bbox, _ignoreGeo /* Internal Use Only */ ) { - // adaptation of Polygonizer class in JTS for use with bboxes - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var polygon = { - type: "Polygon", - coordinates: [ [ - [ bbox[ 0 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 1 ] ] - ] ] - }; - - if ( wasGeodetic ) { - polygon.coordinates = $.geo.proj.toGeodetic( polygon.coordinates ); - } - - return polygon; - }, - - reaspect: function (bbox, ratio, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var width = this.width(bbox, true), - height = this.height(bbox, true), - center = this.center(bbox, true), - dx, dy; - - if (width !== 0 && height !== 0 && ratio > 0) { - if (width / height > ratio) { - dx = width / 2; - dy = dx / ratio; - } else { - dy = height / 2; - dx = dy * ratio; - } - - bbox = [center[0] - dx, center[1] - dy, center[0] + dx, center[1] + dy]; - } - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - recenter: function( bbox, center, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj ) { - if ( this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - if ( this._isGeodetic( center ) ) { - center = $.geo.proj.fromGeodetic(center); - } - } - - var halfWidth = ( bbox[ 2 ] - bbox[ 0 ] ) / 2, - halfHeight = ( bbox[ 3 ] - bbox[ 1 ] ) / 2; - - bbox = [ - center[ 0 ] - halfWidth, - center[ 1 ] - halfHeight, - center[ 0 ] + halfWidth, - center[ 1 ] + halfHeight - ]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - scaleBy: function ( bbox, scale, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var c = this.center(bbox, true), - dx = (bbox[2] - bbox[0]) * scale / 2, - dy = (bbox[3] - bbox[1]) * scale / 2; - - bbox = [c[0] - dx, c[1] - dy, c[0] + dx, c[1] + dy]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - width: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[2] - bbox[0]; - }, - - // - // geometry functions - // - - // bbox (Geometry.getEnvelope in JTS) - - bbox: function ( geom, _ignoreGeo /* Internal Use Only */ ) { - var result, wasGeodetic = false; - if ( !geom ) { - return undefined; - } else if ( geom.bbox ) { - result = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.bbox ) ) ? $.geo.proj.fromGeodetic( geom.bbox ) : geom.bbox; - } else { - result = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var coordinates = this._allCoordinates( geom ), - curCoord = 0; - - if ( coordinates.length === 0 ) { - return undefined; - } - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coordinates ) ) { - wasGeodetic = true; - coordinates = $.geo.proj.fromGeodetic( coordinates ); - } - - for ( ; curCoord < coordinates.length; curCoord++ ) { - result[0] = Math.min(coordinates[curCoord][0], result[0]); - result[1] = Math.min(coordinates[curCoord][1], result[1]); - result[2] = Math.max(coordinates[curCoord][0], result[2]); - result[3] = Math.max(coordinates[curCoord][1], result[3]); - } - } - - return wasGeodetic ? $.geo.proj.toGeodetic(result) : result; - }, - - // centroid - - centroid: function( geom, _ignoreGeo /* Internal Use Only */ ) { - switch (geom.type) { - case "Point": - return $.extend({}, geom); - - case "LineString": - case "Polygon": - var a = 0, - c = [0, 0], - coords = $.merge( [ ], geom.type == "Polygon" ? geom.coordinates[0] : geom.coordinates ), - i = 1, j, n, - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coords ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic(coords); - } - - //if (coords[0][0] != coords[coords.length - 1][0] || coords[0][1] != coords[coords.length - 1][1]) { - // coords.push(coords[0]); - //} - - for (; i <= coords.length; i++) { - j = i % coords.length; - - bbox[0] = Math.min(coords[j][0], bbox[0]); - bbox[1] = Math.min(coords[j][1], bbox[1]); - bbox[2] = Math.max(coords[j][0], bbox[2]); - bbox[3] = Math.max(coords[j][1], bbox[3]); - - n = (coords[i - 1][0] * coords[j][1]) - (coords[j][0] * coords[i - 1][1]); - a += n; - c[0] += (coords[i - 1][0] + coords[j][0]) * n; - c[1] += (coords[i - 1][1] + coords[j][1]) * n; - } - - if (a === 0) { - if (coords.length > 0) { - c[0] = Math.min( Math.max( coords[0][0], bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( coords[0][1], bbox[ 1 ] ), bbox[ 3 ] ); - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } else { - return undefined; - } - } - - a *= 3; - //c[0] /= a; - //c[1] /= a; - - c[0] = Math.min( Math.max( c[0] / a, bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( c[1] / a, bbox[ 1 ] ), bbox[ 3 ] ); - - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } - return undefined; - }, - - // contains - - contains: function (geom1, geom2) { - if (geom1.type != "Polygon") { - return false; - } - - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1.coordinates, geom2.coordinates); - - case "LineString": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates); - - case "Polygon": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates[0]); - - default: - return false; - } - }, - - _containsPolygonPoint: function (polygonCoordinates, pointCoordinate) { - if (polygonCoordinates.length === 0 || polygonCoordinates[0].length < 4) { - return false; - } - - var rayCross = 0, - a = polygonCoordinates[0][0], - i = 1, - b, - x; - - for (; i < polygonCoordinates[0].length; i++) { - b = polygonCoordinates[0][i]; - - if ((a[1] <= pointCoordinate[1] && pointCoordinate[1] < b[1]) || (b[1] <= pointCoordinate[1] && pointCoordinate[1] < a[1]) && (pointCoordinate[0] < a[0] || pointCoordinate[0] < b[0])) { - x = a[0] + (b[0] - a[0]) * (pointCoordinate[1] - a[1]) / (b[1] - a[1]); - - if (x > pointCoordinate[0]) { - rayCross++; - } - } - - a = b; - } - - return rayCross % 2 == 1; - }, - - _containsPolygonLineString: function (polygonCoordinates, lineStringCoordinates) { - for (var i = 0; i < lineStringCoordinates.length; i++) { - if (!this._containsPolygonPoint(polygonCoordinates, lineStringCoordinates[i])) { - return false; - } - } - return true; - }, - - // distance - - distance: function ( geom1, geom2, _ignoreGeo /* Internal Use Only */ ) { - var geom1CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom1.coordinates ) ) ? $.geo.proj.fromGeodetic(geom1.coordinates) : geom1.coordinates, - geom2CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom2.coordinates ) ) ? $.geo.proj.fromGeodetic(geom2.coordinates) : geom2.coordinates; - - switch (geom1.type) { - case "Point": - switch (geom2.type) { - case "Point": - return this._distancePointPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "LineString": - return this._distanceLineStringPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "Polygon": - return this._containsPolygonPoint(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "LineString": - switch (geom2.type) { - case "Point": - return this._distanceLineStringPoint(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "LineString": - return this._distanceLineStringLineString(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "Polygon": - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "LineString": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected[0]) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected[0]); - default: - return undefined; - } - break; - } - }, - - _distancePointPoint: function (coordinate1, coordinate2) { - var dx = coordinate2[0] - coordinate1[0], - dy = coordinate2[1] - coordinate1[1]; - return Math.sqrt((dx * dx) + (dy * dy)); - }, - - _distanceLineStringPoint: function (lineStringCoordinates, pointCoordinate) { - var minDist = pos_oo; - - if (lineStringCoordinates.length > 0) { - var a = lineStringCoordinates[0], - - apx = pointCoordinate[0] - a[0], - apy = pointCoordinate[1] - a[1]; - - if (lineStringCoordinates.length == 1) { - return Math.sqrt(apx * apx + apy * apy); - } else { - for (var i = 1; i < lineStringCoordinates.length; i++) { - var b = lineStringCoordinates[i], - - abx = b[0] - a[0], - aby = b[1] - a[1], - bpx = pointCoordinate[0] - b[0], - bpy = pointCoordinate[1] - b[1], - - d = this._distanceSegmentPoint(abx, aby, apx, apy, bpx, bpy); - - if (d === 0) { - return 0; - } - - if (d < minDist) { - minDist = d; - } - - a = b; - apx = bpx; - apy = bpy; - } - } - } - - return Math.sqrt(minDist); - }, - - _distanceSegmentPoint: function (abx, aby, apx, apy, bpx, bpy) { - var dot1 = abx * apx + aby * apy; - - if (dot1 <= 0) { - return apx * apx + apy * apy; - } - - var dot2 = abx * abx + aby * aby; - - if (dot1 >= dot2) { - return bpx * bpx + bpy * bpy; - } - - return apx * apx + apy * apy - dot1 * dot1 / dot2; - }, - - _distanceLineStringLineString: function (lineStringCoordinates1, lineStringCoordinates2) { - var minDist = pos_oo; - for (var i = 0; i < lineStringCoordinates2.length; i++) { - minDist = Math.min(minDist, this._distanceLineStringPoint(lineStringCoordinates1, lineStringCoordinates2[i])); - } - return minDist; - }, - - // buffer - - _buffer: function( geom, distance, _ignoreGeo /* Internal Use Only */ ) { - var wasGeodetic = false, - coords = geom.coordinates; - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.coordinates ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic( geom.coordinates ); - } - - if ( geom.type === "Point" ) { - var resultCoords = [], - slices = 180, - i = 0, - a; - - for ( ; i <= slices; i++ ) { - a = ( i * 360 / slices ) * ( Math.PI / 180 ); - resultCoords.push( [ - coords[ 0 ] + Math.cos( a ) * distance, - coords[ 1 ] + Math.sin( a ) * distance - ] ); - } - - return { - type: "Polygon", - coordinates: [ ( wasGeodetic ? $.geo.proj.toGeodetic( resultCoords ) : resultCoords ) ] - }; - } else { - return undefined; - } - }, - - - // - // feature - // - - _flatten: function (geom) { - // return an array of all basic geometries - // not in JTS - var geometries = [], - curGeom = 0; - switch (geom.type) { - case "Feature": - $.merge(geometries, this._flatten(geom.geometry)); - break; - - case "FeatureCollection": - for (; curGeom < geom.features.length; curGeom++) { - $.merge(geometries, this._flatten(geom.features[curGeom].geometry)); - } - break; - - case "GeometryCollection": - for (; curGeom < geom.geometries.length; curGeom++) { - $.merge(geometries, this._flatten(geom.geometries[curGeom])); - } - break; - - default: - geometries[0] = geom; - break; - } - return geometries; - }, - - length: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - lineStringCoordinates, - i = 1, dx, dy; - - switch ( geom.type ) { - case "Point": - return 0; - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][0] - lineStringCoordinates[ i - 1 ][0]; - dy = lineStringCoordinates[ i ][1] - lineStringCoordinates[ i - 1 ][1]; - sum += Math.sqrt((dx * dx) + (dy * dy)); - } - - return sum; - } - - // return undefined; - }, - - area: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - polygonCoordinates, - i = 1, j; - - switch ( geom.type ) { - case "Point": - case "LineString": - return 0; - - case "Polygon": - polygonCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( polygonCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( polygonCoordinates ) ) { - polygonCoordinates = $.geo.proj.fromGeodetic( polygonCoordinates ); - } - - for ( ; i <= polygonCoordinates.length; i++) { - j = i % polygonCoordinates.length; - sum += ( polygonCoordinates[ i - 1 ][ 0 ] - polygonCoordinates[ j ][ 0 ] ) * ( polygonCoordinates[ i - 1 ][ 1 ] + polygonCoordinates[ j ][ 1 ] ) / 2; - } - - return Math.abs( sum ); - } - }, - - pointAlong: function( geom, percentage, _ignoreGeo /* Internal Use Only */ ) { - var totalLength = 0, - previousPercentageSum = 0, - percentageSum = 0, - remainderPercentageSum, - len, - lineStringCoordinates, - segmentLengths = [], - i = 1, dx, dy, - c, c0, c1, - wasGeodetic = false; - - switch ( geom.type ) { - case "Point": - return $.extend( { }, geom ); - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( percentage === 0 ) { - return { - type: "Point", - coordinates: [ lineStringCoordinates[ 0 ][ 0 ], lineStringCoordinates[ 0 ][ 1 ] ] - }; - } else if ( percentage === 1 ) { - i = lineStringCoordinates.length - 1; - return { - type: "Point", - coordinates: [ lineStringCoordinates[ i ][ 0 ], lineStringCoordinates[ i ][ 1 ] ] - }; - } else { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - wasGeodetic = true; - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][ 0 ] - lineStringCoordinates[ i - 1 ][ 0 ]; - dy = lineStringCoordinates[ i ][ 1 ] - lineStringCoordinates[ i - 1 ][ 1 ]; - len = Math.sqrt((dx * dx) + (dy * dy)); - segmentLengths.push( len ); - totalLength += len; - } - - for ( i = 0; i < segmentLengths.length && percentageSum < percentage; i++ ) { - previousPercentageSum = percentageSum; - percentageSum += ( segmentLengths[ i ] / totalLength ); - } - - remainderPercentageSum = percentage - previousPercentageSum; - - c0 = lineStringCoordinates[ i - 1 ]; - c1 = lineStringCoordinates[ i ]; - - c = [ - c0[ 0 ] + ( remainderPercentageSum * ( c1[ 0 ] - c0[ 0 ] ) ), - c0[ 1 ] + ( remainderPercentageSum * ( c1[ 1 ] - c0[ 1 ] ) ) - ]; - - return { - type: "Point", - coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c - }; - } - } - }, - - // - // WKT functions - // - - _WKT: (function () { - function pointToString(value) { - return "POINT " + pointToUntaggedString(value.coordinates); - } - - function pointToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - return "(" + coordinates.join(" ") + ")"; - } - } - - function lineStringToString(value) { - return "LINESTRING " + lineStringToUntaggedString(value.coordinates); - } - - function lineStringToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var points = []; - - for (var i = 0; i < coordinates.length; i++) { - points.push(coordinates[i].join(" ")); - } - - return "(" + points + ")"; - } - } - - function polygonToString(value) { - return "POLYGON " + polygonToUntaggedString(value.coordinates); - } - - function polygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMTPY"; - } else { - var lineStrings = []; - - for (var i = 0; i < coordinates.length; i++) { - lineStrings.push(lineStringToUntaggedString(coordinates[i])); - } - - return "(" + lineStrings + ")"; - } - } - - function multiPointToString(value) { - return "MULTIPOINT " + lineStringToUntaggedString(value.coordinates); - } - - function multiLineStringToString(value) { - return "MULTILINSTRING " + polygonToUntaggedString(value.coordinates); - } - - function multiPolygonToString(value) { - return "MULTIPOLYGON " + multiPolygonToUntaggedString(value.coordinates); - } - - function multiPolygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var polygons = []; - for (var i = 0; i < coordinates.length; i++) { - polygons.push(polygonToUntaggedString(coordinates[i])); - } - return "(" + polygons + ")"; - } - } - - function geometryCollectionToString(value) { - return "GEOMETRYCOLLECTION " + geometryCollectionToUntaggedString(value.geometries); - } - - function geometryCollectionToUntaggedString(geometries) { - if (!(geometries && geometries.length)) { - return "EMPTY"; - } else { - var geometryText = []; - for (var i = 0; i < geometries.length; i++) { - geometryText.push(stringify(geometries[i])); - } - return "(" + geometries + ")"; - } - } - - function stringify(value) { - if (!(value && value.type)) { - return ""; - } else { - switch (value.type) { - case "Point": - return pointToString(value); - - case "LineString": - return lineStringToString(value); - - case "Polygon": - return polygonToString(value); - - case "MultiPoint": - return multiPointToString(value); - - case "MultiLineString": - return multiLineStringToString(value); - - case "MultiPolygon": - return multiPolygonToString(value); - - case "GeometryCollection": - return geometryCollectionToString(value); - - default: - return ""; - } - } - } - - function pointParseUntagged(wkt) { - var pointString = wkt.match( /\(\s*([\d\.\-]+)\s+([\d\.\-]+)\s*\)/ ); - return pointString && pointString.length > 2 ? { - type: "Point", - coordinates: [ - parseFloat(pointString[1]), - parseFloat(pointString[2]) - ] - } : null; - } - - function lineStringParseUntagged(wkt) { - var lineString = wkt.match( /\s*\((.*)\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( lineString && lineString.length > 1 ) { - pointStrings = lineString[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "LineString", - coordinates: coords - }; - } else { - return null; - } - } - - function polygonParseUntagged(wkt) { - var polygon = wkt.match( /\s*\(\s*\((.*)\)\s*\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( polygon && polygon.length > 1 ) { - pointStrings = polygon[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "Polygon", - coordinates: [ coords ] - }; - } else { - return null; - } - } - - function multiPointParseUntagged(wkt) { - var multiSomething; - - if ( wkt.indexOf( "((" ) === -1 ) { - multiSomething = lineStringParseUntagged( wkt ); - } else { - multiSomething = multiLineStringParseUntagged( wkt ); - multiSomething.coordinates = $.geo._allCoordinates( multiSomething ); - } - - multiSomething.type = "MultiPoint"; - - return multiSomething; - } - - function multiLineStringParseUntagged(wkt) { - var lineStringsWkt = wkt.substr( 1, wkt.length - 2 ), - lineStrings = lineStringsWkt.split( ")),((" ), - i = 0, - multiLineString = { - type: "MultiLineString", - coordinates: [ ] - }; - - for ( ; i < lineStrings.length; i++ ) { - multiLineString.coordinates.push( lineStringParseUntagged( lineStrings[ i ] ).coordinates ); - } - - return multiLineString; - } - - function multiPolygonParseUntagged(wkt) { - var polygonsWkt = wkt.substr( 1, wkt.length - 2 ), - polygons = polygonsWkt.split( ")),((" ), - i = 0, - multiPolygon = { - type: "MultiPolygon", - coordinates: [ ] - }; - - for ( ; i < polygons.length; i++ ) { - multiPolygon.coordinates.push( polygonParseUntagged( polygons[ i ] ).coordinates ); - } - - return multiPolygon; - } - - function geometryCollectionParseUntagged( wkt ) { - var geometriesWkt = wkt.substr( 1, wkt.length - 2 ), - geometries = geometriesWkt.match( /\),[a-zA-Z]/g ), - geometryCollection = { - type: "GeometryCollection", - geometries: [ ] - }, - curGeom, - i = 0, curStart = 0, curLen; - - if ( geometries && geometries.length > 0 ) { - for ( ; i < geometries.length; i++ ) { - curLen = geometriesWkt.indexOf( geometries[ i ], curStart ) - curStart + 1; - curGeom = parse( geometriesWkt.substr( curStart, curLen ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - curStart += curLen + 1; - } - - // one more - curGeom = parse( geometriesWkt.substr( curStart ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - - return geometryCollection; - } else { - return null; - } - } - - function parse(wkt) { - wkt = $.trim(wkt); - - var typeIndex = wkt.indexOf( "(" ), - untagged = wkt.substr( typeIndex ); - - switch ($.trim(wkt.substr(0, typeIndex)).toUpperCase()) { - case "POINT": - return pointParseUntagged( untagged ); - - case "LINESTRING": - return lineStringParseUntagged( untagged ); - - case "POLYGON": - return polygonParseUntagged( untagged ); - - case "MULTIPOINT": - return multiPointParseUntagged( untagged ); - - case "MULTILINESTRING": - return multiLineStringParseUntagged( untagged ); - - case "MULTIPOLYGON": - return multiPolygonParseUntagged( untagged ); - - case "GEOMETRYCOLLECTION": - return geometryCollectionParseUntagged( untagged ); - - default: - return null; - } - } - - return { - stringify: stringify, - - parse: parse - }; - }()), - - // - // projection functions - // - - proj: (function () { - var halfPi = 1.5707963267948966192, - quarterPi = 0.7853981633974483096, - radiansPerDegree = 0.0174532925199432958, - degreesPerRadian = 57.295779513082320877, - semiMajorAxis = 6378137; - - return { - fromGeodeticPos: function (coordinate) { - return [ - semiMajorAxis * coordinate[ 0 ] * radiansPerDegree, - semiMajorAxis * Math.log(Math.tan(quarterPi + coordinate[ 1 ] * radiansPerDegree / 2)) - ]; - }, - - fromGeodetic: function ( coordinates ) { - if ( ! $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - fromGeodeticPos = this.fromGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length == 4) { - // bbox - var min = fromGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = fromGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = fromGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - }, - - toGeodeticPos: function (coordinate) { - return [ - (coordinate[ 0 ] / semiMajorAxis) * degreesPerRadian, - (halfPi - 2 * Math.atan(1 / Math.exp(coordinate[ 1 ] / semiMajorAxis))) * degreesPerRadian - ]; - }, - - toGeodetic: function (coordinates) { - if ( $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - toGeodeticPos = this.toGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length == 4) { - // bbox - var min = toGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = toGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = toGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - } - }; - }()), - - // - // service types (defined in other files) - // - - _serviceTypes: {} - }; -}(jQuery, this)); - -(function ($, undefined) { - var _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ); - - $.widget("geo.geographics", { - _$elem: undefined, - _options: {}, - _trueCanvas: true, - _trueDoubleBuffer: true, - - _width: 0, - _height: 0, - - _$canvas: undefined, - _context: undefined, - - _$canvasSceneFront: undefined, //< if _trueCanvas, where canvas images get written (front buffer) - _$canvasSceneBack: undefined, //< if _trueCanvas, where canvas images get written (back buffer) - _timeoutEnd: null, - _requireFlip: false, - - _blitcanvas: undefined, - _blitcontext: undefined, - - _$labelsContainerFront: undefined, - _$labelsContainerBack: undefined, - _labelsHtml: "", - - options: { - style: { - borderRadius: "8px", - color: "#7f0000", - //fill: undefined, - fillOpacity: 0.2, - height: "8px", - opacity: 1, - //stroke: undefined, - strokeOpacity: 1, - strokeWidth: "2px", - visibility: "visible", - width: "8px" - }, - - doubleBuffer: true - }, - - _create: function () { - this._$elem = this.element; - this._options = this.options; - - this._$elem.css( { - webkitTransform: "translateZ(0)", - display: "inline-block", - overflow: "hidden", - textAlign: "left" - } ); - - if (this._$elem.css("position") == "static") { - this._$elem.css("position", "relative"); - } - - this._$elem.addClass( "geo-graphics" ); - - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - var posCss = 'position:absolute;left:0;top:0;margin:0;padding:0;', - sizeCss = 'width:' + this._width + 'px;height:' + this._height + 'px;', - sizeAttr = 'width="' + this._width + '" height="' + this._height + '"'; - - this._blitcanvas = document.createElement( "canvas" ); - - if ( this._blitcanvas.getContext ) { - //this._$elem.append(''); - //this._$canvas = this._$elem.children(':last'); - this._$canvas = $(''); - - // test _trueDoubleBuffer - this._blitcanvas.width = 1; - this._blitcanvas.height = 1; - this._trueDoubleBuffer = this._blitcanvas.toDataURL().length > 6; - - if ( !(this._options.doubleBuffer && this._trueDoubleBuffer) ) { - this._$elem.append( this._$canvas ); - } - - this._context = this._$canvas[0].getContext("2d"); - - //this._blitcanvas = document.createElement( "canvas" ); - this._blitcanvas.width = this._width; - this._blitcanvas.height = this._height; - this._blitcontext = this._blitcanvas.getContext("2d"); - - // create our front & back buffers - this._$canvasSceneFront = $(''); - this._$canvasSceneBack = $(''); - - } else if (_ieVersion <= 8) { - this._trueCanvas = false; - this._$elem.append( '
                                  '); - this._$canvas = this._$elem.children(':last'); - - G_vmlCanvasManager.initElement(this._$canvas[0]); - this._context = this._$canvas[0].getContext("2d"); - this._$canvas.children().css({ backgroundColor: "transparent", width: this._width, height: this._height }); - } - - // create our front & back label containers - this._$labelsContainerFront = $('
                                  '); - this._$labelsContainerBack = $('
                                  '); - }, - - _setOption: function (key, value) { - if (key == "style") { - value = $.extend({}, this._options.style, value); - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - destroy: function () { - $.Widget.prototype.destroy.apply(this, arguments); - this._$elem.html(""); - this._$elem.removeClass( "geo-graphics" ); - }, - - clear: function () { - this._context.clearRect(0, 0, this._width, this._height); - this._labelsHtml = ""; - - //if ( this._options.doubleBuffer ) console.log("clear:_end " + $.now()); - this._end( ); - }, - - drawArc: function (coordinates, startAngle, sweepAngle, style) { - style = this._getGraphicStyle(style); - - if (style.visibility != "hidden" && style.opacity > 0 && style.widthValue > 0 && style.heightValue > 0) { - var r = Math.min(style.widthValue, style.heightValue) / 2; - - startAngle = (startAngle * Math.PI / 180); - sweepAngle = (sweepAngle * Math.PI / 180); - - this._context.save(); - this._context.translate(coordinates[0], coordinates[1]); - if (style.widthValue > style.heightValue) { - this._context.scale(style.widthValue / style.heightValue, 1); - } else { - this._context.scale(1, style.heightValue / style.widthValue); - } - - this._context.beginPath(); - this._context.arc(0, 0, r, startAngle, sweepAngle, false); - - if (this._trueCanvas) { - this._context.restore(); - } - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - if (!this._trueCanvas) { - this._context.restore(); - } - } - - //if ( this._options.doubleBuffer ) console.log("drawArc:_end " + $.now()); - this._end( ); - }, - - drawPoint: function (coordinates, style) { - style = this._getGraphicStyle(style); - if (style.widthValue == style.heightValue && style.heightValue == style.borderRadiusValue) { - this.drawArc(coordinates, 0, 360, style); - } else if (style.visibility != "hidden" && style.opacity > 0) { - style.borderRadiusValue = Math.min(Math.min(style.widthValue, style.heightValue) / 2, style.borderRadiusValue); - coordinates[0] -= style.widthValue / 2; - coordinates[1] -= style.heightValue / 2; - this._context.beginPath(); - this._context.moveTo(coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.lineTo(coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1]); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1], coordinates[0] + style.widthValue, coordinates[1] + style.borderRadiusValue); - this._context.lineTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue, coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.lineTo(coordinates[0] + style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1] + style.heightValue, coordinates[0], coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.lineTo(coordinates[0], coordinates[1] + style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1], coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.closePath(); - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - - this._context.stroke(); - } - - //if ( this._options.doubleBuffer ) console.log("drawPoint:_end " + $.now()); - this._end( ); - } - }, - - drawLineString: function (coordinates, style) { - this._drawLines([coordinates], false, style); - }, - - drawPolygon: function (coordinates, style) { - if ( !this._trueCanvas || coordinates.length == 1 ) { - // either we don't have fancy rendering or there's no need for it (no holes) - this._drawLines( coordinates, true, style ); - } else { - if ( !coordinates || !coordinates.length || coordinates[ 0 ].length < 3 ) { - // this is not a Polygon or it doesn't have a proper outer ring - return; - } - - style = this._getGraphicStyle(style); - - var pixelBbox, i, j; - - if ( style.visibility != "hidden" && style.opacity > 0 ) { - this._blitcontext.clearRect(0, 0, this._width, this._height); - - if ( style.doFill ) { - if ( coordinates.length > 1 ) { - // stencil inner rings - this._blitcontext.globalCompositeOperation = "source-out"; - this._blitcontext.globalAlpha = 1; - - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.fill( ); - } - } - } - - // path outer ring - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ 0 ][ 0 ][ 0 ], coordinates[ 0 ][ 0 ][ 1 ] ); - - pixelBbox = [ coordinates[ 0 ][ 0 ][ 0 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 0 ] + style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] + style.strokeWidthValue ]; - - for ( i = 1; i < coordinates[ 0 ].length - 1; i++ ) { - this._blitcontext.lineTo( coordinates[ 0 ][ i ][ 0 ], coordinates[ 0 ][ i ][ 1 ] ); - - pixelBbox[ 0 ] = Math.min( coordinates[ 0 ][ i ][ 0 ] - style.strokeWidthValue, pixelBbox[ 0 ] ); - pixelBbox[ 1 ] = Math.min( coordinates[ 0 ][ i ][ 1 ] - style.strokeWidthValue, pixelBbox[ 1 ] ); - pixelBbox[ 2 ] = Math.max( coordinates[ 0 ][ i ][ 0 ] + style.strokeWidthValue, pixelBbox[ 2 ] ); - pixelBbox[ 3 ] = Math.max( coordinates[ 0 ][ i ][ 1 ] + style.strokeWidthValue, pixelBbox[ 3 ] ); - } - - this._blitcontext.closePath(); - - this._blitcontext.globalCompositeOperation = "source-out"; - if ( style.doFill ) { - // fill outer ring - this._blitcontext.fillStyle = style.fill; - this._blitcontext.globalAlpha = style.opacity * style.fillOpacity; - this._blitcontext.fill( ); - } - - this._blitcontext.globalCompositeOperation = "source-over"; - if ( style.doStroke ) { - // stroke outer ring - this._blitcontext.lineCap = this._blitcontext.lineJoin = "round"; - this._blitcontext.lineWidth = style.strokeWidthValue; - this._blitcontext.strokeStyle = style.stroke; - - this._blitcontext.globalAlpha = style.opacity * style.strokeOpacity; - this._blitcontext.stroke( ); - - if ( coordinates.length > 1 ) { - // stroke inner rings - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.stroke( ); - } - } - } - - // blit - pixelBbox[ 0 ] = Math.min( Math.max( pixelBbox[ 0 ], 0), this._width ); - pixelBbox[ 1 ] = Math.min( Math.max( pixelBbox[ 1 ], 0), this._height ); - pixelBbox[ 2 ] = Math.min( Math.max( pixelBbox[ 2 ], 0), this._width ); - pixelBbox[ 3 ] = Math.min( Math.max( pixelBbox[ 3 ], 0), this._height ); - - if ( pixelBbox[ 0 ] !== pixelBbox[ 2 ] && pixelBbox[ 1 ] !== pixelBbox[ 3 ] ) { - this._context.drawImage(this._blitcanvas, pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ], pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ] ); - - //if ( this._options.doubleBuffer ) console.log("drawPolygon:_end " + $.now()); - this._end( ); - } - } - } - }, - - drawBbox: function (bbox, style) { - this._drawLines([[ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ]], true, style); - }, - - drawLabel: function( coordinates, label ) { - this._labelsHtml += '
                                  ' + label + '
                                  '; - }, - - resize: function( ) { - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - if ( this._trueCanvas ) { - this._$canvas[0].width = this._width; - this._$canvas[0].height = this._height; - - this._$canvasSceneFront.css( { - width: this._width, - height: this._height - } ); - - this._$canvasSceneBack.css( { - width: this._width, - height: this._height - } ); - } else { - this._$canvas.css( { - width: this._width, - height: this._height - } ); - } - - this._$labelsContainerFront.css( { - width: this._width, - height: this._height - } ); - - this._$labelsContainerBack.css( { - width: this._width, - height: this._height - } ); - }, - - interactiveTransform: function( origin, scale ) { - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - // hide labels for now until they are on the interactive div - //this._$labelsContainerFront.html(""); - - if ( this._trueCanvas ) { - if ( this._options.doubleBuffer && this._trueDoubleBuffer ) { - - - if ( this._requireFlip ) { - var geographics = this; - - var oldCanvasScene = geographics._$canvasSceneFront; - - geographics._$canvasSceneFront = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ).prependTo( geographics._$elem ); - - geographics._$canvasSceneBack = oldCanvasScene.detach(); - - geographics._requireFlip = false; - } - - - //console.log("geographics:interactiveTransform " + this._$canvasSceneFront.prop( "id" ) + ": origin: " + origin.toString() + ", scale: " + scale); - // transform a finished scene, can assume no drawing during these calls - this._$canvasSceneFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - } else { - this._context.clearRect(0, 0, this._width, this._height); - } - - // transform labels - this._$labelsContainerFront.css( { - left: Math.round( origin[ 0 ] ), - top: Math.round( origin[ 1 ] ), - width: this._width * scale, - height: this._height * scale - } ); - }, - - _end: function( ) { - // end/finalize a scene - if ( this._timeoutEnd ) { - clearTimeout( this._timeoutEnd ); - this._timeoutEnd = null; - } - - this._requireFlip = true; - - var geographics = this; - - function endCallback( ) { - if ( !geographics._timeoutEnd ) { - // something has canceled the draw - return; - } - - if ( geographics._trueCanvas && geographics._options.doubleBuffer && geographics._trueDoubleBuffer ) { - //console.log(" endCallback..."); - - //geographics._$canvasSceneFront = - geographics._$canvasSceneBack.prop( "src", "" ).one( "load", function( e ) { - //console.log(" ...flip: show " + geographics._$canvasSceneBack.prop( "id" ) + ", hide " + geographics._$canvasSceneFront.prop("id")); - geographics._requireFlip = false; - var oldCanvasScene = geographics._$canvasSceneFront; - - geographics._$canvasSceneFront = geographics._$canvasSceneBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prependTo( geographics._$elem ); - - geographics._$canvasSceneBack = oldCanvasScene.detach(); - } ).prop( "src", geographics._$canvas[ 0 ].toDataURL( ) ); - } - - - geographics._$labelsContainerBack.html( geographics._labelsHtml ).find("a").css({ - position: "relative", - zIndex: 100, - display: "inline-block", - webkitTransform: "translateZ(0)" - }); - - var oldLabelsContainer = geographics._$labelsContainerFront; - - geographics._$labelsContainerFront = geographics._$labelsContainerBack.css( { - left: 0, - top: 0, - width: geographics._width, - height: geographics._height - } ).prependTo( geographics._$elem ); - - geographics._$labelsContainerBack = oldLabelsContainer.detach(); - - - geographics._timeoutEnd = null; - } - - //if ( this._options.doubleBuffer ) { - this._timeoutEnd = setTimeout( endCallback, 20 ); - //} else { - //geographics._$labelsContainerFront.html( geographics._labelsHtml ); - //} - }, - - _getGraphicStyle: function (style) { - function safeParse(value) { - value = parseInt(value, 10); - return (+value + '') === value ? +value : value; - } - - style = $.extend({}, this._options.style, style); - style.borderRadiusValue = safeParse(style.borderRadius); - style.fill = style.fill || style.color; - style.doFill = style.fill && style.fillOpacity > 0; - style.stroke = style.stroke || style.color; - style.strokeWidthValue = safeParse(style.strokeWidth); - style.doStroke = style.stroke && style.strokeOpacity > 0 && style.strokeWidthValue > 0; - style.widthValue = safeParse(style.width); - style.heightValue = safeParse(style.height); - return style; - }, - - _drawLines: function (coordinates, close, style) { - if (!coordinates || !coordinates.length || coordinates[0].length < 2) { - return; - } - - var i, j; - style = this._getGraphicStyle(style); - - if (style.visibility != "hidden" && style.opacity > 0) { - this._context.beginPath(); - - for (i = 0; i < coordinates.length; i++) { - this._context.moveTo(coordinates[i][0][0], coordinates[i][0][1]); - for (j = 1; j < coordinates[i].length; j++) { - this._context.lineTo(coordinates[i][j][0], coordinates[i][j][1]); - } - } - - if (close) { - this._context.closePath(); - } - - if (close && style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineCap = this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - //if ( this._options.doubleBuffer ) console.log("_drawLines:_end " + $.now()); - this._end( ); - } - } - }); -}(jQuery)); - - -(function ($, undefined) { - var _widgetIdSeed = 0, - _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ), - - _defaultOptions = { - bbox: [-180, -85, 180, 85], - bboxMax: [-180, -85, 180, 85], - center: [0, 0], - cursors: { - "static": "default", - pan: "url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move", - zoom: "crosshair", - dragBox: "crosshair", - dragCircle: "crosshair", - drawPoint: "crosshair", - drawLineString: "crosshair", - drawPolygon: "crosshair", - measureLength: "crosshair", - measureArea: "crosshair" - }, - measureLabels: { - length: "{{:length.toFixed( 2 )}} m", - area: "{{:area.toFixed( 2 )}} sq m" - }, - drawStyle: {}, - shapeStyle: {}, - mode: "pan", - pannable: true, - scroll: "default", - shift: "default", - services: [ - { - "class": "osm", - type: "tiled", - src: function (view) { - return "http://otile" + ((view.index % 4) + 1) + ".mqcdn.com/tiles/1.0.0/osm/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; - }, - attr: "Tiles Courtesy of MapQuest " - } - ], - tilingScheme: { - tileWidth: 256, - tileHeight: 256, - levels: 18, - basePixelSize: 156543.03392799936, - origin: [-20037508.342787, 20037508.342787] - }, - axisLayout: "map", - zoom: 0, - zoomMin: 0, - zoomMax: Number.POSITIVE_INFINITY, - pixelSize: 0 - }; - - $.widget("geo.geomap", { - // private widget members - _$elem: undefined, //< map div for maps, service div for services - _map: undefined, //< only defined in services - _created: false, - _createdGraphics: false, - _widgetId: 0, - _tmplLengthId: "", - _tmplAreaId: "", - - _contentBounds: {}, - - _$resizeContainer: undefined, //< all elements that should match _contentBounds' size - - _$eventTarget: undefined, - _$contentFrame: undefined, - _$existingChildren: undefined, - _$attrList: undefined, - _$servicesContainer: undefined, - _$shapesContainers: undefined, //< all shapesContainer divs (map only) - - _$panContainer: undefined, //< all non-service elements that move while panning - _$shapesContainer: undefined, //< just "our" shapesContainer div (map & service) - _$drawContainer: undefined, - _$measureContainer: undefined, - _$measureLabel: undefined, - - _dpi: 96, - - _currentServices: [], //< internal copy - - _center: undefined, - _pixelSize: undefined, - _centerMax: undefined, - _pixelSizeMax: undefined, - - _userGeodetic: true, - - _centerInteractive: undefined, - _pixelSizeInteractive: undefined, - _timeoutInteractive: null, - _triggerInteractive: false, - - _timeoutRefreshShapes: null, - - _loadCount: 0, - - _wheelTimeout: null, - _wheelLevel: 0, - - _zoomFactor: 2, //< determines what a zoom level means - - _fullZoomFactor: 2, //< interactiveScale factor needed to zoom a whole level - _partialZoomFactor: 1.18920711500273, //< interactiveScale factor needed to zoom a fraction of a level (the fourth root of 2) - - _mouseDown: undefined, - _inOp: undefined, - _toolPan: undefined, - _shiftDown: undefined, - _anchor: undefined, - _current: undefined, - _downDate: undefined, - _moveDate: undefined, - _clickDate: undefined, - _lastMove: undefined, - _lastDrag: undefined, - - _windowHandler: null, - _resizeTimeout: null, - - _panning: undefined, - _velocity: undefined, - _friction: undefined, - - _supportTouch: undefined, - _softDblClick: undefined, - _isTap: undefined, - _isDbltap: undefined, - - _isMultiTouch: undefined, - _multiTouchAnchor: [], //< TouchList - _multiTouchAnchorBbox: undefined, //< bbox - _multiTouchCurrentBbox: undefined, //< bbox - - _drawTimeout: null, //< used in drawPoint mode so we don't send two shape events on dbltap - _drawPixels: [], //< an array of coordinate arrays for drawing lines & polygons, in pixel coordinates - _drawCoords: [], - - _graphicShapes: [], //< an array of objects containing style object refs & GeoJSON object refs - - _initOptions: {}, - - _options: {}, - - options: $.extend({}, _defaultOptions), - - _createWidget: function (options, element) { - this._$elem = $(element); - - if (this._$elem.is(".geo-service")) { - this._graphicShapes = []; - $.Widget.prototype._createWidget.apply(this, arguments); - return; - } - - this._widgetId = _widgetIdSeed++; - this._tmplLengthId = "geoMeasureLength" + this._widgetId; - this._tmplAreaId = "geoMeasureArea" + this._widgetId; - - this._$elem.addClass("geo-map").css( { - webkitTransform: "translateZ(0)" - } ); - - - this._initOptions = options || {}; - - this._forcePosition(this._$elem); - - this._$elem.css("text-align", "left"); - - var size = this._findMapSize(); - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._createChildren(); - - this._center = [ 0, 0 ]; - this._centerMax = [ 0, 0 ]; - this._centerInteractive = [ 0, 0 ]; - - this.options["pixelSize"] = this._pixelSize = this._pixelSizeMax = 156543.03392799936; - - this._mouseDown = - this._inOp = - this._toolPan = - this._shiftDown = - this._panning = - this._isTap = - this._isDbltap = false; - - this._anchor = [ 0, 0 ]; - this._current = [ 0, 0 ]; - this._lastMove = [ 0, 0 ]; - this._lastDrag = [ 0, 0 ]; - this._velocity = [ 0, 0 ]; - - this._friction = [0.8, 0.8]; - - this._downDate = - this._moveDate = - this._clickDate = 0; - - this._drawPixels = []; - this._drawCoords = []; - this._graphicShapes = []; - - - $.Widget.prototype._createWidget.apply(this, arguments); - }, - - _create: function () { - this._options = this.options; - - if (this._$elem.is(".geo-service")) { - this._map = this._$elem.data( "geoMap" ); - this._$elem.data( "geoService", this ); - return; - } - - this._map = this; - - this._supportTouch = "ontouchend" in document; - this._softDblClick = this._supportTouch || _ieVersion == 7; - - var geomap = this, - touchStartEvent = this._supportTouch ? "touchstart" : "mousedown", - touchStopEvent = this._supportTouch ? "touchend touchcancel" : "mouseup", - touchMoveEvent = this._supportTouch ? "touchmove" : "mousemove"; - - $(document).keydown($.proxy(this._document_keydown, this)); - - this._$eventTarget.dblclick($.proxy(this._eventTarget_dblclick, this)); - - this._$eventTarget.bind(touchStartEvent, $.proxy(this._eventTarget_touchstart, this)); - - var dragTarget = (this._$eventTarget[0].setCapture) ? this._$eventTarget : $(document); - dragTarget.bind(touchMoveEvent, $.proxy(this._dragTarget_touchmove, this)); - dragTarget.bind(touchStopEvent, $.proxy(this._dragTarget_touchstop, this)); - - this._$eventTarget.mousewheel($.proxy(this._eventTarget_mousewheel, this)); - - this._windowHandler = function () { - if (geomap._resizeTimeout) { - clearTimeout(geomap._resizeTimeout); - } - geomap._resizeTimeout = setTimeout(function () { - if (geomap._created) { - geomap._$elem.geomap( "resize", true ); - } - }, 500); - }; - - $(window).resize(this._windowHandler); - - this._$drawContainer.geographics({ style: this._initOptions.drawStyle || {}, doubleBuffer: false }); - this._options["drawStyle"] = this._$drawContainer.geographics("option", "style"); - - this._$shapesContainer.geographics( { style: this._initOptions.shapeStyle || { } } ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - - if (this._initOptions) { - // always init tilingScheme right away, even if it's null - if ( this._initOptions.tilingScheme !== undefined ) { - this._setOption("tilingScheme", this._initOptions.tilingScheme || null, false); - } - - if ( this._initOptions.services ) { - // jQuery UI Widget Factory merges user services with our default, we want to clobber the default - this._options[ "services" ] = $.merge( [ ], this._initOptions.services ); - } - if (this._initOptions.bboxMax) { - this._setOption("bboxMax", this._initOptions.bboxMax, false); - this._setOption("bbox", this._initOptions.bboxMax, false); - } - if (this._initOptions.zoomMin !== undefined) { - this._setOption("zoomMin", this._initOptions.zoomMin, false); - } - if (this._initOptions.zoomMax !== undefined) { - this._setOption("zoomMax", this._initOptions.zoomMax, false); - } - if (this._initOptions.bbox) { - this._setOption("bbox", this._initOptions.bbox, false); - } - if (this._initOptions.center) { - this._setOption("center", this._initOptions.center, false); - } - if (this._initOptions.zoom !== undefined) { - this._setOption("zoom", this._initOptions.zoom, false); - } - } - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._createServices(); - this._refresh(); - - this._created = true; - }, - - _setOption: function (key, value, refresh) { - if ( key == "pixelSize" ) { - return; - } - - refresh = (refresh === undefined || refresh); - - if ( this._$elem.is( ".geo-map" ) ) { - this._panFinalize(); - } - - var center, pixelSize, bbox, zoom; - - switch (key) { - case "bbox": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2]; - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height); - - // clamp to zoom - zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( center, pixelSize ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( center, pixelSize, false, refresh ); - } - - value = this._getBbox( center, pixelSize ); - break; - - case "bboxMax": - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - break; - - case "center": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( value, this._pixelSizeInteractive ); - this._interactiveTransform( ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( value, this._pixelSize, false, refresh ); - } - break; - - case "measureLabels": - value = $.extend( this._options[ "measureLabels" ], value ); - - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - break; - - case "drawStyle": - if (this._$drawContainer) { - this._$drawContainer.geographics("option", "style", value); - value = this._$drawContainer.geographics("option", "style"); - } - break; - - case "shapeStyle": - if ( this._$elem.is( ".geo-service" ) && !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("option", "style", value); - value = this._$shapesContainer.geographics("option", "style"); - } - break; - - case "mode": - this._resetDrawing( ); - this._$eventTarget.css("cursor", this._options["cursors"][value]); - break; - - case "zoom": - if ( this._created ) { - this._setZoom(value, false, refresh); - } else { - value = Math.max( value, 0 ); - this._setCenterAndSize( this._center, this._getPixelSize( value ), false, refresh ); - } - break; - } - - $.Widget.prototype._setOption.apply(this, arguments); - - switch ( key ) { - case "bbox": - case "center": - if ( this._userGeodetic ) { - this._options[ "bbox" ] = $.geo.proj.toGeodetic( this._options[ "bbox" ] ); - this._options[ "center" ] = $.geo.proj.toGeodetic( this._center ); - } - break; - - case "tilingScheme": - if ( value !== null ) { - this._pixelSizeMax = this._getPixelSize( 0 ); - this._centerMax = [ - value.origin[ 0 ] + this._pixelSizeMax * value.tileWidth / 2, - value.origin[ 1 ] + this._pixelSizeMax * value.tileHeight / 2 - ]; - } - break; - - case "bboxMax": - if ( $.geo.proj && $.geo._isGeodetic( value ) ) { - bbox = $.geo.proj.fromGeodetic( value ); - } else { - bbox = value; - } - - this._centerMax = $.geo.center( bbox ); - this._pixelSizeMax = Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - break; - - case "services": - this._createServices(); - if (refresh) { - this._refresh(); - this._refreshAllShapes(); - } - break; - - case "shapeStyle": - if ( refresh && this._createdGraphics ) { - this._$shapesContainer.geographics("clear"); - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - break; - } - }, - - destroy: function () { - if ( this._$elem.is(".geo-service") ) { - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - } - } else { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - - this._created = false; - - $(window).unbind("resize", this._windowHandler); - - for ( var i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - - this._$drawContainer.geographics("destroy"); - this._$drawContainer = undefined; - - this._$existingChildren.detach(); - this._$elem.html(""); - this._$elem.append(this._$existingChildren); - this._$elem.removeClass("geo-map"); - } - - $.Widget.prototype.destroy.apply(this, arguments); - }, - - toMap: function (p) { - p = this._toMap(p); - return this._userGeodetic ? $.geo.proj.toGeodetic(p) : p; - }, - - toPixel: function ( p, _center /* Internal Use Only */, _pixelSize /* Internal Use Only */ ) { - return this._toPixel( $.geo.proj ? $.geo.proj.fromGeodetic( p ) : p, _center, _pixelSize ); - }, - - opacity: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "opacity", value, this._$elem ); - } else { - if ( value >= 0 || value <= 1 ) { - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - service.style.opacity = value; - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - $.geo[ "_serviceTypes" ][ service.type ].opacity( this, service ); - } - } - } - } - }, - - toggle: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "toggle", value, this._$elem ); - } else { - - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - if ( value === undefined ) { - // toggle visibility - value = ( service.style.visibility !== "visible" ); - } - - service.style.visibility = ( value ? "visible" : "hidden" ); - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - service.serviceContainer.toggle( value ); - - if ( value ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service ); - } - } - } - } - }, - - zoom: function (numberOfLevels) { - if (numberOfLevels !== null) { - this._setZoom(this._options["zoom"] + numberOfLevels, false, true); - } - }, - - refresh: function ( force, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "refresh", force, this._$elem ); - } else { - this._refresh( force, _serviceContainer ); - this._refreshAllShapes( ); - } - }, - - resize: function ( _trigger /* Internal Use Only */ ) { - var size = this._findMapSize(), - dx = size["width"]/2 - this._contentBounds.width/2, - dy = size["height"]/2 - this._contentBounds.height/2, - i; - - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._$resizeContainer.css( { - width: size["width"], - height: size["height"] - } ); - - for (i = 0; i < this._currentServices.length; i++) { - $.geo["_serviceTypes"][this._currentServices[i].type].resize(this, this._currentServices[i]); - } - - this._$elem.find( ".geo-graphics" ).css( { - width: size["width"], - height: size["height"] - }).geographics( "resize" ); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._setCenterAndSize(this._center, this._pixelSize, _trigger, true); - }, - - append: function ( shape, style, label, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - if ( !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - var shapes, arg, i, realStyle, realLabel, realRefresh; - - if ( $.isArray( shape ) ) { - shapes = shape; - } else if ( shape.type == "FeatureCollection" ) { - shapes = shape.features; - } else { - shapes = [ shape ]; - } - - for ( i = 1; i < arguments.length; i++ ) { - arg = arguments[ i ]; - - if ( typeof arg === "object" ) { - realStyle = arg; - } else if ( typeof arg === "number" || typeof arg === "string" ) { - realLabel = arg; - } else if ( typeof arg === "boolean" ) { - realRefresh = arg; - } - } - - for ( i = 0; i < shapes.length; i++ ) { - if ( shapes[ i ].type != "Point" ) { - var bbox = $.geo.bbox( shapes[ i ] ); - if ( $.geo.proj && $.geo._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - $.data( shapes[ i ], "geoBbox", bbox ); - } - - this._graphicShapes.push( { - shape: shapes[ i ], - style: realStyle, - label: realLabel - } ); - } - - if ( realRefresh === undefined || realRefresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - empty: function ( refresh ) { - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - $.removeData( this._graphicShapes[ i ].shape, "geoBbox" ); - } - - this._graphicShapes = []; - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - }, - - find: function ( selector, pixelTolerance ) { - var isPoint = $.isPlainObject( selector ), - searchPixel = isPoint ? this._map.toPixel( selector.coordinates ) : undefined, - mapTol = this._map._pixelSize * pixelTolerance, - result = [], - graphicShape, - geometries, - curGeom, - i = 0; - - for ( ; i < this._graphicShapes.length; i++ ) { - graphicShape = this._graphicShapes[ i ]; - - if ( isPoint ) { - if ( graphicShape.shape.type == "Point" ) { - if ( $.geo.distance( graphicShape.shape, selector ) <= mapTol ) { - result.push( graphicShape.shape ); - } - } else { - var bbox = $.data( graphicShape.shape, "geoBbox" ), - bboxPolygon = { - type: "Polygon", - coordinates: [ [ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ] ] - }, - projectedPoint = { - type: "Point", - coordinates: $.geo.proj && $.geo._isGeodetic( selector.coordinates ) ? $.geo.proj.fromGeodetic( selector.coordinates ) : selector.coordinates - }; - - if ( $.geo.distance( bboxPolygon, projectedPoint, true ) <= mapTol ) { - geometries = $.geo._flatten( graphicShape.shape ); - for ( curGeom = 0; curGeom < geometries.length; curGeom++ ) { - if ( $.geo.distance( geometries[ curGeom ], selector ) <= mapTol ) { - result.push( graphicShape.shape ); - break; - } - } - } - } - } else { - result.push( graphicShape.shape ); - } - } - - if ( this._$elem.is( ".geo-map" ) ) { - this._$elem.find( ".geo-service" ).each( function( ) { - result = $.merge( result, $( this ).geomap( "find", selector, pixelTolerance ) ); - } ); - } - - return result; - }, - - remove: function ( shape, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - var shapes = $.isArray( shape ) ? shape : [ shape ], - rest; - - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - if ( $.inArray( this._graphicShapes[ i ].shape, shapes ) >= 0 ) { - $.removeData( shape, "geoBbox" ); - rest = this._graphicShapes.slice( i + 1 ); - this._graphicShapes.length = i; - this._graphicShapes.push.apply( this._graphicShapes, rest ); - i--; - } - } - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - this._refreshAllShapes( ); - } - } - }, - - _getBbox: function (center, pixelSize) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - // calculate the internal bbox - var halfWidth = this._contentBounds[ "width" ] / 2 * pixelSize, - halfHeight = this._contentBounds[ "height" ] / 2 * pixelSize; - return [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - }, - - _setBbox: function (value, trigger, refresh) { - var center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2], - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height), - zoom = this._getZoom( center, pixelSize ); - - // clamp to zoom - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._setInteractiveCenterAndSize( center, pixelSize ); - this._interactiveTransform( ); - }, - - _getBboxMax: function () { - // calculate the internal bboxMax - var halfWidth = this._contentBounds["width"] / 2 * this._pixelSizeMax, - halfHeight = this._contentBounds["height"] / 2 * this._pixelSizeMax; - return [this._centerMax[0] - halfWidth, this._centerMax[1] - halfHeight, this._centerMax[0] + halfWidth, this._centerMax[1] + halfHeight]; - }, - - _getCenter: function () { - return this._center; - }, - - _getContentBounds: function () { - return this._contentBounds; - }, - - _getServicesContainer: function () { - return this._$servicesContainer; - }, - - _getZoom: function ( center, pixelSize ) { - // calculate the internal zoom level, vs. public zoom property - // this does not take zoomMin or zoomMax into account - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var tilingScheme = this._options["tilingScheme"]; - if ( tilingScheme ) { - if ( tilingScheme.pixelSizes ) { - var roundedPixelSize = Math.floor(pixelSize * 1000), - levels = tilingScheme.pixelSizes.length, - i = levels - 1; - - for ( ; i >= 0; i-- ) { - if ( Math.floor( tilingScheme.pixelSizes[ i ] * 1000 ) >= roundedPixelSize ) { - return i; - } - } - - return 0; - } else { - return Math.round( Math.log( tilingScheme.basePixelSize / pixelSize) / Math.log( 2 ) ); - } - } else { - var ratio = this._contentBounds["width"] / this._contentBounds["height"], - bbox = $.geo.reaspect( this._getBbox( center, pixelSize ), ratio, true ), - bboxMax = $.geo.reaspect(this._getBboxMax(), ratio, true); - - return Math.round( Math.log($.geo.width(bboxMax, true) / $.geo.width(bbox, true)) / Math.log(this._zoomFactor) ); - } - }, - - _setZoom: function ( value, trigger, refresh ) { - // set the map widget's zoom, taking zoomMin and zoomMax into account - this._clearInteractiveTimeout( ); - - value = Math.min( Math.max( value, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ); - - this._setInteractiveCenterAndSize( this._centerInteractive, this._getPixelSize( value ) ); - this._interactiveTransform( ); - this._setInteractiveTimeout( trigger ); - }, - - _createChildren: function () { - this._$existingChildren = this._$elem.children(); - - this._forcePosition(this._$existingChildren); - - this._$existingChildren.detach().css( { - mozUserSelect: "none" - } ); - - - var contentSizeCss = "width:" + this._contentBounds["width"] + "px; height:" + this._contentBounds["height"] + "px; margin:0; padding:0;", - contentPosCss = "position:absolute; left:0; top:0;"; - - this._$elem.prepend('
                                  '); - this._$eventTarget = this._$contentFrame = this._$elem.children(':first'); - - this._$contentFrame.append('
                                  '); - this._$servicesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append( '
                                    ' ); - this._$attrList = this._$contentFrame.children( ":last" ); - - this._$contentFrame.append('
                                    '); - this._$drawContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                                    '); - this._$measureContainer = this._$contentFrame.children(':last'); - this._$measureLabel = this._$measureContainer.children(); - - this._$contentFrame.append('
                                    '); - this._$shapesContainer = this._$contentFrame.children(':last'); - - this._$panContainer = $( [ this._$shapesContainer[ 0 ], this._$drawContainer[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$resizeContainer = $( [ this._$contentFrame[ 0 ], this._$servicesContainer[ 0 ], this._$eventTarget[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$contentFrame.append(this._$existingChildren); - - if ( ! $("#geo-measure-style").length ) { - $("head").prepend( '' ); - } - }, - - _createServices: function () { - var service, i; - - for ( i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap( "destroy" ); - $.geo[ "_serviceTypes" ][ this._currentServices[ i ].type ].destroy( this, this._$servicesContainer, this._currentServices[ i ] ); - } - - this._currentServices = [ ]; - this._$servicesContainer.html( "" ); - this._$attrList.html( "" ); - - for ( i = 0; i < this._options[ "services" ].length; i++ ) { - service = this._currentServices[ i ] = $.extend( { }, this._options[ "services" ][ i ] ); - - // keep a reference to the original - service.serviceObject = this._options[ "services" ][ i ]; - - // default the service style property on our copy - service.style = $.extend( { - visibility: "visible", - opacity: 1 - }, service.style ); - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = 'class="geo-service ' + ( service["class"] ? service["class"] : '' ) + '"', - scHtml = '
                                    ', - servicesContainer; - - this._$servicesContainer.append( scHtml ); - serviceContainer = this._$servicesContainer.children( ":last" ); - service.serviceContainer = serviceContainer; - - $.geo[ "_serviceTypes" ][ service.type ].create( this, serviceContainer, service, i ); - - serviceContainer.data( "geoMap", this ).geomap(); - - if ( service.attr ) { - this._$attrList.append( '
                                  • ' + service.attr + '
                                  • ' ); - } - } - - // start with our map-level shapesContainer - this._$shapesContainers = this._$shapesContainer; - - this._$attrList.find( "a" ).css( { - position: "relative", - zIndex: 100 - } ); - }, - - _createServiceGraphics: function( ) { - // only called in the context of a service-level geomap - var $contentFrame = this._$elem.closest( ".geo-content-frame" ); - this._$elem.append('
                                    '); - this._$shapesContainer = this._$elem.children(':last'); - - this._map._$shapesContainers = this._map._$shapesContainers.add( this._$shapesContainer ); - - this._$shapesContainer.geographics( ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - }, - - _refreshDrawing: function ( ) { - this._$drawContainer.geographics("clear"); - - if ( this._drawPixels.length > 0 ) { - var mode = this._options[ "mode" ], - pixels = this._drawPixels, - coords = this._drawCoords, - label, - labelShape, - labelPixel, - widthOver, - heightOver; - - switch ( mode ) { - case "measureLength": - mode = "drawLineString"; - labelShape = { - type: "LineString", - coordinates: coords - }; - label = $.render[ this._tmplLengthId ]( { length: $.geo.length( labelShape, true ) } ); - labelPixel = $.merge( [], pixels[ pixels.length - 1 ] ); - break; - - case "measureArea": - mode = "drawPolygon"; - - labelShape = { - type: "Polygon", - coordinates: [ $.merge( [ ], coords ) ] - }; - labelShape.coordinates[ 0 ].push( coords[ 0 ] ); - - label = $.render[ this._tmplAreaId ]( { area: $.geo.area( labelShape, true ) } ); - labelPixel = this._toPixel( $.geo.centroid( labelShape ).coordinates ); - pixels = [ pixels ]; - break; - - case "drawPolygon": - pixels = [ pixels ]; - break; - } - - this._$drawContainer.geographics( mode, pixels ); - - if ( label ) { - this._$measureLabel.html( label ); - - widthOver = this._contentBounds.width - ( this._$measureLabel.outerWidth( true ) + labelPixel[ 0 ] ); - heightOver = this._contentBounds.height - ( this._$measureLabel.outerHeight( true ) + labelPixel[ 1 ] ); - - if ( widthOver < 0 ) { - labelPixel[ 0 ] += widthOver; - } - - if ( heightOver < 0 ) { - labelPixel[ 1 ] += heightOver; - } - - this._$measureLabel.css( { - left: Math.max( labelPixel[ 0 ], 0 ), - top: Math.max( labelPixel[ 1 ], 0 ) - } ).show(); - } - } - }, - - _resetDrawing: function () { - this._drawPixels = []; - this._drawCoords = []; - this._$drawContainer.geographics("clear"); - this._$measureLabel.hide(); - }, - - _refreshAllShapes: function ( ) { - this._timeoutRefreshShapes = null; - - var service, - geoService, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - geoService = service.serviceContainer.data( "geoService" ); - - if ( geoService._createdGraphics ) { - geoService._$shapesContainer.geographics( "clear" ); - if ( geoService._graphicShapes.length > 0 ) { - geoService._refreshShapes( geoService._$shapesContainer, geoService._graphicShapes, geoService._graphicShapes, geoService._graphicShapes ); - } - } - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics( "clear" ); - if ( this._graphicShapes.length > 0 ) { - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - } - }, - - - _refreshShapes: function (geographics, shapes, styles, labels, center, pixelSize) { - var i, mgi, - shape, - shapeBbox, - style, - label, - hasLabel, - labelPixel, - bbox = this._map._getBbox(center, pixelSize); - - /* - if ( shapes.length > 0 ) { - console.log( "_refreshShapes " + $.now() ); - } - */ - for (i = 0; i < shapes.length; i++) { - shape = shapes[i].shape || shapes[i]; - shape = shape.geometry || shape; - shapeBbox = $.data(shape, "geoBbox"); - - if ( shapeBbox && $.geo._bboxDisjoint( bbox, shapeBbox ) ) { - continue; - } - - style = $.isArray(styles) ? styles[i].style : styles; - label = $.isArray(labels) ? labels[i].label : labels; - hasLabel = ( label !== undefined ); - labelPixel = undefined; - - switch (shape.type) { - case "Point": - labelPixel = this._map.toPixel( shape.coordinates, center, pixelSize ); - this._$shapesContainer.geographics("drawPoint", labelPixel, style); - break; - case "LineString": - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.pointAlong( shape, 0.5 ).coordinates, center, pixelSize ); - } - break; - case "Polygon": - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiPoint": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPoint", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiLineString": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiPolygon": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - - case "GeometryCollection": - this._refreshShapes(geographics, shape.geometries, style, label, center, pixelSize); - break; - } - - if ( hasLabel && labelPixel ) { - this._$shapesContainer.geographics( "drawLabel", labelPixel, label ); - } - } - }, - - _findMapSize: function () { - // really, really attempt to find a size for this thing - // even if it's hidden (look at parents) - var size = { width: 0, height: 0 }, - sizeContainer = this._$elem; - - while (sizeContainer.size() && !(size["width"] > 0 && size["height"] > 0)) { - size = { width: sizeContainer.width(), height: sizeContainer.height() }; - if (size["width"] <= 0 || size["height"] <= 0) { - size = { width: parseInt(sizeContainer.css("width"), 10), height: parseInt(sizeContainer.css("height"), 10) }; - } - sizeContainer = sizeContainer.parent(); - } - return size; - }, - - _forcePosition: function (elem) { - var cssPosition = elem.css("position"); - if (cssPosition != "relative" && cssPosition != "absolute" && cssPosition != "fixed") { - elem.css("position", "relative"); - } - }, - - _getPixelSize: function ( zoom ) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme !== null) { - if (zoom === 0) { - return tilingScheme.pixelSizes ? tilingScheme.pixelSizes[0] : tilingScheme.basePixelSize; - } - - zoom = Math.round(zoom); - zoom = Math.max(zoom, 0); - var levels = tilingScheme.pixelSizes ? tilingScheme.pixelSizes.length : tilingScheme.levels; - zoom = Math.min(zoom, levels - 1); - - if ( tilingScheme.pixelSizes ) { - return tilingScheme.pixelSizes[zoom]; - } else { - return tilingScheme.basePixelSize / Math.pow(2, zoom); - } - } else { - var bbox = $.geo.scaleBy( this._getBboxMax(), 1 / Math.pow( this._zoomFactor, zoom ), true ); - return Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - } - }, - - _getZoomCenterAndSize: function ( anchor, zoomDelta, full ) { - var zoomFactor = ( full ? this._fullZoomFactor : this._partialZoomFactor ), - scale = Math.pow( zoomFactor, -zoomDelta ), - pixelSize = this._pixelSizeInteractive * scale, - zoom = this._getZoom(this._centerInteractive, pixelSize); - - // clamp to zoom - if ( full && this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoomDelta < 0 && zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._pixelSizeInteractive; - } else if ( zoomDelta > 0 && zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._pixelSizeInteractive; - } - } - - var ratio = pixelSize / this._pixelSizeInteractive, - anchorMapCoord = this._toMap( anchor, this._centerInteractive, this._pixelSizeInteractive ), - centerDelta = [(this._centerInteractive[0] - anchorMapCoord[0]) * ratio, (this._centerInteractive[1] - anchorMapCoord[1]) * ratio], - scaleCenter = [anchorMapCoord[0] + centerDelta[0], anchorMapCoord[1] + centerDelta[1]]; - - return { pixelSize: pixelSize, center: scaleCenter }; - }, - - _mouseWheelFinish: function ( refresh ) { - this._wheelTimeout = null; - - if (this._wheelLevel !== 0) { - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, this._wheelLevel, this._options[ "tilingScheme" ] !== null ); - - this._wheelLevel = 0; - } else if ( refresh ) { - this._refresh(); - this._refreshAllShapes( ); - } - }, - - _panFinalize: function () { - if (this._panning) { - this._velocity = [0, 0]; - - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - image = this._options[ "axisLayout" ] === "image", - dxMap = -dx * this._pixelSize, - dyMap = ( image ? -1 : 1 ) * dy * this._pixelSize; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._inOp = false; - this._anchor = this._current; - this._mouseDown = this._toolPan = this._panning = false; - } - }, - - _panMove: function () { - if ( ! this._options[ "pannable" ] ) { - return; - } - - var dx = this._current[0] - this._lastDrag[0], - dy = this._current[1] - this._lastDrag[1], - i = 0, - service, - translateObj; - - if (this._toolPan || dx > 3 || dx < -3 || dy > 3 || dy < -3) { - if (!this._toolPan) { - this._toolPan = true; - this._$eventTarget.css("cursor", this._options["cursors"]["pan"]); - } - - if (this._mouseDown) { - this._velocity = [dx, dy]; - } - - if (dx !== 0 || dy !== 0) { - this._panning = true; - this._lastDrag = this._current; - - this._centerInteractive[ 0 ] -= ( dx * this._pixelSizeInteractive ); - this._centerInteractive[ 1 ] += ( ( this._options[ "axisLayout" ] === "image" ? -1 : 1 ) * dy * this._pixelSizeInteractive ); - this._setInteractiveCenterAndSize( this._centerInteractive, this._pixelSizeInteractive ); - this._interactiveTransform( ); - } - } - }, - - _clearInteractiveTimeout: function() { - if ( this._timeoutRefreshShapes ) { - clearTimeout( this._timeoutRefreshShapes ); - this._timeoutRefreshShapes = null; - } - - if ( this._timeoutInteractive ) { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - return true; - } else { - this._centerInteractive[ 0 ] = this._center[ 0 ]; - this._centerInteractive[ 1 ] = this._center[ 1 ]; - this._pixelSizeInteractive = this._pixelSize; - return false; - } - }, - - _interactiveTransform: function( ) { - var mapWidth = this._contentBounds[ "width" ], - mapHeight = this._contentBounds[ "height" ], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - bbox = [ this._centerInteractive[ 0 ] - halfWidth, this._centerInteractive[ 1 ] - halfHeight, this._centerInteractive[ 0 ] + halfWidth, this._centerInteractive[ 1 ] + halfHeight ]; - - var scalePixelSize = this._pixelSize, - scaleRatio = scalePixelSize / this._pixelSizeInteractive; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = this._toMap( [ 0, 0 ] ), - newPixelPoint = this._toPixel( oldMapOrigin, this._centerInteractive, this._pixelSizeInteractive ); - - - this._$shapesContainers.geographics("interactiveTransform", newPixelPoint, scaleRatio); - - /* - $scaleContainer.css( { - left: Math.round( newPixelPoint[ 0 ] ), - top: Math.round( newPixelPoint[ 1 ] ), - width: mapWidth * scaleRatio, - height: mapHeight * scaleRatio - } ); - */ - - } - - - - - - - - - - - - - - - - - - - - - for ( var i = 0; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo[ "_serviceTypes" ][ service.type ].interactiveTransform( this, service, this._centerInteractive, this._pixelSizeInteractive ); - } - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel( this._drawCoords, this._centerInteractive, this._pixelSizeInteractive ); - this._refreshDrawing(); - } - }, - - _interactiveTimeout: function( ) { - if ( this._isMultiTouch ) { - this._timeoutInteractive = setTimeout( $.proxy( interactiveTimeout, this ), 128 ); - } else if ( this._created && this._timeoutInteractive ) { - this._setCenterAndSize( this._centerInteractive, this._pixelSizeInteractive, this._triggerInteractive, true ); - this._timeoutInteractive = null; - this._triggerInteractive = false; - - this._timeoutRefreshShapes = setTimeout( $.proxy( this._refreshAllShapes, this ), 128 ); - } - }, - - _setInteractiveTimeout: function( trigger ) { - this._timeoutInteractive = setTimeout( $.proxy( this._interactiveTimeout, this ), 128 ); - this._triggerInteractive |= trigger; - }, - - _refresh: function ( force, _serviceContainer ) { - var service, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service, force ); - } - } - }, - - _setInteractiveCenterAndSize: function ( center, pixelSize ) { - // set the temporary (interactive) center & size - // also, update the public-facing options - // this does not take zoomMin or zoomMax into account - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - this._pixelSizeInteractive = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox( center, pixelSize ) ); - this._options["center"] = $.geo.proj.toGeodetic( center ); - } else { - this._options["bbox"] = this._getBbox( center, pixelSize ); - this._options["center"][ 0 ] = center[ 0 ]; - this._options["center"][ 1 ] = center[ 1 ]; - } - - this._options["pixelSize"] = pixelSize; - this._options["zoom"] = this._getZoom( center, pixelSize ); - }, - - _setCenterAndSize: function (center, pixelSize, trigger, refresh) { - if ( ! $.isArray( center ) || center.length != 2 || typeof center[ 0 ] !== "number" || typeof center[ 1 ] !== "number" ) { - return; - } - - // the final call during any extent change - // only called by timeoutInteractive & resize - // clamp to zoom - var zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._center[ 0 ] = center[ 0 ]; - this._center[ 1 ] = center[ 1 ]; - this._options["pixelSize"] = this._pixelSize = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox() ); - this._options["center"] = $.geo.proj.toGeodetic( this._center ); - } else { - this._options["bbox"] = this._getBbox(); - this._options["center"] = $.merge( [ ], center ); - } - - this._options["zoom"] = zoom; - - if (trigger) { - this._trigger("bboxchange", window.event, { bbox: $.merge( [ ], this._options["bbox"] ) }); - } - - if (refresh) { - this._refresh(); - this._refreshAllShapes( ); - this._refreshDrawing(); - } - }, - - _requestQueued: function ( ) { - if ( this._loadCount === 0 ) { - this._trigger( "loadstart", window.event ); - } - this._loadCount++; - }, - - _requestComplete: function ( ) { - this._loadCount--; - if ( this._loadCount <= 0 ) { - this._loadCount = 0; - this._trigger( "loadend", window.event ); - } - }, - - _toMap: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - xRatio = $.geo.width(bbox, true) / width, - yRatio = $.geo.height(bbox, true) / height, - yOffset, - image = this._options[ "axisLayout" ] === "image", - result = [], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - yOffset = (p[ i ][ j ][ k ][1] * yRatio); - result[ i ][ j ][ k ] = [ - bbox[ 0 ] + ( p[ i ][ j ][ k ][ 0 ] * xRatio ), - image ? bbox[ 1 ] + yOffset : bbox[ 3 ] - yOffset - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _toPixel: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - bboxWidth = $.geo.width(bbox, true), - bboxHeight = $.geo.height(bbox, true), - image = this._options[ "axisLayout" ] === "image", - xRatio = width / bboxWidth, - yRatio = height / bboxHeight, - result = [ ], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = [ - Math.round( ( p[ i ][ j ][ k ][ 0 ] - bbox[ 0 ] ) * xRatio ), - Math.round( ( image ? p[ i ][ j ][ k ][ 1 ] - bbox[ 1 ] : bbox[ 3 ] - p[ i ][ j ][ k ][ 1 ] ) * yRatio ) - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _document_keydown: function (e) { - var len = this._drawCoords.length; - if (len > 0 && e.which == 27) { - if (len <= 2) { - this._resetDrawing(); - this._inOp = false; - } else { - this._drawCoords[len - 2] = $.merge( [], this._drawCoords[ len - 1 ] ); - this._drawPixels[len - 2] = $.merge( [], this._drawPixels[ len - 1 ] ); - - this._drawCoords.length--; - this._drawPixels.length--; - - this._refreshDrawing(); - } - } - }, - - _eventTarget_dblclick_zoom: function(e) { - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - this._trigger("dblclick", e, { type: "Point", coordinates: this._toMap(this._current, this._centerInteractive, this._pixelSizeInteractive ) }); - - if (!e.isDefaultPrevented()) { - var centerAndSize = this._getZoomCenterAndSize(this._current, 1, true ); - - this._setInteractiveCenterAndSize( centerAndSize.center, centerAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - }, - - _eventTarget_dblclick: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - var offset = $(e.currentTarget).offset(); - - switch (this._options["mode"]) { - case "drawLineString": - case "measureLength": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - this._drawCoords.length--; - this._trigger( "shape", e, { - type: "LineString", - coordinates: this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords - } ); - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "drawPolygon": - case "measureArea": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - var endIndex = this._drawCoords.length - 1; - if (endIndex > 2) { - this._drawCoords[endIndex] = $.merge( [], this._drawCoords[0] ); - this._trigger( "shape", e, { - type: "Polygon", - coordinates: [ this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords ] - } ); - } - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - default: - this._eventTarget_dblclick_zoom(e); - break; - } - - this._inOp = false; - }, - - _eventTarget_touchstart: function (e) { - if (typeof(document.elementFromPoint) !== "undefined" && document.elementFromPoint(e.pageX, e.pageY).nodeName === "A") { - return; - } - - var mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ); - - if ( mode === "static" ) { - return; - } - - if ( !this._supportTouch && e.which != 1 ) { - return; - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var offset = $(e.currentTarget).offset(), - touches = e.originalEvent.changedTouches; - - if ( this._supportTouch ) { - this._multiTouchAnchor = $.merge( [ ], touches ); - - this._isMultiTouch = this._multiTouchAnchor.length > 1; - - if ( this._isMultiTouch ) { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - touches[1].pageX - offset.left, - touches[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ touches[0].pageX - offset.left, touches[0].pageY - offset.top ]; - } - } else { - this._current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - var downDate = $.now(); - if (downDate - this._downDate < 750) { - if (this._isTap) { - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance > 8) { - this._isTap = false; - } else { - this._current = $.merge( [ ], this._anchor ); - } - } - - if (this._isDbltap) { - this._isDbltap = false; - } else { - this._isDbltap = this._isTap; - } - } else { - this._isDbltap = false; - } - this._isTap = true; - this._downDate = downDate; - } - - this._mouseDown = true; - this._anchor = $.merge( [ ], this._current ); - - if (!this._inOp && e.shiftKey && shift !== "off") { - this._shiftDown = true; - this._$eventTarget.css( "cursor", this._options[ "cursors" ][ shift === "default" ? defaultShift : shift ] ); - } else if ( !this._isMultiTouch && ( this._options[ "pannable" ] || mode === "dragBox" || mode === "dragCircle" ) ) { - this._inOp = true; - - if ( mode !== "zoom" && mode !== "dragBox" && mode !== "dragCircle" ) { - this._lastDrag = this._current; - - if (e.currentTarget.setCapture) { - e.currentTarget.setCapture(); - } - } - } - - e.preventDefault(); - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - }, - - _dragTarget_touchmove: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - var doInteractiveTimeout = false; - if ( this._mouseDown ) { - doInteractiveTimeout = this._clearInteractiveTimeout( ); - } - - var offset = this._$eventTarget.offset(), - drawCoordsLen = this._drawCoords.length, - touches = e.originalEvent.changedTouches, - current, - service, - i = 0; - - if ( this._supportTouch ) { - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 && touches[ 0 ].identifier !== this._multiTouchAnchor[ 0 ].identifier ) { - // switch to multitouch - this._mouseDown = false; - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( touches[ 0 ] ); - - - - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._mouseDown = true; - this._anchor = this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - if ( this._isMultiTouch ) { - - for ( ; i < touches.length; i++ ) { - if ( touches[ i ].identifier === this._multiTouchAnchor[ 0 ].identifier ) { - this._multiTouchCurrentBbox[ 0 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = touches[ i ].pageY - offset.top; - } else if ( touches[ i ].identifier === this._multiTouchAnchor[ 1 ].identifier ) { - this._multiTouchCurrentBbox[ 2 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = touches[ i ].pageY - offset.top; - } - } - - var anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ), - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - var wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - var delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - var pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (current[0] === this._lastMove[0] && current[1] === this._lastMove[1]) { - if ( this._inOp ) { - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - } - - if ( _ieVersion == 7 ) { - this._isDbltap = this._isTap = false; - } - - if (this._mouseDown) { - this._current = current; - this._moveDate = $.now(); - } - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - var mode = this._options["mode"], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - dx, dy, circleSize; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - switch (mode) { - case "zoom": - case "dragBox": - if ( this._mouseDown ) { - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawBbox", [ - this._anchor[ 0 ], - this._anchor[ 1 ], - current[ 0 ], - current[ 1 ] - ] ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "dragCircle": - if ( this._mouseDown ) { - dx = current[ 0 ] - this._anchor[ 0 ]; - dy = current[ 1 ] - this._anchor[ 1 ]; - circleSize = Math.sqrt( ( dx * dx) + ( dy * dy ) ) * 2; - //circleSize = Math.max( Math.abs( current[ 0 ] - this._anchor[ 0 ] ), Math.abs( current[ 1 ] - this._anchor[ 1 ] ) ) * 2; - - // not part of _refreshDrawing - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawArc", this._anchor, 0, 360, { - width: circleSize, - height: circleSize - } ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - if (drawCoordsLen > 0) { - this._drawCoords[drawCoordsLen - 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[drawCoordsLen - 1] = current; - - this._refreshDrawing(); - } - - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - default: - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - } - - this._lastMove = current; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchstop: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if ( !this._mouseDown ) { - if ( _ieVersion == 7 ) { - // ie7 doesn't appear to trigger dblclick on this._$eventTarget, - // we fake regular click here to cause soft dblclick - this._eventTarget_touchstart(e); - } else { - // Chrome & Firefox trigger a rogue mouseup event when doing a dblclick maximize in Windows(/Linux?) - // ignore it - return; - } - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var mouseWasDown = this._mouseDown, - wasToolPan = this._toolPan, - offset = this._$eventTarget.offset(), - mode = this._options[ "mode" ], - shift = this._options[ "shift" ], - defaultShift = ( mode === "dragBox" ? "dragBox" : "zoom" ), - current, i, clickDate, - dx, dy, - coordBuffer, - triggerShape; - - if ( this._shiftDown ) { - mode = ( shift === "default" ? defaultShift : shift ); - } - - if (this._supportTouch) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - this._multiTouchAnchor = []; - this._inOp = false; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - if (this._isTap) { - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - if (Math.sqrt((dx * dx) + (dy * dy)) <= 8) { - current = $.merge( [ ], this._anchor ); - } - } - } - - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._shiftDown = this._mouseDown = this._toolPan = false; - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isMultiTouch = false; - - this._wheelLevel = 0; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return; - } - - if (document.releaseCapture) { - document.releaseCapture(); - } - - if (mouseWasDown) { - clickDate = $.now(); - this._current = current; - - switch ( mode ) { - case "zoom": - case "dragBox": - if ( dx !== 0 || dy !== 0 ) { - var minSize = this._pixelSize * 6, - bboxCoords = this._toMap( [ [ - Math.min( this._anchor[ 0 ], current[ 0 ] ), - Math.max( this._anchor[ 1 ], current[ 1 ] ) - ], [ - Math.max( this._anchor[ 0 ], current[ 0 ] ), - Math.min( this._anchor[ 1 ], current[ 1 ] ) - ] - ] ), - bbox = [ - bboxCoords[0][0], - bboxCoords[0][1], - bboxCoords[1][0], - bboxCoords[1][1] - ]; - - if ( mode === "zoom" ) { - if ( ( bbox[2] - bbox[0] ) < minSize && ( bbox[3] - bbox[1] ) < minSize ) { - bbox = $.geo.scaleBy( this._getBbox( $.geo.center( bbox, true ) ), 0.5, true ); - } - - this._setBbox(bbox, true, true); - doInteractiveTimeout = true; - } else { - triggerShape = $.geo.polygonize( bbox, true ); - triggerShape.bbox = bbox; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - this._trigger( "shape", e, triggerShape ); - } - } else { - if ( mode === "dragBox" ) { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - } - - this._resetDrawing(); - break; - - case "dragCircle": - if ( dx !== 0 || dy !== 0 ) { - var image = this._options[ "axisLayout" ] === "image", - d = Math.sqrt( ( dx * dx) + ( dy * dy ) ), - n = 180, - a; - - this._drawPixels.length = n + 1; - - for ( i = 0; i < n; i++ ) { - a = ( i * 360 / n ) * ( Math.PI / 180 ); - this._drawPixels[ i ] = [ - this._anchor[ 0 ] + Math.cos( a ) * d, - this._anchor[ 1 ] + Math.sin( a ) * d - ]; - } - - this._drawPixels[ n ] = [ - this._drawPixels[ 0 ][ 0 ], - this._drawPixels[ 0 ][ 1 ] - ]; - - // using coordBuffer for bbox coords - coordBuffer = this._toMap( [ - [ this._anchor[ 0 ] - d, this._anchor[ 1 ] + ( image ? -d : d ) ], - [ this._anchor[ 0 ] + d, this._anchor[ 1 ] + ( image ? d : -d ) ] - ] ); - - triggerShape = { - type: "Polygon", - coordinates: [ this._toMap( this._drawPixels ) ], - bbox: [ coordBuffer[ 0 ][ 0 ], coordBuffer[ 0 ][ 1 ], coordBuffer[ 1 ][ 0 ], coordBuffer[ 1 ][ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - - this._resetDrawing(); - } else { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - break; - - case "drawPoint": - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - var geomap = this; - this._drawTimeout = setTimeout(function () { - if (geomap._drawTimeout) { - geomap._trigger("shape", e, { type: "Point", coordinates: geomap.toMap(current) }); - geomap._inOp = false; - geomap._drawTimeout = null; - } - }, 250); - } - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (wasToolPan) { - this._panFinalize(); - } else { - i = (this._drawCoords.length === 0 ? 0 : this._drawCoords.length - 1); - - this._drawCoords[i] = this._toMap(current); - this._drawPixels[i] = current; - - if (i < 2 || !(this._drawCoords[i][0] == this._drawCoords[i-1][0] && - this._drawCoords[i][1] == this._drawCoords[i-1][1])) { - this._drawCoords[i + 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[i + 1] = current; - } - - this._refreshDrawing(); - } - break; - - default: - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - this._inOp = false; - } - } - break; - } - - this._clickDate = clickDate; - - if (this._softDblClick && this._isDbltap) { - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - this._$eventTarget.trigger("dblclick", e); - return false; - } - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _eventTarget_mousewheel: function (e, delta) { - if ( this._options[ "mode" ] === "static" || this._options[ "scroll" ] === "off" ) { - return; - } - - e.preventDefault(); - - if ( this._mouseDown ) { - return false; - } - - if (delta !== 0) { - this._clearInteractiveTimeout( ); - - if ( delta > 0 ) { - delta = Math.ceil( delta ); - } else { - delta = Math.floor( delta ); - } - - var offset = $(e.currentTarget).offset(); - this._anchor = [e.pageX - offset.left, e.pageY - offset.top]; - - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, this._options[ "tilingScheme" ] !== null ), - service, - i = 0; - - this._setInteractiveCenterAndSize( wheelCenterAndSize.center, wheelCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - this._setInteractiveTimeout( true ); - } - - return false; - } - } - ); -}(jQuery)); - - -(function ($, undefined) { - $.geo._serviceTypes.tiled = (function () { - return { - create: function (map, serviceContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0, - reloadTiles: false - }; - - var scHtml = '
                                    '; - - serviceContainer.append(scHtml); - - serviceState.serviceContainer = serviceContainer.children( ":last" ); - - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - //console.log( "tiled.interactiveTransform( " + center.join( ", " ) + ", " + pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ), - tilingScheme = map.options[ "tilingScheme" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( i ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data("pixelSize"), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapCoord = $scaleContainer.data("scaleOrigin"), - newPixelPoint = map._toPixel(oldMapCoord, center, pixelSize); - - $scaleContainer.css( { - left: Math.round(newPixelPoint[0]) + "px", - top: Math.round(newPixelPoint[1]) + "px", - width: tilingScheme.tileWidth * scaleRatio, - height: tilingScheme.tileHeight * scaleRatio - } ); - - /* - if ( $("body")[0].filters !== undefined ) { - $scaleContainer.children().each( function ( i ) { - $( this ).css( "filter", "progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11=" + scaleRatio + ",M22=" + scaleRatio + ",sizingmethod='auto expand')" ); - } ); - } - */ - } - }); - } - }, - - refresh: function (map, service, force) { - //console.log( "tiled.refresh( " + map._center.join( ", " ) + ", " + map._pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ); - - this._cancelUnloaded(map, service); - - if ( serviceState && force ) { - // if hidden atm, we want to make sure we reload this service after it becomes visible - serviceState.reloadTiles = true; - } - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - $serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - image = map.options[ "axisLayout" ] === "image", - ySign = image ? +1 : -1, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - - tileX = Math.floor((bbox[0] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.max( Math.floor( ( image ? bbox[1] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 3 ] ) / (pixelSize * tileHeight) ), 0 ), - tileX2 = Math.ceil((bbox[2] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil( ( image ? bbox[3] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 1 ] ) / (pixelSize * tileHeight) ), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] + ySign * bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMinOrMaxY = tilingScheme.origin[1] + ySign * (fullYAtScale * tileHeight) * pixelSize, - - serviceLeft = Math.round((fullXMinX - bbox[0]) / pixelSize), - serviceTop = Math.round( ( image ? fullYMinOrMaxY - bbox[1] : bbox[3] - fullYMinOrMaxY ) / pixelSize), - - scaleContainers = $serviceContainer.children().show(), - scaleContainer = scaleContainers.filter("[data-pixel-size='" + pixelSize + "']").appendTo($serviceContainer), - - opacity = service.style.opacity, - - x, y, - - loadImageDeferredDone = function( url ) { - // when a Deferred call is done, add the image to the map - // a reference to the correct img element is on the Deferred object itself - serviceObj._loadImage( $.data( this, "img" ), url, pixelSize, map, serviceState, opacity ); - }, - - loadImageDeferredFail = function( ) { - $.data( this, "img" ).remove( ); - serviceState.loadCount--; - map._requestComplete(); - }; - - if (serviceState.reloadTiles) { - scaleContainers.find("img").attr("data-dirty", "true"); - } - - if (!scaleContainer.size()) { - $serviceContainer.append("
                                    "); - scaleContainer = $serviceContainer.children(":last").data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - } else { - scaleContainer.css({ - left: (serviceLeft % tileWidth) + "px", - top: (serviceTop % tileHeight) + "px" - }).data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - - scaleContainer.children().each(function (i) { - var - $img = $(this), - tile = $img.attr("data-tile").split(","); - - $img.css({ - left: Math.round(((parseInt(tile[0], 10) - fullXAtScale) * 100) + (serviceLeft - (serviceLeft % tileWidth)) / tileWidth * 100) + "%", - top: Math.round(((parseInt(tile[1], 10) - fullYAtScale) * 100) + (serviceTop - (serviceTop % tileHeight)) / tileHeight * 100) + "%" - }); - - if (opacity < 1) { - $img.fadeTo(0, opacity); - } - }); - } - - for (x = tileX; x < tileX2; x++) { - for (y = tileY; y < tileY2; y++) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ($img.size() === 0 || serviceState.reloadTiles) { - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] + ySign * (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] + ySign * ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - urlProp = ( service.hasOwnProperty( "src" ) ? "src" : "getUrl" ), - urlArgs = { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl; - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - $.templates( "geoSrc", service[ urlProp ] ); - imageUrl = $.render[ "geoSrc" ]( urlArgs ); - } - - serviceState.loadCount++; - map._requestQueued(); - - if (serviceState.reloadTiles && $img.size() > 0) { - $img.attr("src", imageUrl); - } else { - var imgMarkup = ""; - - scaleContainer.append(imgMarkup); - $img = scaleContainer.children(":last"); - } - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl ) { - // assume Deferred - $.data( imageUrl, "img", $img ); - imageUrl.done( loadImageDeferredDone ).fail( loadImageDeferredFail ); - } else { - $img.remove( ); - } - } - } - } - - scaleContainers.find("[data-dirty]").remove(); - serviceState.reloadTiles = false; - } - }, - - resize: function (map, service) { - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.css( "display", service.style.visibility === "visible" ? "block" : "none" ); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery)); - -(function ($, undefined) { - $.geo._serviceTypes.shingled = (function () { - return { - create: function (map, serviceContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0 - }; - - var scHtml = '
                                    '; - - serviceContainer.append(scHtml); - - serviceState.serviceContainer = serviceContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - var serviceState = $.data( service, "geoServiceState" ), - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds[ "width" ], - mapHeight = contentBounds[ "height" ], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - bbox = [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( i ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data( "pixelSize" ), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin, center, pixelSize ); - - $scaleContainer.css( { - left: Math.round( newPixelPoint[ 0 ] ), - top: Math.round( newPixelPoint[ 1 ] ), - width: mapWidth * scaleRatio, - height: mapHeight * scaleRatio - } ); - } - }); - } - }, - - refresh: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - this._cancelUnloaded(map, service); - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainer = serviceContainer.children('[data-pixel-size="' + pixelSize + '"]'), - - opacity = service.style.opacity, - - $img; - - if (opacity < 1) { - serviceContainer.find("img").attr("data-keep-alive", "0"); - } - - if ( !scaleContainer.size() ) { - serviceContainer.append('
                                    '); - scaleContainer = serviceContainer.children(":last"); - } - - var urlProp = ( service.hasOwnProperty("src") ? "src" : "getUrl" ), - urlArgs = { - bbox: bbox, - width: mapWidth, - height: mapHeight, - zoom: map._getZoom(), - tile: null, - index: 0 - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl, - imagePos = scaleContainer.position( ); - - imagePos.left = - ( imagePos.left ); - imagePos.top = - ( imagePos.top ); - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - $.templates( "geoSrc", service[ urlProp ] ); - imageUrl = $.render[ "geoSrc" ]( urlArgs ); - } - - serviceState.loadCount++; - map._requestQueued(); - - scaleContainer.append(''); - $img = scaleContainer.children(":last").data("center", map._center); - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, map, serviceState, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - map._requestComplete(); - } ); - } - - } - }, - - resize: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState && service && service.style.visibility === "visible" ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainers = serviceContainer.children(); - - scaleContainers.attr("data-pixel-size", "0"); - - scaleContainers.each( function ( i ) { - var $scaleContainer = $(this), - position = $scaleContainer.position( ); - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin ); - - $scaleContainer.css( { - left: position.left + ( mapWidth - $scaleContainer.width( ) ) / 2, - top: position.top + ( mapHeight - $scaleContainer.height( ) ) / 2 - } ); - - } ); - - - /* - scaleContainer.css({ - left: halfWidth + 'px', - top: halfHeight + 'px' - }); - */ - } - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.css("display", service.style.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - // #newpanzoom - serviceContainer.children(':not([data-pixel-size="' + pixelSize + '"])').remove(); - - serviceContainer.find( "img[data-keep-alive]" ).remove( ); - - serviceState.loadCount = 0; - } - }).error(function (e) { - if ( !$.contains(document.body, e.target.jquery ? e.target[0] : e.target) ) { - // this image has been canceled and removed from the DOM - return; - } - - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery)); diff --git a/dist/jquery.geo-1.0b1.js b/dist/jquery.geo-1.0b1.js deleted file mode 100644 index 6a8c9c3..0000000 --- a/dist/jquery.geo-1.0b1.js +++ /dev/null @@ -1,6943 +0,0 @@ -/*! jQuery Geo - v1.0b1.0.1 - 2012-08-01 - * http://jquerygeo.com - * Copyright (c) 2012 Ryan Westphal/Applied Geographics, Inc.; Licensed MIT, GPL */ - -// Copyright 2006 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -// Known Issues: -// -// * Patterns only support repeat. -// * Radial gradient are not implemented. The VML version of these look very -// different from the canvas one. -// * Clipping paths are not implemented. -// * Coordsize. The width and height attribute have higher priority than the -// width and height style values which isn't correct. -// * Painting mode isn't implemented. -// * Canvas width/height should is using content-box by default. IE in -// Quirks mode will draw the canvas using border-box. Either change your -// doctype to HTML5 -// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) -// or use Box Sizing Behavior from WebFX -// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) -// * Non uniform scaling does not correctly scale strokes. -// * Optimize. There is always room for speed improvements. - -// Only add this code if we do not already have a canvas implementation -if (!document.createElement('canvas').getContext) { - - (function () { - - // alias some functions to make (compiled) code shorter - var m = Math; - var mr = m.round; - var ms = m.sin; - var mc = m.cos; - var abs = m.abs; - var sqrt = m.sqrt; - - // this is used for sub pixel precision - var Z = 10; - var Z2 = Z / 2; - - var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; - - /** - * This funtion is assigned to the elements as element.getContext(). - * @this {HTMLElement} - * @return {CanvasRenderingContext2D_} - */ - function getContext() { - return this.context_ || - (this.context_ = new CanvasRenderingContext2D_(this)); - } - - var slice = Array.prototype.slice; - - /** - * Binds a function to an object. The returned function will always use the - * passed in {@code obj} as {@code this}. - * - * Example: - * - * g = bind(f, obj, a, b) - * g(c, d) // will do f.call(obj, a, b, c, d) - * - * @param {Function} f The function to bind the object to - * @param {Object} obj The object that should act as this when the function - * is called - * @param {*} var_args Rest arguments that will be used as the initial - * arguments when the function is called - * @return {Function} A new function that has bound this - */ - function bind(f, obj, var_args) { - var a = slice.call(arguments, 2); - return function () { - return f.apply(obj, a.concat(slice.call(arguments))); - }; - } - - function encodeHtmlAttribute(s) { - return String(s).replace(/&/g, '&').replace(/"/g, '"'); - } - - function addNamespace(doc, prefix, urn) { - if (!doc.namespaces[prefix]) { - doc.namespaces.add(prefix, urn, '#default#VML'); - } - } - - function addNamespacesAndStylesheet(doc) { - addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); - addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); - - // Setup default CSS. Only add one style sheet per document - if (!doc.styleSheets['ex_canvas_']) { - var ss = doc.createStyleSheet(); - ss.owningElement.id = 'ex_canvas_'; - ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + - // default size is 300x150 in Gecko and Opera - 'text-align:left;width:300px;height:150px}'; - } - } - - // Add namespaces and stylesheet at startup. - addNamespacesAndStylesheet(document); - - var G_vmlCanvasManager_ = { - init: function (opt_doc) { - var doc = opt_doc || document; - // Create a dummy element so that IE will allow canvas elements to be - // recognized. - doc.createElement('canvas'); - doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); - }, - - init_: function (doc) { - // find all canvas elements - var els = doc.getElementsByTagName('canvas'); - for (var i = 0; i < els.length; i++) { - this.initElement(els[i]); - } - }, - - /** - * Public initializes a canvas element so that it can be used as canvas - * element from now on. This is called automatically before the page is - * loaded but if you are creating elements using createElement you need to - * make sure this is called on the element. - * @param {HTMLElement} el The canvas element to initialize. - * @return {HTMLElement} the element that was created. - */ - initElement: function (el) { - if (!el.getContext) { - el.getContext = getContext; - - // Add namespaces and stylesheet to document of the element. - addNamespacesAndStylesheet(el.ownerDocument); - - // Remove fallback content. There is no way to hide text nodes so we - // just remove all childNodes. We could hide all elements and remove - // text nodes but who really cares about the fallback content. - el.innerHTML = ''; - - // do not use inline function because that will leak memory - el.attachEvent('onpropertychange', onPropertyChange); - el.attachEvent('onresize', onResize); - - var attrs = el.attributes; - if (attrs.width && attrs.width.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setWidth_(attrs.width.nodeValue); - el.style.width = attrs.width.nodeValue + 'px'; - } else { - el.width = el.clientWidth; - } - if (attrs.height && attrs.height.specified) { - // TODO: use runtimeStyle and coordsize - // el.getContext().setHeight_(attrs.height.nodeValue); - el.style.height = attrs.height.nodeValue + 'px'; - } else { - el.height = el.clientHeight; - } - //el.getContext().setCoordsize_() - } - return el; - } - }; - - function onPropertyChange(e) { - var el = e.srcElement; - - switch (e.propertyName) { - case 'width': - el.getContext().clearRect(); - el.style.width = el.attributes.width.nodeValue + 'px'; - // In IE8 this does not trigger onresize. - el.firstChild.style.width = el.clientWidth + 'px'; - break; - case 'height': - el.getContext().clearRect(); - el.style.height = el.attributes.height.nodeValue + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - break; - } - } - - function onResize(e) { - var el = e.srcElement; - if (el.firstChild) { - el.firstChild.style.width = el.clientWidth + 'px'; - el.firstChild.style.height = el.clientHeight + 'px'; - } - } - - G_vmlCanvasManager_.init(); - - // precompute "00" to "FF" - var decToHex = []; - for (var i = 0; i < 16; i++) { - for (var j = 0; j < 16; j++) { - decToHex[i * 16 + j] = i.toString(16) + j.toString(16); - } - } - - function createMatrixIdentity() { - return [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1] - ]; - } - - function matrixMultiply(m1, m2) { - var result = createMatrixIdentity(); - - for (var x = 0; x < 3; x++) { - for (var y = 0; y < 3; y++) { - var sum = 0; - - for (var z = 0; z < 3; z++) { - sum += m1[x][z] * m2[z][y]; - } - - result[x][y] = sum; - } - } - return result; - } - - function copyState(o1, o2) { - o2.fillStyle = o1.fillStyle; - o2.lineCap = o1.lineCap; - o2.lineJoin = o1.lineJoin; - o2.lineWidth = o1.lineWidth; - o2.miterLimit = o1.miterLimit; - o2.shadowBlur = o1.shadowBlur; - o2.shadowColor = o1.shadowColor; - o2.shadowOffsetX = o1.shadowOffsetX; - o2.shadowOffsetY = o1.shadowOffsetY; - o2.strokeStyle = o1.strokeStyle; - o2.globalAlpha = o1.globalAlpha; - o2.font = o1.font; - o2.textAlign = o1.textAlign; - o2.textBaseline = o1.textBaseline; - o2.arcScaleX_ = o1.arcScaleX_; - o2.arcScaleY_ = o1.arcScaleY_; - o2.lineScale_ = o1.lineScale_; - } - - // var colorData = { - // aliceblue: '#F0F8FF', - // antiquewhite: '#FAEBD7', - // aquamarine: '#7FFFD4', - // azure: '#F0FFFF', - // beige: '#F5F5DC', - // bisque: '#FFE4C4', - // black: '#000000', - // blanchedalmond: '#FFEBCD', - // blueviolet: '#8A2BE2', - // brown: '#A52A2A', - // burlywood: '#DEB887', - // cadetblue: '#5F9EA0', - // chartreuse: '#7FFF00', - // chocolate: '#D2691E', - // coral: '#FF7F50', - // cornflowerblue: '#6495ED', - // cornsilk: '#FFF8DC', - // crimson: '#DC143C', - // cyan: '#00FFFF', - // darkblue: '#00008B', - // darkcyan: '#008B8B', - // darkgoldenrod: '#B8860B', - // darkgray: '#A9A9A9', - // darkgreen: '#006400', - // darkgrey: '#A9A9A9', - // darkkhaki: '#BDB76B', - // darkmagenta: '#8B008B', - // darkolivegreen: '#556B2F', - // darkorange: '#FF8C00', - // darkorchid: '#9932CC', - // darkred: '#8B0000', - // darksalmon: '#E9967A', - // darkseagreen: '#8FBC8F', - // darkslateblue: '#483D8B', - // darkslategray: '#2F4F4F', - // darkslategrey: '#2F4F4F', - // darkturquoise: '#00CED1', - // darkviolet: '#9400D3', - // deeppink: '#FF1493', - // deepskyblue: '#00BFFF', - // dimgray: '#696969', - // dimgrey: '#696969', - // dodgerblue: '#1E90FF', - // firebrick: '#B22222', - // floralwhite: '#FFFAF0', - // forestgreen: '#228B22', - // gainsboro: '#DCDCDC', - // ghostwhite: '#F8F8FF', - // gold: '#FFD700', - // goldenrod: '#DAA520', - // grey: '#808080', - // greenyellow: '#ADFF2F', - // honeydew: '#F0FFF0', - // hotpink: '#FF69B4', - // indianred: '#CD5C5C', - // indigo: '#4B0082', - // ivory: '#FFFFF0', - // khaki: '#F0E68C', - // lavender: '#E6E6FA', - // lavenderblush: '#FFF0F5', - // lawngreen: '#7CFC00', - // lemonchiffon: '#FFFACD', - // lightblue: '#ADD8E6', - // lightcoral: '#F08080', - // lightcyan: '#E0FFFF', - // lightgoldenrodyellow: '#FAFAD2', - // lightgreen: '#90EE90', - // lightgrey: '#D3D3D3', - // lightpink: '#FFB6C1', - // lightsalmon: '#FFA07A', - // lightseagreen: '#20B2AA', - // lightskyblue: '#87CEFA', - // lightslategray: '#778899', - // lightslategrey: '#778899', - // lightsteelblue: '#B0C4DE', - // lightyellow: '#FFFFE0', - // limegreen: '#32CD32', - // linen: '#FAF0E6', - // magenta: '#FF00FF', - // mediumaquamarine: '#66CDAA', - // mediumblue: '#0000CD', - // mediumorchid: '#BA55D3', - // mediumpurple: '#9370DB', - // mediumseagreen: '#3CB371', - // mediumslateblue: '#7B68EE', - // mediumspringgreen: '#00FA9A', - // mediumturquoise: '#48D1CC', - // mediumvioletred: '#C71585', - // midnightblue: '#191970', - // mintcream: '#F5FFFA', - // mistyrose: '#FFE4E1', - // moccasin: '#FFE4B5', - // navajowhite: '#FFDEAD', - // oldlace: '#FDF5E6', - // olivedrab: '#6B8E23', - // orange: '#FFA500', - // orangered: '#FF4500', - // orchid: '#DA70D6', - // palegoldenrod: '#EEE8AA', - // palegreen: '#98FB98', - // paleturquoise: '#AFEEEE', - // palevioletred: '#DB7093', - // papayawhip: '#FFEFD5', - // peachpuff: '#FFDAB9', - // peru: '#CD853F', - // pink: '#FFC0CB', - // plum: '#DDA0DD', - // powderblue: '#B0E0E6', - // rosybrown: '#BC8F8F', - // royalblue: '#4169E1', - // saddlebrown: '#8B4513', - // salmon: '#FA8072', - // sandybrown: '#F4A460', - // seagreen: '#2E8B57', - // seashell: '#FFF5EE', - // sienna: '#A0522D', - // skyblue: '#87CEEB', - // slateblue: '#6A5ACD', - // slategray: '#708090', - // slategrey: '#708090', - // snow: '#FFFAFA', - // springgreen: '#00FF7F', - // steelblue: '#4682B4', - // tan: '#D2B48C', - // thistle: '#D8BFD8', - // tomato: '#FF6347', - // turquoise: '#40E0D0', - // violet: '#EE82EE', - // wheat: '#F5DEB3', - // whitesmoke: '#F5F5F5', - // yellowgreen: '#9ACD32' - // }; - - - function getRgbHslContent(styleString) { - var start = styleString.indexOf('(', 3); - var end = styleString.indexOf(')', start + 1); - var parts = styleString.substring(start + 1, end).split(','); - // add alpha if needed - if (parts.length != 4 || styleString.charAt(3) != 'a') { - parts[3] = 1; - } - return parts; - } - - function percent(s) { - return parseFloat(s) / 100; - } - - function clamp(v, min, max) { - return Math.min(max, Math.max(min, v)); - } - - function hslToRgb(parts) { - var r, g, b, h, s, l; - h = parseFloat(parts[0]) / 360 % 360; - if (h < 0) - h++; - s = clamp(percent(parts[1]), 0, 1); - l = clamp(percent(parts[2]), 0, 1); - if (s == 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1 / 3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1 / 3); - } - - return '#' + decToHex[Math.floor(r * 255)] + - decToHex[Math.floor(g * 255)] + - decToHex[Math.floor(b * 255)]; - } - - function hueToRgb(m1, m2, h) { - if (h < 0) - h++; - if (h > 1) - h--; - - if (6 * h < 1) - return m1 + (m2 - m1) * 6 * h; - else if (2 * h < 1) - return m2; - else if (3 * h < 2) - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - else - return m1; - } - - var processStyleCache = {}; - - function processStyle(styleString) { - if (styleString in processStyleCache) { - return processStyleCache[styleString]; - } - - var str, alpha = 1; - - styleString = String(styleString); - if (styleString.charAt(0) == '#') { - str = styleString; - } else if (/^rgb/.test(styleString)) { - var parts = getRgbHslContent(styleString); - var str = '#', n; - for (var i = 0; i < 3; i++) { - if (parts[i].indexOf('%') != -1) { - n = Math.floor(percent(parts[i]) * 255); - } else { - n = +parts[i]; - } - str += decToHex[clamp(n, 0, 255)]; - } - alpha = +parts[3]; - } else if (/^hsl/.test(styleString)) { - var parts = getRgbHslContent(styleString); - str = hslToRgb(parts); - alpha = parts[3]; - } else { - str = /*colorData[styleString] ||*/styleString; - } - return processStyleCache[styleString] = { color: str, alpha: alpha }; - } - - var DEFAULT_STYLE = { - style: 'normal', - variant: 'normal', - weight: 'normal', - size: 10, - family: 'sans-serif' - }; - - // Internal text style cache - // var fontStyleCache = {}; - - // function processFontStyle(styleString) { - // if (fontStyleCache[styleString]) { - // return fontStyleCache[styleString]; - // } - - // var el = document.createElement('div'); - // var style = el.style; - // try { - // style.font = styleString; - // } catch (ex) { - // // Ignore failures to set to invalid font. - // } - - // return fontStyleCache[styleString] = { - // style: style.fontStyle || DEFAULT_STYLE.style, - // variant: style.fontVariant || DEFAULT_STYLE.variant, - // weight: style.fontWeight || DEFAULT_STYLE.weight, - // size: style.fontSize || DEFAULT_STYLE.size, - // family: style.fontFamily || DEFAULT_STYLE.family - // }; - // } - - // function getComputedStyle(style, element) { - // var computedStyle = {}; - - // for (var p in style) { - // computedStyle[p] = style[p]; - // } - - // // Compute the size - // var canvasFontSize = parseFloat(element.currentStyle.fontSize), - // fontSize = parseFloat(style.size); - - // if (typeof style.size == 'number') { - // computedStyle.size = style.size; - // } else if (style.size.indexOf('px') != -1) { - // computedStyle.size = fontSize; - // } else if (style.size.indexOf('em') != -1) { - // computedStyle.size = canvasFontSize * fontSize; - // } else if(style.size.indexOf('%') != -1) { - // computedStyle.size = (canvasFontSize / 100) * fontSize; - // } else if (style.size.indexOf('pt') != -1) { - // computedStyle.size = fontSize / .75; - // } else { - // computedStyle.size = canvasFontSize; - // } - - // // Different scaling between normal text and VML text. This was found using - // // trial and error to get the same size as non VML text. - // computedStyle.size *= 0.981; - - // return computedStyle; - // } - - // function buildStyle(style) { - // return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + - // style.size + 'px ' + style.family; - // } - - var lineCapMap = { - 'butt': 'flat', - 'round': 'round' - }; - - function processLineCap(lineCap) { - return lineCapMap[lineCap] || 'square'; - } - - /** - * This class implements CanvasRenderingContext2D interface as described by - * the WHATWG. - * @param {HTMLElement} canvasElement The element that the 2D context should - * be associated with - */ - function CanvasRenderingContext2D_(canvasElement) { - this.m_ = createMatrixIdentity(); - - this.mStack_ = []; - this.aStack_ = []; - this.currentPath_ = []; - - // Canvas context properties - this.strokeStyle = '#000'; - this.fillStyle = '#000'; - - this.lineWidth = 1; - this.lineJoin = 'miter'; - this.lineCap = 'butt'; - this.miterLimit = Z * 1; - this.globalAlpha = 1; - //this.font = '10px sans-serif'; - //this.textAlign = 'left'; - //this.textBaseline = 'alphabetic'; - this.canvas = canvasElement; - - var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + - canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; - var el = canvasElement.ownerDocument.createElement('div'); - el.style.cssText = cssText; - canvasElement.appendChild(el); - - var overlayEl = el.cloneNode(false); - // Use a non transparent background. - overlayEl.style.backgroundColor = 'red'; - overlayEl.style.filter = 'alpha(opacity=0)'; - canvasElement.appendChild(overlayEl); - - this.element_ = el; - this.arcScaleX_ = 1; - this.arcScaleY_ = 1; - this.lineScale_ = 1; - } - - var contextPrototype = CanvasRenderingContext2D_.prototype; - contextPrototype.clearRect = function () { - if (this.textMeasureEl_) { - this.textMeasureEl_.removeNode(true); - this.textMeasureEl_ = null; - } - this.element_.innerHTML = ''; - }; - - contextPrototype.beginPath = function () { - // TODO: Branch current matrix so that save/restore has no effect - // as per safari docs. - this.currentPath_ = []; - }; - - contextPrototype.moveTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'moveTo', x: p.x, y: p.y }); - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.lineTo = function (aX, aY) { - var p = getCoords(this, aX, aY); - this.currentPath_.push({ type: 'lineTo', x: p.x, y: p.y }); - - this.currentX_ = p.x; - this.currentY_ = p.y; - }; - - contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY) { - var p = getCoords(this, aX, aY); - var cp1 = getCoords(this, aCP1x, aCP1y); - var cp2 = getCoords(this, aCP2x, aCP2y); - bezierCurveTo(this, cp1, cp2, p); - }; - - // Helper function that takes the already fixed cordinates. - function bezierCurveTo(self, cp1, cp2, p) { - self.currentPath_.push({ - type: 'bezierCurveTo', - cp1x: cp1.x, - cp1y: cp1.y, - cp2x: cp2.x, - cp2y: cp2.y, - x: p.x, - y: p.y - }); - self.currentX_ = p.x; - self.currentY_ = p.y; - } - - contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { - // the following is lifted almost directly from - // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes - - var cp = getCoords(this, aCPx, aCPy); - var p = getCoords(this, aX, aY); - - var cp1 = { - x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), - y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) - }; - var cp2 = { - x: cp1.x + (p.x - this.currentX_) / 3.0, - y: cp1.y + (p.y - this.currentY_) / 3.0 - }; - - bezierCurveTo(this, cp1, cp2, p); - }; - - contextPrototype.arc = function (aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise) { - aRadius *= Z; - var arcType = aClockwise ? 'at' : 'wa'; - - var xStart = aX + mc(aStartAngle) * aRadius - Z2; - var yStart = aY + ms(aStartAngle) * aRadius - Z2; - - var xEnd = aX + mc(aEndAngle) * aRadius - Z2; - var yEnd = aY + ms(aEndAngle) * aRadius - Z2; - - // IE won't render arches drawn counter clockwise if xStart == xEnd. - if (xStart == xEnd && !aClockwise) { - xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something - // that can be represented in binary - } - - var p = getCoords(this, aX, aY); - var pStart = getCoords(this, xStart, yStart); - var pEnd = getCoords(this, xEnd, yEnd); - - this.currentPath_.push({ type: arcType, - x: p.x, - y: p.y, - radius: aRadius, - xStart: pStart.x, - yStart: pStart.y, - xEnd: pEnd.x, - yEnd: pEnd.y - }); - - }; - - // contextPrototype.rect = function(aX, aY, aWidth, aHeight) { - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // }; - - // contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.stroke(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { - // var oldPath = this.currentPath_; - // this.beginPath(); - - // this.moveTo(aX, aY); - // this.lineTo(aX + aWidth, aY); - // this.lineTo(aX + aWidth, aY + aHeight); - // this.lineTo(aX, aY + aHeight); - // this.closePath(); - // this.fill(); - - // this.currentPath_ = oldPath; - // }; - - // contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { - // var gradient = new CanvasGradient_('gradient'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // return gradient; - // }; - - // contextPrototype.createRadialGradient = function(aX0, aY0, aR0, - // aX1, aY1, aR1) { - // var gradient = new CanvasGradient_('gradientradial'); - // gradient.x0_ = aX0; - // gradient.y0_ = aY0; - // gradient.r0_ = aR0; - // gradient.x1_ = aX1; - // gradient.y1_ = aY1; - // gradient.r1_ = aR1; - // return gradient; - // }; - - // contextPrototype.drawImage = function(image, var_args) { - // var dx, dy, dw, dh, sx, sy, sw, sh; - - // // to find the original width we overide the width and height - // var oldRuntimeWidth = image.runtimeStyle.width; - // var oldRuntimeHeight = image.runtimeStyle.height; - // image.runtimeStyle.width = 'auto'; - // image.runtimeStyle.height = 'auto'; - - // // get the original size - // var w = image.width; - // var h = image.height; - - // // and remove overides - // image.runtimeStyle.width = oldRuntimeWidth; - // image.runtimeStyle.height = oldRuntimeHeight; - - // if (arguments.length == 3) { - // dx = arguments[1]; - // dy = arguments[2]; - // sx = sy = 0; - // sw = dw = w; - // sh = dh = h; - // } else if (arguments.length == 5) { - // dx = arguments[1]; - // dy = arguments[2]; - // dw = arguments[3]; - // dh = arguments[4]; - // sx = sy = 0; - // sw = w; - // sh = h; - // } else if (arguments.length == 9) { - // sx = arguments[1]; - // sy = arguments[2]; - // sw = arguments[3]; - // sh = arguments[4]; - // dx = arguments[5]; - // dy = arguments[6]; - // dw = arguments[7]; - // dh = arguments[8]; - // } else { - // throw Error('Invalid number of arguments'); - // } - - // var d = getCoords(this, dx, dy); - - // var w2 = sw / 2; - // var h2 = sh / 2; - - // var vmlStr = []; - - // var W = 10; - // var H = 10; - - // // For some reason that I've now forgotten, using divs didn't work - // vmlStr.push(' ' , - // '', - // ''); - - // this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); - // }; - - contextPrototype.stroke = function (aFill) { - var lineStr = []; - var lineOpen = false; - - var W = 10; - var H = 10; - - lineStr.push(''); - - if (!aFill) { - appendStroke(this, lineStr); - } else { - appendFill(this, lineStr, min, max); - } - - lineStr.push(''); - - this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - }; - - function appendStroke(ctx, lineStr) { - var a = processStyle(ctx.strokeStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - var lineWidth = ctx.lineScale_ * ctx.lineWidth; - - // VML cannot correctly render a line if the width is less than 1px. - // In that case, we dilute the color to make the line look thinner. - if (lineWidth < 1) { - opacity *= lineWidth; - } - - lineStr.push( - '' - ); - } - - function appendFill(ctx, lineStr, min, max) { - var fillStyle = ctx.fillStyle; - var arcScaleX = ctx.arcScaleX_; - var arcScaleY = ctx.arcScaleY_; - var width = max.x - min.x; - var height = max.y - min.y; - // if (fillStyle instanceof CanvasGradient_) { - // // TODO: Gradients transformed with the transformation matrix. - // var angle = 0; - // var focus = {x: 0, y: 0}; - - // // additional offset - // var shift = 0; - // // scale factor for offset - // var expansion = 1; - - // if (fillStyle.type_ == 'gradient') { - // var x0 = fillStyle.x0_ / arcScaleX; - // var y0 = fillStyle.y0_ / arcScaleY; - // var x1 = fillStyle.x1_ / arcScaleX; - // var y1 = fillStyle.y1_ / arcScaleY; - // var p0 = getCoords(ctx, x0, y0); - // var p1 = getCoords(ctx, x1, y1); - // var dx = p1.x - p0.x; - // var dy = p1.y - p0.y; - // angle = Math.atan2(dx, dy) * 180 / Math.PI; - - // // The angle should be a non-negative number. - // if (angle < 0) { - // angle += 360; - // } - - // // Very small angles produce an unexpected result because they are - // // converted to a scientific notation string. - // if (angle < 1e-6) { - // angle = 0; - // } - // } else { - // var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); - // focus = { - // x: (p0.x - min.x) / width, - // y: (p0.y - min.y) / height - // }; - - // width /= arcScaleX * Z; - // height /= arcScaleY * Z; - // var dimension = m.max(width, height); - // shift = 2 * fillStyle.r0_ / dimension; - // expansion = 2 * fillStyle.r1_ / dimension - shift; - // } - - // // We need to sort the color stops in ascending order by offset, - // // otherwise IE won't interpret it correctly. - // var stops = fillStyle.colors_; - // stops.sort(function(cs1, cs2) { - // return cs1.offset - cs2.offset; - // }); - - // var length = stops.length; - // var color1 = stops[0].color; - // var color2 = stops[length - 1].color; - // var opacity1 = stops[0].alpha * ctx.globalAlpha; - // var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; - - // var colors = []; - // for (var i = 0; i < length; i++) { - // var stop = stops[i]; - // colors.push(stop.offset * expansion + shift + ' ' + stop.color); - // } - - // // When colors attribute is used, the meanings of opacity and o:opacity2 - // // are reversed. - // lineStr.push(''); - // } else if (fillStyle instanceof CanvasPattern_) { - // if (width && height) { - // var deltaLeft = -min.x; - // var deltaTop = -min.y; - // lineStr.push(''); - // } - // } else { - var a = processStyle(ctx.fillStyle); - var color = a.color; - var opacity = a.alpha * ctx.globalAlpha; - lineStr.push(''); - // } - } - - contextPrototype.fill = function () { - this.stroke(true); - }; - - contextPrototype.closePath = function () { - this.currentPath_.push({ type: 'close' }); - }; - - function getCoords(ctx, aX, aY) { - var m = ctx.m_; - return { - x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, - y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 - }; - }; - - contextPrototype.save = function () { - var o = {}; - copyState(this, o); - this.aStack_.push(o); - this.mStack_.push(this.m_); - this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); - }; - - contextPrototype.restore = function () { - if (this.aStack_.length) { - copyState(this.aStack_.pop(), this); - this.m_ = this.mStack_.pop(); - } - }; - - function matrixIsFinite(m) { - return isFinite(m[0][0]) && isFinite(m[0][1]) && - isFinite(m[1][0]) && isFinite(m[1][1]) && - isFinite(m[2][0]) && isFinite(m[2][1]); - } - - function setM(ctx, m, updateLineScale) { - if (!matrixIsFinite(m)) { - return; - } - ctx.m_ = m; - - if (updateLineScale) { - // Get the line scale. - // Determinant of this.m_ means how much the area is enlarged by the - // transformation. So its square root can be used as a scale factor - // for width. - var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; - ctx.lineScale_ = sqrt(abs(det)); - } - } - - contextPrototype.translate = function (aX, aY) { - var m1 = [ - [1, 0, 0], - [0, 1, 0], - [aX, aY, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), false); - }; - - // contextPrototype.rotate = function(aRot) { - // var c = mc(aRot); - // var s = ms(aRot); - - // var m1 = [ - // [c, s, 0], - // [-s, c, 0], - // [0, 0, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), false); - // }; - - contextPrototype.scale = function (aX, aY) { - this.arcScaleX_ *= aX; - this.arcScaleY_ *= aY; - var m1 = [ - [aX, 0, 0], - [0, aY, 0], - [0, 0, 1] - ]; - - setM(this, matrixMultiply(m1, this.m_), true); - }; - - // contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { - // var m1 = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, matrixMultiply(m1, this.m_), true); - // }; - - // contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { - // var m = [ - // [m11, m12, 0], - // [m21, m22, 0], - // [dx, dy, 1] - // ]; - - // setM(this, m, true); - // }; - - /** - * The text drawing function. - * The maxWidth argument isn't taken in account, since no browser supports - * it yet. - */ - // contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { - // var m = this.m_, - // delta = 1000, - // left = 0, - // right = delta, - // offset = {x: 0, y: 0}, - // lineStr = []; - - // var fontStyle = getComputedStyle(processFontStyle(this.font), - // this.element_); - - // var fontStyleString = buildStyle(fontStyle); - - // var elementStyle = this.element_.currentStyle; - // var textAlign = this.textAlign.toLowerCase(); - // switch (textAlign) { - // case 'left': - // case 'center': - // case 'right': - // break; - // case 'end': - // textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; - // break; - // case 'start': - // textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; - // break; - // default: - // textAlign = 'left'; - // } - - // // 1.75 is an arbitrary number, as there is no info about the text baseline - // switch (this.textBaseline) { - // case 'hanging': - // case 'top': - // offset.y = fontStyle.size / 1.75; - // break; - // case 'middle': - // break; - // default: - // case null: - // case 'alphabetic': - // case 'ideographic': - // case 'bottom': - // offset.y = -fontStyle.size / 2.25; - // break; - // } - - // switch(textAlign) { - // case 'right': - // left = delta; - // right = 0.05; - // break; - // case 'center': - // left = right = delta / 2; - // break; - // } - - // var d = getCoords(this, x + offset.x, y + offset.y); - - // lineStr.push(''); - - // if (stroke) { - // appendStroke(this, lineStr); - // } else { - // // TODO: Fix the min and max params. - // appendFill(this, lineStr, {x: -left, y: 0}, - // {x: right, y: fontStyle.size}); - // } - - // var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + - // m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; - - // var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); - - // lineStr.push('', - // '', - // ''); - - // this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); - // }; - - // contextPrototype.fillText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, false); - // }; - - // contextPrototype.strokeText = function(text, x, y, maxWidth) { - // this.drawText_(text, x, y, maxWidth, true); - // }; - - // contextPrototype.measureText = function(text) { - // if (!this.textMeasureEl_) { - // var s = ''; - // this.element_.insertAdjacentHTML('beforeEnd', s); - // this.textMeasureEl_ = this.element_.lastChild; - // } - // var doc = this.element_.ownerDocument; - // this.textMeasureEl_.innerHTML = ''; - // this.textMeasureEl_.style.font = this.font; - // // Don't use innerHTML or innerText because they allow markup/whitespace. - // this.textMeasureEl_.appendChild(doc.createTextNode(text)); - // return {width: this.textMeasureEl_.offsetWidth}; - // }; - - /******** STUBS ********/ - // contextPrototype.clip = function() { - // // TODO: Implement - // }; - - // contextPrototype.arcTo = function() { - // // TODO: Implement - // }; - - // contextPrototype.createPattern = function(image, repetition) { - // return new CanvasPattern_(image, repetition); - // }; - - // // Gradient / Pattern Stubs - // function CanvasGradient_(aType) { - // this.type_ = aType; - // this.x0_ = 0; - // this.y0_ = 0; - // this.r0_ = 0; - // this.x1_ = 0; - // this.y1_ = 0; - // this.r1_ = 0; - // this.colors_ = []; - // } - - // CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { - // aColor = processStyle(aColor); - // this.colors_.push({offset: aOffset, - // color: aColor.color, - // alpha: aColor.alpha}); - // }; - - // function CanvasPattern_(image, repetition) { - // assertImageIsValid(image); - // switch (repetition) { - // case 'repeat': - // case null: - // case '': - // this.repetition_ = 'repeat'; - // break - // case 'repeat-x': - // case 'repeat-y': - // case 'no-repeat': - // this.repetition_ = repetition; - // break; - // default: - // throwException('SYNTAX_ERR'); - // } - - // this.src_ = image.src; - // this.width_ = image.width; - // this.height_ = image.height; - // } - - function throwException(s) { - throw new DOMException_(s); - } - - // function assertImageIsValid(img) { - // if (!img || img.nodeType != 1 || img.tagName != 'IMG') { - // throwException('TYPE_MISMATCH_ERR'); - // } - // if (img.readyState != 'complete') { - // throwException('INVALID_STATE_ERR'); - // } - // } - - function DOMException_(s) { - this.code = this[s]; - this.message = s + ': DOM Exception ' + this.code; - } - var p = DOMException_.prototype = new Error; - p.INDEX_SIZE_ERR = 1; - p.DOMSTRING_SIZE_ERR = 2; - p.HIERARCHY_REQUEST_ERR = 3; - p.WRONG_DOCUMENT_ERR = 4; - p.INVALID_CHARACTER_ERR = 5; - p.NO_DATA_ALLOWED_ERR = 6; - p.NO_MODIFICATION_ALLOWED_ERR = 7; - p.NOT_FOUND_ERR = 8; - p.NOT_SUPPORTED_ERR = 9; - p.INUSE_ATTRIBUTE_ERR = 10; - p.INVALID_STATE_ERR = 11; - p.SYNTAX_ERR = 12; - p.INVALID_MODIFICATION_ERR = 13; - p.NAMESPACE_ERR = 14; - p.INVALID_ACCESS_ERR = 15; - p.VALIDATION_ERR = 16; - p.TYPE_MISMATCH_ERR = 17; - - // set up externs - G_vmlCanvasManager = G_vmlCanvasManager_; - CanvasRenderingContext2D = CanvasRenderingContext2D_; - //CanvasGradient = CanvasGradient_; - //CanvasPattern = CanvasPattern_; - DOMException = DOMException_; - })(); - -} // if - -/*! JsRender v1.0pre: http://github.com/BorisMoore/jsrender */ -/* - * Optimized version of jQuery Templates, for rendering to string. - * Does not require jQuery, or HTML DOM - * Integrates with JsViews (http://github.com/BorisMoore/jsviews) - * Copyright 2012, Boris Moore - * Released under the MIT License. - */ -// informal pre beta commit counter: 3 - -this.jsviews || this.jQuery && jQuery.views || (function( window, undefined ) { - -//========================== Top-level vars ========================== - -var versionNumber = "v1.0pre", - - $, rTag, rTmplString, extend, - sub = {}, - FALSE = false, TRUE = true, - jQuery = window.jQuery, - - rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // nil object helper view viewProperty pathTokens leafToken string - - rParams = /(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - - rNewLine = /\r?\n/g, - rUnescapeQuotes = /\\(['"])/g, - rEscapeQuotes = /\\?(['"])/g, - rBuildHash = /\x08(~)?([^\x08]+)\x08/g, - - autoViewKey = 0, - autoTmplName = 0, - escapeMapForHtml = { - "&": "&", - "<": "<", - ">": ">" - }, - tmplAttr = "data-jsv-tmpl", - fnDeclStr = "var j=j||" + (jQuery ? "jQuery." : "js") + "views,", - htmlSpecialChar = /[\x00"&'<>]/g, - slice = Array.prototype.slice, - - render = {}, - - // jsviews object ($.views if jQuery is loaded) - jsv = { - jsviews: versionNumber, - sub: sub, // subscription, e.g. JsViews integration - debugMode: TRUE, - err: function( e ) { - return jsv.debugMode ? ("
                                    Error: " + (e.message || e) + ". ") : '""'; - }, - tmplFn: tmplFn, - render: render, - templates: templates, - tags: tags, - helpers: helpers, - converters: converters, - View: View, - convert: convert, - delimiters: setDelimiters, - tag: renderTag - }; - -//========================== Top-level functions ========================== - -//=================== -// jsviews.delimiters -//=================== - -function setDelimiters( openChars, closeChars ) { - // Set the tag opening and closing delimiters. Default is "{{" and "}}" - // openChar, closeChars: opening and closing strings, each with two characters - var firstOpenChar = "\\" + openChars.charAt( 0 ), // Escape the characters - since they could be regex special characters - secondOpenChar = "\\" + openChars.charAt( 1 ), - firstCloseChar = "\\" + closeChars.charAt( 0 ), - secondCloseChar = "\\" + closeChars.charAt( 1 ); - // Build regex with new delimiters - jsv.rTag = rTag // make rTag available to JsViews (or other components) for parsing binding expressions - = secondOpenChar - // tag (followed by / space or }) or colon or html or code - + "(?:(?:(\\w+(?=[\\/\\s" + firstCloseChar + "]))|(?:(\\w+)?(:)|(>)|(\\*)))" - // params - + "\\s*((?:[^" + firstCloseChar + "]|" + firstCloseChar + "(?!" + secondCloseChar + "))*?)" - // slash or closeBlock - + "(\\/)?|(?:\\/(\\w+)))" - // }} - + firstCloseChar; - - // Default rTag: tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/\s\}]))|(?:(\w+)?(:)|(>)|(\*)))\s*((?:[^}]|}(?!\}))*?)(\/)?|(?:\/(\w+)))}} - - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - rTag = new RegExp( firstOpenChar + rTag + secondCloseChar, "g" ); - rTmplString = new RegExp( "<.*>|" + openChars + ".*" + closeChars ); - return this; -} - -//================= -// View.hlp -//================= - -function getHelper( helper ) { - // Helper method called as view.hlp() from compiled template, for helper functions or template parameters ~foo - var view = this, - tmplHelpers = view.tmpl.helpers || {}; - helper = (view.ctx[ helper ] !== undefined ? view.ctx : tmplHelpers[ helper ] !== undefined ? tmplHelpers : helpers[ helper ] !== undefined ? helpers : {})[ helper ]; - return typeof helper !== "function" ? helper : function() { - return helper.apply(view, arguments); - }; -} - -//================= -// jsviews.convert -//================= - -function convert( converter, view, text ) { - var tmplConverters = view.tmpl.converters; - converter = tmplConverters && tmplConverters[ converter ] || converters[ converter ]; - return converter ? converter.call( view, text ) : text; -} - -//================= -// jsviews.tag -//================= - -function renderTag( tag, parentView, converter, content, tagObject ) { - // Called from within compiled template function, to render a nested tag - // Returns the rendered tag - tagObject.props = tagObject.props || {}; - var ret, - tmpl = tagObject.props.tmpl, - tmplTags = parentView.tmpl.tags, - nestedTemplates = parentView.tmpl.templates, - args = arguments, - tagFn = tmplTags && tmplTags[ tag ] || tags[ tag ]; - - if ( !tagFn ) { - return ""; - } - // Set the tmpl property to the content of the block tag, unless set as an override property on the tag - content = content && parentView.tmpl.tmpls[ content - 1 ]; - tmpl = tmpl || content || undefined; - tagObject.tmpl = - "" + tmpl === tmpl // if a string - ? nestedTemplates && nestedTemplates[ tmpl ] || templates[ tmpl ] || templates( tmpl ) - : tmpl; - - tagObject.isTag = TRUE; - tagObject.converter = converter; - tagObject.view = parentView; - tagObject.renderContent = renderContent; - if ( parentView.ctx ) { - extend( tagObject.ctx, parentView.ctx); - } - - ret = tagFn.apply( tagObject, args.length > 5 ? slice.call( args, 5 ) : [] ); - return ret || ( ret == undefined ? "" : ret.toString()); // (If ret is the value 0 or false, will render to string) -} - -//================= -// View constructor -//================= - -function View( context, path, parentView, data, template, index ) { - // Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded) - var views = parentView.views, -// TODO: add this, as part of smart re-linking on existing content ($.link method), or remove completely -// self = parentView.views[ index ]; -// if ( !self ) { ... } - self = { - tmpl: template, - path: path, - parent: parentView, - data: data, - ctx: context, - views: $.isArray( data ) ? [] : {}, - hlp: getHelper - }; - - if ( $.isArray( views )) { - views.splice( - self.index = index !== undefined - ? index - : views.length, 0, self - ); - } else { - views[ self.index = "_" + autoViewKey++ ] = self; - } - return self; -} - -//================= -// Registration -//================= - -function addToStore( self, store, name, item, process ) { - // Add item to named store such as templates, helpers, converters... - var key, onStore; - if ( name && typeof name === "object" && !name.nodeType ) { - // If name is a map, iterate over map and call store for key - for ( key in name ) { - store( key, name[ key ]); - } - return self; - } - if ( !name || item === undefined ) { - if ( process ) { - item = process( undefined, item || name ); - } - } else if ( "" + name === name ) { // name must be a string - if ( item === null ) { - // If item is null, delete this entry - delete store[name]; - } else if ( item = process ? process( name, item ) : item ) { - store[ name ] = item; - } - } - if ( onStore = sub.onStoreItem ) { - // e.g. JsViews integration - onStore( store, name, item, process ); - } - return item; -} - -function templates( name, tmpl ) { - // Register templates - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, templates, name, tmpl, compile ); -} - -function tags( name, tagFn ) { - // Register template tags - // Setter: Use $.view.tags( name, tagFn ) or $.view.tags({ name: tagFn, ... }) to add additional tags to the registered tags collection. - // Getter: Use var tagFn = $.views.tags( name ) or $.views.tags[name] or $.views.tags.name to return the function for the registered tag. - // Remove: Use $.view.tags( name, null ) to remove a registered tag from $.view.tags. - - // When registering for {{foo a b c==d e=f}}, tagFn should be a function with the signature: - // function(a,b). The 'this' pointer will be a hash with properties c and e. - return addToStore( this, tags, name, tagFn ); -} - -function helpers( name, helperFn ) { - // Register helper functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.helpers( name, helperFn ) or $.view.helpers({ name: helperFn, ... }) to add additional helpers to the registered helpers collection. - // Getter: Use var helperFn = $.views.helpers( name ) or $.views.helpers[name] or $.views.helpers.name to return the function. - // Remove: Use $.view.helpers( name, null ) to remove a registered helper function from $.view.helpers. - // Within a template, access the helper using the syntax: {{... ~myHelper(...) ...}}. - return addToStore( this, helpers, name, helperFn ); -} - -function converters( name, converterFn ) { - // Register converter functions for use in templates (or in data-link expressions if JsViews is loaded) - // Setter: Use $.view.converters( name, converterFn ) or $.view.converters({ name: converterFn, ... }) to add additional converters to the registered converters collection. - // Getter: Use var converterFn = $.views.converters( name ) or $.views.converters[name] or $.views.converters.name to return the converter function. - // Remove: Use $.view.converters( name, null ) to remove a registered converter from $.view.converters. - // Within a template, access the converter using the syntax: {{myConverter:...}}. - return addToStore( this, converters, name, converterFn ); -} - -//================= -// renderContent -//================= - -function renderContent( data, context, parentView, path, index ) { - // Render template against data as a tree of subviews (nested template), or as a string (top-level template). - // tagName parameter for internal use only. Used for rendering templates registered as tags (which may have associated presenter objects) - var i, l, dataItem, newView, itemWrap, itemsWrap, itemResult, parentContext, tmpl, layout, - props = {}, - swapContent = index === TRUE, - self = this, - result = ""; - - if ( self.isTag ) { - // This is a call from renderTag - tmpl = self.tmpl; - context = context || self.ctx; - parentView = parentView || self.view; - path = path || self.path; - index = index || self.index; - props = self.props; - } else { - tmpl = self.jquery && self[0] // This is a call $.fn.render - || self; // This is a call from tmpl.render - } - parentView = parentView || jsv.topView; - parentContext = parentView.ctx; - layout = tmpl.layout; - if ( data === parentView ) { - // Inherit the data from the parent view. - // This may be the contents of an {{if}} block - data = parentView.data; - layout = TRUE; - } - - // Set additional context on views created here, (as modified context inherited from the parent, and be inherited by child views) - // Note: If no jQuery, extend does not support chained copies - so limit extend() to two parameters - context = (context && context === parentContext) - ? parentContext - : (parentContext - // if parentContext, make copy - ? ((parentContext = extend( {}, parentContext ), context) - // If context, merge context with copied parentContext - ? extend( parentContext, context ) - : parentContext) - // if no parentContext, use context, or default to {} - : context || {}); - - if ( props.link === FALSE ) { - // Override inherited value of link by an explicit setting in props: link=false - // The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect. - context.link = FALSE; - } - if ( !tmpl.fn ) { - tmpl = templates[ tmpl ] || templates( tmpl ); - } - itemWrap = context.link && sub.onRenderItem; - itemsWrap = context.link && sub.onRenderItems; - - if ( tmpl ) { - if ( $.isArray( data ) && !layout ) { - // Create a view for the array, whose child views correspond to each data item. - // (Note: if index and parentView are passed in along with parent view, treat as - // insert -e.g. from view.addViews - so parentView is already the view item for array) - newView = swapContent ? parentView : (index !== undefined && parentView) || View( context, path, parentView, data, tmpl, index ); - - for ( i = 0, l = data.length; i < l; i++ ) { - // Create a view for each data item. - dataItem = data[ i ]; - itemResult = tmpl.fn( dataItem, View( context, path, newView, dataItem, tmpl, (index||0) + i ), jsv ); - result += itemWrap ? itemWrap( itemResult, props ) : itemResult; - } - } else { - // Create a view for singleton data object. - newView = swapContent ? parentView : View( context, path, parentView, data, tmpl, index ); - result += (data || layout) ? tmpl.fn( data, newView, jsv ) : ""; - } - parentView.topKey = newView.index; - return itemsWrap ? itemsWrap( result, path, newView.index, tmpl, props ) : result; - } - return ""; // No tmpl. Could throw... -} - -//=========================== -// Build and compile template -//=========================== - -// Generate a reusable function that will serve to render a template against data -// (Compile AST then build template function) - -function syntaxError() { - throw "Syntax error"; -} - -function tmplFn( markup, tmpl, bind ) { - // Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes - // Used for compiling templates, and also by JsViews to build functions for data link expressions - var newNode, node, i, l, code, hasTag, hasEncoder, getsValue, hasConverter, hasViewPath, tag, converter, params, hash, nestedTmpl, allowCode, - tmplOptions = tmpl ? { - allowCode: allowCode = tmpl.allowCode, - debug: tmpl.debug - } : {}, - nested = tmpl && tmpl.tmpls, - astTop = [], - loc = 0, - stack = [], - content = astTop, - current = [,,,astTop], - nestedIndex = 0; - - //==== nested functions ==== - function pushPreceedingContent( shift ) { - shift -= loc; - if ( shift ) { - content.push( markup.substr( loc, shift ).replace( rNewLine, "\\n" )); - } - } - - function parseTag( all, tagName, converter, colon, html, code, params, slash, closeBlock, index ) { - // tag converter colon html code params slash closeBlock - // /{{(?:(?:(\w+(?=[\/!\s\}!]))|(?:(\w+)?(:)|(?:(>)|(\*)))((?:[^\}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g; - // Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, contentMarkup ] - if ( html ) { - colon = ":"; - converter = "html"; - } - var hash = "", - passedCtx = "", - block = !slash && !colon; // Block tag if not self-closing and not {{:}} or {{>}} (special case) - - //==== nested helper function ==== - - tagName = tagName || colon; - pushPreceedingContent( index ); - loc = index + all.length; // location marker - parsed up to here - if ( code ) { - if ( allowCode ) { - content.push([ "*", params.replace( rUnescapeQuotes, "$1" ) ]); - } - } else if ( tagName ) { - if ( tagName === "else" ) { - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - content = current[ 3 ]; - block = TRUE; - } - params = (params - ? parseParams( params, bind ) - .replace( rBuildHash, function( all, isCtx, keyValue ) { - if ( isCtx ) { - passedCtx += keyValue + ","; - } else { - hash += keyValue + ","; - } - return ""; - }) - : ""); - hash = hash.slice( 0, -1 ); - params = params.slice( 0, -1 ); - newNode = [ - tagName, - converter || "", - params, - block && [], - "{" + (hash ? ("props:{" + hash + "},"): "") + "path:'" + params + "'" + (passedCtx ? ",ctx:{" + passedCtx.slice( 0, -1 ) + "}" : "") + "}" - ]; - if ( block ) { - stack.push( current ); - current = newNode; - current[ 5 ] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag - } - content.push( newNode ); - } else if ( closeBlock ) { - //if ( closeBlock !== current[ 0 ]) { - // throw "unmatched close tag: /" + closeBlock + ". Expected /" + current[ 0 ]; - //} - current[ 5 ] = markup.substring( current[ 5 ], index ); // contentMarkup for block tag - current = stack.pop(); - } - if ( !current ) { - throw "Expected block tag"; - } - content = current[ 3 ]; - } - //==== /end of nested functions ==== - - markup = markup.replace( rEscapeQuotes, "\\$1" ); - - // Build the AST (abstract syntax tree) under astTop - markup.replace( rTag, parseTag ); - - pushPreceedingContent( markup.length ); - - // Use the AST (astTop) to build the template function - l = astTop.length; - code = (l ? "" : '"";'); - - for ( i = 0; i < l; i++ ) { - // AST nodes: [ tagName, converter, params, content, hash, contentMarkup ] - node = astTop[ i ]; - if ( node[ 0 ] === "*" ) { - code = code.slice( 0, i ? -1 : -3 ) + ";" + node[ 1 ] + (i + 1 < l ? "ret+=" : ""); - } else if ( "" + node === node ) { // type string - code += '"' + node + '"+'; - } else { - tag = node[ 0 ]; - converter = node[ 1 ]; - params = node[ 2 ]; - content = node[ 3 ]; - hash = node[ 4 ]; - markup = node[ 5 ]; - if ( content ) { - // Create template object for nested template - nestedTmpl = TmplObject( markup, tmplOptions, tmpl, nestedIndex++ ); - // Compile to AST and then to compiled function - tmplFn( markup, nestedTmpl); - nested.push( nestedTmpl ); - } - hasViewPath = hasViewPath || hash.indexOf( "view" ) > -1; - code += (tag === ":" - ? (converter === "html" - ? (hasEncoder = TRUE, "e(" + params) - : converter - ? (hasConverter = TRUE, 'c("' + converter + '",view,' + params) - : (getsValue = TRUE, "((v=" + params + ')!=u?v:""') - ) - : (hasTag = TRUE, 't("' + tag + '",view,"' + (converter || "") + '",' - + (content ? nested.length : '""') // For block tags, pass in the key (nested.length) to the nested content template - + "," + hash + (params ? "," : "") + params)) - + ")+"; - } - } - code = new Function( "data, view, j, b, u", fnDeclStr - + (getsValue ? "v," : "") - + (hasTag ? "t=j.tag," : "") - + (hasConverter ? "c=j.convert," : "") - + (hasEncoder ? "e=j.converters.html," : "") - + "ret; try{\n\n" - + (tmplOptions.debug ? "debugger;" : "") - + (allowCode ? 'ret=' : 'return ') - + code.slice( 0, -1 ) + ";\n\n" - + (allowCode ? "return ret;" : "") - + "}catch(e){return j.err(e);}" - ); - - // Include only the var references that are needed in the code - if ( tmpl ) { - tmpl.fn = code; - tmpl.useVw = hasConverter || hasViewPath || hasTag; - } - return code; -} - -function parseParams( params, bind ) { - var named, - fnCall = {}, - parenDepth = 0, - quoted = FALSE, // boolean for string content in double quotes - aposed = FALSE; // or in single quotes - - function parseTokens( all, lftPrn0, lftPrn, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, prn2, space ) { - // rParams = /(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g, - // lftPrn path operator err eq path2 prn comma lftPrn3 apos quot rtPrn prn2 space - // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space - operator = operator || ""; - lftPrn = lftPrn || lftPrn0 || lftPrn2; - path = path || path2; - prn = prn || prn2 || ""; - operator = operator || ""; - - function parsePath( all, object, helper, view, viewProperty, pathTokens, leafToken ) { - // rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g, - // object helper view viewProperty pathTokens leafToken string - if ( object ) { - var ret = (helper - ? 'view.hlp("' + helper + '")' - : view - ? "view" - : "data") - + (leafToken - ? (viewProperty - ? "." + viewProperty - : helper - ? "" - : (view ? "" : "." + object) - ) + (pathTokens || "") - : (leafToken = helper ? "" : view ? viewProperty || "" : object, "")); - - if ( bind && prn !== "(" ) { - ret = "b(" + ret + ',"' + leafToken + '")'; - } - return ret + (leafToken ? "." + leafToken : ""); - } - return all; - } - - if ( err ) { - syntaxError(); - } else { - return (aposed - // within single-quoted string - ? (aposed = !apos, (aposed ? all : '"')) - : quoted - // within double-quoted string - ? (quoted = !quot, (quoted ? all : '"')) - : - ( - (lftPrn - ? (parenDepth++, lftPrn) - : "") - + (space - ? (parenDepth - ? "" - : named - ? (named = FALSE, "\b") - : "," - ) - : eq - // named param - ? (parenDepth && syntaxError(), named = TRUE, '\b' + path + ':') - : path - // path - ? (path.replace( rPath, parsePath ) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : operator) - ) - : operator - ? all - : rtPrn - // function - ? ((fnCall[ parenDepth-- ] = FALSE, rtPrn) - + (prn - ? (fnCall[ ++parenDepth ] = TRUE, prn) - : "") - ) - : comma - ? (fnCall[ parenDepth ] || syntaxError(), ",") // We don't allow top-level literal arrays or objects - : lftPrn0 - ? "" - : (aposed = apos, quoted = quot, '"') - )) - ); - } - } - params = (params + " " ).replace( rParams, parseTokens ); - return params; -} - -function compile( name, tmpl, parent, options ) { - // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object - // options is the set of template properties, c - var tmplOrMarkup, elem, key, nested, nestedItem; - - //==== nested functions ==== - function tmplOrMarkupFromStr( value ) { - // If value is of type string - treat as selector, or name of compiled template - // Return the template object, if already compiled, or the markup string - - if ( ("" + value === value) || value.nodeType > 0 ) { - // If selector is valid and returns at least one element, get first element - elem = value.nodeType > 0 ? value : !rTmplString.test( value ) && jQuery && jQuery( value )[0]; - if ( elem && elem.type ) { - // It is a script element - // Create a name for data linking if none provided - value = templates[ elem.getAttribute( tmplAttr )]; - if ( !value ) { - // Not already compiled and cached, so compile and cache the name - name = name || "_" + autoTmplName++; - elem.setAttribute( tmplAttr, name ); - value = compile( name, elem.innerHTML, parent, options ); // Use tmpl as options - templates[ name ] = value; - } - } - return value; - } - // If value is not a string or dom element, return undefined - } - - //==== Compile the template ==== - tmplOrMarkup = tmplOrMarkupFromStr( tmpl ); - - // If tmpl is a template object, use it for options - options = options || (tmpl.markup ? tmpl : {}); - options.name = name; - nested = options.templates; - - // If tmpl is not a markup string or a selector string, then it must be a template object - // In that case, get it from the markup property of the object - if ( !tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr( tmpl.markup ))) { - if ( tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode )) { - // if the string references a compiled template object, but the debug or allowCode props are different, need to recompile - tmplOrMarkup = tmplOrMarkup.markup; - } - } - if ( tmplOrMarkup !== undefined ) { - if ( name && !parent ) { - render[ name ] = function() { - return tmpl.render.apply( tmpl, arguments ); - }; - } - if ( tmplOrMarkup.fn || tmpl.fn ) { - // tmpl is already compiled, so use it, or if different name is provided, clone it - if ( tmplOrMarkup.fn ) { - if ( name && name !== tmplOrMarkup.name ) { - tmpl = extend( extend( {}, tmplOrMarkup ), options); - } else { - tmpl = tmplOrMarkup; - } - } - } else { - // tmplOrMarkup is a markup string, not a compiled template - // Create template object - tmpl = TmplObject( tmplOrMarkup, options, parent, 0 ); - // Compile to AST and then to compiled function - tmplFn( tmplOrMarkup, tmpl ); - } - for ( key in nested ) { - // compile nested template declarations - nestedItem = nested[ key ]; - if ( nestedItem.name !== key ) { - nested[ key ] = compile( key, nestedItem, tmpl ); - } - } - return tmpl; - } -} -//==== /end of function compile ==== - -function TmplObject( markup, options, parent, index ) { - // Template object constructor - - // nested helper function - function extendStore( storeName ) { - if ( parent[ storeName ]) { - // Include parent items except if overridden by item of same name in options - tmpl[ storeName ] = extend( extend( {}, parent[ storeName ] ), options[ storeName ] ); - } - } - - options = options || {}; - var tmpl = { - markup: markup, - tmpls: [], - links: [], - render: renderContent - }; - if ( parent ) { - if ( parent.templates ) { - tmpl.templates = extend( extend( {}, parent.templates ), options.templates ); - } - tmpl.parent = parent; - tmpl.name = parent.name + "[" + index + "]"; - tmpl.index = index; - } - - extend( tmpl, options ); - if ( parent ) { - extendStore( "templates" ); - extendStore( "tags" ); - extendStore( "helpers" ); - extendStore( "converters" ); - } - return tmpl; -} - -//========================== Initialize ========================== - -if ( jQuery ) { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is loaded, so make $ the jQuery object - $ = jQuery; - $.templates = templates; - $.render = render; - $.views = jsv; - $.fn.render = renderContent; - -} else { - //////////////////////////////////////////////////////////////////////////////////////////////// - // jQuery is not loaded. - - $ = window.jsviews = jsv; - $.extend = function( target, source ) { - var name; - target = target || {}; - for ( name in source ) { - target[ name ] = source[ name ]; - } - return target; - }; - - $.isArray = Array && Array.isArray || function( obj ) { - return Object.prototype.toString.call( obj ) === "[object Array]"; - }; -} - -extend = $.extend; - -jsv.topView = { views: {}, tmpl: {}, hlp: getHelper, ctx: jsv.helpers }; - -function replacerForHtml( ch ) { - // Original code from Mike Samuel - return escapeMapForHtml[ ch ] - // Intentional assignment that caches the result of encoding ch. - || (escapeMapForHtml[ ch ] = "&#" + ch.charCodeAt( 0 ) + ";"); -} - -//========================== Register tags ========================== - -tags({ - "if": function() { - var ifTag = this, - view = ifTag.view; - - view.onElse = function( tagObject, args ) { - var i = 0, - l = args.length; - - while ( l && !args[ i++ ]) { - // Only render content if args.length === 0 (i.e. this is an else with no condition) or if a condition argument is truey - if ( i === l ) { - return ""; - } - } - view.onElse = undefined; // If condition satisfied, so won't run 'else'. - tagObject.path = ""; - return tagObject.renderContent( view ); - // Test is satisfied, so render content, while remaining in current data context - // By passing the view, we inherit data context from the parent view, and the content is treated as a layout template - // (so if the data is an array, it will not iterate over the data - }; - return view.onElse( this, arguments ); - }, - "else": function() { - var view = this.view; - return view.onElse ? view.onElse( this, arguments ) : ""; - }, - "for": function() { - var i, - self = this, - result = "", - args = arguments, - l = args.length; - if ( self.props.layout ) { - self.tmpl.layout = TRUE; - } - for ( i = 0; i < l; i++ ) { - result += self.renderContent( args[ i ]); - } - return result; - }, - "=": function( value ) { - return value; - }, - "*": function( value ) { - return value; - } -}); - -//========================== Register global helpers ========================== - -// helpers({ // Global helper functions -// // TODO add any useful built-in helper functions -// }); - -//========================== Register converters ========================== - -converters({ - html: function( text ) { - // HTML encoding helper: Replace < > & and ' and " by corresponding entities. - // inspired by Mike Samuel - return text != undefined ? String( text ).replace( htmlSpecialChar, replacerForHtml ) : ""; - } -}); - -//========================== Define default delimiters ========================== -setDelimiters( "{{", "}}" ); - -})( this ); - -/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) - * Licensed under the MIT License (LICENSE.txt). - * - * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. - * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. - * Thanks to: Seamus Leahy for adding deltaX and deltaY - * - * Version: 3.0.6 - * - * Requires: 1.2.2+ - */ - -(function($) { - -var types = ['DOMMouseScroll', 'mousewheel']; - -if ($.event.fixHooks) { - for ( var i=types.length; i; ) { - $.event.fixHooks[ types[--i] ] = $.event.mouseHooks; - } -} - -$.event.special.mousewheel = { - setup: function() { - if ( this.addEventListener ) { - for ( var i=types.length; i; ) { - this.addEventListener( types[--i], handler, false ); - } - } else { - this.onmousewheel = handler; - } - }, - - teardown: function() { - if ( this.removeEventListener ) { - for ( var i=types.length; i; ) { - this.removeEventListener( types[--i], handler, false ); - } - } else { - this.onmousewheel = null; - } - } -}; - -$.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); - }, - - unmousewheel: function(fn) { - return this.unbind("mousewheel", fn); - } -}); - - -function handler(event) { - var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0; - event = $.event.fix(orgEvent); - event.type = "mousewheel"; - - // Old school scrollwheel delta - if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; } - if ( orgEvent.detail ) { delta = -orgEvent.detail/3; } - - // New school multidimensional scroll (touchpads) deltas - deltaY = delta; - - // Gecko - if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { - deltaY = 0; - deltaX = -1*delta; - } - - // Webkit - if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; } - if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; } - - // Add event and delta to the front of the arguments - args.unshift(event, delta, deltaX, deltaY); - - return ($.event.dispatch || $.event.handle).apply(this, args); -} - -})(jQuery); - -/*! - * jQuery UI Widget 1.8.18 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ - -if ( ! $.widget ) { - -(function( $, undefined ) { - -// jQuery 1.4+ -if ( $.cleanData ) { - var _cleanData = $.cleanData; - $.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); - }; -} else { - var _remove = $.fn.remove; - $.fn.remove = function( selector, keepData ) { - return this.each(function() { - if ( !keepData ) { - if ( !selector || $.filter( selector, [ this ] ).length ) { - $( "*", this ).add( [ this ] ).each(function() { - try { - $( this ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - }); - } - } - return _remove.call( $(this), selector, keepData ); - }); - }; -} - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from -// $.each( basePrototype, function( key, val ) { -// if ( $.isPlainObject(val) ) { -// basePrototype[ key ] = $.extend( {}, val ); -// } -// }); - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = Array.prototype.slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - // prevent calls to internal methods - if ( isMethodCall && options.charAt( 0 ) === "_" ) { - return returnValue; - } - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ), - methodValue = instance && $.isFunction( instance[options] ) ? - instance[ options ].apply( instance, args ) : - instance; - // TODO: add this back in 1.9 and use $.error() (see #5972) -// if ( !instance ) { -// throw "cannot call methods on " + name + " prior to initialization; " + -// "attempted to call method '" + options + "'"; -// } -// if ( !$.isFunction( instance[options] ) ) { -// throw "no such method '" + options + "' for " + name + " widget instance"; -// } -// var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, name, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - // $.widget.bridge stores the plugin instance, but we do it anyway - // so that it's stored even before the _create function runs - $.data( element, this.widgetName, this ); - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - var self = this; - this.element.bind( "remove." + this.widgetName, function() { - self.destroy(); - }); - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: function() {}, - _init: function() {}, - - destroy: function() { - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - }, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - [ value ? "addClass" : "removeClass"]( - this.widgetBaseClass + "-disabled" + " " + - "ui-state-disabled" ) - .attr( "aria-disabled", value ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - - return !( $.isFunction(callback) && - callback.call( this.element[0], event, data ) === false || - event.isDefaultPrevented() ); - } -}; - -})( jQuery ); - -}; - - -(function ($, window, undefined) { - var pos_oo = Number.POSITIVE_INFINITY, - neg_oo = Number.NEGATIVE_INFINITY; - - $.geo = { - // - // utility functions - // - - _allCoordinates: function (geom) { - // return array of all positions in all geometries of geom - // not in JTS - var geometries = this._flatten(geom), - curGeom = 0, - result = []; - - for (; curGeom < geometries.length; curGeom++) { - var coordinates = geometries[curGeom].coordinates, - isArray = coordinates && $.isArray(coordinates[0]), - isDblArray = isArray && $.isArray(coordinates[0][0]), - isTriArray = isDblArray && $.isArray(coordinates[0][0][0]), - i, j, k; - - if (!isTriArray) { - if (!isDblArray) { - if (!isArray) { - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - coordinates = [coordinates]; - } - - for (i = 0; i < coordinates.length; i++) { - for (j = 0; j < coordinates[i].length; j++) { - for (k = 0; k < coordinates[i][j].length; k++) { - result.push(coordinates[i][j][k]); - } - } - } - } - return result; - }, - - _isGeodetic: function( coords ) { - // returns true if the first coordinate it can find is geodetic - - while ( $.isArray( coords ) ) { - if ( coords.length > 1 && ! $.isArray( coords[ 0 ] ) ) { - return ( coords[ 0 ] >= -180 && coords[ 0 ] <= 180 && coords[ 1 ] >= -85 && coords[ 1 ] <= 85 ); - } else { - coords = coords[ 0 ]; - } - } - - return false; - }, - - // - // bbox functions - // - - center: function (bbox, _ignoreGeo /* Internal Use Only */) { - // Envelope.centre in JTS - // bbox only, use centroid for geom - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return wasGeodetic ? $.geo.proj.toGeodetic(center) : center; - }, - - expandBy: function (bbox, dx, dy, _ignoreGeo /* Internal Use Only */) { - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - bbox = [bbox[0] - dx, bbox[1] - dy, bbox[2] + dx, bbox[3] + dy]; - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - height: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[3] - bbox[1]; - }, - - _in: function(bbox1, bbox2) { - return bbox1[0] <= bbox2[0] && - bbox1[1] <= bbox2[1] && - bbox1[2] >= bbox2[2] && - bbox1[3] >= bbox2[3]; - }, - - _bboxDisjoint: function( bbox1, bbox2 ) { - return bbox2[ 0 ] > bbox1[ 2 ] || - bbox2[ 2 ] < bbox1[ 0 ] || - bbox2[ 1 ] > bbox1[ 3 ] || - bbox2[ 3 ] < bbox1[ 1 ]; - }, - - include: function( bbox, value, _ignoreGeo /* Internal Use Only */ ) { - // similar to Envelope.expandToInclude in JTS - if ( !value || !$.isArray( value ) ) { - return bbox; - } - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox || value ) ) { - wasGeodetic = true; - } - - if ( !bbox ) { - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - } else if ( wasGeodetic ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - - if ( value.length === 2 ) { - value = [ value[ 0 ], value[ 1 ], value[ 0 ], value[ 1 ] ]; - } - - value = $.geo.proj.fromGeodetic( value ); - - bbox[0] = Math.min( value[ 0 ], bbox[ 0 ] ); - bbox[1] = Math.min( value[ 1 ], bbox[ 1 ] ); - bbox[2] = Math.max( value[ 2 ], bbox[ 2 ] ); - bbox[3] = Math.max( value[ 3 ], bbox[ 3 ] ); - - return wasGeodetic ? $.geo.proj.toGeodetic( bbox ) : bbox; - }, - - polygonize: function( bbox, _ignoreGeo /* Internal Use Only */ ) { - // adaptation of Polygonizer class in JTS for use with bboxes - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var polygon = { - type: "Polygon", - coordinates: [ [ - [ bbox[ 0 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 3 ] ], - [ bbox[ 2 ], bbox[ 1 ] ], - [ bbox[ 0 ], bbox[ 1 ] ] - ] ] - }; - - if ( wasGeodetic ) { - polygon.coordinates = $.geo.proj.toGeodetic( polygon.coordinates ); - } - - return polygon; - }, - - reaspect: function (bbox, ratio, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var width = this.width(bbox, true), - height = this.height(bbox, true), - center = this.center(bbox, true), - dx, dy; - - if (width !== 0 && height !== 0 && ratio > 0) { - if (width / height > ratio) { - dx = width / 2; - dy = dx / ratio; - } else { - dy = height / 2; - dx = dy * ratio; - } - - bbox = [center[0] - dx, center[1] - dy, center[0] + dx, center[1] + dy]; - } - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - recenter: function( bbox, center, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj ) { - if ( this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - if ( this._isGeodetic( center ) ) { - center = $.geo.proj.fromGeodetic(center); - } - } - - var halfWidth = ( bbox[ 2 ] - bbox[ 0 ] ) / 2, - halfHeight = ( bbox[ 3 ] - bbox[ 1 ] ) / 2; - - bbox = [ - center[ 0 ] - halfWidth, - center[ 1 ] - halfHeight, - center[ 0 ] + halfWidth, - center[ 1 ] + halfHeight - ]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - scaleBy: function ( bbox, scale, _ignoreGeo /* Internal Use Only */ ) { - // not in JTS - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - wasGeodetic = true; - bbox = $.geo.proj.fromGeodetic(bbox); - } - - var c = this.center(bbox, true), - dx = (bbox[2] - bbox[0]) * scale / 2, - dy = (bbox[3] - bbox[1]) * scale / 2; - - bbox = [c[0] - dx, c[1] - dy, c[0] + dx, c[1] + dy]; - - return wasGeodetic ? $.geo.proj.toGeodetic(bbox) : bbox; - }, - - width: function (bbox, _ignoreGeo /* Internal Use Only */ ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic(bbox); - } - - return bbox[2] - bbox[0]; - }, - - // - // geometry functions - // - - // bbox (Geometry.getEnvelope in JTS) - - bbox: function ( geom, _ignoreGeo /* Internal Use Only */ ) { - var result, wasGeodetic = false; - if ( !geom ) { - return undefined; - } else if ( geom.bbox ) { - result = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.bbox ) ) ? $.geo.proj.fromGeodetic( geom.bbox ) : geom.bbox; - } else { - result = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var coordinates = this._allCoordinates( geom ), - curCoord = 0; - - if ( coordinates.length === 0 ) { - return undefined; - } - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coordinates ) ) { - wasGeodetic = true; - coordinates = $.geo.proj.fromGeodetic( coordinates ); - } - - for ( ; curCoord < coordinates.length; curCoord++ ) { - result[0] = Math.min(coordinates[curCoord][0], result[0]); - result[1] = Math.min(coordinates[curCoord][1], result[1]); - result[2] = Math.max(coordinates[curCoord][0], result[2]); - result[3] = Math.max(coordinates[curCoord][1], result[3]); - } - } - - return wasGeodetic ? $.geo.proj.toGeodetic(result) : result; - }, - - // centroid - - centroid: function( geom, _ignoreGeo /* Internal Use Only */ ) { - switch (geom.type) { - case "Point": - return $.extend({}, geom); - - case "LineString": - case "Polygon": - var a = 0, - c = [0, 0], - coords = $.merge( [ ], geom.type == "Polygon" ? geom.coordinates[0] : geom.coordinates ), - i = 1, j, n, - bbox = [ pos_oo, pos_oo, neg_oo, neg_oo ]; - - var wasGeodetic = false; - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( coords ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic(coords); - } - - //if (coords[0][0] != coords[coords.length - 1][0] || coords[0][1] != coords[coords.length - 1][1]) { - // coords.push(coords[0]); - //} - - for (; i <= coords.length; i++) { - j = i % coords.length; - - bbox[0] = Math.min(coords[j][0], bbox[0]); - bbox[1] = Math.min(coords[j][1], bbox[1]); - bbox[2] = Math.max(coords[j][0], bbox[2]); - bbox[3] = Math.max(coords[j][1], bbox[3]); - - n = (coords[i - 1][0] * coords[j][1]) - (coords[j][0] * coords[i - 1][1]); - a += n; - c[0] += (coords[i - 1][0] + coords[j][0]) * n; - c[1] += (coords[i - 1][1] + coords[j][1]) * n; - } - - if (a === 0) { - if (coords.length > 0) { - c[0] = Math.min( Math.max( coords[0][0], bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( coords[0][1], bbox[ 1 ] ), bbox[ 3 ] ); - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } else { - return undefined; - } - } - - a *= 3; - //c[0] /= a; - //c[1] /= a; - - c[0] = Math.min( Math.max( c[0] / a, bbox[ 0 ] ), bbox[ 2 ] ); - c[1] = Math.min( Math.max( c[1] / a, bbox[ 1 ] ), bbox[ 3 ] ); - - return { type: "Point", coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c }; - } - return undefined; - }, - - // contains - - contains: function (geom1, geom2) { - if (geom1.type != "Polygon") { - return false; - } - - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1.coordinates, geom2.coordinates); - - case "LineString": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates); - - case "Polygon": - return this._containsPolygonLineString(geom1.coordinates, geom2.coordinates[0]); - - default: - return false; - } - }, - - _containsPolygonPoint: function (polygonCoordinates, pointCoordinate) { - if (polygonCoordinates.length === 0 || polygonCoordinates[0].length < 4) { - return false; - } - - var rayCross = 0, - a = polygonCoordinates[0][0], - i = 1, - b, - x; - - for (; i < polygonCoordinates[0].length; i++) { - b = polygonCoordinates[0][i]; - - if ((a[1] <= pointCoordinate[1] && pointCoordinate[1] < b[1]) || (b[1] <= pointCoordinate[1] && pointCoordinate[1] < a[1]) && (pointCoordinate[0] < a[0] || pointCoordinate[0] < b[0])) { - x = a[0] + (b[0] - a[0]) * (pointCoordinate[1] - a[1]) / (b[1] - a[1]); - - if (x > pointCoordinate[0]) { - rayCross++; - } - } - - a = b; - } - - return rayCross % 2 == 1; - }, - - _containsPolygonLineString: function (polygonCoordinates, lineStringCoordinates) { - for (var i = 0; i < lineStringCoordinates.length; i++) { - if (!this._containsPolygonPoint(polygonCoordinates, lineStringCoordinates[i])) { - return false; - } - } - return true; - }, - - // distance - - distance: function ( geom1, geom2, _ignoreGeo /* Internal Use Only */ ) { - var geom1CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom1.coordinates ) ) ? $.geo.proj.fromGeodetic(geom1.coordinates) : geom1.coordinates, - geom2CoordinatesProjected = ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom2.coordinates ) ) ? $.geo.proj.fromGeodetic(geom2.coordinates) : geom2.coordinates; - - switch (geom1.type) { - case "Point": - switch (geom2.type) { - case "Point": - return this._distancePointPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "LineString": - return this._distanceLineStringPoint(geom2CoordinatesProjected, geom1CoordinatesProjected); - case "Polygon": - return this._containsPolygonPoint(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "LineString": - switch (geom2.type) { - case "Point": - return this._distanceLineStringPoint(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "LineString": - return this._distanceLineStringLineString(geom1CoordinatesProjected, geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom2CoordinatesProjected, geom1CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom2CoordinatesProjected[0], geom1CoordinatesProjected); - default: - return undefined; - } - break; - - case "Polygon": - switch (geom2.type) { - case "Point": - return this._containsPolygonPoint(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringPoint(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "LineString": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected); - case "Polygon": - return this._containsPolygonLineString(geom1CoordinatesProjected, geom2CoordinatesProjected[0]) ? 0 : this._distanceLineStringLineString(geom1CoordinatesProjected[0], geom2CoordinatesProjected[0]); - default: - return undefined; - } - break; - } - }, - - _distancePointPoint: function (coordinate1, coordinate2) { - var dx = coordinate2[0] - coordinate1[0], - dy = coordinate2[1] - coordinate1[1]; - return Math.sqrt((dx * dx) + (dy * dy)); - }, - - _distanceLineStringPoint: function (lineStringCoordinates, pointCoordinate) { - var minDist = pos_oo; - - if (lineStringCoordinates.length > 0) { - var a = lineStringCoordinates[0], - - apx = pointCoordinate[0] - a[0], - apy = pointCoordinate[1] - a[1]; - - if (lineStringCoordinates.length == 1) { - return Math.sqrt(apx * apx + apy * apy); - } else { - for (var i = 1; i < lineStringCoordinates.length; i++) { - var b = lineStringCoordinates[i], - - abx = b[0] - a[0], - aby = b[1] - a[1], - bpx = pointCoordinate[0] - b[0], - bpy = pointCoordinate[1] - b[1], - - d = this._distanceSegmentPoint(abx, aby, apx, apy, bpx, bpy); - - if (d === 0) { - return 0; - } - - if (d < minDist) { - minDist = d; - } - - a = b; - apx = bpx; - apy = bpy; - } - } - } - - return Math.sqrt(minDist); - }, - - _distanceSegmentPoint: function (abx, aby, apx, apy, bpx, bpy) { - var dot1 = abx * apx + aby * apy; - - if (dot1 <= 0) { - return apx * apx + apy * apy; - } - - var dot2 = abx * abx + aby * aby; - - if (dot1 >= dot2) { - return bpx * bpx + bpy * bpy; - } - - return apx * apx + apy * apy - dot1 * dot1 / dot2; - }, - - _distanceLineStringLineString: function (lineStringCoordinates1, lineStringCoordinates2) { - var minDist = pos_oo; - for (var i = 0; i < lineStringCoordinates2.length; i++) { - minDist = Math.min(minDist, this._distanceLineStringPoint(lineStringCoordinates1, lineStringCoordinates2[i])); - } - return minDist; - }, - - // buffer - - _buffer: function( geom, distance, _ignoreGeo /* Internal Use Only */ ) { - var wasGeodetic = false, - coords = geom.coordinates; - - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( geom.coordinates ) ) { - wasGeodetic = true; - coords = $.geo.proj.fromGeodetic( geom.coordinates ); - } - - if ( geom.type === "Point" ) { - var resultCoords = [], - slices = 180, - i = 0, - a; - - for ( ; i <= slices; i++ ) { - a = ( i * 360 / slices ) * ( Math.PI / 180 ); - resultCoords.push( [ - coords[ 0 ] + Math.cos( a ) * distance, - coords[ 1 ] + Math.sin( a ) * distance - ] ); - } - - return { - type: "Polygon", - coordinates: [ ( wasGeodetic ? $.geo.proj.toGeodetic( resultCoords ) : resultCoords ) ] - }; - } else { - return undefined; - } - }, - - - // - // feature - // - - _flatten: function (geom) { - // return an array of all basic geometries - // not in JTS - var geometries = [], - curGeom = 0; - switch (geom.type) { - case "Feature": - $.merge(geometries, this._flatten(geom.geometry)); - break; - - case "FeatureCollection": - for (; curGeom < geom.features.length; curGeom++) { - $.merge(geometries, this._flatten(geom.features[curGeom].geometry)); - } - break; - - case "GeometryCollection": - for (; curGeom < geom.geometries.length; curGeom++) { - $.merge(geometries, this._flatten(geom.geometries[curGeom])); - } - break; - - default: - geometries[0] = geom; - break; - } - return geometries; - }, - - length: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - lineStringCoordinates, - i = 1, dx, dy; - - switch ( geom.type ) { - case "Point": - return 0; - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][0] - lineStringCoordinates[ i - 1 ][0]; - dy = lineStringCoordinates[ i ][1] - lineStringCoordinates[ i - 1 ][1]; - sum += Math.sqrt((dx * dx) + (dy * dy)); - } - - return sum; - } - - // return undefined; - }, - - area: function( geom, _ignoreGeo /* Internal Use Only */ ) { - var sum = 0, - polygonCoordinates, - i = 1, j; - - switch ( geom.type ) { - case "Point": - case "LineString": - return 0; - - case "Polygon": - polygonCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( polygonCoordinates ) { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( polygonCoordinates ) ) { - polygonCoordinates = $.geo.proj.fromGeodetic( polygonCoordinates ); - } - - for ( ; i <= polygonCoordinates.length; i++) { - j = i % polygonCoordinates.length; - sum += ( polygonCoordinates[ i - 1 ][ 0 ] - polygonCoordinates[ j ][ 0 ] ) * ( polygonCoordinates[ i - 1 ][ 1 ] + polygonCoordinates[ j ][ 1 ] ) / 2; - } - - return Math.abs( sum ); - } - }, - - pointAlong: function( geom, percentage, _ignoreGeo /* Internal Use Only */ ) { - var totalLength = 0, - previousPercentageSum = 0, - percentageSum = 0, - remainderPercentageSum, - len, - lineStringCoordinates, - segmentLengths = [], - i = 1, dx, dy, - c, c0, c1, - wasGeodetic = false; - - switch ( geom.type ) { - case "Point": - return $.extend( { }, geom ); - - case "LineString": - lineStringCoordinates = geom.coordinates; - break; - - case "Polygon": - lineStringCoordinates = geom.coordinates[ 0 ]; - break; - } - - if ( lineStringCoordinates ) { - if ( percentage === 0 ) { - return { - type: "Point", - coordinates: [ lineStringCoordinates[ 0 ][ 0 ], lineStringCoordinates[ 0 ][ 1 ] ] - }; - } else if ( percentage === 1 ) { - i = lineStringCoordinates.length - 1; - return { - type: "Point", - coordinates: [ lineStringCoordinates[ i ][ 0 ], lineStringCoordinates[ i ][ 1 ] ] - }; - } else { - if ( !_ignoreGeo && $.geo.proj && this._isGeodetic( lineStringCoordinates ) ) { - wasGeodetic = true; - lineStringCoordinates = $.geo.proj.fromGeodetic( lineStringCoordinates ); - } - - for ( ; i < lineStringCoordinates.length; i++ ) { - dx = lineStringCoordinates[ i ][ 0 ] - lineStringCoordinates[ i - 1 ][ 0 ]; - dy = lineStringCoordinates[ i ][ 1 ] - lineStringCoordinates[ i - 1 ][ 1 ]; - len = Math.sqrt((dx * dx) + (dy * dy)); - segmentLengths.push( len ); - totalLength += len; - } - - for ( i = 0; i < segmentLengths.length && percentageSum < percentage; i++ ) { - previousPercentageSum = percentageSum; - percentageSum += ( segmentLengths[ i ] / totalLength ); - } - - remainderPercentageSum = percentage - previousPercentageSum; - - c0 = lineStringCoordinates[ i - 1 ]; - c1 = lineStringCoordinates[ i ]; - - c = [ - c0[ 0 ] + ( remainderPercentageSum * ( c1[ 0 ] - c0[ 0 ] ) ), - c0[ 1 ] + ( remainderPercentageSum * ( c1[ 1 ] - c0[ 1 ] ) ) - ]; - - return { - type: "Point", - coordinates: wasGeodetic ? $.geo.proj.toGeodetic(c) : c - }; - } - } - }, - - // - // WKT functions - // - - _WKT: (function () { - function pointToString(value) { - return "POINT " + pointToUntaggedString(value.coordinates); - } - - function pointToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - return "(" + coordinates.join(" ") + ")"; - } - } - - function lineStringToString(value) { - return "LINESTRING " + lineStringToUntaggedString(value.coordinates); - } - - function lineStringToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var points = []; - - for (var i = 0; i < coordinates.length; i++) { - points.push(coordinates[i].join(" ")); - } - - return "(" + points + ")"; - } - } - - function polygonToString(value) { - return "POLYGON " + polygonToUntaggedString(value.coordinates); - } - - function polygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMTPY"; - } else { - var lineStrings = []; - - for (var i = 0; i < coordinates.length; i++) { - lineStrings.push(lineStringToUntaggedString(coordinates[i])); - } - - return "(" + lineStrings + ")"; - } - } - - function multiPointToString(value) { - return "MULTIPOINT " + lineStringToUntaggedString(value.coordinates); - } - - function multiLineStringToString(value) { - return "MULTILINSTRING " + polygonToUntaggedString(value.coordinates); - } - - function multiPolygonToString(value) { - return "MULTIPOLYGON " + multiPolygonToUntaggedString(value.coordinates); - } - - function multiPolygonToUntaggedString(coordinates) { - if (!(coordinates && coordinates.length)) { - return "EMPTY"; - } else { - var polygons = []; - for (var i = 0; i < coordinates.length; i++) { - polygons.push(polygonToUntaggedString(coordinates[i])); - } - return "(" + polygons + ")"; - } - } - - function geometryCollectionToString(value) { - return "GEOMETRYCOLLECTION " + geometryCollectionToUntaggedString(value.geometries); - } - - function geometryCollectionToUntaggedString(geometries) { - if (!(geometries && geometries.length)) { - return "EMPTY"; - } else { - var geometryText = []; - for (var i = 0; i < geometries.length; i++) { - geometryText.push(stringify(geometries[i])); - } - return "(" + geometries + ")"; - } - } - - function stringify(value) { - if (!(value && value.type)) { - return ""; - } else { - switch (value.type) { - case "Point": - return pointToString(value); - - case "LineString": - return lineStringToString(value); - - case "Polygon": - return polygonToString(value); - - case "MultiPoint": - return multiPointToString(value); - - case "MultiLineString": - return multiLineStringToString(value); - - case "MultiPolygon": - return multiPolygonToString(value); - - case "GeometryCollection": - return geometryCollectionToString(value); - - default: - return ""; - } - } - } - - function pointParseUntagged(wkt) { - var pointString = wkt.match( /\(\s*([\d\.\-]+)\s+([\d\.\-]+)\s*\)/ ); - return pointString && pointString.length > 2 ? { - type: "Point", - coordinates: [ - parseFloat(pointString[1]), - parseFloat(pointString[2]) - ] - } : null; - } - - function lineStringParseUntagged(wkt) { - var lineString = wkt.match( /\s*\((.*)\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( lineString && lineString.length > 1 ) { - pointStrings = lineString[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "LineString", - coordinates: coords - }; - } else { - return null; - } - } - - function polygonParseUntagged(wkt) { - var polygon = wkt.match( /\s*\(\s*\((.*)\)\s*\)/ ), - coords = [], - pointStrings, - pointParts, - i = 0; - - if ( polygon && polygon.length > 1 ) { - pointStrings = polygon[ 1 ].match( /[\d\.\-]+\s+[\d\.\-]+/g ); - - for ( ; i < pointStrings.length; i++ ) { - pointParts = pointStrings[ i ].match( /\s*([\d\.\-]+)\s+([\d\.\-]+)\s*/ ); - coords[ i ] = [ parseFloat( pointParts[ 1 ] ), parseFloat( pointParts[ 2 ] ) ]; - } - - return { - type: "Polygon", - coordinates: [ coords ] - }; - } else { - return null; - } - } - - function multiPointParseUntagged(wkt) { - var multiSomething; - - if ( wkt.indexOf( "((" ) === -1 ) { - multiSomething = lineStringParseUntagged( wkt ); - } else { - multiSomething = multiLineStringParseUntagged( wkt ); - multiSomething.coordinates = $.geo._allCoordinates( multiSomething ); - } - - multiSomething.type = "MultiPoint"; - - return multiSomething; - } - - function multiLineStringParseUntagged(wkt) { - var lineStringsWkt = wkt.substr( 1, wkt.length - 2 ), - lineStrings = lineStringsWkt.split( ")),((" ), - i = 0, - multiLineString = { - type: "MultiLineString", - coordinates: [ ] - }; - - for ( ; i < lineStrings.length; i++ ) { - multiLineString.coordinates.push( lineStringParseUntagged( lineStrings[ i ] ).coordinates ); - } - - return multiLineString; - } - - function multiPolygonParseUntagged(wkt) { - var polygonsWkt = wkt.substr( 1, wkt.length - 2 ), - polygons = polygonsWkt.split( ")),((" ), - i = 0, - multiPolygon = { - type: "MultiPolygon", - coordinates: [ ] - }; - - for ( ; i < polygons.length; i++ ) { - multiPolygon.coordinates.push( polygonParseUntagged( polygons[ i ] ).coordinates ); - } - - return multiPolygon; - } - - function geometryCollectionParseUntagged( wkt ) { - var geometriesWkt = wkt.substr( 1, wkt.length - 2 ), - geometries = geometriesWkt.match( /\),[a-zA-Z]/g ), - geometryCollection = { - type: "GeometryCollection", - geometries: [ ] - }, - curGeom, - i = 0, curStart = 0, curLen; - - if ( geometries && geometries.length > 0 ) { - for ( ; i < geometries.length; i++ ) { - curLen = geometriesWkt.indexOf( geometries[ i ], curStart ) - curStart + 1; - curGeom = parse( geometriesWkt.substr( curStart, curLen ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - curStart += curLen + 1; - } - - // one more - curGeom = parse( geometriesWkt.substr( curStart ) ); - if ( curGeom ) { - geometryCollection.geometries.push( curGeom ); - } - - return geometryCollection; - } else { - return null; - } - } - - function parse(wkt) { - wkt = $.trim(wkt); - - var typeIndex = wkt.indexOf( "(" ), - untagged = wkt.substr( typeIndex ); - - switch ($.trim(wkt.substr(0, typeIndex)).toUpperCase()) { - case "POINT": - return pointParseUntagged( untagged ); - - case "LINESTRING": - return lineStringParseUntagged( untagged ); - - case "POLYGON": - return polygonParseUntagged( untagged ); - - case "MULTIPOINT": - return multiPointParseUntagged( untagged ); - - case "MULTILINESTRING": - return multiLineStringParseUntagged( untagged ); - - case "MULTIPOLYGON": - return multiPolygonParseUntagged( untagged ); - - case "GEOMETRYCOLLECTION": - return geometryCollectionParseUntagged( untagged ); - - default: - return null; - } - } - - return { - stringify: stringify, - - parse: parse - }; - }()), - - // - // projection functions - // - - proj: (function () { - var halfPi = 1.5707963267948966192, - quarterPi = 0.7853981633974483096, - radiansPerDegree = 0.0174532925199432958, - degreesPerRadian = 57.295779513082320877, - semiMajorAxis = 6378137; - - return { - fromGeodeticPos: function (coordinate) { - return [ - semiMajorAxis * coordinate[ 0 ] * radiansPerDegree, - semiMajorAxis * Math.log(Math.tan(quarterPi + coordinate[ 1 ] * radiansPerDegree / 2)) - ]; - }, - - fromGeodetic: function ( coordinates ) { - if ( ! $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - fromGeodeticPos = this.fromGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length == 4) { - // bbox - var min = fromGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = fromGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = fromGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - }, - - toGeodeticPos: function (coordinate) { - return [ - (coordinate[ 0 ] / semiMajorAxis) * degreesPerRadian, - (halfPi - 2 * Math.atan(1 / Math.exp(coordinate[ 1 ] / semiMajorAxis))) * degreesPerRadian - ]; - }, - - toGeodetic: function (coordinates) { - if ( $.geo._isGeodetic( coordinates ) ) { - return coordinates; - } - - var isMultiPointOrLineString = $.isArray(coordinates[ 0 ]), - toGeodeticPos = this.toGeodeticPos; - - if (!isMultiPointOrLineString && coordinates.length == 4) { - // bbox - var min = toGeodeticPos([ coordinates[ 0 ], coordinates[ 1 ] ]), - max = toGeodeticPos([ coordinates[ 2 ], coordinates[ 3 ] ]); - return [ min[ 0 ], min[ 1 ], max[ 0 ], max[ 1 ] ]; - } else { - // geometry - var isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray(coordinates[ 0 ][ 0 ]), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray(coordinates[ 0 ][ 0 ][ 0 ]), - result = [ ], - i, j, k; - - if (!isMultiPolygon) { - if (!isMultiLineStringOrPolygon) { - if (!isMultiPointOrLineString) { - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - coordinates = [ coordinates ]; - } - - for ( i = 0; i < coordinates.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < coordinates[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < coordinates[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = toGeodeticPos(coordinates[ i ][ j ][ k ]); - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - } - } - }; - }()), - - // - // service types (defined in other files) - // - - _serviceTypes: {} - }; -}(jQuery, this)); - -(function ($, undefined) { - var _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ); - - $.widget("geo.geographics", { - _$elem: undefined, - _options: {}, - _trueCanvas: true, - - _width: 0, - _height: 0, - - _$canvas: undefined, - _context: undefined, - - _blitcanvas: undefined, - _blitcontext: undefined, - - _$labelsContainer: undefined, - - options: { - style: { - borderRadius: "8px", - color: "#7f0000", - //fill: undefined, - fillOpacity: 0.2, - height: "8px", - opacity: 1, - //stroke: undefined, - strokeOpacity: 1, - strokeWidth: "2px", - visibility: "visible", - width: "8px" - } - }, - - _create: function () { - this._$elem = this.element; - this._options = this.options; - - this._$elem.css({ display: "inline-block", overflow: "hidden", textAlign: "left" }); - - if (this._$elem.css("position") == "static") { - this._$elem.css("position", "relative"); - } - - this._$elem.addClass( "geo-graphics" ); - - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - var posCss = 'position:absolute;left:0;top:0;margin:0;padding:0;', - sizeCss = 'width:' + this._width + 'px;height:' + this._height + 'px;', - sizeAttr = 'width="' + this._width + '" height="' + this._height + '"'; - - if (document.createElement('canvas').getContext) { - this._$elem.append(''); - this._$canvas = this._$elem.children(':last'); - this._context = this._$canvas[0].getContext("2d"); - - this._blitcanvas = document.createElement( "canvas" ); - this._blitcanvas.width = this._width; - this._blitcanvas.height = this._height; - this._blitcontext = this._blitcanvas.getContext("2d"); - } else if (_ieVersion <= 8) { - this._trueCanvas = false; - this._$elem.append( '
                                    '); - this._$canvas = this._$elem.children(':last'); - - G_vmlCanvasManager.initElement(this._$canvas[0]); - this._context = this._$canvas[0].getContext("2d"); - this._$canvas.children().css({ backgroundColor: "transparent", width: this._width, height: this._height }); - } - - this._$elem.append('
                                    '); - this._$labelsContainer = this._$elem.children(':last'); - }, - - _setOption: function (key, value) { - if (key == "style") { - value = $.extend({}, this._options.style, value); - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - destroy: function () { - $.Widget.prototype.destroy.apply(this, arguments); - this._$elem.html(""); - this._$elem.removeClass( "geo-graphics" ); - }, - - clear: function () { - this._context.clearRect(0, 0, this._width, this._height); - this._$labelsContainer.html(""); - }, - - drawArc: function (coordinates, startAngle, sweepAngle, style) { - style = this._getGraphicStyle(style); - - if (style.visibility != "hidden" && style.opacity > 0 && style.widthValue > 0 && style.heightValue > 0) { - var r = Math.min(style.widthValue, style.heightValue) / 2; - - startAngle = (startAngle * Math.PI / 180); - sweepAngle = (sweepAngle * Math.PI / 180); - - this._context.save(); - this._context.translate(coordinates[0], coordinates[1]); - if (style.widthValue > style.heightValue) { - this._context.scale(style.widthValue / style.heightValue, 1); - } else { - this._context.scale(1, style.heightValue / style.widthValue); - } - - this._context.beginPath(); - this._context.arc(0, 0, r, startAngle, sweepAngle, false); - - if (this._trueCanvas) { - this._context.restore(); - } - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - - if (!this._trueCanvas) { - this._context.restore(); - } - } - }, - - drawPoint: function (coordinates, style) { - style = this._getGraphicStyle(style); - if (style.widthValue == style.heightValue && style.heightValue == style.borderRadiusValue) { - this.drawArc(coordinates, 0, 360, style); - } else if (style.visibility != "hidden" && style.opacity > 0) { - style.borderRadiusValue = Math.min(Math.min(style.widthValue, style.heightValue) / 2, style.borderRadiusValue); - coordinates[0] -= style.widthValue / 2; - coordinates[1] -= style.heightValue / 2; - this._context.beginPath(); - this._context.moveTo(coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.lineTo(coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1]); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1], coordinates[0] + style.widthValue, coordinates[1] + style.borderRadiusValue); - this._context.lineTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0] + style.widthValue, coordinates[1] + style.heightValue, coordinates[0] + style.widthValue - style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.lineTo(coordinates[0] + style.borderRadiusValue, coordinates[1] + style.heightValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1] + style.heightValue, coordinates[0], coordinates[1] + style.heightValue - style.borderRadiusValue); - this._context.lineTo(coordinates[0], coordinates[1] + style.borderRadiusValue); - this._context.quadraticCurveTo(coordinates[0], coordinates[1], coordinates[0] + style.borderRadiusValue, coordinates[1]); - this._context.closePath(); - - if (style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - - this._context.stroke(); - } - } - }, - - drawLineString: function (coordinates, style) { - this._drawLines([coordinates], false, style); - }, - - drawPolygon: function (coordinates, style) { - if ( !this._trueCanvas || coordinates.length == 1 ) { - // either we don't have fancy rendering or there's no need for it (no holes) - this._drawLines( coordinates, true, style ); - } else { - if ( !coordinates || !coordinates.length || coordinates[ 0 ].length < 3 ) { - // this is not a Polygon or it doesn't have a proper outer ring - return; - } - - style = this._getGraphicStyle(style); - - var pixelBbox, i, j; - - if ( style.visibility != "hidden" && style.opacity > 0 ) { - this._blitcontext.clearRect(0, 0, this._width, this._height); - - if ( style.doFill ) { - if ( coordinates.length > 1 ) { - // stencil inner rings - this._blitcontext.globalCompositeOperation = "source-out"; - this._blitcontext.globalAlpha = 1; - - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.fill( ); - } - } - } - - // path outer ring - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ 0 ][ 0 ][ 0 ], coordinates[ 0 ][ 0 ][ 1 ] ); - - pixelBbox = [ coordinates[ 0 ][ 0 ][ 0 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] - style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 0 ] + style.strokeWidthValue, coordinates[ 0 ][ 0 ][ 1 ] + style.strokeWidthValue ]; - - for ( i = 1; i < coordinates[ 0 ].length - 1; i++ ) { - this._blitcontext.lineTo( coordinates[ 0 ][ i ][ 0 ], coordinates[ 0 ][ i ][ 1 ] ); - - pixelBbox[ 0 ] = Math.min( coordinates[ 0 ][ i ][ 0 ] - style.strokeWidthValue, pixelBbox[ 0 ] ); - pixelBbox[ 1 ] = Math.min( coordinates[ 0 ][ i ][ 1 ] - style.strokeWidthValue, pixelBbox[ 1 ] ); - pixelBbox[ 2 ] = Math.max( coordinates[ 0 ][ i ][ 0 ] + style.strokeWidthValue, pixelBbox[ 2 ] ); - pixelBbox[ 3 ] = Math.max( coordinates[ 0 ][ i ][ 1 ] + style.strokeWidthValue, pixelBbox[ 3 ] ); - } - - this._blitcontext.closePath(); - - this._blitcontext.globalCompositeOperation = "source-out"; - if ( style.doFill ) { - // fill outer ring - this._blitcontext.fillStyle = style.fill; - this._blitcontext.globalAlpha = style.opacity * style.fillOpacity; - this._blitcontext.fill( ); - } - - this._blitcontext.globalCompositeOperation = "source-over"; - if ( style.doStroke ) { - // stroke outer ring - this._blitcontext.lineCap = this._blitcontext.lineJoin = "round"; - this._blitcontext.lineWidth = style.strokeWidthValue; - this._blitcontext.strokeStyle = style.stroke; - - this._blitcontext.globalAlpha = style.opacity * style.strokeOpacity; - this._blitcontext.stroke( ); - - if ( coordinates.length > 1 ) { - // stroke inner rings - for ( i = 1; i < coordinates.length; i++ ) { - this._blitcontext.beginPath(); - this._blitcontext.moveTo( coordinates[ i ][ 0 ][ 0 ], coordinates[ i ][ 0 ][ 1 ] ); - for ( j = 1; j < coordinates[ i ].length; j++ ) { - this._blitcontext.lineTo( coordinates[ i ][ j ][ 0 ], coordinates[ i ][ j ][ 1 ] ); - } - this._blitcontext.closePath(); - - this._blitcontext.stroke( ); - } - } - } - - // blit - pixelBbox[ 0 ] = Math.max( pixelBbox[ 0 ], 0 ); - pixelBbox[ 1 ] = Math.max( pixelBbox[ 1 ], 0 ); - pixelBbox[ 2 ] = Math.min( pixelBbox[ 2 ], this._width ); - pixelBbox[ 3 ] = Math.min( pixelBbox[ 3 ], this._height ); - - this._context.drawImage(this._blitcanvas, pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ], pixelBbox[ 0 ], pixelBbox[ 1 ], pixelBbox[ 2 ] - pixelBbox[ 0 ], pixelBbox[ 3 ] - pixelBbox[ 1 ] ); - } - } - }, - - drawBbox: function (bbox, style) { - this._drawLines([[ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ]], true, style); - }, - - drawLabel: function( coordinates, label ) { - this._$labelsContainer.append( '
                                    ' + label + '
                                    '); - }, - - resize: function( ) { - this._width = this._$elem.width(); - this._height = this._$elem.height(); - - if (!(this._width && this._height)) { - this._width = parseInt(this._$elem.css("width"), 10); - this._height = parseInt(this._$elem.css("height"), 10); - } - - if ( this._trueCanvas ) { - this._$canvas[0].width = this._width; - this._$canvas[0].height = this._height; - } else { - } - - this._$labelsContainer.css( { - width: this._width, - height: this._height - } ); - }, - - _getGraphicStyle: function (style) { - function safeParse(value) { - value = parseInt(value, 10); - return (+value + '') === value ? +value : value; - } - - style = $.extend({}, this._options.style, style); - style.borderRadiusValue = safeParse(style.borderRadius); - style.fill = style.fill || style.color; - style.doFill = style.fill && style.fillOpacity > 0; - style.stroke = style.stroke || style.color; - style.strokeWidthValue = safeParse(style.strokeWidth); - style.doStroke = style.stroke && style.strokeOpacity > 0 && style.strokeWidthValue > 0; - style.widthValue = safeParse(style.width); - style.heightValue = safeParse(style.height); - return style; - }, - - _drawLines: function (coordinates, close, style) { - if (!coordinates || !coordinates.length || coordinates[0].length < 2) { - return; - } - - var i, j; - style = this._getGraphicStyle(style); - - if (style.visibility != "hidden" && style.opacity > 0) { - this._context.beginPath(); - - for (i = 0; i < coordinates.length; i++) { - this._context.moveTo(coordinates[i][0][0], coordinates[i][0][1]); - for (j = 1; j < coordinates[i].length; j++) { - this._context.lineTo(coordinates[i][j][0], coordinates[i][j][1]); - } - } - - if (close) { - this._context.closePath(); - } - - if (close && style.doFill) { - this._context.fillStyle = style.fill; - this._context.globalAlpha = style.opacity * style.fillOpacity; - this._context.fill(); - } - - if (style.doStroke) { - this._context.lineCap = this._context.lineJoin = "round"; - this._context.lineWidth = style.strokeWidthValue; - this._context.strokeStyle = style.stroke; - - this._context.globalAlpha = style.opacity * style.strokeOpacity; - this._context.stroke(); - } - } - } - }); -}(jQuery)); - - -(function ($, undefined) { - var _widgetIdSeed = 0, - _ieVersion = ( function () { - var v = 5, div = document.createElement("div"), a = div.all || []; - do { - div.innerHTML = ""; - } while ( a[0] ); - return v > 6 ? v : !v; - }() ), - - _defaultOptions = { - bbox: [-180, -85, 180, 85], - bboxMax: [-180, -85, 180, 85], - center: [0, 0], - cursors: { - "static": "default", - pan: "url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move", - zoom: "crosshair", - dragBox: "crosshair", - dragCircle: "crosshair", - drawPoint: "crosshair", - drawLineString: "crosshair", - drawPolygon: "crosshair", - measureLength: "crosshair", - measureArea: "crosshair" - }, - measureLabels: { - length: "{{:length.toFixed( 2 )}} m", - area: "{{:area.toFixed( 2 )}} sq m" - }, - drawStyle: {}, - shapeStyle: {}, - mode: "pan", - pannable: true, - scroll: "default", - shift: "default", - services: [ - { - "class": "osm", - type: "tiled", - src: function (view) { - return "http://otile" + ((view.index % 4) + 1) + ".mqcdn.com/tiles/1.0.0/osm/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; - }, - attr: "Tiles Courtesy of MapQuest " - } - ], - tilingScheme: { - tileWidth: 256, - tileHeight: 256, - levels: 18, - basePixelSize: 156543.03392799936, - origin: [-20037508.342787, 20037508.342787] - }, - axisLayout: "map", - zoom: 0, - zoomMin: 0, - zoomMax: Number.POSITIVE_INFINITY, - pixelSize: 0 - }; - - $.widget("geo.geomap", { - // private widget members - _$elem: undefined, //< map div for maps, service div for services - _map: undefined, //< only defined in services - _created: false, - _createdGraphics: false, - _widgetId: 0, - _tmplLengthId: "", - _tmplAreaId: "", - - _contentBounds: {}, - - _$resizeContainer: undefined, //< all elements that should match _contentBounds' size - - _$eventTarget: undefined, - _$contentFrame: undefined, - _$existingChildren: undefined, - _$attrList: undefined, - _$servicesContainer: undefined, - _$shapesContainers: undefined, //< all shapesContainer divs (map only) - - _$panContainer: undefined, //< all non-service elements that move while panning - _$shapesContainer: undefined, //< just "our" shapesContainer div (map & service) - _$drawContainer: undefined, - _$measureContainer: undefined, - _$measureLabel: undefined, - - _dpi: 96, - - _currentServices: [], //< internal copy - - _center: undefined, - _pixelSize: undefined, - _centerMax: undefined, - _pixelSizeMax: undefined, - - _userGeodetic: true, - - _centerInteractive: undefined, - _pixelSizeInteractive: undefined, - _timeoutInteractive: null, - _triggerInteractive: false, - - _loadCount: 0, - - _wheelTimeout: null, - _wheelLevel: 0, - - _zoomFactor: 2, //< determines what a zoom level means - - _fullZoomFactor: 2, //< interactiveScale factor needed to zoom a whole level - _partialZoomFactor: 1.18920711500273, //< interactiveScale factor needed to zoom a fraction of a level (the fourth root of 2) - - _mouseDown: undefined, - _inOp: undefined, - _toolPan: undefined, - _shiftDown: undefined, - _anchor: undefined, - _current: undefined, - _downDate: undefined, - _moveDate: undefined, - _clickDate: undefined, - _lastMove: undefined, - _lastDrag: undefined, - - _windowHandler: null, - _resizeTimeout: null, - - _panning: undefined, - _velocity: undefined, - _friction: undefined, - - _supportTouch: undefined, - _softDblClick: undefined, - _isTap: undefined, - _isDbltap: undefined, - - _isMultiTouch: undefined, - _multiTouchAnchor: [], //< TouchList - _multiTouchAnchorBbox: undefined, //< bbox - _multiTouchCurrentBbox: undefined, //< bbox - - _drawTimeout: null, //< used in drawPoint mode so we don't send two shape events on dbltap - _drawPixels: [], //< an array of coordinate arrays for drawing lines & polygons, in pixel coordinates - _drawCoords: [], - - _graphicShapes: [], //< an array of objects containing style object refs & GeoJSON object refs - - _initOptions: {}, - - _options: {}, - - options: $.extend({}, _defaultOptions), - - _createWidget: function (options, element) { - this._$elem = $(element); - - if (this._$elem.is(".geo-service")) { - this._graphicShapes = []; - $.Widget.prototype._createWidget.apply(this, arguments); - return; - } - - this._widgetId = _widgetIdSeed++; - this._tmplLengthId = "geoMeasureLength" + this._widgetId; - this._tmplAreaId = "geoMeasureArea" + this._widgetId; - - this._$elem.addClass("geo-map").css( { - webkitTransform: "translateZ(0)" - } ); - - - this._initOptions = options || {}; - - this._forcePosition(this._$elem); - - this._$elem.css("text-align", "left"); - - var size = this._findMapSize(); - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._createChildren(); - - this._center = [ 0, 0 ]; - this._centerMax = [ 0, 0 ]; - this._centerInteractive = [ 0, 0 ]; - - this.options["pixelSize"] = this._pixelSize = this._pixelSizeMax = 156543.03392799936; - - this._mouseDown = - this._inOp = - this._toolPan = - this._shiftDown = - this._panning = - this._isTap = - this._isDbltap = false; - - this._anchor = [ 0, 0 ]; - this._current = [ 0, 0 ]; - this._lastMove = [ 0, 0 ]; - this._lastDrag = [ 0, 0 ]; - this._velocity = [ 0, 0 ]; - - this._friction = [0.8, 0.8]; - - this._downDate = - this._moveDate = - this._clickDate = 0; - - this._drawPixels = []; - this._drawCoords = []; - this._graphicShapes = []; - - - $.Widget.prototype._createWidget.apply(this, arguments); - }, - - _create: function () { - this._options = this.options; - - if (this._$elem.is(".geo-service")) { - this._map = this._$elem.data( "geoMap" ); - this._$elem.data( "geoService", this ); - return; - } - - this._map = this; - - this._supportTouch = "ontouchend" in document; - this._softDblClick = this._supportTouch || _ieVersion == 7; - - var geomap = this, - touchStartEvent = this._supportTouch ? "touchstart" : "mousedown", - touchStopEvent = this._supportTouch ? "touchend touchcancel" : "mouseup", - touchMoveEvent = this._supportTouch ? "touchmove" : "mousemove"; - - $(document).keydown($.proxy(this._document_keydown, this)); - - this._$eventTarget.dblclick($.proxy(this._eventTarget_dblclick, this)); - - this._$eventTarget.bind(touchStartEvent, $.proxy(this._eventTarget_touchstart, this)); - - var dragTarget = (this._$eventTarget[0].setCapture) ? this._$eventTarget : $(document); - dragTarget.bind(touchMoveEvent, $.proxy(this._dragTarget_touchmove, this)); - dragTarget.bind(touchStopEvent, $.proxy(this._dragTarget_touchstop, this)); - - this._$eventTarget.mousewheel($.proxy(this._eventTarget_mousewheel, this)); - - this._windowHandler = function () { - if (geomap._resizeTimeout) { - clearTimeout(geomap._resizeTimeout); - } - geomap._resizeTimeout = setTimeout(function () { - if (geomap._created) { - geomap._$elem.geomap( "resize", true ); - } - }, 500); - }; - - $(window).resize(this._windowHandler); - - this._$drawContainer.geographics({ style: this._initOptions.drawStyle || {} }); - this._options["drawStyle"] = this._$drawContainer.geographics("option", "style"); - - this._$shapesContainer.geographics( { style: this._initOptions.shapeStyle || { } } ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - - if (this._initOptions) { - // always init tilingScheme right away, even if it's null - if ( this._initOptions.tilingScheme !== undefined ) { - this._setOption("tilingScheme", this._initOptions.tilingScheme || null, false); - } - - if ( this._initOptions.services ) { - // jQuery UI Widget Factory merges user services with our default, we want to clobber the default - this._options[ "services" ] = $.merge( [ ], this._initOptions.services ); - } - if (this._initOptions.bboxMax) { - this._setOption("bboxMax", this._initOptions.bboxMax, false); - this._setOption("bbox", this._initOptions.bboxMax, false); - } - if (this._initOptions.zoomMin !== undefined) { - this._setOption("zoomMin", this._initOptions.zoomMin, false); - } - if (this._initOptions.zoomMax !== undefined) { - this._setOption("zoomMax", this._initOptions.zoomMax, false); - } - if (this._initOptions.bbox) { - this._setOption("bbox", this._initOptions.bbox, false); - } - if (this._initOptions.center) { - this._setOption("center", this._initOptions.center, false); - } - if (this._initOptions.zoom !== undefined) { - this._setOption("zoom", this._initOptions.zoom, false); - } - } - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._createServices(); - this._refresh(); - - this._created = true; - }, - - _setOption: function (key, value, refresh) { - if ( key == "pixelSize" ) { - return; - } - - refresh = (refresh === undefined || refresh); - - if ( this._$elem.is( ".geo-map" ) ) { - this._panFinalize(); - } - - var center, pixelSize, bbox, zoom; - - switch (key) { - case "bbox": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2]; - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height); - - // clamp to zoom - zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( center, pixelSize ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( center, pixelSize, false, refresh ); - } - - value = this._getBbox( center, pixelSize ); - break; - - case "bboxMax": - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - break; - - case "center": - if ( this._created ) { - this._clearInteractiveTimeout( ); - } - - this._userGeodetic = $.geo.proj && $.geo._isGeodetic( value ); - if ( this._userGeodetic ) { - value = $.geo.proj.fromGeodetic( value ); - } - - if ( this._created ) { - this._setInteractiveCenterAndSize( value, this._pixelSize ); - this._setInteractiveTimeout( false ); - } else { - this._setCenterAndSize( value, this._pixelSize, false, refresh ); - } - break; - - case "measureLabels": - value = $.extend( this._options[ "measureLabels" ], value ); - - - $.templates( this._tmplLengthId, this._options[ "measureLabels" ].length ); - $.templates( this._tmplAreaId, this._options[ "measureLabels" ].area ); - - break; - - case "drawStyle": - if (this._$drawContainer) { - this._$drawContainer.geographics("option", "style", value); - value = this._$drawContainer.geographics("option", "style"); - } - break; - - case "shapeStyle": - if ( this._$elem.is( ".geo-service" ) && !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("option", "style", value); - value = this._$shapesContainer.geographics("option", "style"); - } - break; - - case "mode": - this._resetDrawing( ); - this._$eventTarget.css("cursor", this._options["cursors"][value]); - break; - - case "zoom": - if ( this._created ) { - this._setZoom(value, false, refresh); - } else { - value = Math.max( value, 0 ); - this._setCenterAndSize( this._center, this._getPixelSize( value ), false, refresh ); - } - break; - } - - $.Widget.prototype._setOption.apply(this, arguments); - - switch ( key ) { - case "bbox": - case "center": - if ( this._userGeodetic ) { - this._options[ "bbox" ] = $.geo.proj.toGeodetic( this._options[ "bbox" ] ); - this._options[ "center" ] = $.geo.proj.toGeodetic( this._center ); - } - break; - - case "tilingScheme": - if ( value !== null ) { - this._pixelSizeMax = this._getPixelSize( 0 ); - this._centerMax = [ - value.origin[ 0 ] + this._pixelSizeMax * value.tileWidth / 2, - value.origin[ 1 ] + this._pixelSizeMax * value.tileHeight / 2 - ]; - } - break; - - case "bboxMax": - if ( $.geo.proj && $.geo._isGeodetic( value ) ) { - bbox = $.geo.proj.fromGeodetic( value ); - } else { - bbox = value; - } - - this._centerMax = $.geo.center( bbox ); - this._pixelSizeMax = Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - break; - - case "services": - this._createServices(); - if (refresh) { - this._refresh(); - } - break; - - case "shapeStyle": - if ( refresh && this._createdGraphics ) { - this._$shapesContainer.geographics("clear"); - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - break; - } - }, - - destroy: function () { - if ( this._$elem.is(".geo-service") ) { - if ( this._createdGraphics ) { - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - } - } else { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - - this._created = false; - - $(window).unbind("resize", this._windowHandler); - - for ( var i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap("destroy"); - $.geo["_serviceTypes"][this._currentServices[i].type].destroy(this, this._$servicesContainer, this._currentServices[i]); - } - - this._$shapesContainer.geographics("destroy"); - this._$shapesContainer = undefined; - this._createdGraphics = false; - - this._$drawContainer.geographics("destroy"); - this._$drawContainer = undefined; - - this._$existingChildren.detach(); - this._$elem.html(""); - this._$elem.append(this._$existingChildren); - this._$elem.removeClass("geo-map"); - } - - $.Widget.prototype.destroy.apply(this, arguments); - }, - - toMap: function (p) { - p = this._toMap(p); - return this._userGeodetic ? $.geo.proj.toGeodetic(p) : p; - }, - - toPixel: function ( p, _center /* Internal Use Only */, _pixelSize /* Internal Use Only */ ) { - return this._toPixel( $.geo.proj ? $.geo.proj.fromGeodetic( p ) : p, _center, _pixelSize ); - }, - - opacity: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "opacity", value, this._$elem ); - } else { - if ( value >= 0 || value <= 1 ) { - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - service.style.opacity = value; - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - $.geo[ "_serviceTypes" ][ service.type ].opacity( this, service ); - } - } - } - } - }, - - toggle: function ( value, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "toggle", value, this._$elem ); - } else { - - for ( var i = 0; i < this._currentServices.length; i++ ) { - var service = this._currentServices[ i ]; - - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - if ( value === undefined ) { - // toggle visibility - value = ( service.style.visibility !== "visible" ); - } - - service.style.visibility = ( value ? "visible" : "hidden" ); - - // update the original service object's style property - service.serviceObject.style = $.extend( { }, service.serviceObject.style, service.style ); - - service.serviceContainer.toggle( value ); - - if ( value ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service ); - } - } - } - } - }, - - zoom: function (numberOfLevels) { - if (numberOfLevels !== null) { - this._setZoom(this._options["zoom"] + numberOfLevels, false, true); - } - }, - - refresh: function ( force, _serviceContainer ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._$elem.closest( ".geo-map" ).geomap( "refresh", force, this._$elem ); - } else { - this._refresh( force, _serviceContainer ); - } - }, - - resize: function ( _trigger /* Internal Use Only */ ) { - var size = this._findMapSize(), - dx = size["width"]/2 - this._contentBounds.width/2, - dy = size["height"]/2 - this._contentBounds.height/2, - i; - - this._contentBounds = { - x: parseInt(this._$elem.css("padding-left"), 10), - y: parseInt(this._$elem.css("padding-top"), 10), - width: size["width"], - height: size["height"] - }; - - this._$resizeContainer.css( { - width: size["width"], - height: size["height"] - } ); - - for (i = 0; i < this._currentServices.length; i++) { - $.geo["_serviceTypes"][this._currentServices[i].type].resize(this, this._currentServices[i]); - } - - this._$elem.find( ".geo-graphics" ).css( { - width: size["width"], - height: size["height"] - }).geographics( "resize" ); - - for (i = 0; i < this._drawPixels.length; i++) { - this._drawPixels[i][0] += dx; - this._drawPixels[i][1] += dy; - } - - this._setCenterAndSize(this._center, this._pixelSize, _trigger, true); - }, - - append: function ( shape, style, label, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - if ( !this._createdGraphics ) { - this._createServiceGraphics( ); - } - - var shapes, arg, i, realStyle, realLabel, realRefresh; - - if ( $.isArray( shape ) ) { - shapes = shape; - } else if ( shape.type == "FeatureCollection" ) { - shapes = shape.features; - } else { - shapes = [ shape ]; - } - - for ( i = 1; i < arguments.length; i++ ) { - arg = arguments[ i ]; - - if ( typeof arg === "object" ) { - realStyle = arg; - } else if ( typeof arg === "number" || typeof arg === "string" ) { - realLabel = arg; - } else if ( typeof arg === "boolean" ) { - realRefresh = arg; - } - } - - for ( i = 0; i < shapes.length; i++ ) { - if ( shapes[ i ].type != "Point" ) { - var bbox = $.geo.bbox( shapes[ i ] ); - if ( $.geo.proj && $.geo._isGeodetic( bbox ) ) { - bbox = $.geo.proj.fromGeodetic( bbox ); - } - $.data( shapes[ i ], "geoBbox", bbox ); - } - - this._graphicShapes.push( { - shape: shapes[ i ], - style: realStyle, - label: realLabel - } ); - } - - if ( realRefresh === undefined || realRefresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - } - } - }, - - empty: function ( refresh ) { - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - $.removeData( this._graphicShapes[ i ].shape, "geoBbox" ); - } - - this._graphicShapes = []; - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - } - }, - - find: function ( selector, pixelTolerance ) { - var isPoint = $.isPlainObject( selector ), - searchPixel = isPoint ? this._map.toPixel( selector.coordinates ) : undefined, - mapTol = this._map._pixelSize * pixelTolerance, - result = [], - graphicShape, - geometries, - curGeom, - i = 0; - - for ( ; i < this._graphicShapes.length; i++ ) { - graphicShape = this._graphicShapes[ i ]; - - if ( isPoint ) { - if ( graphicShape.shape.type == "Point" ) { - if ( $.geo.distance( graphicShape.shape, selector ) <= mapTol ) { - result.push( graphicShape.shape ); - } - } else { - var bbox = $.data( graphicShape.shape, "geoBbox" ), - bboxPolygon = { - type: "Polygon", - coordinates: [ [ - [bbox[0], bbox[1]], - [bbox[0], bbox[3]], - [bbox[2], bbox[3]], - [bbox[2], bbox[1]], - [bbox[0], bbox[1]] - ] ] - }, - projectedPoint = { - type: "Point", - coordinates: $.geo.proj && $.geo._isGeodetic( selector.coordinates ) ? $.geo.proj.fromGeodetic( selector.coordinates ) : selector.coordinates - }; - - if ( $.geo.distance( bboxPolygon, projectedPoint, true ) <= mapTol ) { - geometries = $.geo._flatten( graphicShape.shape ); - for ( curGeom = 0; curGeom < geometries.length; curGeom++ ) { - if ( $.geo.distance( geometries[ curGeom ], selector ) <= mapTol ) { - result.push( graphicShape.shape ); - break; - } - } - } - } - } else { - result.push( graphicShape.shape ); - } - } - - if ( this._$elem.is( ".geo-map" ) ) { - this._$elem.find( ".geo-service" ).each( function( ) { - result = $.merge( result, $( this ).geomap( "find", selector, pixelTolerance ) ); - } ); - } - - return result; - }, - - remove: function ( shape, refresh ) { - if ( shape && ( $.isPlainObject( shape ) || ( $.isArray( shape ) && shape.length > 0 ) ) ) { - var shapes = $.isArray( shape ) ? shape : [ shape ], - rest; - - for ( var i = 0; i < this._graphicShapes.length; i++ ) { - if ( $.inArray( this._graphicShapes[ i ].shape, shapes ) >= 0 ) { - $.removeData( shape, "geoBbox" ); - rest = this._graphicShapes.slice( i + 1 ); - this._graphicShapes.length = i; - this._graphicShapes.push.apply( this._graphicShapes, rest ); - i--; - } - } - - if ( refresh === undefined || refresh ) { - if ( this._$elem.is( ".geo-service" ) ) { - this._refresh( false, this._$elem ); - } else { - this._refresh( ); - } - } - } - }, - - _getBbox: function (center, pixelSize) { - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - // calculate the internal bbox - var halfWidth = this._contentBounds[ "width" ] / 2 * pixelSize, - halfHeight = this._contentBounds[ "height" ] / 2 * pixelSize; - return [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - }, - - _setBbox: function (value, trigger, refresh) { - var center = [value[0] + (value[2] - value[0]) / 2, value[1] + (value[3] - value[1]) / 2], - pixelSize = Math.max($.geo.width(value, true) / this._contentBounds.width, $.geo.height(value, true) / this._contentBounds.height), - zoom = this._getZoom( center, pixelSize ); - - // clamp to zoom - if ( this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._setInteractiveCenterAndSize( center, pixelSize ); - this._interactiveTransform( ); - }, - - _getBboxMax: function () { - // calculate the internal bboxMax - var halfWidth = this._contentBounds["width"] / 2 * this._pixelSizeMax, - halfHeight = this._contentBounds["height"] / 2 * this._pixelSizeMax; - return [this._centerMax[0] - halfWidth, this._centerMax[1] - halfHeight, this._centerMax[0] + halfWidth, this._centerMax[1] + halfHeight]; - }, - - _getCenter: function () { - return this._center; - }, - - _getContentBounds: function () { - return this._contentBounds; - }, - - _getServicesContainer: function () { - return this._$servicesContainer; - }, - - _getZoom: function ( center, pixelSize ) { - // calculate the internal zoom level, vs. public zoom property - // this does not take zoomMin or zoomMax into account - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var tilingScheme = this._options["tilingScheme"]; - if ( tilingScheme ) { - if ( tilingScheme.pixelSizes ) { - var roundedPixelSize = Math.floor(pixelSize * 1000), - levels = tilingScheme.pixelSizes.length, - i = levels - 1; - - for ( ; i >= 0; i-- ) { - if ( Math.floor( tilingScheme.pixelSizes[ i ] * 1000 ) >= roundedPixelSize ) { - return i; - } - } - - return 0; - } else { - return Math.round( Math.log( tilingScheme.basePixelSize / pixelSize) / Math.log( 2 ) ); - } - } else { - var ratio = this._contentBounds["width"] / this._contentBounds["height"], - bbox = $.geo.reaspect( this._getBbox( center, pixelSize ), ratio, true ), - bboxMax = $.geo.reaspect(this._getBboxMax(), ratio, true); - - return Math.round( Math.log($.geo.width(bboxMax, true) / $.geo.width(bbox, true)) / Math.log(this._zoomFactor) ); - } - }, - - _setZoom: function ( value, trigger, refresh ) { - // set the map widget's zoom, taking zoomMin and zoomMax into account - this._clearInteractiveTimeout( ); - - value = Math.min( Math.max( value, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ); - this._setInteractiveCenterAndSize( this._center, this._getPixelSize( value ) ); - this._interactiveTransform( ); - - this._setInteractiveTimeout( trigger ); - }, - - _createChildren: function () { - this._$existingChildren = this._$elem.children(); - - this._forcePosition(this._$existingChildren); - - this._$existingChildren.detach().css( { - mozUserSelect: "none" - } ); - - - var contentSizeCss = "width:" + this._contentBounds["width"] + "px; height:" + this._contentBounds["height"] + "px; margin:0; padding:0;", - contentPosCss = "position:absolute; left:0; top:0;"; - - this._$elem.prepend('
                                    '); - this._$eventTarget = this._$contentFrame = this._$elem.children(':first'); - - this._$contentFrame.append('
                                    '); - this._$servicesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                                    '); - this._$shapesContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append( '
                                      ' ); - this._$attrList = this._$contentFrame.children( ":last" ); - - this._$contentFrame.append('
                                      '); - this._$drawContainer = this._$contentFrame.children(':last'); - - this._$contentFrame.append('
                                      '); - this._$measureContainer = this._$contentFrame.children(':last'); - this._$measureLabel = this._$measureContainer.children(); - - this._$panContainer = $( [ this._$shapesContainer[ 0 ], this._$drawContainer[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$resizeContainer = $( [ this._$contentFrame[ 0 ], this._$servicesContainer[ 0 ], this._$eventTarget[ 0 ], this._$measureContainer[ 0 ] ] ); - - this._$contentFrame.append(this._$existingChildren); - - if ( ! $("#geo-measure-style").length ) { - $("head").prepend( '' ); - } - }, - - _createServices: function () { - var service, i; - - for ( i = 0; i < this._currentServices.length; i++ ) { - this._currentServices[ i ].serviceContainer.geomap( "destroy" ); - $.geo[ "_serviceTypes" ][ this._currentServices[ i ].type ].destroy( this, this._$servicesContainer, this._currentServices[ i ] ); - } - - this._currentServices = [ ]; - this._$servicesContainer.html( "" ); - this._$attrList.html( "" ); - - for ( i = 0; i < this._options[ "services" ].length; i++ ) { - service = this._currentServices[ i ] = $.extend( { }, this._options[ "services" ][ i ] ); - - // keep a reference to the original - service.serviceObject = this._options[ "services" ][ i ]; - - // default the service style property on our copy - service.style = $.extend( { - visibility: "visible", - opacity: 1 - }, service.style ); - - var idString = service.id ? ' id="' + service.id + '"' : "", - classString = 'class="geo-service ' + ( service["class"] ? service["class"] : '' ) + '"', - scHtml = '
                                      ', - servicesContainer; - - this._$servicesContainer.append( scHtml ); - serviceContainer = this._$servicesContainer.children( ":last" ); - service.serviceContainer = serviceContainer; - - $.geo[ "_serviceTypes" ][ service.type ].create( this, serviceContainer, service, i ); - - serviceContainer.data( "geoMap", this ).geomap(); - - if ( service.attr ) { - this._$attrList.append( '
                                    • ' + service.attr + '
                                    • ' ); - } - } - - // start with our map-level shapesContainer - this._$shapesContainers = this._$shapesContainer; - - this._$attrList.find( "a" ).css( { - position: "relative", - zIndex: 100 - } ); - }, - - _createServiceGraphics: function( ) { - // only called in the context of a service-level geomap - var $contentFrame = this._$elem.closest( ".geo-content-frame" ); - this._$elem.append('
                                      '); - this._$shapesContainer = this._$elem.children(':last'); - - this._map._$shapesContainers = this._map._$shapesContainers.add( this._$shapesContainer ); - - this._$shapesContainer.geographics( ); - this._createdGraphics = true; - - this._options["shapeStyle"] = this._$shapesContainer.geographics("option", "style"); - }, - - _refreshDrawing: function ( ) { - this._$drawContainer.geographics("clear"); - - if ( this._drawPixels.length > 0 ) { - var mode = this._options[ "mode" ], - pixels = this._drawPixels, - coords = this._drawCoords, - label, - labelShape, - labelPixel, - widthOver, - heightOver; - - switch ( mode ) { - case "measureLength": - mode = "drawLineString"; - labelShape = { - type: "LineString", - coordinates: coords - }; - label = $.render[ this._tmplLengthId ]( { length: $.geo.length( labelShape, true ) } ); - labelPixel = $.merge( [], pixels[ pixels.length - 1 ] ); - break; - - case "measureArea": - mode = "drawPolygon"; - - labelShape = { - type: "Polygon", - coordinates: [ $.merge( [ ], coords ) ] - }; - labelShape.coordinates[ 0 ].push( coords[ 0 ] ); - - label = $.render[ this._tmplAreaId ]( { area: $.geo.area( labelShape, true ) } ); - labelPixel = this._toPixel( $.geo.centroid( labelShape ).coordinates ); - pixels = [ pixels ]; - break; - - case "drawPolygon": - pixels = [ pixels ]; - break; - } - - this._$drawContainer.geographics( mode, pixels ); - - if ( label ) { - this._$measureLabel.html( label ); - - widthOver = this._contentBounds.width - ( this._$measureLabel.outerWidth( true ) + labelPixel[ 0 ] ); - heightOver = this._contentBounds.height - ( this._$measureLabel.outerHeight( true ) + labelPixel[ 1 ] ); - - if ( widthOver < 0 ) { - labelPixel[ 0 ] += widthOver; - } - - if ( heightOver < 0 ) { - labelPixel[ 1 ] += heightOver; - } - - this._$measureLabel.css( { - left: Math.max( labelPixel[ 0 ], 0 ), - top: Math.max( labelPixel[ 1 ], 0 ) - } ).show(); - } - } - }, - - _resetDrawing: function () { - this._drawPixels = []; - this._drawCoords = []; - this._$drawContainer.geographics("clear"); - this._$measureLabel.hide(); - }, - - _refreshShapes: function (geographics, shapes, styles, labels, center, pixelSize) { - var i, mgi, - shape, - shapeBbox, - style, - label, - hasLabel, - labelPixel, - bbox = this._map._getBbox(center, pixelSize); - - for (i = 0; i < shapes.length; i++) { - shape = shapes[i].shape || shapes[i]; - shape = shape.geometry || shape; - shapeBbox = $.data(shape, "geoBbox"); - - if ( shapeBbox && $.geo._bboxDisjoint( bbox, shapeBbox ) ) { - continue; - } - - style = $.isArray(styles) ? styles[i].style : styles; - label = $.isArray(labels) ? labels[i].label : labels; - hasLabel = ( label !== undefined ); - labelPixel = undefined; - - switch (shape.type) { - case "Point": - labelPixel = this._map.toPixel( shape.coordinates, center, pixelSize ); - this._$shapesContainer.geographics("drawPoint", labelPixel, style); - break; - case "LineString": - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.pointAlong( shape, 0.5 ).coordinates, center, pixelSize ); - } - break; - case "Polygon": - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates, center, pixelSize), style); - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiPoint": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPoint", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiLineString": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawLineString", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - case "MultiPolygon": - for (mgi = 0; mgi < shape.coordinates.length; mgi++) { - this._$shapesContainer.geographics("drawPolygon", this._map.toPixel(shape.coordinates[mgi], center, pixelSize), style); - } - if ( hasLabel ) { - labelPixel = this._map.toPixel( $.geo.centroid( shape ).coordinates, center, pixelSize ); - } - break; - - case "GeometryCollection": - this._refreshShapes(geographics, shape.geometries, style, label, center, pixelSize); - break; - } - - if ( hasLabel && labelPixel ) { - this._$shapesContainer.geographics( "drawLabel", labelPixel, label ); - } - } - }, - - _findMapSize: function () { - // really, really attempt to find a size for this thing - // even if it's hidden (look at parents) - var size = { width: 0, height: 0 }, - sizeContainer = this._$elem; - - while (sizeContainer.size() && !(size["width"] > 0 && size["height"] > 0)) { - size = { width: sizeContainer.width(), height: sizeContainer.height() }; - if (size["width"] <= 0 || size["height"] <= 0) { - size = { width: parseInt(sizeContainer.css("width"), 10), height: parseInt(sizeContainer.css("height"), 10) }; - } - sizeContainer = sizeContainer.parent(); - } - return size; - }, - - _forcePosition: function (elem) { - var cssPosition = elem.css("position"); - if (cssPosition != "relative" && cssPosition != "absolute" && cssPosition != "fixed") { - elem.css("position", "relative"); - } - }, - - _getPixelSize: function ( zoom ) { - var tilingScheme = this._options["tilingScheme"]; - if (tilingScheme !== null) { - if (zoom === 0) { - return tilingScheme.pixelSizes ? tilingScheme.pixelSizes[0] : tilingScheme.basePixelSize; - } - - zoom = Math.round(zoom); - zoom = Math.max(zoom, 0); - var levels = tilingScheme.pixelSizes ? tilingScheme.pixelSizes.length : tilingScheme.levels; - zoom = Math.min(zoom, levels - 1); - - if ( tilingScheme.pixelSizes ) { - return tilingScheme.pixelSizes[zoom]; - } else { - return tilingScheme.basePixelSize / Math.pow(2, zoom); - } - } else { - var bbox = $.geo.scaleBy( this._getBboxMax(), 1 / Math.pow( this._zoomFactor, zoom ), true ); - return Math.max( $.geo.width( bbox, true ) / this._contentBounds.width, $.geo.height( bbox, true ) / this._contentBounds.height ); - } - }, - - _getZoomCenterAndSize: function ( anchor, zoomDelta, full ) { - var zoomFactor = ( full ? this._fullZoomFactor : this._partialZoomFactor ), - scale = Math.pow( zoomFactor, -zoomDelta ), - pixelSize = this._pixelSizeInteractive * scale, - zoom = this._getZoom(this._centerInteractive, pixelSize); - - // clamp to zoom - if ( full && this._options[ "tilingScheme" ] ) { - pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoomDelta < 0 && zoom < this._options[ "zoomMin" ] ) { - pixelSize = this._pixelSizeInteractive; - } else if ( zoomDelta > 0 && zoom > this._options[ "zoomMax" ] ) { - pixelSize = this._pixelSizeInteractive; - } - } - - var ratio = pixelSize / this._pixelSizeInteractive, - anchorMapCoord = this._toMap( anchor, this._centerInteractive, this._pixelSizeInteractive ), - centerDelta = [(this._centerInteractive[0] - anchorMapCoord[0]) * ratio, (this._centerInteractive[1] - anchorMapCoord[1]) * ratio], - scaleCenter = [anchorMapCoord[0] + centerDelta[0], anchorMapCoord[1] + centerDelta[1]]; - - return { pixelSize: pixelSize, center: scaleCenter }; - }, - - _mouseWheelFinish: function ( refresh ) { - this._wheelTimeout = null; - - if (this._wheelLevel !== 0) { - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, this._wheelLevel, this._options[ "tilingScheme" ] !== null ); - - this._wheelLevel = 0; - } else if ( refresh ) { - this._refresh(); - } - }, - - _panFinalize: function () { - if (this._panning) { - this._velocity = [0, 0]; - - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - image = this._options[ "axisLayout" ] === "image", - dxMap = -dx * this._pixelSize, - dyMap = ( image ? -1 : 1 ) * dy * this._pixelSize; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._inOp = false; - this._anchor = this._current; - this._mouseDown = this._toolPan = this._panning = false; - } - }, - - _panMove: function () { - if ( ! this._options[ "pannable" ] ) { - return; - } - - var dx = this._current[0] - this._lastDrag[0], - dy = this._current[1] - this._lastDrag[1], - i = 0, - service, - translateObj; - - if (this._toolPan || dx > 3 || dx < -3 || dy > 3 || dy < -3) { - if (!this._toolPan) { - this._toolPan = true; - this._$eventTarget.css("cursor", this._options["cursors"]["pan"]); - } - - if (this._mouseDown) { - this._velocity = [dx, dy]; - } - - if (dx !== 0 || dy !== 0) { - this._panning = true; - this._lastDrag = this._current; - - this._centerInteractive[ 0 ] -= ( dx * this._pixelSizeInteractive ); - this._centerInteractive[ 1 ] += ( ( this._options[ "axisLayout" ] === "image" ? -1 : 1 ) * dy * this._pixelSizeInteractive ); - this._setInteractiveCenterAndSize( this._centerInteractive, this._pixelSizeInteractive ); - this._interactiveTransform( ); - } - } - }, - - _clearInteractiveTimeout: function() { - if ( this._timeoutInteractive ) { - clearTimeout( this._timeoutInteractive ); - this._timeoutInteractive = null; - return true; - } else { - this._centerInteractive[ 0 ] = this._center[ 0 ]; - this._centerInteractive[ 1 ] = this._center[ 1 ]; - this._pixelSizeInteractive = this._pixelSize; - return false; - } - }, - - _interactiveTransform: function( ) { - if ( this._$shapesContainers ) { - this._$shapesContainers.geographics("clear"); - } - - for ( var i = 0; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - $.geo[ "_serviceTypes" ][ service.type ].interactiveTransform( this, service, this._centerInteractive, this._pixelSizeInteractive ); - } - - if (this._drawCoords.length > 0) { - this._drawPixels = this._toPixel( this._drawCoords, this._centerInteractive, this._pixelSizeInteractive ); - this._refreshDrawing(); - } - }, - - _setInteractiveTimeout: function( trigger ) { - var geomap = this; - - function interactiveTimeoutCallback( ) { - if ( geomap._isMultiTouch ) { - geomap._timeoutInteractive = setTimeout( interactiveTimeoutCallback, 128 ); - } else if ( geomap._created && geomap._timeoutInteractive ) { - geomap._setCenterAndSize( geomap._centerInteractive, geomap._pixelSizeInteractive, geomap._triggerInteractive, true ); - geomap._timeoutInteractive = null; - geomap._triggerInteractive = false; - } - } - - this._timeoutInteractive = setTimeout( interactiveTimeoutCallback, 128 ); - this._triggerInteractive |= trigger; - }, - - _refresh: function ( force, _serviceContainer ) { - var service, - geoService, - i = 0; - - for ( ; i < this._currentServices.length; i++ ) { - service = this._currentServices[ i ]; - if ( !_serviceContainer || service.serviceContainer[ 0 ] == _serviceContainer[ 0 ] ) { - $.geo[ "_serviceTypes" ][ service.type ].refresh( this, service, force ); - geoService = service.serviceContainer.data( "geoService" ); - - if ( geoService._createdGraphics ) { - geoService._$shapesContainer.geographics( "clear" ); - if ( geoService._graphicShapes.length > 0 ) { - geoService._refreshShapes( geoService._$shapesContainer, geoService._graphicShapes, geoService._graphicShapes, geoService._graphicShapes ); - } - } - } - } - - if ( this._createdGraphics ) { - this._$shapesContainer.geographics( "clear" ); - if ( this._graphicShapes.length > 0 ) { - this._refreshShapes( this._$shapesContainer, this._graphicShapes, this._graphicShapes, this._graphicShapes ); - } - } - }, - - _setInteractiveCenterAndSize: function ( center, pixelSize ) { - // set the temporary (interactive) center & size - // also, update the public-facing options - // this does not take zoomMin or zoomMax into account - this._centerInteractive[ 0 ] = center[ 0 ]; - this._centerInteractive[ 1 ] = center[ 1 ]; - this._pixelSizeInteractive = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox( center, pixelSize ) ); - this._options["center"] = $.geo.proj.toGeodetic( center ); - } else { - this._options["bbox"] = this._getBbox( center, pixelSize ); - this._options["center"][ 0 ] = center[ 0 ]; - this._options["center"][ 1 ] = center[ 1 ]; - } - - this._options["pixelSize"] = pixelSize; - this._options["zoom"] = this._getZoom( center, pixelSize ); - }, - - _setCenterAndSize: function (center, pixelSize, trigger, refresh) { - if ( ! $.isArray( center ) || center.length != 2 || typeof center[ 0 ] !== "number" || typeof center[ 1 ] !== "number" ) { - return; - } - - // the final call during any extent change - // only called by timeoutInteractive & resize - // clamp to zoom - var zoom = this._getZoom( center, pixelSize ); - - if ( this._options[ "tilingScheme" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( Math.min( Math.max( zoom, this._options[ "zoomMin" ] ), this._options[ "zoomMax" ] ) ); - } else { - if ( zoom < this._options[ "zoomMin" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMin" ] ); - } else if ( zoom > this._options[ "zoomMax" ] ) { - this._pixelSizeInteractive = pixelSize = this._getPixelSize( this._options[ "zoomMax" ] ); - } - } - - this._center[ 0 ] = center[ 0 ]; - this._center[ 1 ] = center[ 1 ]; - this._options["pixelSize"] = this._pixelSize = pixelSize; - - if ( this._userGeodetic ) { - this._options["bbox"] = $.geo.proj.toGeodetic( this._getBbox() ); - this._options["center"] = $.geo.proj.toGeodetic( this._center ); - } else { - this._options["bbox"] = this._getBbox(); - this._options["center"] = $.merge( [ ], center ); - } - - this._options["zoom"] = zoom; - - if (trigger) { - this._trigger("bboxchange", window.event, { bbox: $.merge( [ ], this._options["bbox"] ) }); - } - - if (refresh) { - this._refresh(); - this._refreshDrawing(); - } - }, - - _requestQueued: function ( ) { - if ( this._loadCount === 0 ) { - this._trigger( "loadstart", window.event ); - } - this._loadCount++; - }, - - _requestComplete: function ( ) { - this._loadCount--; - if ( this._loadCount <= 0 ) { - this._loadCount = 0; - this._trigger( "loadend", window.event ); - } - }, - - _toMap: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - xRatio = $.geo.width(bbox, true) / width, - yRatio = $.geo.height(bbox, true) / height, - yOffset, - image = this._options[ "axisLayout" ] === "image", - result = [], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - yOffset = (p[ i ][ j ][ k ][1] * yRatio); - result[ i ][ j ][ k ] = [ - bbox[ 0 ] + ( p[ i ][ j ][ k ][ 0 ] * xRatio ), - image ? bbox[ 1 ] + yOffset : bbox[ 3 ] - yOffset - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _toPixel: function (p, center, pixelSize) { - // ignores $.geo.proj - - center = center || this._center; - pixelSize = pixelSize || this._pixelSize; - - var isMultiPointOrLineString = $.isArray( p[ 0 ] ), - isMultiLineStringOrPolygon = isMultiPointOrLineString && $.isArray( p[ 0 ][ 0 ] ), - isMultiPolygon = isMultiLineStringOrPolygon && $.isArray( p[ 0 ][ 0 ][ 0 ] ), - width = this._contentBounds["width"], - height = this._contentBounds["height"], - halfWidth = width / 2 * pixelSize, - halfHeight = height / 2 * pixelSize, - bbox = [center[0] - halfWidth, center[1] - halfHeight, center[0] + halfWidth, center[1] + halfHeight], - bboxWidth = $.geo.width(bbox, true), - bboxHeight = $.geo.height(bbox, true), - image = this._options[ "axisLayout" ] === "image", - xRatio = width / bboxWidth, - yRatio = height / bboxHeight, - result = [ ], - i, j, k; - - if ( !isMultiPolygon ) { - if ( !isMultiLineStringOrPolygon ) { - if ( !isMultiPointOrLineString ) { - p = [ p ]; - } - p = [ p ]; - } - p = [ p ]; - } - - for ( i = 0; i < p.length; i++ ) { - result[ i ] = [ ]; - for ( j = 0; j < p[ i ].length; j++ ) { - result[ i ][ j ] = [ ]; - for ( k = 0; k < p[ i ][ j ].length; k++ ) { - result[ i ][ j ][ k ] = [ - Math.round( ( p[ i ][ j ][ k ][ 0 ] - bbox[ 0 ] ) * xRatio ), - Math.round( ( image ? p[ i ][ j ][ k ][ 1 ] - bbox[ 1 ] : bbox[ 3 ] - p[ i ][ j ][ k ][ 1 ] ) * yRatio ) - ]; - } - } - } - - return isMultiPolygon ? result : isMultiLineStringOrPolygon ? result[ 0 ] : isMultiPointOrLineString ? result[ 0 ][ 0 ] : result[ 0 ][ 0 ][ 0 ]; - }, - - _document_keydown: function (e) { - var len = this._drawCoords.length; - if (len > 0 && e.which == 27) { - if (len <= 2) { - this._resetDrawing(); - this._inOp = false; - } else { - this._drawCoords[len - 2] = $.merge( [], this._drawCoords[ len - 1 ] ); - this._drawPixels[len - 2] = $.merge( [], this._drawPixels[ len - 1 ] ); - - this._drawCoords.length--; - this._drawPixels.length--; - - this._refreshDrawing(); - } - } - }, - - _eventTarget_dblclick_zoom: function(e) { - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - this._trigger("dblclick", e, { type: "Point", coordinates: this._toMap(this._current, this._centerInteractive, this._pixelSizeInteractive ) }); - - if (!e.isDefaultPrevented()) { - var centerAndSize = this._getZoomCenterAndSize(this._current, 1, true ); - - this._setInteractiveCenterAndSize( centerAndSize.center, centerAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - }, - - _eventTarget_dblclick: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - var offset = $(e.currentTarget).offset(); - - switch (this._options["mode"]) { - case "drawLineString": - case "measureLength": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - this._drawCoords.length--; - this._trigger( "shape", e, { - type: "LineString", - coordinates: this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords - } ); - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - case "drawPolygon": - case "measureArea": - if ( this._drawCoords.length > 1 && ! ( this._drawCoords[0][0] == this._drawCoords[1][0] && - this._drawCoords[0][1] == this._drawCoords[1][1] ) ) { - var endIndex = this._drawCoords.length - 1; - if (endIndex > 2) { - this._drawCoords[endIndex] = $.merge( [], this._drawCoords[0] ); - this._trigger( "shape", e, { - type: "Polygon", - coordinates: [ this._userGeodetic ? $.geo.proj.toGeodetic(this._drawCoords) : this._drawCoords ] - } ); - } - } else { - this._eventTarget_dblclick_zoom(e); - } - this._resetDrawing(); - break; - - default: - this._eventTarget_dblclick_zoom(e); - break; - } - - this._inOp = false; - }, - - _eventTarget_touchstart: function (e) { - var mode = this._options[ "mode" ], - shift = this._options[ "shift" ]; - - if ( mode === "static" ) { - return; - } - - if ( !this._supportTouch && e.which != 1 ) { - return; - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var offset = $(e.currentTarget).offset(), - touches = e.originalEvent.changedTouches; - - if ( this._supportTouch ) { - this._multiTouchAnchor = $.merge( [ ], touches ); - - this._isMultiTouch = this._multiTouchAnchor.length > 1; - - if ( this._isMultiTouch ) { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - touches[1].pageX - offset.left, - touches[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - this._multiTouchCurrentBbox = [ - touches[0].pageX - offset.left, - touches[0].pageY - offset.top, - NaN, - NaN - ]; - - this._current = [ touches[0].pageX - offset.left, touches[0].pageY - offset.top ]; - } - } else { - this._current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - var downDate = $.now(); - if (downDate - this._downDate < 750) { - if (this._isTap) { - var dx = this._current[0] - this._anchor[0], - dy = this._current[1] - this._anchor[1], - distance = Math.sqrt((dx * dx) + (dy * dy)); - if (distance > 8) { - this._isTap = false; - } else { - this._current = $.merge( [ ], this._anchor ); - } - } - - if (this._isDbltap) { - this._isDbltap = false; - } else { - this._isDbltap = this._isTap; - } - } else { - this._isDbltap = false; - } - this._isTap = true; - this._downDate = downDate; - } - - this._mouseDown = true; - this._anchor = $.merge( [ ], this._current ); - - if (!this._inOp && e.shiftKey && shift !== "off") { - this._shiftDown = true; - this._$eventTarget.css( "cursor", this._options[ "cursors" ][ shift === "default" ? "zoom" : shift ] ); - } else if ( !this._isMultiTouch && ( this._options[ "pannable" ] || mode === "dragBox" || mode === "dragCircle" ) ) { - this._inOp = true; - - if ( mode !== "zoom" && mode !== "dragBox" && mode !== "dragCircle" ) { - this._lastDrag = this._current; - - if (e.currentTarget.setCapture) { - e.currentTarget.setCapture(); - } - } - } - - e.preventDefault(); - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - return false; - }, - - _dragTarget_touchmove: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - var doInteractiveTimeout = false; - if ( this._mouseDown ) { - doInteractiveTimeout = this._clearInteractiveTimeout( ); - } - - var offset = this._$eventTarget.offset(), - drawCoordsLen = this._drawCoords.length, - touches = e.originalEvent.changedTouches, - current, - service, - i = 0; - - if ( this._supportTouch ) { - if ( !this._isMultiTouch && this._mouseDown && this._multiTouchAnchor.length > 0 && touches[ 0 ].identifier !== this._multiTouchAnchor[ 0 ].identifier ) { - // switch to multitouch - this._mouseDown = false; - this._isMultiTouch = true; - this._wheelLevel = 0; - - this._multiTouchAnchor.push( touches[ 0 ] ); - - - - - this._multiTouchCurrentBbox = [ - this._multiTouchCurrentBbox[ 0 ], - this._multiTouchCurrentBbox[ 1 ], - this._multiTouchAnchor[1].pageX - offset.left, - this._multiTouchAnchor[1].pageY - offset.top - ]; - - this._multiTouchAnchorBbox = $.merge( [ ], this._multiTouchCurrentBbox ); - - this._mouseDown = true; - this._anchor = this._current = $.geo.center( this._multiTouchCurrentBbox, true ); - - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - if ( this._isMultiTouch ) { - - for ( ; i < touches.length; i++ ) { - if ( touches[ i ].identifier === this._multiTouchAnchor[ 0 ].identifier ) { - this._multiTouchCurrentBbox[ 0 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 1 ] = touches[ i ].pageY - offset.top; - } else if ( touches[ i ].identifier === this._multiTouchAnchor[ 1 ].identifier ) { - this._multiTouchCurrentBbox[ 2 ] = touches[ i ].pageX - offset.left; - this._multiTouchCurrentBbox[ 3 ] = touches[ i ].pageY - offset.top; - } - } - - var anchorDistance = $.geo._distancePointPoint( [ this._multiTouchAnchorBbox[ 0 ], this._multiTouchAnchorBbox[ 1 ] ], [ this._multiTouchAnchorBbox[ 2 ], this._multiTouchAnchorBbox[ 3 ] ] ), - currentDistance = $.geo._distancePointPoint( [ this._multiTouchCurrentBbox[ 0 ], this._multiTouchCurrentBbox[ 1 ] ], [ this._multiTouchCurrentBbox[ 2 ], this._multiTouchCurrentBbox[ 3 ] ] ); - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - - var wheelLevel = ( ( currentDistance - anchorDistance ) / anchorDistance ); - - if ( wheelLevel > 0 ) { - wheelLevel *= 5; - } else { - wheelLevel *= 10; - } - - var delta = wheelLevel - this._wheelLevel; - - this._wheelLevel = wheelLevel; - - var pinchCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, false ); - - this._setInteractiveCenterAndSize( pinchCenterAndSize.center, pinchCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - doInteractiveTimeout = true; - - current = $.geo.center( this._multiTouchCurrentBbox, true ); - } else { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - } - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (current[0] === this._lastMove[0] && current[1] === this._lastMove[1]) { - if ( this._inOp ) { - e.preventDefault(); - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - } - - if ( _ieVersion == 7 ) { - this._isDbltap = this._isTap = false; - } - - if (this._mouseDown) { - this._current = current; - this._moveDate = $.now(); - } - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return false; - } - - var shift = this._options[ "shift" ], - mode = this._shiftDown ? ( shift === "default" ? "zoom" : shift ) : this._options["mode"], - dx, dy, circleSize; - - switch (mode) { - case "zoom": - case "dragBox": - if ( this._mouseDown ) { - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawBbox", [ - this._anchor[ 0 ], - this._anchor[ 1 ], - current[ 0 ], - current[ 1 ] - ] ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "dragCircle": - if ( this._mouseDown ) { - dx = current[ 0 ] - this._anchor[ 0 ]; - dy = current[ 1 ] - this._anchor[ 1 ]; - circleSize = Math.sqrt( ( dx * dx) + ( dy * dy ) ) * 2; - //circleSize = Math.max( Math.abs( current[ 0 ] - this._anchor[ 0 ] ), Math.abs( current[ 1 ] - this._anchor[ 1 ] ) ) * 2; - - // not part of _refreshDrawing - this._$drawContainer.geographics( "clear" ); - this._$drawContainer.geographics( "drawArc", this._anchor, 0, 360, { - width: circleSize, - height: circleSize - } ); - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - if (drawCoordsLen > 0) { - this._drawCoords[drawCoordsLen - 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[drawCoordsLen - 1] = current; - - this._refreshDrawing(); - } - - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - - default: - if (this._mouseDown || this._toolPan) { - this._panMove(); - doInteractiveTimeout = true; - } else { - this._trigger("move", e, { type: "Point", coordinates: this.toMap(current) }); - } - break; - } - - this._lastMove = current; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _dragTarget_touchstop: function (e) { - if ( this._options[ "mode" ] === "static" ) { - return; - } - - if ( !this._mouseDown ) { - if ( _ieVersion == 7 ) { - // ie7 doesn't appear to trigger dblclick on this._$eventTarget, - // we fake regular click here to cause soft dblclick - this._eventTarget_touchstart(e); - } else { - // Chrome & Firefox trigger a rogue mouseup event when doing a dblclick maximize in Windows(/Linux?) - // ignore it - return false; - } - } - - var doInteractiveTimeout = this._clearInteractiveTimeout( ); - - var mouseWasDown = this._mouseDown, - wasToolPan = this._toolPan, - offset = this._$eventTarget.offset(), - shift = this._options[ "shift" ], - mode = this._shiftDown ? ( shift === "default" ? "zoom" : shift ) : this._options["mode"], - current, i, clickDate, - dx, dy, - coordBuffer, - triggerShape; - - - if (this._supportTouch) { - current = [e.originalEvent.changedTouches[0].pageX - offset.left, e.originalEvent.changedTouches[0].pageY - offset.top]; - this._multiTouchAnchor = []; - this._inOp = false; - } else { - current = [e.pageX - offset.left, e.pageY - offset.top]; - } - - if (this._softDblClick) { - if (this._isTap) { - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - if (Math.sqrt((dx * dx) + (dy * dy)) <= 8) { - current = $.merge( [ ], this._anchor ); - } - } - } - - dx = current[0] - this._anchor[0]; - dy = current[1] - this._anchor[1]; - - this._$eventTarget.css("cursor", this._options["cursors"][this._options["mode"]]); - - this._shiftDown = this._mouseDown = this._toolPan = false; - - if ( this._isMultiTouch ) { - e.preventDefault( ); - this._isMultiTouch = false; - - this._wheelLevel = 0; - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - return; - } - - if (document.releaseCapture) { - document.releaseCapture(); - } - - if (mouseWasDown) { - clickDate = $.now(); - this._current = current; - - switch ( mode ) { - case "zoom": - case "dragBox": - if ( dx !== 0 || dy !== 0 ) { - var minSize = this._pixelSize * 6, - bboxCoords = this._toMap( [ [ - Math.min( this._anchor[ 0 ], current[ 0 ] ), - Math.max( this._anchor[ 1 ], current[ 1 ] ) - ], [ - Math.max( this._anchor[ 0 ], current[ 0 ] ), - Math.min( this._anchor[ 1 ], current[ 1 ] ) - ] - ] ), - bbox = [ - bboxCoords[0][0], - bboxCoords[0][1], - bboxCoords[1][0], - bboxCoords[1][1] - ]; - - if ( mode === "zoom" ) { - if ( ( bbox[2] - bbox[0] ) < minSize && ( bbox[3] - bbox[1] ) < minSize ) { - bbox = $.geo.scaleBy( this._getBbox( $.geo.center( bbox, true ) ), 0.5, true ); - } - - this._setBbox(bbox, true, true); - doInteractiveTimeout = true; - } else { - triggerShape = $.geo.polygonize( bbox, true ); - triggerShape.bbox = bbox; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - this._trigger( "shape", e, triggerShape ); - } - } else { - if ( mode === "dragBox" ) { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - } - - this._resetDrawing(); - break; - - case "dragCircle": - if ( dx !== 0 || dy !== 0 ) { - var image = this._options[ "axisLayout" ] === "image", - d = Math.sqrt( ( dx * dx) + ( dy * dy ) ), - n = 180, - a; - - this._drawPixels.length = n + 1; - - for ( i = 0; i < n; i++ ) { - a = ( i * 360 / n ) * ( Math.PI / 180 ); - this._drawPixels[ i ] = [ - this._anchor[ 0 ] + Math.cos( a ) * d, - this._anchor[ 1 ] + Math.sin( a ) * d - ]; - } - - this._drawPixels[ n ] = [ - this._drawPixels[ 0 ][ 0 ], - this._drawPixels[ 0 ][ 1 ] - ]; - - // using coordBuffer for bbox coords - coordBuffer = this._toMap( [ - [ this._anchor[ 0 ] - d, this._anchor[ 1 ] + ( image ? -d : d ) ], - [ this._anchor[ 0 ] + d, this._anchor[ 1 ] + ( image ? d : -d ) ] - ] ); - - triggerShape = { - type: "Polygon", - coordinates: [ this._toMap( this._drawPixels ) ], - bbox: [ coordBuffer[ 0 ][ 0 ], coordBuffer[ 0 ][ 1 ], coordBuffer[ 1 ][ 0 ], coordBuffer[ 1 ][ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - - this._resetDrawing(); - } else { - coordBuffer = this._toMap( current ); - - triggerShape = { - type: "Point", - coordinates: [ coordBuffer[ 0 ], coordBuffer[ 1 ] ], - bbox: [ coordBuffer[ 0 ], coordBuffer[ 1 ], coordBuffer[ 0 ], coordBuffer[ 1 ] ] - }; - - if ( this._userGeodetic ) { - triggerShape.coordinates = $.geo.proj.toGeodetic( triggerShape.coordinates ); - triggerShape.bbox = $.geo.proj.toGeodetic( triggerShape.bbox ); - } - - this._trigger( "shape", e, triggerShape ); - } - break; - - case "drawPoint": - if (this._drawTimeout) { - window.clearTimeout(this._drawTimeout); - this._drawTimeout = null; - } - - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - var geomap = this; - this._drawTimeout = setTimeout(function () { - if (geomap._drawTimeout) { - geomap._trigger("shape", e, { type: "Point", coordinates: geomap.toMap(current) }); - geomap._inOp = false; - geomap._drawTimeout = null; - } - }, 250); - } - } - break; - - case "drawLineString": - case "drawPolygon": - case "measureLength": - case "measureArea": - if (wasToolPan) { - this._panFinalize(); - } else { - i = (this._drawCoords.length === 0 ? 0 : this._drawCoords.length - 1); - - this._drawCoords[i] = this._toMap(current); - this._drawPixels[i] = current; - - if (i < 2 || !(this._drawCoords[i][0] == this._drawCoords[i-1][0] && - this._drawCoords[i][1] == this._drawCoords[i-1][1])) { - this._drawCoords[i + 1] = this._toMap( current, this._centerInteractive, this._pixelSizeInteractive ); - this._drawPixels[i + 1] = current; - } - - this._refreshDrawing(); - } - break; - - default: - if (wasToolPan) { - this._panFinalize(); - } else { - if (clickDate - this._clickDate > 100) { - this._trigger("click", e, { type: "Point", coordinates: this.toMap(current) }); - this._inOp = false; - } - } - break; - } - - this._clickDate = clickDate; - - if (this._softDblClick && this._isDbltap) { - this._isDbltap = this._isTap = false; - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - this._$eventTarget.trigger("dblclick", e); - return false; - } - } - - if ( doInteractiveTimeout ) { - this._setInteractiveTimeout( true ); - } - - if ( this._inOp ) { - e.preventDefault(); - return false; - } - }, - - _eventTarget_mousewheel: function (e, delta) { - if ( this._options[ "mode" ] === "static" || this._options[ "scroll" ] === "off" ) { - return; - } - - e.preventDefault(); - - if ( this._mouseDown ) { - return false; - } - - if (delta !== 0) { - this._clearInteractiveTimeout( ); - - if ( delta > 0 ) { - delta = Math.ceil( delta ); - } else { - delta = Math.floor( delta ); - } - - var offset = $(e.currentTarget).offset(); - this._anchor = [e.pageX - offset.left, e.pageY - offset.top]; - - var wheelCenterAndSize = this._getZoomCenterAndSize( this._anchor, delta, this._options[ "tilingScheme" ] !== null ), - service, - i = 0; - - this._setInteractiveCenterAndSize( wheelCenterAndSize.center, wheelCenterAndSize.pixelSize ); - this._interactiveTransform( ); - - this._setInteractiveTimeout( true ); - } - - return false; - } - } - ); -}(jQuery)); - - -(function ($, undefined) { - $.geo._serviceTypes.tiled = (function () { - return { - create: function (map, serviceContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0, - reloadTiles: false - }; - - var scHtml = '
                                      '; - - serviceContainer.append(scHtml); - - serviceState.serviceContainer = serviceContainer.children( ":last" ); - - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - //console.log( "tiled.interactiveTransform( " + center.join( ", " ) + ", " + pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ), - tilingScheme = map.options[ "tilingScheme" ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( i ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data("pixelSize"), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapCoord = $scaleContainer.data("scaleOrigin"), - newPixelPoint = map._toPixel(oldMapCoord, center, pixelSize); - - $scaleContainer.css( { - left: Math.round(newPixelPoint[0]) + "px", - top: Math.round(newPixelPoint[1]) + "px", - width: tilingScheme.tileWidth * scaleRatio, - height: tilingScheme.tileHeight * scaleRatio - } ); - - /* - if ( $("body")[0].filters !== undefined ) { - $scaleContainer.children().each( function ( i ) { - $( this ).css( "filter", "progid:DXImageTransform.Microsoft.Matrix(FilterType=bilinear,M11=" + scaleRatio + ",M22=" + scaleRatio + ",sizingmethod='auto expand')" ); - } ); - } - */ - } - }); - } - }, - - refresh: function (map, service, force) { - //console.log( "tiled.refresh( " + map._center.join( ", " ) + ", " + map._pixelSize + ")" ); - var serviceState = $.data( service, "geoServiceState" ); - - this._cancelUnloaded(map, service); - - if ( serviceState && force ) { - // if hidden atm, we want to make sure we reload this service after it becomes visible - serviceState.reloadTiles = true; - } - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - $serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - image = map.options[ "axisLayout" ] === "image", - ySign = image ? +1 : -1, - - tilingScheme = map.options["tilingScheme"], - tileWidth = tilingScheme.tileWidth, - tileHeight = tilingScheme.tileHeight, - - tileX = Math.floor((bbox[0] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY = Math.max( Math.floor( ( image ? bbox[1] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 3 ] ) / (pixelSize * tileHeight) ), 0 ), - tileX2 = Math.ceil((bbox[2] - tilingScheme.origin[0]) / (pixelSize * tileWidth)), - tileY2 = Math.ceil( ( image ? bbox[3] - tilingScheme.origin[1] : tilingScheme.origin[1] - bbox[ 1 ] ) / (pixelSize * tileHeight) ), - - bboxMax = map._getBboxMax(), - pixelSizeAtZero = map._getPixelSize(0), - ratio = pixelSizeAtZero / pixelSize, - fullXAtScale = Math.floor((bboxMax[0] - tilingScheme.origin[0]) / (pixelSizeAtZero * tileWidth)) * ratio, - fullYAtScale = Math.floor((tilingScheme.origin[1] + ySign * bboxMax[3]) / (pixelSizeAtZero * tileHeight)) * ratio, - - fullXMinX = tilingScheme.origin[0] + (fullXAtScale * tileWidth) * pixelSize, - fullYMinOrMaxY = tilingScheme.origin[1] + ySign * (fullYAtScale * tileHeight) * pixelSize, - - serviceLeft = Math.round((fullXMinX - bbox[0]) / pixelSize), - serviceTop = Math.round( ( image ? fullYMinOrMaxY - bbox[1] : bbox[3] - fullYMinOrMaxY ) / pixelSize), - - scaleContainers = $serviceContainer.children().show(), - scaleContainer = scaleContainers.filter("[data-pixel-size='" + pixelSize + "']").appendTo($serviceContainer), - - opacity = service.style.opacity, - - x, y, - - loadImageDeferredDone = function( url ) { - // when a Deferred call is done, add the image to the map - // a reference to the correct img element is on the Deferred object itself - serviceObj._loadImage( $.data( this, "img" ), url, pixelSize, map, serviceState, opacity ); - }, - - loadImageDeferredFail = function( ) { - $.data( this, "img" ).remove( ); - serviceState.loadCount--; - map._requestComplete(); - }; - - if (serviceState.reloadTiles) { - scaleContainers.find("img").attr("data-dirty", "true"); - } - - if (!scaleContainer.size()) { - $serviceContainer.append("
                                      "); - scaleContainer = $serviceContainer.children(":last").data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - } else { - scaleContainer.css({ - left: (serviceLeft % tileWidth) + "px", - top: (serviceTop % tileHeight) + "px" - }).data("scaleOrigin", map._toMap( [ (serviceLeft % tileWidth), (serviceTop % tileHeight) ] ) ); - - scaleContainer.children().each(function (i) { - var - $img = $(this), - tile = $img.attr("data-tile").split(","); - - $img.css({ - left: Math.round(((parseInt(tile[0], 10) - fullXAtScale) * 100) + (serviceLeft - (serviceLeft % tileWidth)) / tileWidth * 100) + "%", - top: Math.round(((parseInt(tile[1], 10) - fullYAtScale) * 100) + (serviceTop - (serviceTop % tileHeight)) / tileHeight * 100) + "%" - }); - - if (opacity < 1) { - $img.fadeTo(0, opacity); - } - }); - } - - for (x = tileX; x < tileX2; x++) { - for (y = tileY; y < tileY2; y++) { - var tileStr = "" + x + "," + y, - $img = scaleContainer.children("[data-tile='" + tileStr + "']").removeAttr("data-dirty"); - - if ($img.size() === 0 || serviceState.reloadTiles) { - var bottomLeft = [ - tilingScheme.origin[0] + (x * tileWidth) * pixelSize, - tilingScheme.origin[1] + ySign * (y * tileHeight) * pixelSize - ], - - topRight = [ - tilingScheme.origin[0] + ((x + 1) * tileWidth - 1) * pixelSize, - tilingScheme.origin[1] + ySign * ((y + 1) * tileHeight - 1) * pixelSize - ], - - tileBbox = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]], - - urlProp = ( service.hasOwnProperty( "src" ) ? "src" : "getUrl" ), - urlArgs = { - bbox: tileBbox, - width: tileWidth, - height: tileHeight, - zoom: map._getZoom(), - tile: { - row: y, - column: x - }, - index: Math.abs(y + x) - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl; - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - $.templates( "geoSrc", service[ urlProp ] ); - imageUrl = $.render[ "geoSrc" ]( urlArgs ); - } - - serviceState.loadCount++; - map._requestQueued(); - - if (serviceState.reloadTiles && $img.size() > 0) { - $img.attr("src", imageUrl); - } else { - var imgMarkup = ""; - - scaleContainer.append(imgMarkup); - $img = scaleContainer.children(":last"); - } - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else if ( imageUrl ) { - // assume Deferred - $.data( imageUrl, "img", $img ); - imageUrl.done( loadImageDeferredDone ).fail( loadImageDeferredFail ); - } else { - $img.remove( ); - } - } - } - } - - scaleContainers.find("[data-dirty]").remove(); - serviceState.reloadTiles = false; - } - }, - - resize: function (map, service) { - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.css( "display", service.style.visibility === "visible" ? "block" : "none" ); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data( service, "geoServiceState" ); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery)); - -(function ($, undefined) { - $.geo._serviceTypes.shingled = (function () { - return { - create: function (map, serviceContainer, service, index) { - var serviceState = $.data(service, "geoServiceState"); - - if ( !serviceState ) { - serviceState = { - loadCount: 0 - }; - - var scHtml = '
                                      '; - - serviceContainer.append(scHtml); - - serviceState.serviceContainer = serviceContainer.children(":last"); - $.data(service, "geoServiceState", serviceState); - } - - return serviceState.serviceContainer; - }, - - destroy: function (map, serviceContainer, service) { - var serviceState = $.data(service, "geoServiceState"); - - serviceState.serviceContainer.remove(); - - $.removeData(service, "geoServiceState"); - }, - - interactiveTransform: function ( map, service, center, pixelSize ) { - var serviceState = $.data( service, "geoServiceState" ), - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds[ "width" ], - mapHeight = contentBounds[ "height" ], - - halfWidth = mapWidth / 2, - halfHeight = mapHeight / 2, - - bbox = [ center[ 0 ] - halfWidth, center[ 1 ] - halfHeight, center[ 0 ] + halfWidth, center[ 1 ] + halfHeight ]; - - if ( serviceState ) { - this._cancelUnloaded( map, service ); - - serviceState.serviceContainer.children( ).each( function ( i ) { - var $scaleContainer = $(this), - scalePixelSize = $scaleContainer.data( "pixelSize" ), - scaleRatio = scalePixelSize / pixelSize; - - if ( scalePixelSize > 0 ) { - scaleRatio = Math.round(scaleRatio * 1000) / 1000; - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin, center, pixelSize ); - - $scaleContainer.css( { - left: Math.round( newPixelPoint[ 0 ] ), - top: Math.round( newPixelPoint[ 1 ] ), - width: mapWidth * scaleRatio, - height: mapHeight * scaleRatio - } ); - - - // #newpanzoom - /* - .children("img").each(function (i) { - var $img = $(this), - imgCenter = $img.data("center"), - x = (Math.round((imgCenter[0] - center[0]) / scalePixelSize) - halfWidth) * scaleRatio, - y = (Math.round((center[1] - imgCenter[1]) / scalePixelSize) - halfHeight) * scaleRatio; - - $img.css({ left: x + "px", top: y + "px" }); - }); - */ - } - }); - } - }, - - refresh: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - this._cancelUnloaded(map, service); - - if ( serviceState && service && service.style.visibility === "visible" && !( serviceState.serviceContainer.is( ":hidden" ) ) ) { - - var bbox = map._getBbox(), - pixelSize = map._pixelSize, - - serviceObj = this, - serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainer = serviceContainer.children('[data-pixel-size="' + pixelSize + '"]'), - - opacity = service.style.opacity, - - $img; - - if (opacity < 1) { - serviceContainer.find("img").attr("data-keep-alive", "0"); - } - - if ( !scaleContainer.size() ) { - serviceContainer.append('
                                      '); - scaleContainer = serviceContainer.children(":last"); - } - - var urlProp = ( service.hasOwnProperty("src") ? "src" : "getUrl" ), - urlArgs = { - bbox: bbox, - width: mapWidth, - height: mapHeight, - zoom: map._getZoom(), - tile: null, - index: 0 - }, - isFunc = $.isFunction( service[ urlProp ] ), - imageUrl, - imagePos = scaleContainer.position( ); - - imagePos.left = - ( imagePos.left ); - imagePos.top = - ( imagePos.top ); - - if ( isFunc ) { - imageUrl = service[ urlProp ]( urlArgs ); - } else { - $.templates( "geoSrc", service[ urlProp ] ); - imageUrl = $.render[ "geoSrc" ]( urlArgs ); - } - - serviceState.loadCount++; - map._requestQueued(); - - scaleContainer.append(''); - $img = scaleContainer.children(":last").data("center", map._center); - - if ( typeof imageUrl === "string" ) { - serviceObj._loadImage( $img, imageUrl, pixelSize, map, serviceState, opacity ); - } else { - // assume Deferred - imageUrl.done( function( url ) { - serviceObj._loadImage( $img, url, pixelSize, map, serviceState, opacity ); - } ).fail( function( ) { - $img.remove( ); - serviceState.loadCount--; - map._requestComplete(); - } ); - } - - } - }, - - resize: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if ( serviceState && service && service.style.visibility === "visible" ) { - this._cancelUnloaded(map, service); - - var serviceContainer = serviceState.serviceContainer, - - contentBounds = map._getContentBounds(), - mapWidth = contentBounds["width"], - mapHeight = contentBounds["height"], - - scaleContainers = serviceContainer.children(); - - scaleContainers.attr("data-pixel-size", "0"); - - scaleContainers.each( function ( i ) { - var $scaleContainer = $(this), - position = $scaleContainer.position( ); - - var oldMapOrigin = $scaleContainer.data( "origin" ), - newPixelPoint = map._toPixel( oldMapOrigin ); - - $scaleContainer.css( { - left: position.left + ( mapWidth - $scaleContainer.width( ) ) / 2, - top: position.top + ( mapHeight - $scaleContainer.height( ) ) / 2 - } ); - - } ); - - - /* - scaleContainer.css({ - left: halfWidth + 'px', - top: halfHeight + 'px' - }); - */ - } - }, - - opacity: function ( map, service ) { - var serviceState = $.data( service, "geoServiceState" ); - serviceState.serviceContainer.find( "img" ).stop( true ).fadeTo( "fast", service.style.opacity ); - }, - - toggle: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - serviceState.serviceContainer.css("display", service.style.visibility === "visible" ? "block" : "none"); - }, - - _cancelUnloaded: function (map, service) { - var serviceState = $.data(service, "geoServiceState"); - - if (serviceState && serviceState.loadCount > 0) { - serviceState.serviceContainer.find("img:hidden").remove(); - while (serviceState.loadCount > 0) { - serviceState.loadCount--; - map._requestComplete(); - } - } - }, - - _loadImage: function ( $img, url, pixelSize, map, serviceState, opacity ) { - var serviceContainer = serviceState.serviceContainer; - - $img.load(function (e) { - if (opacity < 1) { - $(e.target).fadeTo(0, opacity); - } else { - $(e.target).show(); - } - - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - // #newpanzoom - serviceContainer.children(':not([data-pixel-size="' + pixelSize + '"])').remove(); - - serviceContainer.find( "img[data-keep-alive]" ).remove( ); - - serviceState.loadCount = 0; - } - }).error(function (e) { - $(e.target).remove(); - serviceState.loadCount--; - map._requestComplete(); - - if (serviceState.loadCount <= 0) { - serviceContainer.children(":not([data-pixel-size='" + pixelSize + "'])").remove(); - serviceState.loadCount = 0; - } - }).attr("src", url); - } - }; - }()); -}(jQuery)); diff --git a/dist/jquery.geo-1.0b1.min.js b/dist/jquery.geo-1.0b1.min.js deleted file mode 100644 index c3c1f38..0000000 --- a/dist/jquery.geo-1.0b1.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery Geo - v1.0b1.0.1 - 2012-08-01 - * http://jquerygeo.com - * Copyright (c) 2012 Ryan Westphal/Applied Geographics, Inc.; Licensed MIT, GPL */ -document.createElement("canvas").getContext||function(){function j(){return this.context_||(this.context_=new I(this))}function l(a,b,c){var d=k.call(arguments,2);return function(){return a.apply(b,d.concat(k.call(arguments)))}}function m(a){return String(a).replace(/&/g,"&").replace(/"/g,""")}function n(a,b,c){a.namespaces[b]||a.namespaces.add(b,c,"#default#VML")}function o(a){n(a,"g_vml_","urn:schemas-microsoft-com:vml"),n(a,"g_o_","urn:schemas-microsoft-com:office:office");if(!a.styleSheets.ex_canvas_){var b=a.createStyleSheet();b.owningElement.id="ex_canvas_",b.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function q(a){var b=a.srcElement;switch(a.propertyName){case"width":b.getContext().clearRect(),b.style.width=b.attributes.width.nodeValue+"px",b.firstChild.style.width=b.clientWidth+"px";break;case"height":b.getContext().clearRect(),b.style.height=b.attributes.height.nodeValue+"px",b.firstChild.style.height=b.clientHeight+"px"}}function r(a){var b=a.srcElement;b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px",b.firstChild.style.height=b.clientHeight+"px")}function v(){return[[1,0,0],[0,1,0],[0,0,1]]}function w(a,b){var c=v();for(var d=0;d<3;d++)for(var e=0;e<3;e++){var f=0;for(var g=0;g<3;g++)f+=a[d][g]*b[g][e];c[d][e]=f}return c}function x(a,b){b.fillStyle=a.fillStyle,b.lineCap=a.lineCap,b.lineJoin=a.lineJoin,b.lineWidth=a.lineWidth,b.miterLimit=a.miterLimit,b.shadowBlur=a.shadowBlur,b.shadowColor=a.shadowColor,b.shadowOffsetX=a.shadowOffsetX,b.shadowOffsetY=a.shadowOffsetY,b.strokeStyle=a.strokeStyle,b.globalAlpha=a.globalAlpha,b.font=a.font,b.textAlign=a.textAlign,b.textBaseline=a.textBaseline,b.arcScaleX_=a.arcScaleX_,b.arcScaleY_=a.arcScaleY_,b.lineScale_=a.lineScale_}function y(a){var b=a.indexOf("(",3),c=a.indexOf(")",b+1),d=a.substring(b+1,c).split(",");if(d.length!=4||a.charAt(3)!="a")d[3]=1;return d}function z(a){return parseFloat(a)/100}function A(a,b,c){return Math.min(c,Math.max(b,a))}function B(a){var b,c,d,e,f,g;e=parseFloat(a[0])/360%360,e<0&&e++,f=A(z(a[1]),0,1),g=A(z(a[2]),0,1);if(f==0)b=c=d=g;else{var h=g<.5?g*(1+f):g+f-g*f,i=2*g-h;b=C(i,h,e+1/3),c=C(i,h,e),d=C(i,h,e-1/3)}return"#"+s[Math.floor(b*255)]+s[Math.floor(c*255)]+s[Math.floor(d*255)]}function C(a,b,c){return c<0&&c++,c>1&&c--,6*c<1?a+(b-a)*6*c:2*c<1?b:3*c<2?a+(b-a)*(2/3-c)*6:a}function E(a){if(a in D)return D[a];var b,c=1;a=String(a);if(a.charAt(0)=="#")b=a;else if(/^rgb/.test(a)){var d=y(a),b="#",e;for(var f=0;f<3;f++)d[f].indexOf("%")!=-1?e=Math.floor(z(d[f])*255):e=+d[f],b+=s[A(e,0,255)];c=+d[3]}else if(/^hsl/.test(a)){var d=y(a);b=B(d),c=d[3]}else b=a;return D[a]={color:b,alpha:c}}function H(a){return G[a]||"square"}function I(a){this.m_=v(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.strokeStyle="#000",this.fillStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=g*1,this.globalAlpha=1,this.canvas=a;var b="width:"+a.clientWidth+"px;height:"+a.clientHeight+"px;overflow:hidden;position:absolute",c=a.ownerDocument.createElement("div");c.style.cssText=b,a.appendChild(c);var d=c.cloneNode(!1);d.style.backgroundColor="red",d.style.filter="alpha(opacity=0)",a.appendChild(d),this.element_=c,this.arcScaleX_=1,this.arcScaleY_=1,this.lineScale_=1}function K(a,b,c,d){a.currentPath_.push({type:"bezierCurveTo",cp1x:b.x,cp1y:b.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y}),a.currentX_=d.x,a.currentY_=d.y}function L(a,b){var c=E(a.strokeStyle),d=c.color,e=c.alpha*a.globalAlpha,f=a.lineScale_*a.lineWidth;f<1&&(e*=f),b.push("')}function M(a,b,c,d){var e=a.fillStyle,f=a.arcScaleX_,g=a.arcScaleY_,h=d.x-c.x,i=d.y-c.y,j=E(a.fillStyle),k=j.color,l=j.alpha*a.globalAlpha;b.push('')}function N(a,b,c){var d=a.m_;return{x:g*(b*d[0][0]+c*d[1][0]+d[2][0])-h,y:g*(b*d[0][1]+c*d[1][1]+d[2][1])-h}}function O(a){return isFinite(a[0][0])&&isFinite(a[0][1])&&isFinite(a[1][0])&&isFinite(a[1][1])&&isFinite(a[2][0])&&isFinite(a[2][1])}function P(a,b,c){if(!O(b))return;a.m_=b;if(c){var d=b[0][0]*b[1][1]-b[0][1]*b[1][0];a.lineScale_=f(e(d))}}function Q(a){throw new R(a)}function R(a){this.code=this[a],this.message=a+": DOM Exception "+this.code}var a=Math,b=a.round,c=a.sin,d=a.cos,e=a.abs,f=a.sqrt,g=10,h=g/2,i=+navigator.userAgent.match(/MSIE ([\d.]+)?/)[1],k=Array.prototype.slice;o(document);var p={init:function(a){var b=a||document;b.createElement("canvas"),b.attachEvent("onreadystatechange",l(this.init_,this,b))},init_:function(a){var b=a.getElementsByTagName("canvas");for(var c=0;cj.x)j.x=l.x;if(i.y==null||l.yj.y)j.y=l.y}}c.push(' ">'),a?M(this,c,i,j):L(this,c),c.push(""),this.element_.insertAdjacentHTML("beforeEnd",c.join(""))},J.fill=function(){this.stroke(!0)},J.closePath=function(){this.currentPath_.push({type:"close"})},J.save=function(){var a={};x(this,a),this.aStack_.push(a),this.mStack_.push(this.m_),this.m_=w(v(),this.m_)},J.restore=function(){this.aStack_.length&&(x(this.aStack_.pop(),this),this.m_=this.mStack_.pop())},J.translate=function(a,b){var c=[[1,0,0],[0,1,0],[a,b,1]];P(this,w(c,this.m_),!1)},J.scale=function(a,b){this.arcScaleX_*=a,this.arcScaleY_*=b;var c=[[a,0,0],[0,b,0],[0,0,1]];P(this,w(c,this.m_),!0)};var S=R.prototype=new Error;S.INDEX_SIZE_ERR=1,S.DOMSTRING_SIZE_ERR=2,S.HIERARCHY_REQUEST_ERR=3,S.WRONG_DOCUMENT_ERR=4,S.INVALID_CHARACTER_ERR=5,S.NO_DATA_ALLOWED_ERR=6,S.NO_MODIFICATION_ALLOWED_ERR=7,S.NOT_FOUND_ERR=8,S.NOT_SUPPORTED_ERR=9,S.INUSE_ATTRIBUTE_ERR=10,S.INVALID_STATE_ERR=11,S.SYNTAX_ERR=12,S.INVALID_MODIFICATION_ERR=13,S.NAMESPACE_ERR=14,S.INVALID_ACCESS_ERR=15,S.VALIDATION_ERR=16,S.TYPE_MISMATCH_ERR=17,G_vmlCanvasManager=p,CanvasRenderingContext2D=I,DOMException=R}(),this.jsviews||this.jQuery&&jQuery.views||function(a,b){function A(a,b){var c="\\"+a.charAt(0),d="\\"+a.charAt(1),g="\\"+b.charAt(0),h="\\"+b.charAt(1);return z.rTag=e=d+"(?:(?:(\\w+(?=[\\/\\s"+g+"]))|(?:(\\w+)?(:)|(>)|(\\*)))"+"\\s*((?:[^"+g+"]|"+g+"(?!"+h+"))*?)"+"(\\/)?|(?:\\/(\\w+)))"+g,e=new RegExp(c+e+h,"g"),f=new RegExp("<.*>|"+a+".*"+b),this}function B(a){var c=this,d=c.tmpl.helpers||{};return a=(c.ctx[a]!==b?c.ctx:d[a]!==b?d:I[a]!==b?I:{})[a],typeof a!="function"?a:function(){return a.apply(c,arguments)}}function C(a,b,c){var d=b.tmpl.converters;return a=d&&d[a]||J[a],a?a.call(b,c):c}function D(a,c,d,e,f){f.props=f.props||{};var h,i=f.props.tmpl,k=c.tmpl.tags,l=c.tmpl.templates,m=arguments,n=k&&k[a]||H[a];return n?(e=e&&c.tmpl.tmpls[e-1],i=i||e||b,f.tmpl=""+i===i?l&&l[i]||G[i]||G(i):i,f.isTag=j,f.converter=d,f.view=c,f.renderContent=K,c.ctx&&g(f.ctx,c.ctx),h=n.apply(f,m.length>5?x.call(m,5):[]),h||(h==b?"":h.toString())):""}function E(a,c,e,f,g,h){var i=e.views,j={tmpl:g,path:c,parent:e,data:f,ctx:a,views:d.isArray(f)?[]:{},hlp:B};return d.isArray(i)?i.splice(j.index=h!==b?h:i.length,0,j):i[j.index="_"+r++]=j,j}function F(a,c,d,e,f){var g,i;if(d&&typeof d=="object"&&!d.nodeType){for(g in d)c(g,d[g]);return a}if(!d||e===b)f&&(e=f(b,e||d));else if(""+d===d)if(e===null)delete c[d];else if(e=f?f(d,e):e)c[d]=e;return(i=h.onStoreItem)&&i(c,d,e,f),e}function G(a,b){return F(this,G,a,b,O)}function H(a,b){return F(this,H,a,b)}function I(a,b){return F(this,I,a,b)}function J(a,b){return F(this,J,a,b)}function K(a,c,e,f,k){var l,m,n,o,p,q,r,s,t,u,v={},w=k===j,x=this,y="";x.isTag?(t=x.tmpl,c=c||x.ctx,e=e||x.view,f=f||x.path,k=k||x.index,v=x.props):t=x.jquery&&x[0]||x,e=e||z.topView,s=e.ctx,u=t.layout,a===e&&(a=e.data,u=j),c=c&&c===s?s:s?(s=g({},s),c)?g(s,c):s:c||{},v.link===i&&(c.link=i),t.fn||(t=G[t]||G(t)),p=c.link&&h.onRenderItem,q=c.link&&h.onRenderItems;if(t){if(d.isArray(a)&&!u){o=w?e:k!==b&&e||E(c,f,e,a,t,k);for(l=0,m=a.length;l-1,i+=(t===":"?u==="html"?(l=j,"e("+w):u?(r=j,'c("'+u+'",view,'+w):(m=j,"((v="+w+')!=u?v:""'):(k=j,'t("'+t+'",view,"'+(u||"")+'",'+(F?B.length:'""')+","+x+(w?",":"")+w))+")+");return i=new Function("data, view, j, b, u",v+(m?"v,":"")+(k?"t=j.tag,":"")+(r?"c=j.convert,":"")+(l?"e=j.converters.html,":"")+"ret; try{\n\n"+(A.debug?"debugger;":"")+(z?"ret=":"return ")+i.slice(0,-1)+";\n\n"+(z?"return ret;":"")+"}catch(e){return j.err(e);}"),b&&(b.fn=i,b.useVw=r||s||k),i}function N(a,b){function h(a,h,k,m,n,o,p,q,r,s,t,u,v,w,x,y){function z(a,c,d,e,f,g,h){if(c){var i=(d?'view.hlp("'+d+'")':e?"view":"data")+(h?(f?"."+f:d?"":e?"":"."+c)+(g||""):(h=d?"":e?f||"":c,""));return b&&r!=="("&&(i="b("+i+',"'+h+'")'),i+(h?"."+h:"")}return a}n=n||"",k=k||h||t,m=m||q,r=r||x||"",n=n||"";if(o)L();else return g?(g=!u,g?a:'"'):f?(f=!v,f?a:'"'):(k?(e++,k):"")+(y?e?"":c?(c=i,"\b"):",":p?(e&&L(),c=j,"\b"+m+":"):m?m.replace(l,z)+(r?(d[++e]=j,r):n):n?a:w?(d[e--]=i,w)+(r?(d[++e]=j,r):""):s?(d[e]||L(),","):h?"":(g=u,f=v,'"'))}var c,d={},e=0,f=i,g=i;return a=(a+" ").replace(m,h),a}function O(a,c,d,e){function n(b){if(""+b===b||b.nodeType>0)return i=b.nodeType>0?b:!f.test(b)&&k&&k(b)[0],i&&i.type&&(b=G[i.getAttribute(u)],b||(a=a||"_"+s++,i.setAttribute(u,a),b=O(a,i.innerHTML,d,e),G[a]=b)),b}var h,i,j,l,m;h=n(c),e=e||(c.markup?c:{}),e.name=a,l=e.templates,!h&&c.markup&&(h=n(c.markup))&&h.fn&&(h.debug!==c.debug||h.allowCode!==c.allowCode)&&(h=h.markup);if(h!==b){a&&!d&&(y[a]=function(){return c.render.apply(c,arguments)}),h.fn||c.fn?h.fn&&(a&&a!==h.name?c=g(g({},h),e):c=h):(c=P(h,e,d,0),M(h,c));for(j in l)m=l[j],m.name!==j&&(l[j]=O(j,m,c));return c}}function P(a,b,c,d){function e(a){c[a]&&(f[a]=g(g({},c[a]),b[a]))}b=b||{};var f={markup:a,tmpls:[],links:[],render:K};return c&&(c.templates&&(f.templates=g(g({},c.templates),b.templates)),f.parent=c,f.name=c.name+"["+d+"]",f.index=d),g(f,b),c&&(e("templates"),e("tags"),e("helpers"),e("converters")),f}function Q(a){return t[a]||(t[a]="&#"+a.charCodeAt(0)+";")}var c="v1.0pre",d,e,f,g,h={},i=!1,j=!0,k=a.jQuery,l=/^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g,m=/(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,n=/\r?\n/g,o=/\\(['"])/g,p=/\\?(['"])/g,q=/\x08(~)?([^\x08]+)\x08/g,r=0,s=0,t={"&":"&","<":"<",">":">"},u="data-jsv-tmpl",v="var j=j||"+(k?"jQuery.":"js")+"views,",w=/[\x00"&'<>]/g,x=Array.prototype.slice,y={},z={jsviews:c,sub:h,debugMode:j,err:function(a){return z.debugMode?"
                                      Error: "+(a.message||a)+". ":'""'},tmplFn:M,render:y,templates:G,tags:H,helpers:I,converters:J,View:E,convert:C,delimiters:A,tag:D};k?(d=k,d.templates=G,d.render=y,d.views=z,d.fn.render=K):(d=a.jsviews=z,d.extend=function(a,b){var c;a=a||{};for(c in b)a[c]=b[c];return a},d.isArray=Array&&Array.isArray||function(a){return Object.prototype.toString.call(a)==="[object Array]"}),g=d.extend,z.topView={views:{},tmpl:{},hlp:B,ctx:z.helpers},H({"if":function(){var a=this,c=a.view;return c.onElse=function(a,d){var e=0,f=d.length;while(f&&!d[e++])if(e===f)return"";return c.onElse=b,a.path="",a.renderContent(c)},c.onElse(this,arguments)},"else":function(){var a=this.view;return a.onElse?a.onElse(this,arguments):""},"for":function(){var a,b=this,c="",d=arguments,e=d.length;b.props.layout&&(b.tmpl.layout=j);for(a=0;a1&&!a.isArray(b[0]))return b[0]>=-180&&b[0]<=180&&b[1]>=-85&&b[1]<=85;b=b[0]}return!1},center:function(b,c){var d=!1;!c&&a.geo.proj&&this._isGeodetic(b)&&(d=!0,b=a.geo.proj.fromGeodetic(b));var e=[(b[0]+b[2])/2,(b[1]+b[3])/2];return d?a.geo.proj.toGeodetic(e):e},expandBy:function(b,c,d,e){var f=!1;return!e&&a.geo.proj&&this._isGeodetic(b)&&(f=!0,b=a.geo.proj.fromGeodetic(b)),b=[b[0]-c,b[1]-d,b[2]+c,b[3]+d],f?a.geo.proj.toGeodetic(b):b},height:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[3]-b[1]},_in:function(a,b){return a[0]<=b[0]&&a[1]<=b[1]&&a[2]>=b[2]&&a[3]>=b[3]},_bboxDisjoint:function(a,b){return b[0]>a[2]||b[2]a[3]||b[3]0&&(f/g>c?(i=f/2,j=i/c):(j=g/2,i=j*c),b=[h[0]-i,h[1]-j,h[0]+i,h[1]+j]),e?a.geo.proj.toGeodetic(b):b},recenter:function(b,c,d){var e=!1;!d&&a.geo.proj&&(this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b)),this._isGeodetic(c)&&(c=a.geo.proj.fromGeodetic(c)));var f=(b[2]-b[0])/2,g=(b[3]-b[1])/2;return b=[c[0]-f,c[1]-g,c[0]+f,c[1]+g],e?a.geo.proj.toGeodetic(b):b},scaleBy:function(b,c,d){var e=!1;!d&&a.geo.proj&&this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b));var f=this.center(b,!0),g=(b[2]-b[0])*c/2,h=(b[3]-b[1])*c/2;return b=[f[0]-g,f[1]-h,f[0]+g,f[1]+h],e?a.geo.proj.toGeodetic(b):b},width:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[2]-b[0]},bbox:function(b,f){var g,h=!1;if(!b)return c;if(b.bbox)g=!f&&a.geo.proj&&this._isGeodetic(b.bbox)?a.geo.proj.fromGeodetic(b.bbox):b.bbox;else{g=[d,d,e,e];var i=this._allCoordinates(b),j=0;if(i.length===0)return c;!f&&a.geo.proj&&this._isGeodetic(i)&&(h=!0,i=a.geo.proj.fromGeodetic(i));for(;j0?(h[0]=Math.min(Math.max(i[0][0],m[0]),m[2]),h[1]=Math.min(Math.max(i[0][1],m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(h):h}):c;return g*=3,h[0]=Math.min(Math.max(h[0]/g,m[0]),m[2]),h[1]=Math.min(Math.max(h[1]/g,m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(h):h}}return c},contains:function(a,b){if(a.type!="Polygon")return!1;switch(b.type){case"Point":return this._containsPolygonPoint(a.coordinates,b.coordinates);case"LineString":return this._containsPolygonLineString(a.coordinates,b.coordinates);case"Polygon":return this._containsPolygonLineString(a.coordinates,b.coordinates[0]);default:return!1}},_containsPolygonPoint:function(a,b){if(a.length===0||a[0].length<4)return!1;var c=0,d=a[0][0],e=1,f,g;for(;eb[0]&&c++;d=f}return c%2==1},_containsPolygonLineString:function(a,b){for(var c=0;c0){var e=a[0],f=b[0]-e[0],g=b[1]-e[1];if(a.length==1)return Math.sqrt(f*f+g*g);for(var h=1;h=h?e*e+f*f:c*c+d*d-g*g/h},_distanceLineStringLineString:function(a,b){var c=d;for(var e=0;e2?{type:"Point",coordinates:[parseFloat(b[1]),parseFloat(b[2])]}:null}function p(a){var b=a.match(/\s*\((.*)\)/),c=[],d,e,f=0;if(b&&b.length>1){d=b[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);for(;f1){d=b[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);for(;f0){for(;f
                                      ";while(c[0]);return a>6?a:!a}();a.widget("geo.geographics",{_$elem:b,_options:{},_trueCanvas:!0,_width:0,_height:0,_$canvas:b,_context:b,_blitcanvas:b,_blitcontext:b,_$labelsContainer:b,options:{style:{borderRadius:"8px",color:"#7f0000",fillOpacity:.2,height:"8px",opacity:1,strokeOpacity:1,strokeWidth:"2px",visibility:"visible",width:"8px"}},_create:function(){this._$elem=this.element,this._options=this.options,this._$elem.css({display:"inline-block",overflow:"hidden",textAlign:"left"}),this._$elem.css("position")=="static"&&this._$elem.css("position","relative"),this._$elem.addClass("geo-graphics"),this._width=this._$elem.width(),this._height=this._$elem.height();if(!this._width||!this._height)this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10);var a="position:absolute;left:0;top:0;margin:0;padding:0;",b="width:"+this._width+"px;height:"+this._height+"px;",d='width="'+this._width+'" height="'+this._height+'"';document.createElement("canvas").getContext?(this._$elem.append("'),this._$canvas=this._$elem.children(":last"),this._context=this._$canvas[0].getContext("2d"),this._blitcanvas=document.createElement("canvas"),this._blitcanvas.width=this._width,this._blitcanvas.height=this._height,this._blitcontext=this._blitcanvas.getContext("2d")):c<=8&&(this._trueCanvas=!1,this._$elem.append("
                                      '),this._$canvas=this._$elem.children(":last"),G_vmlCanvasManager.initElement(this._$canvas[0]),this._context=this._$canvas[0].getContext("2d"),this._$canvas.children().css({backgroundColor:"transparent",width:this._width,height:this._height})),this._$elem.append('
                                      '),this._$labelsContainer=this._$elem.children(":last")},_setOption:function(b,c){b=="style"&&(c=a.extend({},this._options.style,c)),a.Widget.prototype._setOption.apply(this,arguments)},destroy:function(){a.Widget.prototype.destroy.apply(this,arguments),this._$elem.html(""),this._$elem.removeClass("geo-graphics")},clear:function(){this._context.clearRect(0,0,this._width,this._height),this._$labelsContainer.html("")},drawArc:function(a,b,c,d){d=this._getGraphicStyle(d);if(d.visibility!="hidden"&&d.opacity>0&&d.widthValue>0&&d.heightValue>0){var e=Math.min(d.widthValue,d.heightValue)/2;b=b*Math.PI/180,c=c*Math.PI/180,this._context.save(),this._context.translate(a[0],a[1]),d.widthValue>d.heightValue?this._context.scale(d.widthValue/d.heightValue,1):this._context.scale(1,d.heightValue/d.widthValue),this._context.beginPath(),this._context.arc(0,0,e,b,c,!1),this._trueCanvas&&this._context.restore(),d.doFill&&(this._context.fillStyle=d.fill,this._context.globalAlpha=d.opacity*d.fillOpacity,this._context.fill()),d.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=d.strokeWidthValue,this._context.strokeStyle=d.stroke,this._context.globalAlpha=d.opacity*d.strokeOpacity,this._context.stroke()),this._trueCanvas||this._context.restore()}},drawPoint:function(a,b){b=this._getGraphicStyle(b),b.widthValue==b.heightValue&&b.heightValue==b.borderRadiusValue?this.drawArc(a,0,360,b):b.visibility!="hidden"&&b.opacity>0&&(b.borderRadiusValue=Math.min(Math.min(b.widthValue,b.heightValue)/2,b.borderRadiusValue),a[0]-=b.widthValue/2,a[1]-=b.heightValue/2,this._context.beginPath(),this._context.moveTo(a[0]+b.borderRadiusValue,a[1]),this._context.lineTo(a[0]+b.widthValue-b.borderRadiusValue,a[1]),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1],a[0]+b.widthValue,a[1]+b.borderRadiusValue),this._context.lineTo(a[0]+b.widthValue,a[1]+b.heightValue-b.borderRadiusValue),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1]+b.heightValue,a[0]+b.widthValue-b.borderRadiusValue,a[1]+b.heightValue),this._context.lineTo(a[0]+b.borderRadiusValue,a[1]+b.heightValue),this._context.quadraticCurveTo(a[0],a[1]+b.heightValue,a[0],a[1]+b.heightValue-b.borderRadiusValue),this._context.lineTo(a[0],a[1]+b.borderRadiusValue),this._context.quadraticCurveTo(a[0],a[1],a[0]+b.borderRadiusValue,a[1]),this._context.closePath(),b.doFill&&(this._context.fillStyle=b.fill,this._context.globalAlpha=b.opacity*b.fillOpacity,this._context.fill()),b.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=b.strokeWidthValue,this._context.strokeStyle=b.stroke,this._context.globalAlpha=b.opacity*b.strokeOpacity,this._context.stroke()))},drawLineString:function(a,b){this._drawLines([a],!1,b)},drawPolygon:function(a,b){if(!this._trueCanvas||a.length==1)this._drawLines(a,!0,b);else{if(!a||!a.length||a[0].length<3)return;b=this._getGraphicStyle(b);var c,d,e;if(b.visibility!="hidden"&&b.opacity>0){this._blitcontext.clearRect(0,0,this._width,this._height);if(b.doFill&&a.length>1){this._blitcontext.globalCompositeOperation="source-out",this._blitcontext.globalAlpha=1;for(d=1;d1)for(d=1;d'+b+"")},resize:function(){this._width=this._$elem.width(),this._height=this._$elem.height();if(!this._width||!this._height)this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10);this._trueCanvas&&(this._$canvas[0].width=this._width,this._$canvas[0].height=this._height),this._$labelsContainer.css({width:this._width,height:this._height})},_getGraphicStyle:function(b){function c(a){return a=parseInt(a,10),+a+""===a?+a:a}return b=a.extend({},this._options.style,b),b.borderRadiusValue=c(b.borderRadius),b.fill=b.fill||b.color,b.doFill=b.fill&&b.fillOpacity>0,b.stroke=b.stroke||b.color,b.strokeWidthValue=c(b.strokeWidth),b.doStroke=b.stroke&&b.strokeOpacity>0&&b.strokeWidthValue>0,b.widthValue=c(b.width),b.heightValue=c(b.height),b},_drawLines:function(a,b,c){if(!a||!a.length||a[0].length<2)return;var d,e;c=this._getGraphicStyle(c);if(c.visibility!="hidden"&&c.opacity>0){this._context.beginPath();for(d=0;d
                                      ";while(c[0]);return a>6?a:!a}(),e={bbox:[-180,-85,180,85],bboxMax:[-180,-85,180,85],center:[0,0],cursors:{"static":"default",pan:"url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move",zoom:"crosshair",dragBox:"crosshair",dragCircle:"crosshair",drawPoint:"crosshair",drawLineString:"crosshair",drawPolygon:"crosshair",measureLength:"crosshair",measureArea:"crosshair"},measureLabels:{length:"{{:length.toFixed( 2 )}} m",area:"{{:area.toFixed( 2 )}} sq m"},drawStyle:{},shapeStyle:{},mode:"pan",pannable:!0,scroll:"default",shift:"default",services:[{"class":"osm",type:"tiled",src:function(a){return"http://otile"+(a.index%4+1)+".mqcdn.com/tiles/1.0.0/osm/"+a.zoom+"/"+a.tile.column+"/"+a.tile.row+".png"},attr:"Tiles Courtesy of MapQuest "}],tilingScheme:{tileWidth:256,tileHeight:256,levels:18,basePixelSize:156543.03392799935,origin:[-20037508.342787,20037508.342787]},axisLayout:"map",zoom:0,zoomMin:0,zoomMax:Number.POSITIVE_INFINITY,pixelSize:0};a.widget("geo.geomap",{_$elem:b,_map:b,_created:!1,_createdGraphics:!1,_widgetId:0,_tmplLengthId:"",_tmplAreaId:"",_contentBounds:{},_$resizeContainer:b,_$eventTarget:b,_$contentFrame:b,_$existingChildren:b,_$attrList:b,_$servicesContainer:b,_$shapesContainers:b,_$panContainer:b,_$shapesContainer:b,_$drawContainer:b,_$measureContainer:b,_$measureLabel:b,_dpi:96,_currentServices:[],_center:b,_pixelSize:b,_centerMax:b,_pixelSizeMax:b,_userGeodetic:!0,_centerInteractive:b,_pixelSizeInteractive:b,_timeoutInteractive:null,_triggerInteractive:!1,_loadCount:0,_wheelTimeout:null,_wheelLevel:0,_zoomFactor:2,_fullZoomFactor:2,_partialZoomFactor:1.18920711500273,_mouseDown:b,_inOp:b,_toolPan:b,_shiftDown:b,_anchor:b,_current:b,_downDate:b,_moveDate:b,_clickDate:b,_lastMove:b,_lastDrag:b,_windowHandler:null,_resizeTimeout:null,_panning:b,_velocity:b,_friction:b,_supportTouch:b,_softDblClick:b,_isTap:b,_isDbltap:b,_isMultiTouch:b,_multiTouchAnchor:[],_multiTouchAnchorBbox:b,_multiTouchCurrentBbox:b,_drawTimeout:null,_drawPixels:[],_drawCoords:[],_graphicShapes:[],_initOptions:{},_options:{},options:a.extend({},e),_createWidget:function(b,d){this._$elem=a(d);if(this._$elem.is(".geo-service")){this._graphicShapes=[],a.Widget.prototype._createWidget.apply(this,arguments);return}this._widgetId=c++,this._tmplLengthId="geoMeasureLength"+this._widgetId,this._tmplAreaId="geoMeasureArea"+this._widgetId,this._$elem.addClass("geo-map").css({webkitTransform:"translateZ(0)"}),this._initOptions=b||{},this._forcePosition(this._$elem),this._$elem.css("text-align","left");var e=this._findMapSize();this._contentBounds={x:parseInt(this._$elem.css("padding-left"),10),y:parseInt(this._$elem.css("padding-top"),10),width:e.width,height:e.height},this._createChildren(),this._center=[0,0],this._centerMax=[0,0],this._centerInteractive=[0,0],this.options.pixelSize=this._pixelSize=this._pixelSizeMax=156543.03392799935,this._mouseDown=this._inOp=this._toolPan=this._shiftDown=this._panning=this._isTap=this._isDbltap=!1,this._anchor=[0,0],this._current=[0,0],this._lastMove=[0,0],this._lastDrag=[0,0],this._velocity=[0,0],this._friction=[.8,.8],this._downDate=this._moveDate=this._clickDate=0,this._drawPixels=[],this._drawCoords=[],this._graphicShapes=[],a.Widget.prototype._createWidget.apply(this,arguments)},_create:function(){this._options=this.options;if(this._$elem.is(".geo-service")){this._map=this._$elem.data("geoMap"),this._$elem.data("geoService",this);return}this._map=this,this._supportTouch="ontouchend"in document,this._softDblClick=this._supportTouch||d==7;var c=this,e=this._supportTouch?"touchstart":"mousedown",f=this._supportTouch?"touchend touchcancel":"mouseup",g=this._supportTouch?"touchmove":"mousemove";a(document).keydown(a.proxy(this._document_keydown,this)),this._$eventTarget.dblclick(a.proxy(this._eventTarget_dblclick,this)),this._$eventTarget.bind(e,a.proxy(this._eventTarget_touchstart,this));var h=this._$eventTarget[0].setCapture?this._$eventTarget:a(document);h.bind(g,a.proxy(this._dragTarget_touchmove,this)),h.bind(f,a.proxy(this._dragTarget_touchstop,this)),this._$eventTarget.mousewheel(a.proxy(this._eventTarget_mousewheel,this)),this._windowHandler=function(){c._resizeTimeout&&clearTimeout(c._resizeTimeout),c._resizeTimeout=setTimeout(function(){c._created&&c._$elem.geomap("resize",!0)},500)},a(window).resize(this._windowHandler),this._$drawContainer.geographics({style:this._initOptions.drawStyle||{}}),this._options.drawStyle=this._$drawContainer.geographics("option","style"),this._$shapesContainer.geographics({style:this._initOptions.shapeStyle||{}}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style"),this._initOptions&&(this._initOptions.tilingScheme!==b&&this._setOption("tilingScheme",this._initOptions.tilingScheme||null,!1),this._initOptions.services&&(this._options.services=a.merge([],this._initOptions.services)),this._initOptions.bboxMax&&(this._setOption("bboxMax",this._initOptions.bboxMax,!1),this._setOption("bbox",this._initOptions.bboxMax,!1)),this._initOptions.zoomMin!==b&&this._setOption("zoomMin",this._initOptions.zoomMin,!1),this._initOptions.zoomMax!==b&&this._setOption("zoomMax",this._initOptions.zoomMax,!1),this._initOptions.bbox&&this._setOption("bbox",this._initOptions.bbox,!1),this._initOptions.center&&this._setOption("center",this._initOptions.center,!1),this._initOptions.zoom!==b&&this._setOption("zoom",this._initOptions.zoom,!1)),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area),this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._createServices(),this._refresh(),this._created=!0},_setOption:function(c,d,e){if(c=="pixelSize")return;e=e===b||e,this._$elem.is(".geo-map")&&this._panFinalize();var f,g,h,i;switch(c){case"bbox":this._created&&this._clearInteractiveTimeout(),this._userGeodetic=a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),f=[d[0]+(d[2]-d[0])/2,d[1]+(d[3]-d[1])/2],g=Math.max(a.geo.width(d,!0)/this._contentBounds.width,a.geo.height(d,!0)/this._contentBounds.height),i=this._getZoom(f,g),this._options.tilingScheme?g=this._getPixelSize(Math.min(Math.max(i,this._options.zoomMin),this._options.zoomMax)):ithis._options.zoomMax&&(g=this._getPixelSize(this._options.zoomMax)),this._created?(this._setInteractiveCenterAndSize(f,g),this._setInteractiveTimeout(!1)):this._setCenterAndSize(f,g,!1,e),d=this._getBbox(f,g);break;case"bboxMax":this._userGeodetic=a.geo.proj&&a.geo._isGeodetic(d);break;case"center":this._created&&this._clearInteractiveTimeout(),this._userGeodetic=a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),this._created?(this._setInteractiveCenterAndSize(d,this._pixelSize),this._setInteractiveTimeout(!1)):this._setCenterAndSize(d,this._pixelSize,!1,e);break;case"measureLabels":d=a.extend(this._options.measureLabels,d),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area);break;case"drawStyle":this._$drawContainer&&(this._$drawContainer.geographics("option","style",d),d=this._$drawContainer.geographics("option","style"));break;case"shapeStyle":this._$elem.is(".geo-service")&&!this._createdGraphics&&this._createServiceGraphics(),this._createdGraphics&&(this._$shapesContainer.geographics("option","style",d),d=this._$shapesContainer.geographics("option","style"));break;case"mode":this._resetDrawing(),this._$eventTarget.css("cursor",this._options.cursors[d]);break;case"zoom":this._created?this._setZoom(d,!1,e):(d=Math.max(d,0),this._setCenterAndSize(this._center,this._getPixelSize(d),!1,e))}a.Widget.prototype._setOption.apply(this,arguments);switch(c){case"bbox":case"center":this._userGeodetic&&(this._options.bbox=a.geo.proj.toGeodetic(this._options.bbox),this._options.center=a.geo.proj.toGeodetic(this._center));break;case"tilingScheme":d!==null&&(this._pixelSizeMax=this._getPixelSize(0),this._centerMax=[d.origin[0]+this._pixelSizeMax*d.tileWidth/2,d.origin[1]+this._pixelSizeMax*d.tileHeight/2]);break;case"bboxMax":a.geo.proj&&a.geo._isGeodetic(d)?h=a.geo.proj.fromGeodetic(d):h=d,this._centerMax=a.geo.center(h),this._pixelSizeMax=Math.max(a.geo.width(h,!0)/this._contentBounds.width,a.geo.height(h,!0)/this._contentBounds.height);break;case"services":this._createServices(),e&&this._refresh();break;case"shapeStyle":e&&this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))}},destroy:function(){if(this._$elem.is(".geo-service"))this._createdGraphics&&(this._$shapesContainer.geographics("destroy"),this._$shapesContainer=b,this._createdGraphics=!1);else{clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,this._created=!1,a(window).unbind("resize",this._windowHandler);for(var c=0;c=0||b<=1)for(var d=0;d0)){this._createdGraphics||this._createServiceGraphics();var g,h,i,j,k,l;a.isArray(c)?g=c:c.type=="FeatureCollection"?g=c.features:g=[c];for(i=1;i0)){var e=a.isArray(c)?c:[c],f;for(var g=0;g=0&&(a.removeData(c,"geoBbox"),f=this._graphicShapes.slice(g+1),this._graphicShapes.length=g,this._graphicShapes.push.apply(this._graphicShapes,f),g--);if(d===b||d)this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh()}},_getBbox:function(a,b){a=a||this._center,b=b||this._pixelSize;var c=this._contentBounds.width/2*b,d=this._contentBounds.height/2*b;return[a[0]-c,a[1]-d,a[0]+c,a[1]+d]},_setBbox:function(b,c,d){var e=[b[0]+(b[2]-b[0])/2,b[1]+(b[3]-b[1])/2],f=Math.max(a.geo.width(b,!0)/this._contentBounds.width,a.geo.height(b,!0)/this._contentBounds.height),g=this._getZoom(e,f);this._options.tilingScheme?f=this._getPixelSize(Math.min(Math.max(g,this._options.zoomMin),this._options.zoomMax)):gthis._options.zoomMax&&(f=this._getPixelSize(this._options.zoomMax)),this._setInteractiveCenterAndSize(e,f),this._interactiveTransform()},_getBboxMax:function(){var a=this._contentBounds.width/2*this._pixelSizeMax,b=this._contentBounds.height/2*this._pixelSizeMax;return[this._centerMax[0]-a,this._centerMax[1]-b,this._centerMax[0]+a,this._centerMax[1]+b]},_getCenter:function(){return this._center},_getContentBounds:function(){return this._contentBounds},_getServicesContainer:function(){return this._$servicesContainer},_getZoom:function(b,c){b=b||this._center,c=c||this._pixelSize;var d=this._options.tilingScheme;if(d){if(d.pixelSizes){var e=Math.floor(c*1e3),f=d.pixelSizes.length,g=f-1;for(;g>=0;g--)if(Math.floor(d.pixelSizes[g]*1e3)>=e)return g;return 0}return Math.round(Math.log(d.basePixelSize/c)/Math.log(2))}var h=this._contentBounds.width/this._contentBounds.height,i=a.geo.reaspect(this._getBbox(b,c),h,!0),j=a.geo.reaspect(this._getBboxMax(),h,!0);return Math.round(Math.log(a.geo.width(j,!0)/a.geo.width(i,!0))/Math.log(this._zoomFactor))},_setZoom:function(a,b,c){this._clearInteractiveTimeout(),a=Math.min(Math.max(a,this._options.zoomMin),this._options.zoomMax),this._setInteractiveCenterAndSize(this._center,this._getPixelSize(a)),this._interactiveTransform(),this._setInteractiveTimeout(b)},_createChildren:function(){this._$existingChildren=this._$elem.children(),this._forcePosition(this._$existingChildren),this._$existingChildren.detach().css({mozUserSelect:"none"});var b="width:"+this._contentBounds.width+"px; height:"+this._contentBounds.height+"px; margin:0; padding:0;",c="position:absolute; left:0; top:0;";this._$elem.prepend('
                                      '),this._$eventTarget=this._$contentFrame=this._$elem.children(":first"),this._$contentFrame.append('
                                      '),this._$servicesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                                      '),this._$shapesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                                        '),this._$attrList=this._$contentFrame.children(":last"),this._$contentFrame.append('
                                        '),this._$drawContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                                        '),this._$measureContainer=this._$contentFrame.children(":last"),this._$measureLabel=this._$measureContainer.children(),this._$panContainer=a([this._$shapesContainer[0],this._$drawContainer[0],this._$measureContainer[0]]),this._$resizeContainer=a([this._$contentFrame[0],this._$servicesContainer[0],this._$eventTarget[0],this._$measureContainer[0]]),this._$contentFrame.append(this._$existingChildren),a("#geo-measure-style").length||a("head").prepend('")},_createServices:function(){var b,c;for(c=0;c',g;this._$servicesContainer.append(f),serviceContainer=this._$servicesContainer.children(":last"),b.serviceContainer=serviceContainer,a.geo._serviceTypes[b.type].create(this,serviceContainer,b,c),serviceContainer.data("geoMap",this).geomap(),b.attr&&this._$attrList.append("
                                      • "+b.attr+"
                                      • ")}this._$shapesContainers=this._$shapesContainer,this._$attrList.find("a").css({position:"relative",zIndex:100})},_createServiceGraphics:function(){var a=this._$elem.closest(".geo-content-frame");this._$elem.append('
                                        '),this._$shapesContainer=this._$elem.children(":last"),this._map._$shapesContainers=this._map._$shapesContainers.add(this._$shapesContainer),this._$shapesContainer.geographics(),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style")},_refreshDrawing:function(){this._$drawContainer.geographics("clear");if(this._drawPixels.length>0){var b=this._options.mode,c=this._drawPixels,d=this._drawCoords,e,f,g,h,i;switch(b){case"measureLength":b="drawLineString",f={type:"LineString",coordinates:d},e=a.render[this._tmplLengthId]({length:a.geo.length(f,!0)}),g=a.merge([],c[c.length-1]);break;case"measureArea":b="drawPolygon",f={type:"Polygon",coordinates:[a.merge([],d)]},f.coordinates[0].push(d[0]),e=a.render[this._tmplAreaId]({area:a.geo.area(f,!0)}),g=this._toPixel(a.geo.centroid(f).coordinates),c=[c];break;case"drawPolygon":c=[c]}this._$drawContainer.geographics(b,c),e&&(this._$measureLabel.html(e),h=this._contentBounds.width-(this._$measureLabel.outerWidth(!0)+g[0]),i=this._contentBounds.height-(this._$measureLabel.outerHeight(!0)+g[1]),h<0&&(g[0]+=h),i<0&&(g[1]+=i),this._$measureLabel.css({left:Math.max(g[0],0),top:Math.max(g[1],0)}).show())}},_resetDrawing:function(){this._drawPixels=[],this._drawCoords=[],this._$drawContainer.geographics("clear"),this._$measureLabel.hide()},_refreshShapes:function(c,d,e,f,g,h){var i,j,k,l,m,n,o,p,q=this._map._getBbox(g,h);for(i=0;i0&&a.height>0)){a={width:b.width(),height:b.height()};if(a.width<=0||a.height<=0)a={width:parseInt(b.css("width"),10),height:parseInt(b.css("height"),10)};b=b.parent()}return a},_forcePosition:function(a){var b=a.css("position");b!="relative"&&b!="absolute"&&b!="fixed"&&a.css("position","relative")},_getPixelSize:function(b){var c=this._options.tilingScheme;if(c!==null){if(b===0)return c.pixelSizes?c.pixelSizes[0]:c.basePixelSize;b=Math.round(b),b=Math.max(b,0);var d=c.pixelSizes?c.pixelSizes.length:c.levels;return b=Math.min(b,d-1),c.pixelSizes?c.pixelSizes[b]:c.basePixelSize/Math.pow(2,b)}var e=a.geo.scaleBy(this._getBboxMax(),1/Math.pow(this._zoomFactor,b),!0);return Math.max(a.geo.width(e,!0)/this._contentBounds.width,a.geo.height(e,!0)/this._contentBounds.height)},_getZoomCenterAndSize:function(a,b,c){var d=c?this._fullZoomFactor:this._partialZoomFactor,e=Math.pow(d,-b),f=this._pixelSizeInteractive*e,g=this._getZoom(this._centerInteractive,f);c&&this._options.tilingScheme?f=this._getPixelSize(Math.min(Math.max(g,this._options.zoomMin),this._options.zoomMax)):b<0&&g0&&g>this._options.zoomMax&&(f=this._pixelSizeInteractive);var h=f/this._pixelSizeInteractive,i=this._toMap(a,this._centerInteractive,this._pixelSizeInteractive),j=[(this._centerInteractive[0]-i[0])*h,(this._centerInteractive[1]-i[1])*h],k=[i[0]+j[0],i[1]+j[1]];return{pixelSize:f,center:k}},_mouseWheelFinish:function(a){this._wheelTimeout=null;if(this._wheelLevel!==0){var b=this._getZoomCenterAndSize(this._anchor,this._wheelLevel,this._options.tilingScheme!==null);this._wheelLevel=0}else a&&this._refresh()},_panFinalize:function(){if(this._panning){this._velocity=[0,0];var a=this._current[0]-this._anchor[0],b=this._current[1]-this._anchor[1],c=this._options.axisLayout==="image",d=-a*this._pixelSize,e=(c?-1:1)*b*this._pixelSize;this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._inOp=!1,this._anchor=this._current,this._mouseDown=this._toolPan=this._panning=!1}},_panMove:function(){if(!this._options.pannable)return;var a=this._current[0]-this._lastDrag[0],b=this._current[1]-this._lastDrag[1],c=0,d,e;if(this._toolPan||a>3||a<-3||b>3||b<-3){this._toolPan||(this._toolPan=!0,this._$eventTarget.css("cursor",this._options.cursors.pan)),this._mouseDown&&(this._velocity=[a,b]);if(a!==0||b!==0)this._panning=!0,this._lastDrag=this._current,this._centerInteractive[0]-=a*this._pixelSizeInteractive,this._centerInteractive[1]+=(this._options.axisLayout==="image"?-1:1)*b*this._pixelSizeInteractive,this._setInteractiveCenterAndSize(this._centerInteractive,this._pixelSizeInteractive),this._interactiveTransform()}},_clearInteractiveTimeout:function(){return this._timeoutInteractive?(clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,!0):(this._centerInteractive[0]=this._center[0],this._centerInteractive[1]=this._center[1],this._pixelSizeInteractive=this._pixelSize,!1)},_interactiveTransform:function(){this._$shapesContainers&&this._$shapesContainers.geographics("clear");for(var b=0;b0&&(this._drawPixels=this._toPixel(this._drawCoords,this._centerInteractive,this._pixelSizeInteractive),this._refreshDrawing())},_setInteractiveTimeout:function(a){function c(){b._isMultiTouch?b._timeoutInteractive=setTimeout(c,128):b._created&&b._timeoutInteractive&&(b._setCenterAndSize(b._centerInteractive,b._pixelSizeInteractive,b._triggerInteractive,!0),b._timeoutInteractive=null,b._triggerInteractive=!1)}var b=this;this._timeoutInteractive=setTimeout(c,128),this._triggerInteractive|=a},_refresh:function(b,c){var d,e,f=0;for(;f0&&e._refreshShapes(e._$shapesContainer,e._graphicShapes,e._graphicShapes,e._graphicShapes))}this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._graphicShapes.length>0&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))},_setInteractiveCenterAndSize:function(b,c){this._centerInteractive[0]=b[0],this._centerInteractive[1]=b[1],this._pixelSizeInteractive=c,this._userGeodetic?(this._options.bbox=a.geo.proj.toGeodetic(this._getBbox(b,c)),this._options.center=a.geo.proj.toGeodetic(b)):(this._options.bbox=this._getBbox(b,c),this._options.center[0]=b[0],this._options.center[1]=b[1]),this._options.pixelSize=c,this._options.zoom=this._getZoom(b,c)},_setCenterAndSize:function(b,c,d,e){if(!a.isArray(b)||b.length!=2||typeof b[0]!="number"||typeof b[1]!="number")return;var f=this._getZoom(b,c);this._options.tilingScheme?this._pixelSizeInteractive=c=this._getPixelSize(Math.min(Math.max(f,this._options.zoomMin),this._options.zoomMax)):fthis._options.zoomMax&&(this._pixelSizeInteractive=c=this._getPixelSize(this._options.zoomMax)),this._center[0]=b[0],this._center[1]=b[1],this._options.pixelSize=this._pixelSize=c,this._userGeodetic?(this._options.bbox=a.geo.proj.toGeodetic(this._getBbox()),this._options.center=a.geo.proj.toGeodetic(this._center)):(this._options.bbox=this._getBbox(),this._options.center=a.merge([],b)),this._options.zoom=f,d&&this._trigger("bboxchange",window.event,{bbox:a.merge([],this._options.bbox)}),e&&(this._refresh(),this._refreshDrawing())},_requestQueued:function(){this._loadCount===0&&this._trigger("loadstart",window.event),this._loadCount++},_requestComplete:function(){this._loadCount--,this._loadCount<=0&&(this._loadCount=0,this._trigger("loadend",window.event))},_toMap:function(b,c,d){c=c||this._center,d=d||this._pixelSize;var e=a.isArray(b[0]),f=e&&a.isArray(b[0][0]),g=f&&a.isArray(b[0][0][0]),h=this._contentBounds.width,i=this._contentBounds.height,j=h/2*d,k=i/2*d,l=[c[0]-j,c[1]-k,c[0]+j,c[1]+k],m=a.geo.width(l,!0)/h,n=a.geo.height(l,!0)/i,o,p=this._options.axisLayout==="image",q=[],r,s,t;g||(f||(e||(b=[b]),b=[b]),b=[b]);for(r=0;r0&&b.which==27&&(c<=2?(this._resetDrawing(),this._inOp=!1):(this._drawCoords[c-2]=a.merge([],this._drawCoords[c-1]),this._drawPixels[c-2]=a.merge([],this._drawPixels[c-1]),this._drawCoords.length--,this._drawPixels.length--,this._refreshDrawing()))},_eventTarget_dblclick_zoom:function(a){var b=this._clearInteractiveTimeout();this._trigger("dblclick",a,{type:"Point",coordinates:this._toMap(this._current,this._centerInteractive,this._pixelSizeInteractive)});if(!a.isDefaultPrevented()){var c=this._getZoomCenterAndSize(this._current,1,!0);this._setInteractiveCenterAndSize(c.center,c.pixelSize),this._interactiveTransform(),b=!0}b&&this._setInteractiveTimeout(!0)},_eventTarget_dblclick:function(b){if(this._options.mode==="static")return;this._drawTimeout&&(window.clearTimeout(this._drawTimeout),this._drawTimeout=null);var c=a(b.currentTarget).offset();switch(this._options.mode){case"drawLineString":case"measureLength":this._drawCoords.length>1&&(this._drawCoords[0][0]!=this._drawCoords[1][0]||this._drawCoords[0][1]!=this._drawCoords[1][1])?(this._drawCoords.length--,this._trigger("shape",b,{type:"LineString",coordinates:this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords})):this._eventTarget_dblclick_zoom(b),this._resetDrawing();break;case"drawPolygon":case"measureArea":if(this._drawCoords.length>1&&(this._drawCoords[0][0]!=this._drawCoords[1][0]||this._drawCoords[0][1]!=this._drawCoords[1][1])){var d=this._drawCoords.length-1;d>2&&(this._drawCoords[d]=a.merge([],this._drawCoords[0]),this._trigger("shape",b,{type:"Polygon",coordinates:[this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords]}))}else this._eventTarget_dblclick_zoom(b);this._resetDrawing();break;default:this._eventTarget_dblclick_zoom(b)}this._inOp=!1},_eventTarget_touchstart:function(b){var c=this._options.mode,d=this._options.shift;if(c==="static")return;if(!this._supportTouch&&b.which!=1)return;var e=this._clearInteractiveTimeout(),f=a(b.currentTarget).offset(),g=b.originalEvent.changedTouches;this._supportTouch?(this._multiTouchAnchor=a.merge([],g),this._isMultiTouch=this._multiTouchAnchor.length>1,this._isMultiTouch?(this._multiTouchCurrentBbox=[g[0].pageX-f.left,g[0].pageY-f.top,g[1].pageX-f.left,g[1].pageY-f.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._current=a.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchCurrentBbox=[g[0].pageX-f.left,g[0].pageY-f.top,NaN,NaN],this._current=[g[0].pageX-f.left,g[0].pageY-f.top])):this._current=[b.pageX-f.left,b.pageY-f.top];if(this._softDblClick){var h=a.now();if(h-this._downDate<750){if(this._isTap){var i=this._current[0]-this._anchor[0],j=this._current[1]-this._anchor[1],k=Math.sqrt(i*i+j*j);k>8?this._isTap=!1:this._current=a.merge([],this._anchor)}this._isDbltap?this._isDbltap=!1:this._isDbltap=this._isTap}else this._isDbltap=!1;this._isTap=!0,this._downDate=h}return this._mouseDown=!0,this._anchor=a.merge([],this._current),!this._inOp&&b.shiftKey&&d!=="off"?(this._shiftDown=!0,this._$eventTarget.css("cursor",this._options.cursors[d==="default"?"zoom":d])):!this._isMultiTouch&&(this._options.pannable||c==="dragBox"||c==="dragCircle")&&(this._inOp=!0,c!=="zoom"&&c!=="dragBox"&&c!=="dragCircle"&&(this._lastDrag=this._current,b.currentTarget.setCapture&&b.currentTarget.setCapture())),b.preventDefault(),e&&this._setInteractiveTimeout(!0),!1},_dragTarget_touchmove:function(b){if(this._options.mode==="static")return;var c=!1;this._mouseDown&&(c=this._clearInteractiveTimeout());var e=this._$eventTarget.offset(),f=this._drawCoords.length,g=b.originalEvent.changedTouches,h,i,j=0;if(this._supportTouch){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&g[0].identifier!==this._multiTouchAnchor[0].identifier)return this._mouseDown=!1,this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(g[0]),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-e.left,this._multiTouchAnchor[1].pageY-e.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._mouseDown=!0,this._anchor=this._current=a.geo.center(this._multiTouchCurrentBbox,!0),c&&this._setInteractiveTimeout(!0),!1;if(this._isMultiTouch){for(;j0?m*=5:m*=10;var n=m-this._wheelLevel;this._wheelLevel=m;var o=this._getZoomCenterAndSize(this._anchor,n,!1);this._setInteractiveCenterAndSize(o.center,o.pixelSize),this._interactiveTransform(),c=!0,h=a.geo.center(this._multiTouchCurrentBbox,!0)}else h=[b.originalEvent.changedTouches[0].pageX-e.left,b.originalEvent.changedTouches[0].pageY-e.top]}else h=[b.pageX-e.left,b.pageY-e.top];if(h[0]===this._lastMove[0]&&h[1]===this._lastMove[1]&&this._inOp)return b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1;d==7&&(this._isDbltap=this._isTap=!1),this._mouseDown&&(this._current=h,this._moveDate=a.now());if(this._isMultiTouch)return b.preventDefault(),this._isDbltap=this._isTap=!1,c&&this._setInteractiveTimeout(!0),!1;var p=this._options.shift,q=this._shiftDown?p==="default"?"zoom":p:this._options.mode,r,s,t;switch(q){case"zoom":case"dragBox":this._mouseDown?(this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawBbox",[this._anchor[0],this._anchor[1],h[0],h[1]])):this._trigger("move",b,{type:"Point",coordinates:this.toMap(h)});break;case"dragCircle":this._mouseDown?(r=h[0]-this._anchor[0],s=h[1]-this._anchor[1],t=Math.sqrt(r*r+s*s)*2,this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawArc",this._anchor,0,360,{width:t,height:t})):this._trigger("move",b,{type:"Point",coordinates:this.toMap(h)});break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":this._mouseDown||this._toolPan?(this._panMove(),c=!0):(f>0&&(this._drawCoords[f-1]=this._toMap(h,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[f-1]=h,this._refreshDrawing()),this._trigger("move",b,{type:"Point",coordinates:this.toMap(h)}));break;default:this._mouseDown||this._toolPan?(this._panMove(),c=!0):this._trigger("move",b,{type:"Point",coordinates:this.toMap(h)})}this._lastMove=h,c&&this._setInteractiveTimeout(!0);if(this._inOp)return b.preventDefault(),!1},_dragTarget_touchstop:function(b){if(this._options.mode==="static")return;if(!this._mouseDown)if(d==7)this._eventTarget_touchstart(b);else return!1;var c=this._clearInteractiveTimeout(),e=this._mouseDown,f=this._toolPan,g=this._$eventTarget.offset(),h=this._options.shift,i=this._shiftDown?h==="default"?"zoom":h:this._options.mode,j,k,l,m,n,o,p;this._supportTouch?(j=[b.originalEvent.changedTouches[0].pageX-g.left,b.originalEvent.changedTouches[0].pageY-g.top],this._multiTouchAnchor=[],this._inOp=!1):j=[b.pageX-g.left,b.pageY-g.top],this._softDblClick&&this._isTap&&(m=j[0]-this._anchor[0],n=j[1]-this._anchor[1],Math.sqrt(m*m+n*n)<=8&&(j=a.merge([],this._anchor))),m=j[0]-this._anchor[0],n=j[1]-this._anchor[1],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._shiftDown=this._mouseDown=this._toolPan=!1;if(this._isMultiTouch){b.preventDefault(),this._isMultiTouch=!1,this._wheelLevel=0,c&&this._setInteractiveTimeout(!0);return}document.releaseCapture&&document.releaseCapture();if(e){l=a.now(),this._current=j;switch(i){case"zoom":case"dragBox":if(m!==0||n!==0){var q=this._pixelSize*6,r=this._toMap([[Math.min(this._anchor[0],j[0]),Math.max(this._anchor[1],j[1])],[Math.max(this._anchor[0],j[0]),Math.min(this._anchor[1],j[1])]]),s=[r[0][0],r[0][1],r[1][0],r[1][1]];i==="zoom"?(s[2]-s[0]100){var x=this;this._drawTimeout=setTimeout(function(){x._drawTimeout&&(x._trigger("shape",b,{type:"Point",coordinates:x.toMap(j)}),x._inOp=!1,x._drawTimeout=null)},250)}break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":if(f)this._panFinalize();else{k=this._drawCoords.length===0?0:this._drawCoords.length-1,this._drawCoords[k]=this._toMap(j),this._drawPixels[k]=j;if(k<2||this._drawCoords[k][0]!=this._drawCoords[k-1][0]||this._drawCoords[k][1]!=this._drawCoords[k-1][1])this._drawCoords[k+1]=this._toMap(j,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[k+1]=j;this._refreshDrawing()}break;default:f?this._panFinalize():l-this._clickDate>100&&(this._trigger("click",b,{type:"Point",coordinates:this.toMap(j)}),this._inOp=!1)}this._clickDate=l;if(this._softDblClick&&this._isDbltap)return this._isDbltap=this._isTap=!1,c&&this._setInteractiveTimeout(!0),this._$eventTarget.trigger("dblclick",b),!1}c&&this._setInteractiveTimeout(!0);if(this._inOp)return b.preventDefault(),!1},_eventTarget_mousewheel:function(b,c){if(this._options.mode==="static"||this._options.scroll==="off")return;b.preventDefault();if(this._mouseDown)return!1;if(c!==0){this._clearInteractiveTimeout(),c>0?c=Math.ceil(c):c=Math.floor(c);var d=a(b.currentTarget).offset();this._anchor=[b.pageX-d.left,b.pageY-d.top];var e=this._getZoomCenterAndSize(this._anchor,c,this._options.tilingScheme!==null),f,g=0;this._setInteractiveCenterAndSize(e.center,e.pixelSize),this._interactiveTransform(),this._setInteractiveTimeout(!0)}return!1}})}(jQuery),function(a,b){a.geo._serviceTypes.tiled=function(){return{create:function(b,c,d,e){var f=a.data(d,"geoServiceState");if(!f){f={loadCount:0,reloadTiles:!1};var g='
                                        ';c.append(g),f.serviceContainer=c.children(":last"),a.data(d,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b.options.tilingScheme;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(c){var f=a(this),h=f.data("pixelSize"),i=h/e;if(h>0){i=Math.round(i*1e3)/1e3;var j=f.data("scaleOrigin"),k=b._toPixel(j,d,e);f.css({left:Math.round(k[0])+"px",top:Math.round(k[1])+"px",width:g.tileWidth*i,height:g.tileHeight*i})}}))},refresh:function(b,c,d){var e=a.data(c,"geoServiceState");this._cancelUnloaded(b,c),e&&d&&(e.reloadTiles=!0);if(e&&c&&c.style.visibility==="visible"&&!e.serviceContainer.is(":hidden")){var f=b._getBbox(),g=b._pixelSize,h=this,i=e.serviceContainer,j=b._getContentBounds(),k=j.width,l=j.height,m=b.options.axisLayout==="image",n=m?1:-1,o=b.options.tilingScheme,p=o.tileWidth,q=o.tileHeight,r=Math.floor((f[0]-o.origin[0])/(g*p)),s=Math.max(Math.floor((m?f[1]-o.origin[1]:o.origin[1]-f[3])/(g*q)),0),t=Math.ceil((f[2]-o.origin[0])/(g*p)),u=Math.ceil((m?f[3]-o.origin[1]:o.origin[1]-f[1])/(g*q)),v=b._getBboxMax(),w=b._getPixelSize(0),x=w/g,y=Math.floor((v[0]-o.origin[0])/(w*p))*x,z=Math.floor((o.origin[1]+n*v[3])/(w*q))*x,A=o.origin[0]+y*p*g,B=o.origin[1]+n*z*q*g,C=Math.round((A-f[0])/g),D=Math.round((m?B-f[1]:f[3]-B)/g),E=i.children().show(),F=E.filter("[data-pixel-size='"+g+"']").appendTo(i),G=c.style.opacity,H,I,J=function(c){h._loadImage(a.data(this,"img"),c,g,b,e,G)},K=function(){a.data(this,"img").remove(),e.loadCount--,b._requestComplete()};e.reloadTiles&&E.find("img").attr("data-dirty","true"),F.size()?(F.css({left:C%p+"px",top:D%q+"px"}).data("scaleOrigin",b._toMap([C%p,D%q])),F.children().each(function(b){var c=a(this),d=c.attr("data-tile").split(",");c.css({left:Math.round((parseInt(d[0],10)-y)*100+(C-C%p)/p*100)+"%",top:Math.round((parseInt(d[1],10)-z)*100+(D-D%q)/q*100)+"%"}),G<1&&c.fadeTo(0,G)})):(i.append("
                                        "),F=i.children(":last").data("scaleOrigin",b._toMap([C%p,D%q])));for(H=r;H0)M.attr("src",T);else{var U="",F.append(U),M=F.children(":last")}typeof T=="string"?h._loadImage(M,T,g,b,e,G):T?(a.data(T,"img",M),T.done(J).fail(K)):M.remove()}}E.find("[data-dirty]").remove(),e.reloadTiles=!1}},resize:function(a,b){},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display",c.style.visibility==="visible"?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0){d.serviceContainer.find("img:hidden").remove();while(d.loadCount>0)d.loadCount--,b._requestComplete()}},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){g<1?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).error(function(b){a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).attr("src",c)}}}()}(jQuery),function(a,b){a.geo._serviceTypes.shingled=function(){return{create:function(b,c,d,e){var f=a.data(d,"geoServiceState");if(!f){f={loadCount:0};var g='
                                        ';c.append(g),f.serviceContainer=c.children(":last"),a.data(d,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b._getContentBounds(),h=g.width,i=g.height,j=h/2,k=i/2,l=[d[0]-j,d[1]-k,d[0]+j,d[1]+k];f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(c){var f=a(this),g=f.data("pixelSize"),j=g/e;if(g>0){j=Math.round(j*1e3)/1e3;var k=f.data("origin"),l=b._toPixel(k,d,e);f.css({left:Math.round(l[0]),top:Math.round(l[1]),width:h*j,height:i*j})}}))},refresh:function(b,c){var d=a.data(c,"geoServiceState");this._cancelUnloaded(b,c);if(d&&c&&c.style.visibility==="visible"&&!d.serviceContainer.is(":hidden")){var e=b._getBbox(),f=b._pixelSize,g=this,h=d.serviceContainer,i=b._getContentBounds(),j=i.width,k=i.height,l=h.children('[data-pixel-size="'+f+'"]'),m=c.style.opacity,n;m<1&&h.find("img").attr("data-keep-alive","0"),l.size()||(h.append('
                                        '),l=h.children(":last"));var o=c.hasOwnProperty("src")?"src":"getUrl",p={bbox:e,width:j,height:k,zoom:b._getZoom(),tile:null,index:0},q=a.isFunction(c[o]),r,s=l.position();s.left=-s.left,s.top=-s.top,q?r=c[o](p):(a.templates("geoSrc",c[o]),r=a.render.geoSrc(p)),d.loadCount++,b._requestQueued(),l.append(''),n=l.children(":last").data("center",b._center),typeof r=="string"?g._loadImage(n,r,f,b,d,m):r.done(function(a){g._loadImage(n,a,f,b,d,m)}).fail(function(){n.remove(),d.loadCount--,b._requestComplete()})}},resize:function(b,c){var d=a.data(c,"geoServiceState");if(d&&c&&c.style.visibility==="visible"){this._cancelUnloaded(b,c);var e=d.serviceContainer,f=b._getContentBounds(),g=f.width,h=f.height,i=e.children();i.attr("data-pixel-size","0"),i.each(function(c){var d=a(this),e=d.position(),f=d.data("origin"),i=b._toPixel(f);d.css({left:e.left+(g-d.width())/2,top:e.top+(h-d.height())/2})})}},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display",c.style.visibility==="visible"?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0){d.serviceContainer.find("img:hidden").remove();while(d.loadCount>0)d.loadCount--,b._requestComplete()}},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){g<1?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(':not([data-pixel-size="'+d+'"])').remove(),h.find("img[data-keep-alive]").remove(),f.loadCount=0)}).error(function(b){a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).attr("src",c)}}}()}(jQuery) \ No newline at end of file diff --git a/dist/jquery.geo-1.0.0-rc1.1.js b/dist/jquery.geo.js similarity index 99% rename from dist/jquery.geo-1.0.0-rc1.1.js rename to dist/jquery.geo.js index c65a3b8..2f996d2 100644 --- a/dist/jquery.geo-1.0.0-rc1.1.js +++ b/dist/jquery.geo.js @@ -1,4 +1,4 @@ -/*! jQuery Geo - v1.0.0-rc1.1 - 2016-06-05 +/*! jQuery Geo - v1.0.0-rc1.2 - 2016-07-14 * http://jquerygeo.com * Copyright (c) 2016 Ryan Morrison-Westphal; Licensed MIT */ // Copyright 2006 Google Inc. @@ -2499,7 +2499,7 @@ setDelimiters( "{{", "}}" ); * http://docs.jquery.com/UI/Widget */ -if ( ! $.widget ) { +if ( ! jQuery.widget ) { (function( $, undefined ) { @@ -4589,9 +4589,9 @@ $.Widget.prototype = { "class": "osm", type: "tiled", src: function (view) { - return "//otile" + ((view.index % 4) + 1) + ((location.protocol === 'https:') ? "-s" : "") + ".mqcdn.com/tiles/1.0.0/osm/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; + return "//" + String.fromCharCode(97 + (view.index % 3)) + ".tile.openstreetmap.org/" + view.zoom + "/" + view.tile.column + "/" + view.tile.row + ".png"; }, - attr: 'Tiles Courtesy of MapQuest ' + attr: '© OpenStreetMap contributors' } ], tilingScheme: { diff --git a/dist/jquery.geo.min.js b/dist/jquery.geo.min.js new file mode 100644 index 0000000..de170b6 --- /dev/null +++ b/dist/jquery.geo.min.js @@ -0,0 +1,7 @@ +/*! jQuery Geo - v1.0.0-rc1.2 - 2016-07-14 +* http://jquerygeo.com +* Copyright (c) 2016 Ryan Morrison-Westphal; Licensed MIT */ +document.createElement("canvas").getContext||!function(){function a(){return this.context_||(this.context_=new q(this))}function b(a,b,c){var d=G.call(arguments,2);return function(){return a.apply(b,d.concat(G.call(arguments)))}}function c(a,b,c){a.namespaces[b]||a.namespaces.add(b,c,"#default#VML")}function d(a){if(c(a,"g_vml_","urn:schemas-microsoft-com:vml"),c(a,"g_o_","urn:schemas-microsoft-com:office:office"),!a.styleSheets.ex_canvas_){var b=a.createStyleSheet();b.owningElement.id="ex_canvas_",b.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function e(a){var b=a.srcElement;switch(a.propertyName){case"width":b.getContext().clearRect(),b.style.width=b.attributes.width.nodeValue+"px",b.firstChild.style.width=b.clientWidth+"px";break;case"height":b.getContext().clearRect(),b.style.height=b.attributes.height.nodeValue+"px",b.firstChild.style.height=b.clientHeight+"px"}}function f(a){var b=a.srcElement;b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px",b.firstChild.style.height=b.clientHeight+"px")}function g(){return[[1,0,0],[0,1,0],[0,0,1]]}function h(a,b){for(var c=g(),d=0;3>d;d++)for(var e=0;3>e;e++){for(var f=0,h=0;3>h;h++)f+=a[d][h]*b[h][e];c[d][e]=f}return c}function i(a,b){b.fillStyle=a.fillStyle,b.lineCap=a.lineCap,b.lineJoin=a.lineJoin,b.lineWidth=a.lineWidth,b.miterLimit=a.miterLimit,b.shadowBlur=a.shadowBlur,b.shadowColor=a.shadowColor,b.shadowOffsetX=a.shadowOffsetX,b.shadowOffsetY=a.shadowOffsetY,b.strokeStyle=a.strokeStyle,b.globalAlpha=a.globalAlpha,b.font=a.font,b.textAlign=a.textAlign,b.textBaseline=a.textBaseline,b.arcScaleX_=a.arcScaleX_,b.arcScaleY_=a.arcScaleY_,b.lineScale_=a.lineScale_}function j(a){var b=a.indexOf("(",3),c=a.indexOf(")",b+1),d=a.substring(b+1,c).split(",");return(4!=d.length||"a"!=a.charAt(3))&&(d[3]=1),d}function k(a){return parseFloat(a)/100}function l(a,b,c){return Math.min(c,Math.max(b,a))}function m(a){var b,c,d,e,f,g;if(e=parseFloat(a[0])/360%360,0>e&&e++,f=l(k(a[1]),0,1),g=l(k(a[2]),0,1),0==f)b=c=d=g;else{var h=.5>g?g*(1+f):g+f-g*f,i=2*g-h;b=n(i,h,e+1/3),c=n(i,h,e),d=n(i,h,e-1/3)}return"#"+I[Math.floor(255*b)]+I[Math.floor(255*c)]+I[Math.floor(255*d)]}function n(a,b,c){return 0>c&&c++,c>1&&c--,1>6*c?a+6*(b-a)*c:1>2*c?b:2>3*c?a+(b-a)*(2/3-c)*6:a}function o(a){if(a in L)return L[a];var b,c=1;if(a=String(a),"#"==a.charAt(0))b=a;else if(/^rgb/.test(a)){for(var d,e=j(a),b="#",f=0;3>f;f++)d=-1!=e[f].indexOf("%")?Math.floor(255*k(e[f])):+e[f],b+=I[l(d,0,255)];c=+e[3]}else if(/^hsl/.test(a)){var e=j(a);b=m(e),c=e[3]}else b=a;return L[a]={color:b,alpha:c}}function p(a){return M[a]||"square"}function q(a){this.m_=g(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.strokeStyle="#000",this.fillStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=1*E,this.globalAlpha=1,this.canvas=a;var b="width:"+a.clientWidth+"px;height:"+a.clientHeight+"px;overflow:hidden;position:absolute",c=a.ownerDocument.createElement("div");c.style.cssText=b,a.appendChild(c);var d=c.cloneNode(!1);d.style.backgroundColor="red",d.style.filter="alpha(opacity=0)",a.appendChild(d),this.element_=c,this.arcScaleX_=1,this.arcScaleY_=1,this.lineScale_=1}function r(a,b,c,d){a.currentPath_.push({type:"bezierCurveTo",cp1x:b.x,cp1y:b.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y}),a.currentX_=d.x,a.currentY_=d.y}function s(a,b){var c=o(a.strokeStyle),d=c.color,e=c.alpha*a.globalAlpha,f=a.lineScale_*a.lineWidth;1>f&&(e*=f),b.push("')}function t(a,b,c,d){var e=(a.fillStyle,a.arcScaleX_,a.arcScaleY_,d.x-c.x,d.y-c.y,o(a.fillStyle)),f=e.color,g=e.alpha*a.globalAlpha;b.push('')}function u(a,b,c){var d=a.m_;return{x:E*(b*d[0][0]+c*d[1][0]+d[2][0])-F,y:E*(b*d[0][1]+c*d[1][1]+d[2][1])-F}}function v(a){return isFinite(a[0][0])&&isFinite(a[0][1])&&isFinite(a[1][0])&&isFinite(a[1][1])&&isFinite(a[2][0])&&isFinite(a[2][1])}function w(a,b,c){if(v(b)&&(a.m_=b,c)){var d=b[0][0]*b[1][1]-b[0][1]*b[1][0];a.lineScale_=D(C(d))}}function x(a){this.code=this[a],this.message=a+": DOM Exception "+this.code}var y=Math,z=y.round,A=y.sin,B=y.cos,C=y.abs,D=y.sqrt,E=10,F=E/2,G=(+navigator.userAgent.match(/MSIE ([\d.]+)?/)[1],Array.prototype.slice);d(document);var H={init:function(a){var c=a||document;c.createElement("canvas"),c.attachEvent("onreadystatechange",b(this.init_,this,c))},init_:function(a){for(var b=a.getElementsByTagName("canvas"),c=0;cJ;J++)for(var K=0;16>K;K++)I[16*J+K]=J.toString(16)+K.toString(16);var L={},M={butt:"flat",round:"round"},N=q.prototype;N.clearRect=function(){this.textMeasureEl_&&(this.textMeasureEl_.removeNode(!0),this.textMeasureEl_=null),this.element_.innerHTML=""},N.beginPath=function(){this.currentPath_=[]},N.moveTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"moveTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.lineTo=function(a,b){var c=u(this,a,b);this.currentPath_.push({type:"lineTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},N.bezierCurveTo=function(a,b,c,d,e,f){var g=u(this,e,f),h=u(this,a,b),i=u(this,c,d);r(this,h,i,g)},N.quadraticCurveTo=function(a,b,c,d){var e=u(this,a,b),f=u(this,c,d),g={x:this.currentX_+2/3*(e.x-this.currentX_),y:this.currentY_+2/3*(e.y-this.currentY_)},h={x:g.x+(f.x-this.currentX_)/3,y:g.y+(f.y-this.currentY_)/3};r(this,g,h,f)},N.arc=function(a,b,c,d,e,f){c*=E;var g=f?"at":"wa",h=a+B(d)*c-F,i=b+A(d)*c-F,j=a+B(e)*c-F,k=b+A(e)*c-F;h!=j||f||(h+=.125);var l=u(this,a,b),m=u(this,h,i),n=u(this,j,k);this.currentPath_.push({type:g,x:l.x,y:l.y,radius:c,xStart:m.x,yStart:m.y,xEnd:n.x,yEnd:n.y})},N.stroke=function(a){var b=[],c=10,d=10;b.push("f.x)&&(f.x=i.x),(null==e.y||i.yf.y)&&(f.y=i.y))}b.push(' ">'),a?t(this,b,e,f):s(this,b),b.push(""),this.element_.insertAdjacentHTML("beforeEnd",b.join(""))},N.fill=function(){this.stroke(!0)},N.closePath=function(){this.currentPath_.push({type:"close"})},N.save=function(){var a={};i(this,a),this.aStack_.push(a),this.mStack_.push(this.m_),this.m_=h(g(),this.m_)},N.restore=function(){this.aStack_.length&&(i(this.aStack_.pop(),this),this.m_=this.mStack_.pop())},N.translate=function(a,b){var c=[[1,0,0],[0,1,0],[a,b,1]];w(this,h(c,this.m_),!1)},N.scale=function(a,b){this.arcScaleX_*=a,this.arcScaleY_*=b;var c=[[a,0,0],[0,b,0],[0,0,1]];w(this,h(c,this.m_),!0)};var O=x.prototype=new Error;O.INDEX_SIZE_ERR=1,O.DOMSTRING_SIZE_ERR=2,O.HIERARCHY_REQUEST_ERR=3,O.WRONG_DOCUMENT_ERR=4,O.INVALID_CHARACTER_ERR=5,O.NO_DATA_ALLOWED_ERR=6,O.NO_MODIFICATION_ALLOWED_ERR=7,O.NOT_FOUND_ERR=8,O.NOT_SUPPORTED_ERR=9,O.INUSE_ATTRIBUTE_ERR=10,O.INVALID_STATE_ERR=11,O.SYNTAX_ERR=12,O.INVALID_MODIFICATION_ERR=13,O.NAMESPACE_ERR=14,O.INVALID_ACCESS_ERR=15,O.VALIDATION_ERR=16,O.TYPE_MISMATCH_ERR=17,G_vmlCanvasManager=H,CanvasRenderingContext2D=q,DOMException=x}(),this.jsviews||this.jQuery&&jQuery.views||function(a,b){function c(a,b){var c="\\"+a.charAt(0),d="\\"+a.charAt(1),e="\\"+b.charAt(0),f="\\"+b.charAt(1);return Q.rTag=u=d+"(?:(?:(\\w+(?=[\\/\\s"+e+"]))|(?:(\\w+)?(:)|(>)|(\\*)))\\s*((?:[^"+e+"]|"+e+"(?!"+f+"))*?)(\\/)?|(?:\\/(\\w+)))"+e,u=new RegExp(c+u+f,"g"),v=new RegExp("<.*>|"+a+".*"+b),this}function d(a){var c=this,d=c.tmpl.helpers||{};return a=(c.ctx[a]!==b?c.ctx:d[a]!==b?d:k[a]!==b?k:{})[a],"function"!=typeof a?a:function(){return a.apply(c,arguments)}}function e(a,b,c){var d=b.tmpl.converters;return a=d&&d[a]||l[a],a?a.call(b,c):c}function f(a,c,d,e,f){f.props=f.props||{};var g,h=f.props.tmpl,k=c.tmpl.tags,l=c.tmpl.templates,n=arguments,o=k&&k[a]||j[a];return o?(e=e&&c.tmpl.tmpls[e-1],h=h||e||b,f.tmpl=""+h===h?l&&l[h]||i[h]||i(h):h,f.isTag=A,f.converter=d,f.view=c,f.renderContent=m,c.ctx&&w(f.ctx,c.ctx),g=o.apply(f,n.length>5?O.call(n,5):[]),g||(g==b?"":g.toString())):""}function g(a,c,e,f,g,h){var i=e.views,j={tmpl:g,path:c,parent:e,data:f,ctx:a,views:t.isArray(f)?[]:{},hlp:d};return t.isArray(i)?i.splice(j.index=h!==b?h:i.length,0,j):i[j.index="_"+I++]=j,j}function h(a,c,d,e,f){var g,h;if(d&&"object"==typeof d&&!d.nodeType){for(g in d)c(g,d[g]);return a}return d&&e!==b?""+d===d&&(null===e?delete c[d]:(e=f?f(d,e):e)&&(c[d]=e)):f&&(e=f(b,e||d)),(h=y.onStoreItem)&&h(c,d,e,f),e}function i(a,b){return h(this,i,a,b,q)}function j(a,b){return h(this,j,a,b)}function k(a,b){return h(this,k,a,b)}function l(a,b){return h(this,l,a,b)}function m(a,c,d,e,f){var h,j,k,l,m,n,o,p,q,r,s={},u=f===A,v=this,x="";if(v.isTag?(q=v.tmpl,c=c||v.ctx,d=d||v.view,e=e||v.path,f=f||v.index,s=v.props):q=v.jquery&&v[0]||v,d=d||Q.topView,p=d.ctx,r=q.layout,a===d&&(a=d.data,r=A),c=c&&c===p?p:p?(p=w({},p),c?w(p,c):p):c||{},s.link===z&&(c.link=z),q.fn||(q=i[q]||i(q)),m=c.link&&y.onRenderItem,n=c.link&&y.onRenderItems,q){if(t.isArray(a)&&!r)for(l=u?d:f!==b&&d||g(c,e,d,a,q,f),h=0,j=a.length;j>h;h++)k=a[h],o=q.fn(k,g(c,e,l,k,q,(f||0)+h),Q),x+=m?m(o,s):o;else l=u?d:g(c,e,d,a,q,f),x+=a||r?q.fn(a,l,Q):"";return d.topKey=l.index,n?n(x,e,l.index,q,s):x}return""}function n(){throw"Syntax error"}function o(a,b,c){function d(b){b-=D,b&&J.push(a.substr(D,b).replace(E,"\\n"))}function e(b,e,g,h,i,j,k,l,m,n){i&&(h=":",g="html");var o="",q="",r=!l&&!h;if(e=e||h,d(n),D=n+b.length,j?y&&J.push(["*",k.replace(F,"$1")]):e?("else"===e&&(K[5]=a.substring(K[5],n),K=I.pop(),J=K[3],r=A),k=k?p(k,c).replace(H,function(a,b,c){return b?q+=c+",":o+=c+",",""}):"",o=o.slice(0,-1),k=k.slice(0,-1),f=[e,g||"",k,r&&[],"{"+(o?"props:{"+o+"},":"")+"path:'"+k+"'"+(q?",ctx:{"+q.slice(0,-1)+"}":"")+"}"],r&&(I.push(K),K=f,K[5]=D),J.push(f)):m&&(K[5]=a.substring(K[5],n),K=I.pop()),!K)throw"Expected block tag";J=K[3]}var f,g,h,i,j,k,l,m,n,q,s,t,v,w,x,y,z=b?{allowCode:y=b.allowCode,debug:b.debug}:{},B=b&&b.tmpls,C=[],D=0,I=[],J=C,K=[,,,C],L=0;for(a=a.replace(G,"\\$1"),a.replace(u,e),d(a.length),i=C.length,j=i?"":'"";',h=0;i>h;h++)g=C[h],"*"===g[0]?j=j.slice(0,h?-1:-3)+";"+g[1]+(i>h+1?"ret+=":""):""+g===g?j+='"'+g+'"+':(s=g[0],t=g[1],v=g[2],J=g[3],w=g[4],a=g[5],J&&(x=r(a,z,b,L++),o(a,x),B.push(x)),q=q||w.indexOf("view")>-1,j+=(":"===s?"html"===t?(l=A,"e("+v):t?(n=A,'c("'+t+'",view,'+v):(m=A,"((v="+v+')!=u?v:""'):(k=A,'t("'+s+'",view,"'+(t||"")+'",'+(J?B.length:'""')+","+w+(v?",":"")+v))+")+");return j=new Function("data, view, j, b, u",M+(m?"v,":"")+(k?"t=j.tag,":"")+(n?"c=j.convert,":"")+(l?"e=j.converters.html,":"")+"ret; try{\n\n"+(z.debug?"debugger;":"")+(y?"ret=":"return ")+j.slice(0,-1)+";\n\n"+(y?"return ret;":"")+"}catch(e){return j.err(e);}"),b&&(b.fn=j,b.useVw=n||q||k),j}function p(a,b){function c(a,c,i,j,k,l,m,o,p,q,r,s,t,u,v,w){function x(a,c,d,e,f,g,h){if(c){var i=(d?'view.hlp("'+d+'")':e?"view":"data")+(h?(f?"."+f:d?"":e?"":"."+c)+(g||""):(h=d?"":e?f||"":c,""));return b&&"("!==p&&(i="b("+i+',"'+h+'")'),i+(h?"."+h:"")}return a}return k=k||"",i=i||c||r,j=j||o,p=p||v||"",k=k||"",l?void n():h?(h=!s,h?a:'"'):g?(g=!t,g?a:'"'):(i?(f++,i):"")+(w?f?"":d?(d=z,"\b"):",":m?(f&&n(),d=A,"\b"+j+":"):j?j.replace(C,x)+(p?(e[++f]=A,p):k):k?a:u?(e[f--]=z,u+(p?(e[++f]=A,p):"")):q?(e[f]||n(),","):c?"":(h=s,g=t,'"'))}var d,e={},f=0,g=z,h=z;return a=(a+" ").replace(D,c)}function q(a,c,d,e){function f(b){return""+b===b||b.nodeType>0?(h=b.nodeType>0?b:!v.test(b)&&B&&B(b)[0],h&&h.type&&(b=i[h.getAttribute(L)],b||(a=a||"_"+J++,h.setAttribute(L,a),b=q(a,h.innerHTML,d,e),i[a]=b)),b):void 0}var g,h,j,k,l;if(g=f(c),e=e||(c.markup?c:{}),e.name=a,k=e.templates,!g&&c.markup&&(g=f(c.markup))&&(!g.fn||g.debug===c.debug&&g.allowCode===c.allowCode||(g=g.markup)),g!==b){a&&!d&&(P[a]=function(){return c.render.apply(c,arguments)}),g.fn||c.fn?g.fn&&(c=a&&a!==g.name?w(w({},g),e):g):(c=r(g,e,d,0),o(g,c));for(j in k)l=k[j],l.name!==j&&(k[j]=q(j,l,c));return c}}function r(a,b,c,d){function e(a){c[a]&&(f[a]=w(w({},c[a]),b[a]))}b=b||{};var f={markup:a,tmpls:[],links:[],render:m};return c&&(c.templates&&(f.templates=w(w({},c.templates),b.templates)),f.parent=c,f.name=c.name+"["+d+"]",f.index=d),w(f,b),c&&(e("templates"),e("tags"),e("helpers"),e("converters")),f}function s(a){return K[a]||(K[a]="&#"+a.charCodeAt(0)+";")}var t,u,v,w,x="v1.0pre",y={},z=!1,A=!0,B=a.jQuery,C=/^(?:null|true|false|\d[\d.]*|([\w$]+|~([\w$]+)|#(view|([\w$]+))?)([\w$.]*?)(?:[.[]([\w$]+)\]?)?|(['"]).*\8)$/g,D=/(\()(?=|\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*([)\]])([([]?))|(\s+)/g,E=/\r?\n/g,F=/\\(['"])/g,G=/\\?(['"])/g,H=/\x08(~)?([^\x08]+)\x08/g,I=0,J=0,K={"&":"&","<":"<",">":">"},L="data-jsv-tmpl",M="var j=j||"+(B?"jQuery.":"js")+"views,",N=/[\x00"&'<>]/g,O=Array.prototype.slice,P={},Q={jsviews:x,sub:y,debugMode:A,err:function(a){return Q.debugMode?"
                                        Error: "+(a.message||a)+". ":'""'},tmplFn:o,render:P,templates:i,tags:j,helpers:k,converters:l,View:g,convert:e,delimiters:c,tag:f};B?(t=B,t.templates=i,t.render=P,t.views=Q,t.fn.render=m):(t=a.jsviews=Q,t.extend=function(a,b){var c;a=a||{};for(c in b)a[c]=b[c];return a},t.isArray=Array&&Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)}),w=t.extend,Q.topView={views:{},tmpl:{},hlp:d,ctx:Q.helpers},j({"if":function(){var a=this,c=a.view;return c.onElse=function(a,d){for(var e=0,f=d.length;f&&!d[e++];)if(e===f)return"";return c.onElse=b,a.path="",a.renderContent(c)},c.onElse(this,arguments)},"else":function(){var a=this.view;return a.onElse?a.onElse(this,arguments):""},"for":function(){var a,b=this,c="",d=arguments,e=d.length;for(b.props.layout&&(b.tmpl.layout=A),a=0;e>a;a++)c+=b.renderContent(d[a]);return c},"=":function(a){return a},"*":function(a){return a}}),l({html:function(a){return a!=b?String(a).replace(N,s):""}}),c("{{","}}")}(this),function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})}),jQuery.widget||!function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d,e=0;null!=(d=b[e]);e++)try{a(d).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){return c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}}),d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e,f=b.split(".")[0];b=b.split(".")[1],e=f+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][e]=function(c){return!!a.data(c,b)},a[f]=a[f]||{},a[f][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[f][b].prototype=a.extend(!0,g,{namespace:f,widgetName:b,widgetEventPrefix:a[f][b].prototype.widgetEventPrefix||b,widgetBaseClass:e},d),a.widget.bridge(b,a[f][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f="string"==typeof e,g=Array.prototype.slice.call(arguments,1),h=this;return e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e,f&&"_"===e.charAt(0)?h:(f?this.each(function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;return f!==d&&f!==b?(h=f,!1):void 0}):this.each(function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))}),h)}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(0===arguments.length)return a.extend({},this.options);if("string"==typeof c){if(d===b)return this.options[c];e={},e[c]=d}return this._setOptions(e),this},_setOptions:function(b){var c=this;return a.each(b,function(a,b){c._setOption(a,b)}),this},_setOption:function(a,b){return this.options[a]=b,"disabled"===a&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",b),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];if(d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}}(jQuery),function(a,b,c){b.toStaticHTML=b.toStaticHTML||function(a){return a};var d=Number.POSITIVE_INFINITY,e=Number.NEGATIVE_INFINITY;a.geo={_allCoordinates:function(b){for(var c=this._flatten(b),d=0,e=[];d1&&!a.isArray(b[0]))return b[0]>=-180.001&&b[0]<=180.001&&b[1]>=-90.001&&b[1]<=90.001;b=b[0]}return!1},center:function(b,c){var d=!1;!c&&a.geo.proj&&this._isGeodetic(b)&&(d=!0,b=a.geo.proj.fromGeodetic(b));var e=[(b[0]+b[2])/2,(b[1]+b[3])/2];return d?a.geo.proj.toGeodetic(e):e},expandBy:function(b,c,d,e){var f=!1;return!e&&a.geo.proj&&this._isGeodetic(b)&&(f=!0,b=a.geo.proj.fromGeodetic(b)),b=[b[0]-c,b[1]-d,b[2]+c,b[3]+d],f?a.geo.proj.toGeodetic(b):b},height:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[3]-b[1]},_in:function(a,b){return a[0]<=b[0]&&a[1]<=b[1]&&a[2]>=b[2]&&a[3]>=b[3]},_bboxDisjoint:function(a,b){return b[0]>a[2]||b[2]a[3]||b[3]0&&(h/i>c?(f=h/2,g=f/c):(g=i/2,f=g*c),b=[j[0]-f,j[1]-g,j[0]+f,j[1]+g]),e?a.geo.proj.toGeodetic(b):b},recenter:function(b,c,d){var e=!1;!d&&a.geo.proj&&(this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b)),this._isGeodetic(c)&&(c=a.geo.proj.fromGeodetic(c)));var f=(b[2]-b[0])/2,g=(b[3]-b[1])/2;return b=[c[0]-f,c[1]-g,c[0]+f,c[1]+g],e?a.geo.proj.toGeodetic(b):b},scaleBy:function(b,c,d){var e=!1;!d&&a.geo.proj&&this._isGeodetic(b)&&(e=!0,b=a.geo.proj.fromGeodetic(b));var f=this.center(b,!0),g=(b[2]-b[0])*c/2,h=(b[3]-b[1])*c/2;return b=[f[0]-g,f[1]-h,f[0]+g,f[1]+h],e?a.geo.proj.toGeodetic(b):b},width:function(b,c){return!c&&a.geo.proj&&this._isGeodetic(b)&&(b=a.geo.proj.fromGeodetic(b)),b[2]-b[0]},bbox:function(b,f){var g,h=!1;if(!b)return c;if(b.bbox)g=!f&&a.geo.proj&&this._isGeodetic(b.bbox)?a.geo.proj.fromGeodetic(b.bbox):b.bbox;else{g=[d,d,e,e];var i=this._allCoordinates(b),j=0;if(0===i.length)return c;for(!f&&a.geo.proj&&this._isGeodetic(i)&&(h=!0,i=a.geo.proj.fromGeodetic(i));j0?(g[0]=Math.min(Math.max(k[0][0],m[0]),m[2]),g[1]=Math.min(Math.max(k[0][1],m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g}):c:(j*=3,g[0]=Math.min(Math.max(g[0]/j,m[0]),m[2]),g[1]=Math.min(Math.max(g[1]/j,m[1]),m[3]),{type:"Point",coordinates:n?a.geo.proj.toGeodetic(g):g});case"MultiPoint":if(b.coordinates.length>0)return g=b.coordinates[0],{type:"Point",coordinates:[g[0],g[1]]};break;case"MultiLineString":case"MultiPolygon":if(b.coordinates.length>0)return this.centroid({type:b.type.substr(5),coordinates:b.coordinates[0]},f)}return c},contains:function(a,b){if("Polygon"!==a.type)return!1;switch(b.type){case"Point":return this._containsPolygonPoint(a.coordinates,b.coordinates);case"LineString":return this._containsPolygonLineString(a.coordinates,b.coordinates);case"Polygon":return this._containsPolygonLineString(a.coordinates,b.coordinates[0]);default:return!1}},_containsPolygonPoint:function(a,b){if(0===a.length||a[0].length<4)return!1;for(var c,d,e=0,f=a[0][0],g=1;gb[0]&&e++),f=c;return e%2===1},_containsPolygonLineString:function(a,b){for(var c=0;c0){var e=a[0],f=b[0]-e[0],g=b[1]-e[1];if(1===a.length)return Math.sqrt(f*f+g*g);for(var h=1;hn&&(c=n),e=i,f=l,g=m}}return Math.sqrt(c)},_distanceSegmentPoint:function(a,b,c,d,e,f){var g=a*c+b*d;if(0>=g)return c*c+d*d;var h=a*a+b*b;return g>=h?e*e+f*f:c*c+d*d-g*g/h},_distanceLineStringLineString:function(a,b){for(var c=d,e=0;e=k;k++)h=360*k/j*(Math.PI/180),i.push([g[0]+Math.cos(h)*d,g[1]+Math.sin(h)*d]);return{type:"Polygon",coordinates:[f?a.geo.proj.toGeodetic(i):i]}}return c},_basic:function(a){for(var b,c,d=[],e=0,f=this._flatten(a);eo;q++)n=o,o+=p[q]/m;return e=c-n,k=g[q-1],l=g[q],j=[k[0]+e*(l[0]-k[0]),k[1]+e*(l[1]-k[1])],{type:"Point",coordinates:r?a.geo.proj.toGeodetic(j):j}}},WKT:function(){function b(a){return"POINT "+c(a.coordinates)}function c(a){return a&&a.length?"("+a.join(" ")+")":"EMPTY"}function d(a){return"LINESTRING "+e(a.coordinates)}function e(a){if(a&&a.length){for(var b=[],c=0;c2?{type:"Point",coordinates:[parseFloat(b[1]),parseFloat(b[2])]}:null}function p(a){var b,c,d=a.match(/\s*\((.*)\)/),e=[],f=0;if(d&&d.length>1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f1){for(b=d[1].match(/[\d\.\-]+\s+[\d\.\-]+/g);f0){for(;g
                                        ";while(c[0]);return a>6?a:!a}();a.widget("geo.geographics",{_$elem:c,_options:{},_trueCanvas:!0,_trueDoubleBuffer:!0,_width:0,_height:0,_$canvas:c,_context:c,_$canvasSceneFront:c,_$canvasSceneBack:c,_$canvasSceneStale:c,_$canvasSceneDrawn:c,_timeoutEnd:null,_requireFlip:!1,_blitcanvas:c,_blitcontext:c,_$labelsContainerFront:c,_$labelsContainerBack:c,_labelsHtml:"",options:{style:{borderRadius:"8px",color:"#7f0000",fillOpacity:.2,height:"8px",opacity:1,strokeOpacity:1,strokeWidth:"2px",visibility:"visible",width:"8px"},doubleBuffer:!0},_create:function(){this._$elem=this.element,this._options=this.options,this._$elem.css({webkitTransform:"translateZ(0)",display:"inline-block",overflow:"hidden",textAlign:"left"}),"static"===this._$elem.css("position")&&this._$elem.css("position","relative"),this._$elem.addClass("geo-graphics"),this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10));var c="position:absolute;left:0;top:0;margin:0;padding:0;",e="width:"+this._width+"px;height:"+this._height+"px;",f='width="'+this._width+'" height="'+this._height+'"';this._blitcanvas=document.createElement("canvas"),this._blitcanvas.getContext?(this._$canvas=a(b.toStaticHTML("')),this._blitcanvas.width=1,this._blitcanvas.height=1,this._trueDoubleBuffer=this._blitcanvas.toDataURL().length>6,this._options.doubleBuffer&&this._trueDoubleBuffer||this._$elem.append(this._$canvas),this._context=this._$canvas[0].getContext("2d"),this._blitcanvas.width=this._width,this._blitcanvas.height=this._height,this._blitcontext=this._blitcanvas.getContext("2d"),this._$canvasSceneFront=a(b.toStaticHTML('')).on("load",a.proxy(this._canvasImgLoad,this)),this._$canvasSceneBack=a(b.toStaticHTML('')).on("load",a.proxy(this._canvasImgLoad,this))):8>=d&&(this._trueCanvas=!1,this._$elem.append("
                                        '),this._$canvas=this._$elem.children(":last"),G_vmlCanvasManager.initElement(this._$canvas[0]),this._context=this._$canvas[0].getContext("2d"),this._$canvas.children().css({backgroundColor:"transparent",width:this._width,height:this._height})),this._$labelsContainerFront=a(b.toStaticHTML('
                                        ')),this._$labelsContainerBack=a(b.toStaticHTML('
                                        '))},_setOption:function(b,c){"style"===b&&(c=a.extend({},this._options.style,c)),a.Widget.prototype._setOption.apply(this,arguments)},destroy:function(){a.Widget.prototype.destroy.apply(this,arguments),this._$elem.html(""),this._$elem.removeClass("geo-graphics")},clear:function(){this._context.clearRect(0,0,this._width,this._height),this._labelsHtml="",this._end()},drawArc:function(a,b,c,d){if(d=this._getGraphicStyle(d),"hidden"!==d.visibility&&d.opacity>0&&d.widthValue>0&&d.heightValue>0){var e=Math.min(d.widthValue,d.heightValue)/2;b=b*Math.PI/180,c=c*Math.PI/180,this._context.save(),this._context.translate(a[0],a[1]),d.widthValue>d.heightValue?this._context.scale(d.widthValue/d.heightValue,1):this._context.scale(1,d.heightValue/d.widthValue),this._context.beginPath(),this._context.arc(0,0,e,b,c,!1),this._trueCanvas&&this._context.restore(),d.doFill&&(this._context.fillStyle=d.fill,this._context.globalAlpha=d.opacity*d.fillOpacity,this._context.fill()),d.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=d.strokeWidthValue,this._context.strokeStyle=d.stroke,this._context.globalAlpha=d.opacity*d.strokeOpacity,this._context.stroke()),this._trueCanvas||this._context.restore()}this._end()},drawPoint:function(a,b){b=this._getGraphicStyle(b),b.widthValue===b.heightValue&&b.heightValue===b.borderRadiusValue?this.drawArc(a,0,360,b):"hidden"!==b.visibility&&b.opacity>0&&(b.borderRadiusValue=Math.min(Math.min(b.widthValue,b.heightValue)/2,b.borderRadiusValue),a[0]-=b.widthValue/2,a[1]-=b.heightValue/2,this._context.beginPath(),this._context.moveTo(a[0]+b.borderRadiusValue,a[1]),this._context.lineTo(a[0]+b.widthValue-b.borderRadiusValue,a[1]),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1],a[0]+b.widthValue,a[1]+b.borderRadiusValue),this._context.lineTo(a[0]+b.widthValue,a[1]+b.heightValue-b.borderRadiusValue),this._context.quadraticCurveTo(a[0]+b.widthValue,a[1]+b.heightValue,a[0]+b.widthValue-b.borderRadiusValue,a[1]+b.heightValue),this._context.lineTo(a[0]+b.borderRadiusValue,a[1]+b.heightValue),this._context.quadraticCurveTo(a[0],a[1]+b.heightValue,a[0],a[1]+b.heightValue-b.borderRadiusValue),this._context.lineTo(a[0],a[1]+b.borderRadiusValue),this._context.quadraticCurveTo(a[0],a[1],a[0]+b.borderRadiusValue,a[1]),this._context.closePath(),b.doFill&&(this._context.fillStyle=b.fill,this._context.globalAlpha=b.opacity*b.fillOpacity,this._context.fill()),b.doStroke&&(this._context.lineJoin="round",this._context.lineWidth=b.strokeWidthValue,this._context.strokeStyle=b.stroke,this._context.globalAlpha=b.opacity*b.strokeOpacity,this._context.stroke()),this._end())},drawLineString:function(a,b){this._drawLines([a],!1,b)},drawPolygon:function(a,b){if(this._trueCanvas&&1!==a.length){if(!a||!a.length||a[0].length<3)return;b=this._getGraphicStyle(b),this._blitcontext.globalCompositeOperation="copy";var c,d,e;if("hidden"!==b.visibility&&b.opacity>0){if(this._blitcontext.clearRect(0,0,this._width,this._height),b.doFill&&a.length>1){for(this._blitcontext.globalCompositeOperation="source-out",this._blitcontext.globalAlpha=1,this._blitcontext.beginPath(),d=1;d1))for(d=1;d'+b+""},resize:function(a,b){this._width=this._$elem.width(),this._height=this._$elem.height(),this._width&&this._height||(this._width=parseInt(this._$elem.css("width"),10),this._height=parseInt(this._$elem.css("height"),10)),this._trueCanvas?(this._$canvas[0].width=this._width,this._$canvas[0].height=this._height,this._$canvasSceneFront.css({left:a,top:b}),this._$canvasSceneBack.css({width:this._width,height:this._height})):this._$canvas.css({width:this._width,height:this._height});var c=this._$labelsContainerFront.position();this._$labelsContainerFront.css({left:c.left+a,top:c.top+b,width:this._width,height:this._height}),this._$labelsContainerBack.css({width:this._width,height:this._height})},interactiveTransform:function(a,b){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._trueCanvas&&this._options.doubleBuffer&&this._trueDoubleBuffer?(this._canvasSceneLoad(),this._$canvasSceneFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})):this._context.clearRect(0,0,this._width,this._height),this._$labelsContainerFront.css({left:Math.round(a[0]),top:Math.round(a[1]),width:this._width*b,height:this._height*b})},_canvasImgLoad:function(){var a=this;a._$canvasSceneFront=a._$canvasSceneDrawn.prependTo(a._$elem),a._$canvasSceneBack=a._$canvasSceneStale,a._$canvasSceneBack.detach()},_canvasSceneLoad:function(){var a=this;a._requireFlip&&(a._requireFlip=!1,a._$canvasSceneStale=a._$canvasSceneFront,a._$canvasSceneDrawn=a._$canvasSceneBack.css({left:0,top:0,width:a._width,height:a._height}).prop("src",a._$canvas[0].toDataURL()))},_endCallback:function(){var a=this;if(a._timeoutEnd){a._trueCanvas&&a._options.doubleBuffer&&a._trueDoubleBuffer&&this._canvasSceneLoad(),a._$labelsContainerBack.html(b.toStaticHTML(a._labelsHtml)).find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"});var c=a._$labelsContainerFront;a._$labelsContainerFront=a._$labelsContainerBack.css({left:0,top:0,width:a._width,height:a._height}).appendTo(a._$elem),a._$labelsContainerBack=c.detach(),a._timeoutEnd=null}},_end:function(){this._timeoutEnd&&(clearTimeout(this._timeoutEnd),this._timeoutEnd=null),this._requireFlip=!0,this._timeoutEnd=setTimeout(a.proxy(this._endCallback,this),20)},_getGraphicStyle:function(b){function c(a){return a=parseInt(a,10),+a+""===a?+a:a}return b=a.extend({},this._options.style,b),b.borderRadiusValue=c(b.borderRadius),b.fill=b.fill||b.color,b.doFill=b.fill&&b.fillOpacity>0,b.stroke=b.stroke||b.color,b.strokeWidthValue=c(b.strokeWidth),b.doStroke=b.stroke&&b.strokeOpacity>0&&b.strokeWidthValue>0,b.widthValue=c(b.width),b.heightValue=c(b.height),b},_drawLines:function(a,b,c){if(a&&a.length&&!(a[0].length<2)){var d,e;if(c=this._getGraphicStyle(c),"hidden"!==c.visibility&&c.opacity>0){for(this._context.beginPath(),d=0;d
                                        ";while(c[0]);return a>6?a:!a}(),f=function(){return(navigator.userAgent.match(/gecko\/*\d/i)||[]).length>0}(),g={bbox:[-180,-85,180,85],bboxMax:[-180,-85,180,85],center:[0,0],cursors:{"static":"default",pan:"url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAgACAAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAA//AAAd/wAAGf+AAAH9gAADbYAAA2yAAAZsAAAGbAAAAGAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//4AB//8AAf//AAD//5AA///gAP//4AD//8AF///AB///5A////5///8=), move",click:"crosshair",zoom:"crosshair",dragBox:"crosshair",dragCircle:"crosshair",drawPoint:"crosshair",drawLineString:"crosshair",drawPolygon:"crosshair",measureLength:"crosshair",measureArea:"crosshair"},measureLabels:{length:"{{:length.toFixed( 2 )}} m",area:"{{:area.toFixed( 2 )}} sq m"},drawStyle:{},shapeStyle:{},mode:"pan",pannable:!0,scroll:"default",shift:"default",services:[{"class":"osm",type:"tiled",src:function(a){return"//"+String.fromCharCode(97+a.index%3)+".tile.openstreetmap.org/"+a.zoom+"/"+a.tile.column+"/"+a.tile.row+".png"},attr:'© OpenStreetMap contributors'}],tilingScheme:{tileWidth:256,tileHeight:256,levels:18,basePixelSize:156543.03392799935,origin:[-20037508.342787,20037508.342787]},axisLayout:"map",zoom:0,zoomMin:0,zoomMax:Number.POSITIVE_INFINITY,zoomFactor:2,pixelSize:0};a.widget("geo.geomap",{_$elem:c,_map:c,_created:!1,_createdGraphics:!1,_widgetId:0,_tmplLengthId:"",_tmplAreaId:"",_contentBounds:{},_$resizeContainer:c,_$eventTarget:c,_$contentFrame:c,_$existingChildren:c,_$attrList:c,_$servicesContainer:c,_$shapesContainers:c,_$panContainer:c,_$shapesContainer:c,_$drawContainer:c,_$measureContainer:c,_$measureLabel:c,_dpi:96,_currentServices:[],_center:c,_pixelSize:c,_centerMax:c,_pixelSizeMax:c,_pixelSizeMin:c,_userGeodetic:!0,_centerInteractive:c,_pixelSizeInteractive:c,_timeoutInteractive:null,_timeoutWheel:null,_triggerInteractive:!1,_timeoutRefreshShapes:null,_loadCount:0,_wheelLevel:0,_fullZoomFactor:2,_partialZoomFactor:1.18920711500273,_mouseDown:c,_inOp:c,_toolPan:c,_shiftDown:c,_anchor:c,_current:c,_downDate:c,_moveDate:c,_clickDate:c,_lastMove:c,_lastDrag:c,_windowHandler:null,_resizeTimeout:null,_panning:c,_velocity:c,_friction:c,_pointerEvents:c,_supportTouch:c,_softDblClick:c,_isTap:c,_isDbltap:c,_isMultiTouch:c,_multiTouchAnchor:[],_multiTouchAnchorBbox:c,_multiTouchCurrentBbox:c,_drawTimeout:null,_drawPixels:[],_drawCoords:[],_graphicShapes:[],_initOptions:{},_options:{},options:a.extend({},g),_createWidget:function(b,c){if(this._$elem=a(c),this._$elem.is(".geo-service"))return this._graphicShapes=[],void a.Widget.prototype._createWidget.apply(this,arguments);this._widgetId=d++,this._serviceIdSeed=0,this._tmplLengthId="geoMeasureLength"+this._widgetId,this._tmplAreaId="geoMeasureArea"+this._widgetId,this._$elem.addClass("geo-map").css({webkitTransform:"translateZ(0)",touchAction:"none"}),this._initOptions=b||{},this._forcePosition(this._$elem),this._$elem.css("text-align","left");var e=this._findMapSize();this._contentBounds={x:parseInt(this._$elem.css("padding-left"),10),y:parseInt(this._$elem.css("padding-top"),10),width:e.width,height:e.height},this._createChildren(),this._center=[0,0],this._centerMax=[0,0],this._centerInteractive=[0,0],this.options.pixelSize=this._pixelSize=this._pixelSizeMax=156543.03392799935,this._pixelSizeMin=this._pixelSizeMax/Math.pow(2,17),this._mouseDown=this._inOp=this._toolPan=this._shiftDown=this._panning=this._isTap=this._isDbltap=this._isMultiTouch=!1,this._anchor=[0,0],this._current=[0,0],this._lastMove=[0,0],this._lastDrag=[0,0],this._velocity=[0,0],this._friction=[.8,.8],this._downDate=this._moveDate=this._clickDate=0,this._drawPixels=[],this._drawCoords=[],this._graphicShapes=[],a.Widget.prototype._createWidget.apply(this,arguments)},_create:function(){if(this._options=this.options,this._$elem.is(".geo-service"))return this._map=this._$elem.data("geoMap"),void this._$elem.data("geoService",this);this._map=this,this._pointerEvents=b.PointerEvent,this._supportTouch="ontouchend"in document,this._softDblClick=this._pointerEvents||this._supportTouch||7===e;var d=this,g=this._pointerEvents?"pointerdown":this._supportTouch?"touchstart mousedown":"mousedown",h=this._pointerEvents?"pointerup pointercancel":this._supportTouch?"touchend touchcancel mouseup":"mouseup",i=this._pointerEvents?"pointermove":this._supportTouch?"touchmove mousemove":"mousemove";a(document).keydown(a.proxy(this._document_keydown,this)),this._softDblClick?this._$eventTarget.on("softdblclick",a.proxy(this._eventTarget_dblclick,this)):this._$eventTarget.dblclick(a.proxy(this._eventTarget_dblclick,this)),this._$eventTarget.bind(g,a.proxy(this._eventTarget_touchstart,this));var j=this._$eventTarget[0].setCapture||this._pointerEvents?this._$eventTarget:a(document);j.bind(i,a.proxy(this._dragTarget_touchmove,this)),j.bind(h,a.proxy(this._dragTarget_touchstop,this)),this._$eventTarget.mousewheel(a.proxy(this._eventTarget_mousewheel,this)),this._windowHandler=function(){d._resizeTimeout&&clearTimeout(d._resizeTimeout),d._resizeTimeout=setTimeout(function(){d._created&&d._$elem.geomap("resize",!0)},500)},a(b).resize(this._windowHandler),this._$drawContainer.geographics({style:this._initOptions.drawStyle||{},doubleBuffer:!1}),this._options.drawStyle=this._$drawContainer.geographics("option","style"),this._$shapesContainer.geographics({style:this._initOptions.shapeStyle||{},doubleBuffer:!f}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style"),this._initOptions&&(this._initOptions.tilingScheme!==c&&this._setOption("tilingScheme",this._initOptions.tilingScheme||null,!1),this._initOptions.services&&(this._options.services=a.merge([],this._initOptions.services)),this._initOptions.bboxMax&&(this._setOption("bboxMax",this._initOptions.bboxMax,!1),this._setOption("bbox",this._initOptions.bboxMax,!1)),this._initOptions.zoomMin!==c&&this._setOption("zoomMin",this._initOptions.zoomMin,!1),this._initOptions.zoomMax!==c&&this._setOption("zoomMax",this._initOptions.zoomMax,!1),this._initOptions.zoomFactor!==c&&(this._setOption("zoomFactor",this._initOptions.zoomFactor,!1),this._fullZoomFactor=this._initOptions.zoomFactor,this._partialZoomFactor=Math.pow(4,1/this._fullZoomFactor)),this._initOptions.bbox&&this._setOption("bbox",this._initOptions.bbox,!1),this._initOptions.center&&this._setOption("center",this._initOptions.center,!1),this._initOptions.zoom!==c&&this._setOption("zoom",this._initOptions.zoom,!1)),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area),this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._createServices(),this._refresh(),this._created=!0},_setOption:function(b,d,e){if("pixelSize"!==b){e=e===c||e,this._$elem.is(".geo-map")&&this._panFinalize();var f,g,h,i;switch(b){case"bbox":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),f=[d[0]+(d[2]-d[0])/2,d[1]+(d[3]-d[1])/2],g=Math.max(a.geo.width(d,!0)/this._contentBounds.width,a.geo.height(d,!0)/this._contentBounds.height),i=this._getZoom(f,g),this._options.tilingScheme?g=this._getPixelSize(Math.min(Math.max(i,this._options.zoomMin),this._options.zoomMax)):ithis._options.zoomMax&&(g=this._getPixelSize(this._options.zoomMax)),this._created?(this._setInteractiveCenterAndSize(f,g),this._setInteractiveTimeout(!1)):this._setCenterAndSize(f,g,!1,e),d=this._getBbox(f,g);break;case"bboxMax":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d);break;case"center":this._created&&this._clearInteractiveTimeout(),this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj&&a.geo._isGeodetic(d),this._userGeodetic&&(d=a.geo.proj.fromGeodetic(d)),this._created?(this._setInteractiveCenterAndSize(d,this._pixelSizeInteractive),this._interactiveTransform(),this._setInteractiveTimeout(!1)):this._setCenterAndSize(d,this._pixelSize,!1,e);break;case"measureLabels":d=a.extend(this._options.measureLabels,d),a.templates(this._tmplLengthId,this._options.measureLabels.length),a.templates(this._tmplAreaId,this._options.measureLabels.area);break;case"drawStyle":this._$drawContainer&&(this._$drawContainer.geographics("option","style",d),d=this._$drawContainer.geographics("option","style"));break;case"shapeStyle":this._$elem.is(".geo-service")&&!this._createdGraphics&&this._createServiceGraphics(),this._createdGraphics&&(this._$shapesContainer.geographics("option","style",d),d=this._$shapesContainer.geographics("option","style"));break;case"mode":this._resetDrawing(),this._$eventTarget.css("cursor",this._options.cursors[d]);break;case"zoom":this._userGeodetic="map"===this._options.axisLayout&&a.geo.proj,this._created?this._setZoom(d,!1,e):(d=Math.max(d,0),this._setCenterAndSize(this._center,this._getPixelSize(d),!1,e))}switch(a.Widget.prototype._setOption.apply(this,arguments),b){case"bbox":case"center":this._userGeodetic&&(this._options.bbox=a.geo.proj.toGeodetic(this._options.bbox),this._options.center=a.geo.proj.toGeodetic(this._center));break;case"tilingScheme":null!==d&&(this._pixelSizeMax=this._getPixelSize(0),this._pixelSizeMin=this._getPixelSize(d.pixelSizes?d.pixelSizes.length-1:d.levels-1),this._centerMax=[d.origin[0]+this._pixelSizeMax*d.tileWidth/2,d.origin[1]+this._pixelSizeMax*d.tileHeight/2]);break;case"bboxMax":h=this._userGeodetic?a.geo.proj.fromGeodetic(d):d,this._centerMax=a.geo.center(h),this._pixelSizeMax=Math.max(a.geo.width(h,!0)/this._contentBounds.width,a.geo.height(h,!0)/this._contentBounds.height);break;case"services":this._createServices(),e&&(this._refresh(),this._refreshAllShapes());break;case"shapeStyle":e&&this._createdGraphics&&(this._$shapesContainer.geographics("clear"),this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))}}},destroy:function(){if(this._$elem.is(".geo-service"))this._createdGraphics&&(this._$shapesContainer.geographics("destroy"),this._$shapesContainer=c,this._createdGraphics=!1);else{clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,this._created=!1,a(b).unbind("resize",this._windowHandler);for(var d=0;d=0||1>=b)for(var d=0;d0)){this._createdGraphics||this._createServiceGraphics();var d,e,f,g,h,i;for(d=a.isArray(b)?b:"FeatureCollection"===b.type?b.features:[b],f=1;f=0;g--)if(d=this._graphicShapes[g],h)if("Point"===d.shape.type)a.geo.distance(d.shape,b)<=i&&j.push(d.shape);else{var k=a.data(d.shape,"geoBbox"),l={type:"Polygon",coordinates:[[[k[0],k[1]],[k[0],k[3]],[k[2],k[3]],[k[2],k[1]],[k[0],k[1]]]]},m={type:"Point",coordinates:a.geo.proj&&a.geo._isGeodetic(b.coordinates)?a.geo.proj.fromGeodetic(b.coordinates):b.coordinates};if(a.geo.distance(l,m,!0)<=i)for(e=a.geo._basic(d.shape),f=0;f0)){for(var e,f=a.isArray(b)?b:[b],g=0;g=0&&(e=this._graphicShapes.slice(g+1),this._graphicShapes.length=g,this._graphicShapes.push.apply(this._graphicShapes,e),g--);(d===c||d)&&(this._$elem.is(".geo-service")?this._refresh(!1,this._$elem):this._refresh(),this._refreshAllShapes())}},_getBbox:function(a,b){a=a||this._center,b=b||this._pixelSize;var c=this._contentBounds.width/2*b,d=this._contentBounds.height/2*b;return[a[0]-c,a[1]-d,a[0]+c,a[1]+d]},_setBbox:function(b){var c=[b[0]+(b[2]-b[0])/2,b[1]+(b[3]-b[1])/2],d=Math.max(a.geo.width(b,!0)/this._contentBounds.width,a.geo.height(b,!0)/this._contentBounds.height),e=this._getZoom(c,d);this._options.tilingScheme?d=this._getPixelSize(Math.min(Math.max(e,this._options.zoomMin),this._options.zoomMax)):ethis._options.zoomMax&&(d=this._getPixelSize(this._options.zoomMax)),this._setInteractiveCenterAndSize(c,d),this._interactiveTransform()},_getBboxMax:function(){var a=this._contentBounds.width/2*this._pixelSizeMax,b=this._contentBounds.height/2*this._pixelSizeMax;return[this._centerMax[0]-a,this._centerMax[1]-b,this._centerMax[0]+a,this._centerMax[1]+b]},_getCenter:function(){return this._center},_getContentBounds:function(){return this._contentBounds},_getServicesContainer:function(){return this._$servicesContainer},_getZoom:function(b,c){b=b||this._center,c=c||this._pixelSize;var d=this._options.tilingScheme;if(d){if(d.pixelSizes){for(var e=Math.floor(1e3*c),f=d.pixelSizes.length,g=f-1;g>=0;g--)if(Math.floor(1e3*d.pixelSizes[g])>=e)return g;return 0}return Math.round(Math.log(d.basePixelSize/c)/Math.log(2))}var h=this._contentBounds.width/this._contentBounds.height,i=a.geo.reaspect(this._getBbox(b,c),h,!0),j=a.geo.reaspect(this._getBboxMax(),h,!0);return Math.round(Math.log(a.geo.width(j,!0)/a.geo.width(i,!0))/Math.log(this._fullZoomFactor))},_setZoom:function(a,b){this._clearInteractiveTimeout(),a=Math.min(Math.max(a,this._options.zoomMin),this._options.zoomMax),this._setInteractiveCenterAndSize(this._centerInteractive,this._getPixelSize(a)),this._interactiveTransform(),this._setInteractiveTimeout(b)},_createChildren:function(){this._$existingChildren=this._$elem.children(),this._forcePosition(this._$existingChildren),this._$existingChildren.detach().css({mozUserSelect:"none"});var c="width:"+this._contentBounds.width+"px; height:"+this._contentBounds.height+"px; margin:0; padding:0;",d="position:absolute; left:0; top:0;";this._$elem.prepend(b.toStaticHTML('
                                        ')),this._$eventTarget=this._$contentFrame=this._$elem.children(":first"),this._$contentFrame.append('
                                        '),this._$servicesContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                                          '),this._$attrList=this._$contentFrame.children(":last"),this._$contentFrame.append('
                                          '),this._$drawContainer=this._$contentFrame.children(":last"),this._$contentFrame.append('
                                          '), +this._$measureContainer=this._$contentFrame.children(":last"),this._$measureLabel=this._$measureContainer.children(),this._$contentFrame.append('
                                          '),this._$shapesContainer=this._$contentFrame.children(":last"),this._$panContainer=a([this._$shapesContainer[0],this._$drawContainer[0],this._$measureContainer[0]]),this._$resizeContainer=a([this._$contentFrame[0],this._$servicesContainer[0],this._$eventTarget[0],this._$measureContainer[0]]),this._$contentFrame.append(this._$existingChildren),a("#geo-measure-style").length||a("head").prepend(b.toStaticHTML('"))},_createServices:function(){var c,d;for(d=0;d';this._$servicesContainer.append(b.toStaticHTML(h)),e=this._$servicesContainer.children(":last"),c.serviceContainer=e,a.geo._serviceTypes[c.type].create(this,e,c,d),e.data("geoMap",this).geomap(),c.attr&&this._$attrList.append("
                                        • "+c.attr+"
                                        • ")}this._$shapesContainers=this._$shapesContainer,this._$attrList.find("a").css({position:"relative",zIndex:1,display:"inline-block",webkitTransform:"translateZ(0)"})},_createServiceGraphics:function(){var a=this._$elem.closest(".geo-content-frame");this._$elem.append('
                                          '),this._$shapesContainer=this._$elem.children(":last"),this._map._$shapesContainers=this._map._$shapesContainers.add(this._$shapesContainer),this._$shapesContainer.geographics({doubleBuffer:!f}),this._createdGraphics=!0,this._options.shapeStyle=this._$shapesContainer.geographics("option","style")},_refreshDrawing:function(){if(this._$drawContainer.geographics("clear"),this._drawPixels.length>0){var b,c,d,e,f,g=this._options.mode,h=this._drawPixels,i=this._drawCoords;switch(g){case"measureLength":g="drawLineString",c={type:"LineString",coordinates:i},b=a.render[this._tmplLengthId]({length:a.geo.length(c,!0)}),d=a.merge([],h[h.length-1]);break;case"measureArea":g="drawPolygon",c={type:"Polygon",coordinates:[a.merge([],i)]},c.coordinates[0].push(i[0]),b=a.render[this._tmplAreaId]({area:a.geo.area(c,!0)}),d=this._toPixel(a.geo.centroid(c).coordinates),h=[h];break;case"drawPolygon":h=[h]}this._$drawContainer.geographics(g,h),b&&(this._$measureLabel.html(b),e=this._contentBounds.width-(this._$measureLabel.outerWidth(!0)+d[0]),f=this._contentBounds.height-(this._$measureLabel.outerHeight(!0)+d[1]),0>e&&(d[0]+=e),0>f&&(d[1]+=f),this._$measureLabel.css({left:Math.max(d[0],0),top:Math.max(d[1],0)}).show())}},_resetDrawing:function(){this._drawPixels=[],this._drawCoords=[],this._$drawContainer.geographics("clear"),this._$measureLabel.hide()},_refreshAllShapes:function(a){this._timeoutRefreshShapes=null;for(var b,c,d=0;d0&&c._refreshShapes(c._$shapesContainer,c._graphicShapes,c._graphicShapes,c._graphicShapes)));this._createdGraphics&&!a&&(this._$shapesContainer.geographics("clear"),this._graphicShapes.length>0&&this._refreshShapes(this._$shapesContainer,this._graphicShapes,this._graphicShapes,this._graphicShapes))},_refreshShapes:function(b,d,e,f,g,h){var i,j,k,l,m,n,o,p,q,r=this._map._getBbox(g,h);for(i=0;i0&&a.height>0);)a={width:b.width(),height:b.height()},(a.width<=0||a.height<=0)&&(a={width:parseInt(b.css("width"),10),height:parseInt(b.css("height"),10)}),b=b.parent();return a},_forcePosition:function(a){var b=a.css("position");"relative"!==b&&"absolute"!==b&&"fixed"!==b&&a.css("position","relative")},_getPixelSize:function(b){var c=this._options.tilingScheme;if(null!==c){if(0===b)return c.pixelSizes?c.pixelSizes[0]:c.basePixelSize;b=Math.round(b),b=Math.max(b,0);var d=c.pixelSizes?c.pixelSizes.length:c.levels;return b=Math.min(b,d-1),c.pixelSizes?c.pixelSizes[b]:c.basePixelSize/Math.pow(2,b)}var e=a.geo.scaleBy(this._getBboxMax(),1/Math.pow(this._fullZoomFactor,b),!0);return Math.max(a.geo.width(e,!0)/this._contentBounds.width,a.geo.height(e,!0)/this._contentBounds.height)},_getZoomCenterAndSize:function(a,b,c){var d=c?this._fullZoomFactor:this._partialZoomFactor,e=Math.pow(d,-b),f=this._pixelSizeInteractive*e;this._options.tilingScheme&&(f=Math.min(Math.max(f,this._pixelSizeMin),this._pixelSizeMax));var g=this._getZoom(this._centerInteractive,f);c&&this._options.tilingScheme?f=this._getPixelSize(Math.min(Math.max(g,this._options.zoomMin),this._options.zoomMax)):0>b&&g0&&g>this._options.zoomMax&&(f=this._pixelSizeInteractive);var h=f/this._pixelSizeInteractive,i=this._toMap(a,this._centerInteractive,this._pixelSizeInteractive),j=[(this._centerInteractive[0]-i[0])*h,(this._centerInteractive[1]-i[1])*h],k=[i[0]+j[0],i[1]+j[1]];return{pixelSize:f,center:k}},_panFinalize:function(){this._panning&&(this._velocity=[0,0],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._inOp=!1,this._anchor=this._current,this._mouseDown=this._toolPan=this._panning=!1)},_panMove:function(){if(this._options.pannable){var a=this._current[0]-this._lastDrag[0],b=this._current[1]-this._lastDrag[1];(this._toolPan||a>3||-3>a||b>3||-3>b)&&(this._toolPan||(this._toolPan=!0,this._$eventTarget.css("cursor",this._options.cursors.pan)),this._mouseDown&&(this._velocity=[a,b]),(0!==a||0!==b)&&(this._panning=!0,this._lastDrag=this._current,this._centerInteractive[0]-=a*this._pixelSizeInteractive,this._centerInteractive[1]+=("image"===this._options.axisLayout?-1:1)*b*this._pixelSizeInteractive,this._setInteractiveCenterAndSize(this._centerInteractive,this._pixelSizeInteractive),this._interactiveTransform()))}},_clearInteractiveTimeout:function(){return this._timeoutRefreshShapes&&(clearTimeout(this._timeoutRefreshShapes),this._timeoutRefreshShapes=null),this._timeoutInteractive?(clearTimeout(this._timeoutInteractive),this._timeoutInteractive=null,!0):(this._centerInteractive[0]=this._center[0],this._centerInteractive[1]=this._center[1],this._pixelSizeInteractive=this._pixelSize,!1)},_interactiveTransform:function(){var b,c=this._pixelSize,d=c/this._pixelSizeInteractive;if(c>0){d=Math.round(1e3*d)/1e3;var e=this._toMap([0,0]),f=this._toPixel(e,this._centerInteractive,this._pixelSizeInteractive);this._$shapesContainers.geographics("interactiveTransform",f,d)}for(var g=0;g0&&(this._drawPixels=this._toPixel(this._drawCoords,this._centerInteractive,this._pixelSizeInteractive),this._refreshDrawing())},_interactiveTimeout:function(){this._isMultiTouch?this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128):this._created&&this._timeoutInteractive&&(this._setCenterAndSize(this._centerInteractive,this._pixelSizeInteractive,this._triggerInteractive,!0),this._timeoutInteractive=null,this._triggerInteractive=!1,this._timeoutRefreshShapes=setTimeout(a.proxy(this._refreshAllShapes,this),128))},_setInteractiveTimeout:function(b){this._timeoutInteractive=setTimeout(a.proxy(this._interactiveTimeout,this),128),this._triggerInteractive|=b},_refresh:function(b,c){for(var d,e=0;ethis._options.zoomMax&&(this._pixelSizeInteractive=d=this._getPixelSize(this._options.zoomMax)),this._centerInteractive[0]=c[0],this._centerInteractive[1]=c[1],this._created&&this._interactiveTransform(),this._options.pixelSize=this._pixelSize=d,this._center[0]=c[0],this._center[1]=c[1],this._userGeodetic?(this._options.bbox=a.geo.proj.toGeodetic(this._getBbox()),this._options.center=a.geo.proj.toGeodetic(this._center)):(this._options.bbox=this._getBbox(),this._options.center=a.merge([],c)),this._options.zoom=g,e&&this._trigger("bboxchange",b.event,{bbox:a.merge([],this._options.bbox)}),f&&(this._refresh(),this._refreshAllShapes(),this._refreshDrawing())}},_requestQueued:function(){0===this._loadCount&&this._trigger("loadstart",b.event),this._loadCount++},_requestComplete:function(){this._loadCount--,this._loadCount<=0&&(this._loadCount=0,this._trigger("loadend",b.event))},_toMap:function(b,c,d){c=c||this._center,d=d||this._pixelSize;var e,f,g,h,i=a.isArray(b[0]),j=i&&a.isArray(b[0][0]),k=j&&a.isArray(b[0][0][0]),l=this._contentBounds.width,m=this._contentBounds.height,n=l/2*d,o=m/2*d,p=[c[0]-n,c[1]-o,c[0]+n,c[1]+o],q=a.geo.width(p,!0)/l,r=a.geo.height(p,!0)/m,s="image"===this._options.axisLayout,t=[];for(k||(j||(i||(b=[b]),b=[b]),b=[b]),f=0;f0&&27===b.which&&(2>=c?(this._resetDrawing(),this._inOp=!1):(this._drawCoords[c-2]=a.merge([],this._drawCoords[c-1]),this._drawPixels[c-2]=a.merge([],this._drawPixels[c-1]),this._drawCoords.length--,this._drawPixels.length--,this._refreshDrawing()))},_eventTarget_dblclick_zoom:function(a){var b=this._clearInteractiveTimeout();if(this._trigger("dblclick",a,{type:"Point",coordinates:this._toMap(this._current,this._centerInteractive,this._pixelSizeInteractive)}),!a.isDefaultPrevented()){var c=this._getZoomCenterAndSize(this._current,1,!0);this._setInteractiveCenterAndSize(c.center,c.pixelSize),this._interactiveTransform(),b=!0}b&&this._setInteractiveTimeout(!0)},_eventTarget_dblclick:function(c){if("static"!==this._options.mode){switch(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),this._options.mode){case"drawLineString":case"measureLength":this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])?(this._drawCoords.length--,this._trigger("shape",c,{type:"LineString",coordinates:this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords})):this._eventTarget_dblclick_zoom(c),this._resetDrawing();break;case"drawPolygon":case"measureArea":if(this._drawCoords.length>1&&(this._drawCoords[0][0]!==this._drawCoords[1][0]||this._drawCoords[0][1]!==this._drawCoords[1][1])){var d=this._drawCoords.length-1;d>2&&(this._drawCoords[d]=a.merge([],this._drawCoords[0]),this._trigger("shape",c,{type:"Polygon",coordinates:[this._userGeodetic?a.geo.proj.toGeodetic(this._drawCoords):this._drawCoords]}))}else this._eventTarget_dblclick_zoom(c);this._resetDrawing();break;default:this._eventTarget_dblclick_zoom(c)}this._inOp=!1}},_eventTarget_touchstart:function(b){if("undefined"!=typeof document.elementFromPoint){var c=document.elementFromPoint(b.pageX,b.pageY);if(c&&"A"===c.nodeName)return}var d=this._options.mode,e=this._options.shift,f="dragBox"===d?"dragBox":"zoom";if("static"!==d&&(this._pointerEvents||this._supportTouch||1===b.which)){var g=this._clearInteractiveTimeout(),h=a(b.currentTarget).offset(),i=b.originalEvent.changedTouches;if(this._pointerEvents){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0)return b.currentTarget.setPointerCapture(b.originalEvent.pointerId),this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-h.left,this._multiTouchAnchor[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=a.geo.center(this._multiTouchCurrentBbox,!0),this._current=a.merge([],this._anchor),g&&this._setInteractiveTimeout(!0),!1;this._multiTouchAnchor.length<2&&(b.currentTarget.setPointerCapture(b.originalEvent.pointerId),this._multiTouchAnchor.push(b.originalEvent),this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top,NaN,NaN],this._current=[this._multiTouchAnchor[0].pageX-h.left,this._multiTouchAnchor[0].pageY-h.top])}else this._supportTouch&&i?(this._multiTouchAnchor=a.merge([],i),this._isMultiTouch=this._multiTouchAnchor.length>1,this._isMultiTouch?(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,i[1].pageX-h.left,i[1].pageY-h.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._current=a.geo.center(this._multiTouchCurrentBbox,!0)):(this._multiTouchCurrentBbox=[i[0].pageX-h.left,i[0].pageY-h.top,NaN,NaN],this._current=[i[0].pageX-h.left,i[0].pageY-h.top])):this._current=[b.pageX-h.left,b.pageY-h.top];if(this._softDblClick){var j=a.now();if(j-this._downDate<750){if(this._isTap){var k=this._current[0]-this._anchor[0],l=this._current[1]-this._anchor[1],m=Math.sqrt(k*k+l*l);m>8?this._isTap=!1:this._current=a.merge([],this._anchor)}this._isDbltap?this._isDbltap=!1:this._isDbltap=this._isTap}else this._isDbltap=!1;this._isTap=!0,this._downDate=j}return this._mouseDown=!0,this._anchor=a.merge([],this._current),!this._inOp&&b.shiftKey&&"off"!==e?(this._shiftDown=!0,this._$eventTarget.css("cursor",this._options.cursors["default"===e?f:e])):this._isMultiTouch||!this._options.pannable&&"dragBox"!==d&&"dragCircle"!==d||(this._inOp=!0,"zoom"!==d&&"dragBox"!==d&&"dragCircle"!==d&&(this._lastDrag=this._current,b.currentTarget.setCapture&&b.currentTarget.setCapture())),b.preventDefault(),g&&this._setInteractiveTimeout(!0),!1}},_dragTarget_touchmove:function(b){if("static"!==this._options.mode){var c=!1;this._mouseDown&&(c=this._clearInteractiveTimeout());var d,f,g,h,i,j,k=this._$eventTarget.offset(),l=this._drawCoords.length,m=b.originalEvent.changedTouches,n=null;if(this._pointerEvents)if(this._isMultiTouch){if(b.originalEvent.pointerId===this._multiTouchAnchor[0].pointerId)this._multiTouchCurrentBbox[0]=b.originalEvent.pageX-k.left,this._multiTouchCurrentBbox[1]=b.originalEvent.pageY-k.top;else{if(b.originalEvent.pointerId!==this._multiTouchAnchor[1].pointerId)return b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1;this._multiTouchCurrentBbox[2]=b.originalEvent.pageX-k.left,this._multiTouchCurrentBbox[3]=b.originalEvent.pageY-k.top}d=a.geo._distancePointPoint([this._multiTouchAnchorBbox[0],this._multiTouchAnchorBbox[1]],[this._multiTouchAnchorBbox[2],this._multiTouchAnchorBbox[3]]),f=a.geo._distancePointPoint([this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1]],[this._multiTouchCurrentBbox[2],this._multiTouchCurrentBbox[3]]),g=(f-d)/d,g*=g>0?5:10,h=g-this._wheelLevel,this._wheelLevel=g,i=this._getZoomCenterAndSize(this._anchor,h,!1),this._setInteractiveCenterAndSize(i.center,i.pixelSize),this._interactiveTransform(),c=!0,n=a.geo.center(this._multiTouchCurrentBbox,!0)}else this._multiTouchAnchor[0]=b.originalEvent,this._multiTouchCurrentBbox=[this._multiTouchAnchor[0].pageX-k.left,this._multiTouchAnchor[0].pageY-k.top,NaN,NaN],n=[b.originalEvent.pageX-k.left,b.originalEvent.pageY-k.top];else if(this._supportTouch&&m){if(!this._isMultiTouch&&this._mouseDown&&this._multiTouchAnchor.length>0&&m[0].identifier!==this._multiTouchAnchor[0].identifier)return this._isMultiTouch=!0,this._wheelLevel=0,this._multiTouchAnchor.push(m[0]),this._multiTouchCurrentBbox=[this._multiTouchCurrentBbox[0],this._multiTouchCurrentBbox[1],this._multiTouchAnchor[1].pageX-k.left,this._multiTouchAnchor[1].pageY-k.top],this._multiTouchAnchorBbox=a.merge([],this._multiTouchCurrentBbox),this._anchor=this._current=a.geo.center(this._multiTouchCurrentBbox,!0),c&&this._setInteractiveTimeout(!0),!1;if(this._isMultiTouch){for(j=0;j0?5:10,h=g-this._wheelLevel,this._wheelLevel=g,i=this._getZoomCenterAndSize(this._anchor,h,!1),this._setInteractiveCenterAndSize(i.center,i.pixelSize),this._interactiveTransform(),c=!0,n=a.geo.center(this._multiTouchCurrentBbox,!0)}else n=[b.originalEvent.changedTouches[0].pageX-k.left,b.originalEvent.changedTouches[0].pageY-k.top]}else n=[b.pageX-k.left,b.pageY-k.top];if(null===n)return b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1;if(n[0]===this._lastMove[0]&&n[1]===this._lastMove[1])return this._inOp?(b.preventDefault(),c&&this._setInteractiveTimeout(!0),!1):!1;if(7===e&&(this._isDbltap=this._isTap=!1),this._mouseDown&&(this._current=n,this._moveDate=a.now()),this._isMultiTouch)return b.preventDefault(),this._isDbltap=this._isTap=!1,c&&this._setInteractiveTimeout(!0),!1;var o,p,q,r=this._options.mode,s=this._options.shift,t="dragBox"===r?"dragBox":"zoom";switch(this._shiftDown&&(r="default"===s?t:s),r){case"zoom":case"dragBox":this._mouseDown?(this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawBbox",[this._anchor[0],this._anchor[1],n[0],n[1]])):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)});break;case"dragCircle":this._mouseDown?(o=n[0]-this._anchor[0],p=n[1]-this._anchor[1],q=2*Math.sqrt(o*o+p*p),this._$drawContainer.geographics("clear"),this._$drawContainer.geographics("drawArc",this._anchor,0,360,{width:q,height:q})):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)});break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":this._mouseDown||this._toolPan?(this._panMove(),c=!0):(l>0&&(this._drawCoords[l-1]=this._toMap(n,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[l-1]=n,this._refreshDrawing()),this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)}));break;default:this._mouseDown||this._toolPan?(this._panMove(),c=!0):this._trigger("move",b,{type:"Point",coordinates:this.toMap(n)})}return this._lastMove=n,c&&this._setInteractiveTimeout(!0),this._inOp?(b.preventDefault(),!1):void 0}},_dragTarget_touchstop:function(c){if("static"!==this._options.mode){if(!this._mouseDown){if(7!==e)return;this._eventTarget_touchstart(c)}var d,f,g,h,i,j,k=this._clearInteractiveTimeout(),l=this._mouseDown,m=this._toolPan,n=this._$eventTarget.offset(),o=this._options.mode,p=this._options.shift,q="dragBox"===o?"dragBox":"zoom",r=null;if(this._shiftDown&&(o="default"===p?q:p),this._pointerEvents){if(c.originalEvent.pointerId!==this._multiTouchAnchor[0].pointerId&&c.originalEvent.pointerId!==this._multiTouchAnchor[1].pointerId)return c.preventDefault(),void(k&&this._setInteractiveTimeout(!0));c.currentTarget.releasePointerCapture(c.originalEvent.pointerId),r=[c.originalEvent.pageX-n.left,c.originalEvent.pageY-n.top],this._multiTouchAnchor=[],this._inOp=!1}else this._supportTouch&&c.originalEvent.changedTouches?(r=[c.originalEvent.changedTouches[0].pageX-n.left,c.originalEvent.changedTouches[0].pageY-n.top],this._multiTouchAnchor=[],this._inOp=!1):r=[c.pageX-n.left,c.pageY-n.top];if(this._softDblClick&&this._isTap&&(g=r[0]-this._anchor[0],h=r[1]-this._anchor[1],Math.sqrt(g*g+h*h)<=8&&(r=a.merge([],this._anchor))),g=r[0]-this._anchor[0],h=r[1]-this._anchor[1],this._$eventTarget.css("cursor",this._options.cursors[this._options.mode]),this._shiftDown=this._mouseDown=this._toolPan=!1,this._isMultiTouch)return c.preventDefault(),this._isMultiTouch=!1,this._wheelLevel=0,void(k&&this._setInteractiveTimeout(!0));if(document.releaseCapture&&document.releaseCapture(),l){switch(f=a.now(),this._current=r,o){case"zoom":case"dragBox":if(0!==g||0!==h){var s=6*this._pixelSize,t=this._toMap([this._anchor,r]),u=[Math.min(t[0][0],t[1][0]),Math.min(t[0][1],t[1][1]),Math.max(t[0][0],t[1][0]),Math.max(t[0][1],t[1][1])];"zoom"===o?(u[2]-u[0]d;d++)v=360*d/y*(Math.PI/180),this._drawPixels[d]=[this._anchor[0]+Math.cos(v)*x,this._anchor[1]+Math.sin(v)*x];this._drawPixels[y]=[this._drawPixels[0][0],this._drawPixels[0][1]],i=this._toMap([[this._anchor[0]-x,this._anchor[1]+(w?-x:x)],[this._anchor[0]+x,this._anchor[1]+(w?x:-x)]]),j={type:"Polygon",coordinates:[this._toMap(this._drawPixels)],bbox:[i[0][0],i[0][1],i[1][0],i[1][1]]},this._userGeodetic&&(j.coordinates=a.geo.proj.toGeodetic(j.coordinates),j.bbox=a.geo.proj.toGeodetic(j.bbox)),this._trigger("shape",c,j),this._resetDrawing()}else i=this._toMap(r),j={type:"Point",coordinates:[i[0],i[1]],bbox:[i[0],i[1],i[0],i[1]]},this._userGeodetic&&(j.coordinates=a.geo.proj.toGeodetic(j.coordinates),j.bbox=a.geo.proj.toGeodetic(j.bbox)),this._trigger("shape",c,j);break;case"drawPoint":if(this._drawTimeout&&(b.clearTimeout(this._drawTimeout),this._drawTimeout=null),m)this._panFinalize();else if(f-this._clickDate>100){var z=this;this._drawTimeout=setTimeout(function(){z._drawTimeout&&(z._trigger("shape",c,{type:"Point",coordinates:z.toMap(r)}),z._inOp=!1,z._drawTimeout=null)},250)}break;case"drawLineString":case"drawPolygon":case"measureLength":case"measureArea":m?this._panFinalize():(this._trigger("click",c,{type:"Point",coordinates:this.toMap(r)}),c.isDefaultPrevented()||(d=0===this._drawCoords.length?0:this._drawCoords.length-1,this._drawCoords[d]=this._toMap(r),this._drawPixels[d]=r,(2>d||this._drawCoords[d][0]!==this._drawCoords[d-1][0]||this._drawCoords[d][1]!==this._drawCoords[d-1][1])&&(this._drawCoords[d+1]=this._toMap(r,this._centerInteractive,this._pixelSizeInteractive),this._drawPixels[d+1]=r),this._refreshDrawing()));break;default:m?this._panFinalize():f-this._clickDate>100&&(this._trigger("click",c,{type:"Point",coordinates:this.toMap(r)}),this._inOp=!1)}if(this._clickDate=f,this._softDblClick&&this._isDbltap)return this._isDbltap=this._isTap=!1,k&&this._setInteractiveTimeout(!0),this._$eventTarget.trigger("softdblclick",c),!1}return k&&this._setInteractiveTimeout(!0),this._inOp?(c.preventDefault(),!1):void 0}},_eventTarget_mousewheel:function(b){if("static"!==this._options.mode&&"off"!==this._options.scroll){if(b.preventDefault(),this._mouseDown)return!1;if(0!==b.deltaY){this._timeoutWheel&&(clearTimeout(this._timeoutWheel),this._timeoutWheel=null);var c=this,d=b.currentTarget,e=b.deltaY,f=b.pageX,g=b.pageY;this._timeoutWheel=setTimeout(function(){c._clearInteractiveTimeout();var b=e>0?1:-1,h=a(d).offset();c._anchor=[f-h.left,g-h.top];var i=c._getZoomCenterAndSize(c._anchor,b,null!==c._options.tilingScheme);c._setInteractiveCenterAndSize(i.center,i.pixelSize),c._interactiveTransform(),c._setInteractiveTimeout(!0)},30)}return!1}}})}(jQuery,window),function(a,b,c){a.geo._serviceTypes.tiled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0,reloadTiles:!1};var g='
                                          ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b.options.tilingScheme;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),h=f/e;if(f>0){h=Math.round(1e3*h)/1e3;var i=c.data("scaleOrigin"),j=b._toPixel(i,d,e);c.css({left:Math.round(j[0])+"px",top:Math.round(j[1])+"px",width:g.tileWidth*h,height:g.tileHeight*h})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&f&&(g.reloadTiles=!0),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i,j=d._getBbox(),k=d._pixelSize,l=this,m=g.serviceContainer,n="image"===d.options.axisLayout,o=n?1:-1,p=d.options.tilingScheme,q=p.tileWidth,r=p.tileHeight,s=Math.floor((j[0]-p.origin[0])/(k*q)),t=Math.max(Math.floor((n?j[1]-p.origin[1]:p.origin[1]-j[3])/(k*r)),0),u=Math.ceil((j[2]-p.origin[0])/(k*q)),v=Math.ceil((n?j[3]-p.origin[1]:p.origin[1]-j[1])/(k*r)),w=d._getBboxMax(),x=d._getPixelSize(0),y=x/k,z=Math.floor((w[0]-p.origin[0])/(x*q))*y,A=Math.floor((p.origin[1]+o*w[3])/(x*r))*y,B=p.origin[0]+z*q*k,C=p.origin[1]+o*(A*r)*k,D=Math.round((B-j[0])/k),E=Math.round((n?C-j[1]:j[3]-C)/k),F=m.children().show(),G=F.filter("[data-pixel-size='"+k+"']").appendTo(m),H=e.style.opacity,I=function(a){l._loadImage(this.img,a,k,d,g,H)},J=function(){delete this.img,g.loadCount--,d._requestComplete()};for(g.reloadTiles&&F.find("img").attr("data-dirty","true"),G.size()?(G.css({left:D%q+"px",top:E%r+"px"}).data("scaleOrigin",d._toMap([D%q,E%r])),G.children().each(function(){var b=a(this),c=b.attr("data-tile").split(",");b.css({left:Math.round(100*(parseInt(c[0],10)-z)+(D-D%q)/q*100)+"%",top:Math.round(100*(parseInt(c[1],10)-A)+(E-E%r)/r*100)+"%"}),1>H&&b.fadeTo(0,H)})):(m.append(b.toStaticHTML("
                                          ")),G=m.children(":last").data("scaleOrigin",d._toMap([D%q,E%r]))),h=s;u>h;h++)for(i=t;v>i;i++){var K=""+h+","+i,L=G.children("[data-tile='"+K+"']").removeAttr("data-dirty");if(0===L.size()||g.reloadTiles){var M,N=[p.origin[0]+h*q*k,p.origin[1]+o*(i*r)*k],O=[p.origin[0]+((h+1)*q-1)*k,p.origin[1]+o*((i+1)*r-1)*k],P=[N[0],N[1],O[0],O[1]],Q={bbox:P,width:q,height:r,zoom:d._getZoom(),tile:{row:i,column:h},index:Math.abs(i+h)},R=a.isFunction(e.src);if(R?M=e.src(Q):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),M=a.render[this._tmplGeoSrcId](Q)):M=e.src,g.loadCount++,d._requestQueued(),g.reloadTiles&&L.size()>0)L.attr("src",M);else{var S="",G.append(b.toStaticHTML(S)),L=G.children(":last")}"string"==typeof M?l._loadImage(L,M,k,d,g,H):M&&a.isFunction(M.promise)?(a.extend(M.promise(),{img:L}),M.done(I).fail(J)):L.remove()}}F.find("[data-dirty]").remove(),g.reloadTiles=!1}},resize:function(){},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--,b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){1>g?a(b.target).fadeTo(0,g):a(b.target).show(), +f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).error(function(b){a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0)}).attr("src",c)}}}()}(jQuery,window),function(a,b,c){a.geo._serviceTypes.shingled=function(){var c=new RegExp("<.*>|{{.*}}");return{_serviceId:0,_tmplGeoSrcId:"",create:function(c,d,e){this._serviceId=c._serviceIdSeed++,this._tmplGeoSrcId="geoSrc"+this._serviceId;var f=a.data(e,"geoServiceState");if(!f){f={loadCount:0};var g='
                                          ';d.append(b.toStaticHTML(g)),f.serviceContainer=d.children(":last"),a.data(e,"geoServiceState",f)}return f.serviceContainer},destroy:function(b,c,d){var e=a.data(d,"geoServiceState");e.serviceContainer.remove(),a.removeData(d,"geoServiceState")},interactiveTransform:function(b,c,d,e){var f=a.data(c,"geoServiceState"),g=b._getContentBounds(),h=g.width,i=g.height;f&&(this._cancelUnloaded(b,c),f.serviceContainer.children().each(function(){var c=a(this),f=c.data("pixelSize"),g=f/e;if(f>0){g=Math.round(1e3*g)/1e3;var j=c.data("origin"),k=b._toPixel(j,d,e);c.css({left:Math.round(k[0]),top:Math.round(k[1]),width:h*g,height:i*g})}}))},refresh:function(d,e,f){var g=a.data(e,"geoServiceState");if(this._cancelUnloaded(d,e),g&&e&&"visible"===e.style.visibility&&!g.serviceContainer.is(":hidden")){var h,i=d._getBbox(),j=d._pixelSize,k=this,l=g.serviceContainer,m=d._getContentBounds(),n=m.width,o=m.height,p=l.children('[data-pixel-size="'+j+'"]'),q=e.style.opacity;1>q||f||1===e.shinglesMax?l.find("img").attr("data-keep-alive","0"):e.shinglesMax>1&&l.find("img").slice(0,-(e.shinglesMax-1)).attr("data-keep-alive","0"),p.size()||(l.append(b.toStaticHTML('
                                          ')),p=l.children(":last"));var r,s={bbox:i,width:n,height:o,zoom:d._getZoom(),tile:null,index:0},t=a.isFunction(e.src),u=p.position();u.left=-u.left,u.top=-u.top,t?r=e.src(s):c.test(e.src)?(a.templates(this._tmplGeoSrcId,e.src),r=a.render[this._tmplGeoSrcId](s)):r=e.src,g.loadCount++,d._requestQueued(),p.append(b.toStaticHTML('')),h=p.children(":last").data("center",d._center),"string"==typeof r?k._loadImage(h,r,j,d,g,q):r&&r.done(function(a){k._loadImage(h,a,j,d,g,q)}).fail(function(){h.remove(),g.loadCount--,d._requestComplete()})}},resize:function(b,c){var d=a.data(c,"geoServiceState");if(d&&c&&"visible"===c.style.visibility){this._cancelUnloaded(b,c);var e=d.serviceContainer,f=b._getContentBounds(),g=f.width,h=f.height,i=e.children();i.attr("data-pixel-size","0"),i.each(function(){var b=a(this),c=b.position();b.css({left:c.left+(g-b.width())/2,top:c.top+(h-b.height())/2})})}},opacity:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.find("img").stop(!0).fadeTo("fast",c.style.opacity)},toggle:function(b,c){var d=a.data(c,"geoServiceState");d.serviceContainer.css("display","visible"===c.style.visibility?"block":"none")},_cancelUnloaded:function(b,c){var d=a.data(c,"geoServiceState");if(d&&d.loadCount>0)for(d.serviceContainer.find("img:hidden").remove();d.loadCount>0;)d.loadCount--,b._requestComplete()},_loadImage:function(b,c,d,e,f,g){var h=f.serviceContainer;b.load(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(1>g?a(b.target).fadeTo(0,g):a(b.target).show(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(':not([data-pixel-size="'+d+'"])').remove(),h.find("img[data-keep-alive]").remove(),f.loadCount=0))}).error(function(b){a.contains(document.body,b.target.jquery?b.target[0]:b.target)&&(a(b.target).remove(),f.loadCount--,e._requestComplete(),f.loadCount<=0&&(h.children(":not([data-pixel-size='"+d+"'])").remove(),f.loadCount=0))}).attr("src",c)}}}()}(jQuery,window); \ No newline at end of file