/* ========================================================================
 * Bootstrap: tooltip.js v3.3.7
 * http://getbootstrap.com/javascript/#tooltip
 * Inspired by the original jQuery.tipsy by Jason Frame
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // TOOLTIP PUBLIC CLASS DEFINITION
  // ===============================

  var Tooltip = function (element, options) {
    this.type       = null
    this.options    = null
    this.enabled    = null
    this.timeout    = null
    this.hoverState = null
    this.$element   = null
    this.inState    = null

    this.init('tooltip', element, options)
  }

  Tooltip.VERSION  = '3.3.7'

  Tooltip.TRANSITION_DURATION = 150

  Tooltip.DEFAULTS = {
    animation: true,
    placement: 'top',
    selector: false,
    template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
    trigger: 'hover focus',
    title: '',
    delay: 0,
    html: false,
    container: false,
    viewport: {
      selector: 'body',
      padding: 0
    }
  }

  Tooltip.prototype.init = function (type, element, options) {
    this.enabled   = true
    this.type      = type
    this.$element  = $(element)
    this.options   = this.getOptions(options)
    this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
    this.inState   = { click: false, hover: false, focus: false }

    if (this.$element[0] instanceof document.constructor && !this.options.selector) {
      throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
    }

    var triggers = this.options.trigger.split(' ')

    for (var i = triggers.length; i--;) {
      var trigger = triggers[i]

      if (trigger == 'click') {
        this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
      } else if (trigger != 'manual') {
        var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focusin'
        var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'

        this.$element.on(eventIn  + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
        this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
      }
    }

    this.options.selector ?
      (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
      this.fixTitle()
  }

  Tooltip.prototype.getDefaults = function () {
    return Tooltip.DEFAULTS
  }

  Tooltip.prototype.getOptions = function (options) {
    options = $.extend({}, this.getDefaults(), this.$element.data(), options)

    if (options.delay && typeof options.delay == 'number') {
      options.delay = {
        show: options.delay,
        hide: options.delay
      }
    }

    return options
  }

  Tooltip.prototype.getDelegateOptions = function () {
    var options  = {}
    var defaults = this.getDefaults()

    this._options && $.each(this._options, function (key, value) {
      if (defaults[key] != value) options[key] = value
    })

    return options
  }

  Tooltip.prototype.enter = function (obj) {
    var self = obj instanceof this.constructor ?
      obj : $(obj.currentTarget).data('bs.' + this.type)

    if (!self) {
      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
      $(obj.currentTarget).data('bs.' + this.type, self)
    }

    if (obj instanceof $.Event) {
      self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
    }

    if (self.tip().hasClass('in') || self.hoverState == 'in') {
      self.hoverState = 'in'
      return
    }

    clearTimeout(self.timeout)

    self.hoverState = 'in'

    if (!self.options.delay || !self.options.delay.show) return self.show()

    self.timeout = setTimeout(function () {
      if (self.hoverState == 'in') self.show()
    }, self.options.delay.show)
  }

  Tooltip.prototype.isInStateTrue = function () {
    for (var key in this.inState) {
      if (this.inState[key]) return true
    }

    return false
  }

  Tooltip.prototype.leave = function (obj) {
    var self = obj instanceof this.constructor ?
      obj : $(obj.currentTarget).data('bs.' + this.type)

    if (!self) {
      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
      $(obj.currentTarget).data('bs.' + this.type, self)
    }

    if (obj instanceof $.Event) {
      self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
    }

    if (self.isInStateTrue()) return

    clearTimeout(self.timeout)

    self.hoverState = 'out'

    if (!self.options.delay || !self.options.delay.hide) return self.hide()

    self.timeout = setTimeout(function () {
      if (self.hoverState == 'out') self.hide()
    }, self.options.delay.hide)
  }

  Tooltip.prototype.show = function () {
    var e = $.Event('show.bs.' + this.type)

    if (this.hasContent() && this.enabled) {
      this.$element.trigger(e)

      var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
      if (e.isDefaultPrevented() || !inDom) return
      var that = this

      var $tip = this.tip()

      var tipId = this.getUID(this.type)

      this.setContent()
      $tip.attr('id', tipId)
      this.$element.attr('aria-describedby', tipId)

      if (this.options.animation) $tip.addClass('fade')

      var placement = typeof this.options.placement == 'function' ?
        this.options.placement.call(this, $tip[0], this.$element[0]) :
        this.options.placement

      var autoToken = /\s?auto?\s?/i
      var autoPlace = autoToken.test(placement)
      if (autoPlace) placement = placement.replace(autoToken, '') || 'top'

      $tip
        .detach()
        .css({ top: 0, left: 0, display: 'block' })
        .addClass(placement)
        .data('bs.' + this.type, this)

      this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
      this.$element.trigger('inserted.bs.' + this.type)

      var pos          = this.getPosition()
      var actualWidth  = $tip[0].offsetWidth
      var actualHeight = $tip[0].offsetHeight

      if (autoPlace) {
        var orgPlacement = placement
        var viewportDim = this.getPosition(this.$viewport)

        placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top'    :
                    placement == 'top'    && pos.top    - actualHeight < viewportDim.top    ? 'bottom' :
                    placement == 'right'  && pos.right  + actualWidth  > viewportDim.width  ? 'left'   :
                    placement == 'left'   && pos.left   - actualWidth  < viewportDim.left   ? 'right'  :
                    placement

        $tip
          .removeClass(orgPlacement)
          .addClass(placement)
      }

      var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)

      this.applyPlacement(calculatedOffset, placement)

      var complete = function () {
        var prevHoverState = that.hoverState
        that.$element.trigger('shown.bs.' + that.type)
        that.hoverState = null

        if (prevHoverState == 'out') that.leave(that)
      }

      $.support.transition && this.$tip.hasClass('fade') ?
        $tip
          .one('bsTransitionEnd', complete)
          .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
        complete()
    }
  }

  Tooltip.prototype.applyPlacement = function (offset, placement) {
    var $tip   = this.tip()
    var width  = $tip[0].offsetWidth
    var height = $tip[0].offsetHeight

    // manually read margins because getBoundingClientRect includes difference
    var marginTop = parseInt($tip.css('margin-top'), 10)
    var marginLeft = parseInt($tip.css('margin-left'), 10)

    // we must check for NaN for ie 8/9
    if (isNaN(marginTop))  marginTop  = 0
    if (isNaN(marginLeft)) marginLeft = 0

    offset.top  += marginTop
    offset.left += marginLeft

    // $.fn.offset doesn't round pixel values
    // so we use setOffset directly with our own function B-0
    $.offset.setOffset($tip[0], $.extend({
      using: function (props) {
        $tip.css({
          top: Math.round(props.top),
          left: Math.round(props.left)
        })
      }
    }, offset), 0)

    $tip.addClass('in')

    // check to see if placing tip in new offset caused the tip to resize itself
    var actualWidth  = $tip[0].offsetWidth
    var actualHeight = $tip[0].offsetHeight

    if (placement == 'top' && actualHeight != height) {
      offset.top = offset.top + height - actualHeight
    }

    var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)

    if (delta.left) offset.left += delta.left
    else offset.top += delta.top

    var isVertical          = /top|bottom/.test(placement)
    var arrowDelta          = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
    var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'

    $tip.offset(offset)
    this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
  }

  Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
    this.arrow()
      .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
      .css(isVertical ? 'top' : 'left', '')
  }

  Tooltip.prototype.setContent = function () {
    var $tip  = this.tip()
    var title = this.getTitle()

    $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
    $tip.removeClass('fade in top bottom left right')
  }

  Tooltip.prototype.hide = function (callback) {
    var that = this
    var $tip = $(this.$tip)
    var e    = $.Event('hide.bs.' + this.type)

    function complete() {
      if (that.hoverState != 'in') $tip.detach()
      if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary.
        that.$element
          .removeAttr('aria-describedby')
          .trigger('hidden.bs.' + that.type)
      }
      callback && callback()
    }

    this.$element.trigger(e)

    if (e.isDefaultPrevented()) return

    $tip.removeClass('in')

    $.support.transition && $tip.hasClass('fade') ?
      $tip
        .one('bsTransitionEnd', complete)
        .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
      complete()

    this.hoverState = null

    return this
  }

  Tooltip.prototype.fixTitle = function () {
    var $e = this.$element
    if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
      $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
    }
  }

  Tooltip.prototype.hasContent = function () {
    return this.getTitle()
  }

  Tooltip.prototype.getPosition = function ($element) {
    $element   = $element || this.$element

    var el     = $element[0]
    var isBody = el.tagName == 'BODY'

    var elRect    = el.getBoundingClientRect()
    if (elRect.width == null) {
      // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
      elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
    }
    var isSvg = window.SVGElement && el instanceof window.SVGElement
    // Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3.
    // See https://github.com/twbs/bootstrap/issues/20280
    var elOffset  = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset())
    var scroll    = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
    var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null

    return $.extend({}, elRect, scroll, outerDims, elOffset)
  }

  Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
    return placement == 'bottom' ? { top: pos.top + pos.height,   left: pos.left + pos.width / 2 - actualWidth / 2 } :
           placement == 'top'    ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
           placement == 'left'   ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
        /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }

  }

  Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
    var delta = { top: 0, left: 0 }
    if (!this.$viewport) return delta

    var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
    var viewportDimensions = this.getPosition(this.$viewport)

    if (/right|left/.test(placement)) {
      var topEdgeOffset    = pos.top - viewportPadding - viewportDimensions.scroll
      var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
      if (topEdgeOffset < viewportDimensions.top) { // top overflow
        delta.top = viewportDimensions.top - topEdgeOffset
      } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
        delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
      }
    } else {
      var leftEdgeOffset  = pos.left - viewportPadding
      var rightEdgeOffset = pos.left + viewportPadding + actualWidth
      if (leftEdgeOffset < viewportDimensions.left) { // left overflow
        delta.left = viewportDimensions.left - leftEdgeOffset
      } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
        delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
      }
    }

    return delta
  }

  Tooltip.prototype.getTitle = function () {
    var title
    var $e = this.$element
    var o  = this.options

    title = $e.attr('data-original-title')
      || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)

    return title
  }

  Tooltip.prototype.getUID = function (prefix) {
    do prefix += ~~(Math.random() * 1000000)
    while (document.getElementById(prefix))
    return prefix
  }

  Tooltip.prototype.tip = function () {
    if (!this.$tip) {
      this.$tip = $(this.options.template)
      if (this.$tip.length != 1) {
        throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
      }
    }
    return this.$tip
  }

  Tooltip.prototype.arrow = function () {
    return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
  }

  Tooltip.prototype.enable = function () {
    this.enabled = true
  }

  Tooltip.prototype.disable = function () {
    this.enabled = false
  }

  Tooltip.prototype.toggleEnabled = function () {
    this.enabled = !this.enabled
  }

  Tooltip.prototype.toggle = function (e) {
    var self = this
    if (e) {
      self = $(e.currentTarget).data('bs.' + this.type)
      if (!self) {
        self = new this.constructor(e.currentTarget, this.getDelegateOptions())
        $(e.currentTarget).data('bs.' + this.type, self)
      }
    }

    if (e) {
      self.inState.click = !self.inState.click
      if (self.isInStateTrue()) self.enter(self)
      else self.leave(self)
    } else {
      self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
    }
  }

  Tooltip.prototype.destroy = function () {
    var that = this
    clearTimeout(this.timeout)
    this.hide(function () {
      that.$element.off('.' + that.type).removeData('bs.' + that.type)
      if (that.$tip) {
        that.$tip.detach()
      }
      that.$tip = null
      that.$arrow = null
      that.$viewport = null
      that.$element = null
    })
  }


  // TOOLTIP PLUGIN DEFINITION
  // =========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.tooltip')
      var options = typeof option == 'object' && option

      if (!data && /destroy|hide/.test(option)) return
      if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.tooltip

  $.fn.tooltip             = Plugin
  $.fn.tooltip.Constructor = Tooltip


  // TOOLTIP NO CONFLICT
  // ===================

  $.fn.tooltip.noConflict = function () {
    $.fn.tooltip = old
    return this
  }

}(jQuery);
;
!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):a.proj4=b()}(this,function(){"use strict";function a(a,b){if(a[b])return a[b];for(var c,d,e=Object.keys(a),f=b.toLowerCase().replace(Ub,""),g=-1;++g<e.length;)if(c=e[g],d=c.toLowerCase().replace(Ub,""),d===f)return a[c]}function b(a){if("string"!=typeof a)throw new Error("not a string");this.text=a.trim(),this.level=0,this.place=0,this.root=null,this.stack=[],this.currentObject=null,this.state=Wb}function c(a){var c=new b(a);return c.output()}function d(a,b,c){Array.isArray(b)&&(c.unshift(b),b=null);var d=b?{}:a,f=c.reduce(function(a,b){return e(b,a),a},d);b&&(a[b]=f)}function e(a,b){if(!Array.isArray(a))return void(b[a]=!0);var c=a.shift();if("PARAMETER"===c&&(c=a.shift()),1===a.length)return Array.isArray(a[0])?(b[c]={},void e(a[0],b[c])):void(b[c]=a[0]);if(!a.length)return void(b[c]=!0);if("TOWGS84"===c)return void(b[c]=a);Array.isArray(c)||(b[c]={});var f;switch(c){case"UNIT":case"PRIMEM":case"VERT_DATUM":return b[c]={name:a[0].toLowerCase(),convert:a[1]},void(3===a.length&&e(a[2],b[c]));case"SPHEROID":case"ELLIPSOID":return b[c]={name:a[0],a:a[1],rf:a[2]},void(4===a.length&&e(a[3],b[c]));case"PROJECTEDCRS":case"PROJCRS":case"GEOGCS":case"GEOCCS":case"PROJCS":case"LOCAL_CS":case"GEODCRS":case"GEODETICCRS":case"GEODETICDATUM":case"EDATUM":case"ENGINEERINGDATUM":case"VERT_CS":case"VERTCRS":case"VERTICALCRS":case"COMPD_CS":case"COMPOUNDCRS":case"ENGINEERINGCRS":case"ENGCRS":case"FITTED_CS":case"LOCAL_DATUM":case"DATUM":return a[0]=["name",a[0]],void d(b,c,a);default:for(f=-1;++f<a.length;)if(!Array.isArray(a[f]))return e(a,b[c]);return d(b,c,a)}}function f(a,b){var c=b[0],d=b[1];!(c in a)&&d in a&&(a[c]=a[d],3===b.length&&(a[c]=b[2](a[c])))}function g(a){return a*fc}function h(a){function b(b){var c=a.to_meter||1;return b*c}"GEOGCS"===a.type?a.projName="longlat":"LOCAL_CS"===a.type?(a.projName="identity",a.local=!0):"object"==typeof a.PROJECTION?a.projName=Object.keys(a.PROJECTION)[0]:a.projName=a.PROJECTION,a.UNIT&&(a.units=a.UNIT.name.toLowerCase(),"metre"===a.units&&(a.units="meter"),a.UNIT.convert&&("GEOGCS"===a.type?a.DATUM&&a.DATUM.SPHEROID&&(a.to_meter=a.UNIT.convert*a.DATUM.SPHEROID.a):(a.to_meter=a.UNIT.convert,10)));var c=a.GEOGCS;"GEOGCS"===a.type&&(c=a),c&&(c.DATUM?a.datumCode=c.DATUM.name.toLowerCase():a.datumCode=c.name.toLowerCase(),"d_"===a.datumCode.slice(0,2)&&(a.datumCode=a.datumCode.slice(2)),"new_zealand_geodetic_datum_1949"!==a.datumCode&&"new_zealand_1949"!==a.datumCode||(a.datumCode="nzgd49"),"wgs_1984"===a.datumCode&&("Mercator_Auxiliary_Sphere"===a.PROJECTION&&(a.sphere=!0),a.datumCode="wgs84"),"_ferro"===a.datumCode.slice(-6)&&(a.datumCode=a.datumCode.slice(0,-6)),"_jakarta"===a.datumCode.slice(-8)&&(a.datumCode=a.datumCode.slice(0,-8)),~a.datumCode.indexOf("belge")&&(a.datumCode="rnb72"),c.DATUM&&c.DATUM.SPHEROID&&(a.ellps=c.DATUM.SPHEROID.name.replace("_19","").replace(/[Cc]larke\_18/,"clrk"),"international"===a.ellps.toLowerCase().slice(0,13)&&(a.ellps="intl"),a.a=c.DATUM.SPHEROID.a,a.rf=parseFloat(c.DATUM.SPHEROID.rf,10)),~a.datumCode.indexOf("osgb_1936")&&(a.datumCode="osgb36"),~a.datumCode.indexOf("osni_1952")&&(a.datumCode="osni52"),(~a.datumCode.indexOf("tm65")||~a.datumCode.indexOf("geodetic_datum_of_1965"))&&(a.datumCode="ire65")),a.b&&!isFinite(a.b)&&(a.b=a.a);var d=function(b){return f(a,b)},e=[["standard_parallel_1","Standard_Parallel_1"],["standard_parallel_2","Standard_Parallel_2"],["false_easting","False_Easting"],["false_northing","False_Northing"],["central_meridian","Central_Meridian"],["latitude_of_origin","Latitude_Of_Origin"],["latitude_of_origin","Central_Parallel"],["scale_factor","Scale_Factor"],["k0","scale_factor"],["latitude_of_center","Latitude_of_center"],["lat0","latitude_of_center",g],["longitude_of_center","Longitude_Of_Center"],["longc","longitude_of_center",g],["x0","false_easting",b],["y0","false_northing",b],["long0","central_meridian",g],["lat0","latitude_of_origin",g],["lat0","standard_parallel_1",g],["lat1","standard_parallel_1",g],["lat2","standard_parallel_2",g],["alpha","azimuth",g],["srsCode","name"]];e.forEach(d),a.long0||!a.longc||"Albers_Conic_Equal_Area"!==a.projName&&"Lambert_Azimuthal_Equal_Area"!==a.projName||(a.long0=a.longc),a.lat_ts||!a.lat1||"Stereographic_South_Pole"!==a.projName&&"Polar Stereographic (variant B)"!==a.projName||(a.lat0=g(a.lat1>0?90:-90),a.lat_ts=a.lat1)}function i(a){var b=this;if(2===arguments.length){var c=arguments[1];"string"==typeof c?"+"===c.charAt(0)?i[a]=Vb(arguments[1]):i[a]=gc(arguments[1]):i[a]=c}else if(1===arguments.length){if(Array.isArray(a))return a.map(function(a){Array.isArray(a)?i.apply(b,a):i(a)});if("string"==typeof a){if(a in i)return i[a]}else"EPSG"in a?i["EPSG:"+a.EPSG]=a:"ESRI"in a?i["ESRI:"+a.ESRI]=a:"IAU2000"in a?i["IAU2000:"+a.IAU2000]=a:console.log(a);return}}function j(a){return"string"==typeof a}function k(a){return a in i}function l(a){return hc.some(function(b){return a.indexOf(b)>-1})}function m(a){return"+"===a[0]}function n(a){return j(a)?k(a)?i[a]:l(a)?gc(a):m(a)?Vb(a):void 0:a}function o(){var a=this.b/this.a;this.es=1-a*a,"x0"in this||(this.x0=0),"y0"in this||(this.y0=0),this.e=Math.sqrt(this.es),this.lat_ts?this.sphere?this.k0=Math.cos(this.lat_ts):this.k0=jc(this.e,Math.sin(this.lat_ts),Math.cos(this.lat_ts)):this.k0||(this.k?this.k0=this.k:this.k0=1)}function p(a){var b=a.x,c=a.y;if(c*Ob>90&&-90>c*Ob&&b*Ob>180&&-180>b*Ob)return null;var d,e;if(Math.abs(Math.abs(c)-Ib)<=Mb)return null;if(this.sphere)d=this.x0+this.a*this.k0*lc(b-this.long0),e=this.y0+this.a*this.k0*Math.log(Math.tan(Pb+.5*c));else{var f=Math.sin(c),g=mc(this.e,c,f);d=this.x0+this.a*this.k0*lc(b-this.long0),e=this.y0-this.a*this.k0*Math.log(g)}return a.x=d,a.y=e,a}function q(a){var b,c,d=a.x-this.x0,e=a.y-this.y0;if(this.sphere)c=Ib-2*Math.atan(Math.exp(-e/(this.a*this.k0)));else{var f=Math.exp(-e/(this.a*this.k0));if(c=nc(this.e,f),-9999===c)return null}return b=lc(this.long0+d/(this.a*this.k0)),a.x=b,a.y=c,a}function r(){}function s(a){return a}function t(a,b){var c=uc.length;return a.names?(uc[c]=a,a.names.forEach(function(a){tc[a.toLowerCase()]=c}),this):(console.log(b),!0)}function u(a){if(!a)return!1;var b=a.toLowerCase();return"undefined"!=typeof tc[b]&&uc[tc[b]]?uc[tc[b]]:void 0}function v(){sc.forEach(t)}function w(a,b,c,d){var e=a*a,f=b*b,g=(e-f)/e,h=0;d?(a*=1-g*(Jb+g*(Kb+g*Lb)),e=a*a,g=0):h=Math.sqrt(g);var i=(e-f)/f;return{es:g,e:h,ep2:i}}function x(b,c,d,e,f){if(!b){var g=a(wc,e);g||(g=xc),b=g.a,c=g.b,d=g.rf}return d&&!c&&(c=(1-1/d)*b),(0===d||Math.abs(b-c)<Mb)&&(f=!0,c=b),{a:b,b:c,rf:d,sphere:f}}function y(a,b,c,d,e,f){var g={};return void 0===a||"none"===a?g.datum_type=Gb:g.datum_type=Fb,b&&(g.datum_params=b.map(parseFloat),0===g.datum_params[0]&&0===g.datum_params[1]&&0===g.datum_params[2]||(g.datum_type=Db),g.datum_params.length>3&&(0===g.datum_params[3]&&0===g.datum_params[4]&&0===g.datum_params[5]&&0===g.datum_params[6]||(g.datum_type=Eb,g.datum_params[3]*=Hb,g.datum_params[4]*=Hb,g.datum_params[5]*=Hb,g.datum_params[6]=g.datum_params[6]/1e6+1))),g.a=c,g.b=d,g.es=e,g.ep2=f,g}function z(b,c){if(!(this instanceof z))return new z(b);c=c||function(a){if(a)throw a};var d=n(b);if("object"!=typeof d)return void c(b);var e=z.projections.get(d.projName);if(!e)return void c(b);if(d.datumCode&&"none"!==d.datumCode){var f=a(yc,d.datumCode);f&&(d.datum_params=f.towgs84?f.towgs84.split(","):null,d.ellps=f.ellipse,d.datumName=f.datumName?f.datumName:d.datumCode)}d.k0=d.k0||1,d.axis=d.axis||"enu",d.ellps=d.ellps||"wgs84";var g=x(d.a,d.b,d.rf,d.ellps,d.sphere),h=w(g.a,g.b,g.rf,d.R_A),i=d.datum||y(d.datumCode,d.datum_params,g.a,g.b,h.es,h.ep2);ic(this,d),ic(this,e),this.a=g.a,this.b=g.b,this.rf=g.rf,this.sphere=g.sphere,this.es=h.es,this.e=h.e,this.ep2=h.ep2,this.datum=i,this.init(),c(null,this)}function A(a,b){return a.datum_type!==b.datum_type?!1:a.a!==b.a||Math.abs(a.es-b.es)>5e-11?!1:a.datum_type===Db?a.datum_params[0]===b.datum_params[0]&&a.datum_params[1]===b.datum_params[1]&&a.datum_params[2]===b.datum_params[2]:a.datum_type===Eb?a.datum_params[0]===b.datum_params[0]&&a.datum_params[1]===b.datum_params[1]&&a.datum_params[2]===b.datum_params[2]&&a.datum_params[3]===b.datum_params[3]&&a.datum_params[4]===b.datum_params[4]&&a.datum_params[5]===b.datum_params[5]&&a.datum_params[6]===b.datum_params[6]:!0}function B(a,b,c){var d,e,f,g,h=a.x,i=a.y,j=a.z?a.z:0;if(-Ib>i&&i>-1.001*Ib)i=-Ib;else if(i>Ib&&1.001*Ib>i)i=Ib;else if(-Ib>i||i>Ib)return null;return h>Math.PI&&(h-=2*Math.PI),e=Math.sin(i),g=Math.cos(i),f=e*e,d=c/Math.sqrt(1-b*f),{x:(d+j)*g*Math.cos(h),y:(d+j)*g*Math.sin(h),z:(d*(1-b)+j)*e}}function C(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u=1e-12,v=u*u,w=30,x=a.x,y=a.y,z=a.z?a.z:0;if(e=Math.sqrt(x*x+y*y),f=Math.sqrt(x*x+y*y+z*z),u>e/c){if(r=0,u>f/c)return s=Ib,t=-d,{x:a.x,y:a.y,z:a.z}}else r=Math.atan2(y,x);g=z/f,h=e/f,i=1/Math.sqrt(1-b*(2-b)*h*h),l=h*(1-b)*i,m=g*i,q=0;do q++,k=c/Math.sqrt(1-b*m*m),t=e*l+z*m-k*(1-b*m*m),j=b*k/(k+t),i=1/Math.sqrt(1-j*(2-j)*h*h),n=h*(1-j)*i,o=g*i,p=o*l-n*m,l=n,m=o;while(p*p>v&&w>q);return s=Math.atan(o/Math.abs(n)),{x:r,y:s,z:t}}function D(a,b,c){if(b===Db)return{x:a.x+c[0],y:a.y+c[1],z:a.z+c[2]};if(b===Eb){var d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],j=c[6];return{x:j*(a.x-i*a.y+h*a.z)+d,y:j*(i*a.x+a.y-g*a.z)+e,z:j*(-h*a.x+g*a.y+a.z)+f}}}function E(a,b,c){if(b===Db)return{x:a.x-c[0],y:a.y-c[1],z:a.z-c[2]};if(b===Eb){var d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],j=c[6],k=(a.x-d)/j,l=(a.y-e)/j,m=(a.z-f)/j;return{x:k+i*l-h*m,y:-i*k+l+g*m,z:h*k-g*l+m}}}function F(a){return a===Db||a===Eb}function G(a){if("function"==typeof Number.isFinite){if(Number.isFinite(a))return;throw new TypeError("coordinates must be finite numbers")}if("number"!=typeof a||a!==a||!isFinite(a))throw new TypeError("coordinates must be finite numbers")}function H(a,b){return(a.datum.datum_type===Db||a.datum.datum_type===Eb)&&"WGS84"!==b.datumCode||(b.datum.datum_type===Db||b.datum.datum_type===Eb)&&"WGS84"!==a.datumCode}function I(a,b,c){var d;return Array.isArray(c)&&(c=Bc(c)),Cc(c),a.datum&&b.datum&&H(a,b)&&(d=new z("WGS84"),c=I(a,d,c),a=d),"enu"!==a.axis&&(c=Ac(a,!1,c)),"longlat"===a.projName?c={x:c.x*Nb,y:c.y*Nb}:(a.to_meter&&(c={x:c.x*a.to_meter,y:c.y*a.to_meter}),c=a.inverse(c)),a.from_greenwich&&(c.x+=a.from_greenwich),c=zc(a.datum,b.datum,c),b.from_greenwich&&(c={x:c.x-b.from_greenwich,y:c.y}),"longlat"===b.projName?c={x:c.x*Ob,y:c.y*Ob}:(c=b.forward(c),b.to_meter&&(c={x:c.x/b.to_meter,y:c.y/b.to_meter})),"enu"!==b.axis?Ac(b,!0,c):c}function J(a,b,c){var d,e,f;return Array.isArray(c)?(d=I(a,b,c),3===c.length?[d.x,d.y,d.z]:[d.x,d.y]):(e=I(a,b,c),f=Object.keys(c),2===f.length?e:(f.forEach(function(a){"x"!==a&&"y"!==a&&(e[a]=c[a])}),e))}function K(a){return a instanceof z?a:a.oProj?a.oProj:z(a)}function L(a,b,c){a=K(a);var d,e=!1;return"undefined"==typeof b?(b=a,a=Dc,e=!0):("undefined"!=typeof b.x||Array.isArray(b))&&(c=b,b=a,a=Dc,e=!0),b=K(b),c?J(a,b,c):(d={forward:function(c){return J(a,b,c)},inverse:function(c){return J(b,a,c)}},e&&(d.oProj=b),d)}function M(a,b){return b=b||5,U(R({lat:a[1],lon:a[0]}),b)}function N(a){var b=S(Y(a.toUpperCase()));return b.lat&&b.lon?[b.lon,b.lat,b.lon,b.lat]:[b.left,b.bottom,b.right,b.top]}function O(a){var b=S(Y(a.toUpperCase()));return b.lat&&b.lon?[b.lon,b.lat]:[(b.left+b.right)/2,(b.top+b.bottom)/2]}function P(a){return a*(Math.PI/180)}function Q(a){return 180*(a/Math.PI)}function R(a){var b,c,d,e,f,g,h,i,j,k=a.lat,l=a.lon,m=6378137,n=.00669438,o=.9996,p=P(k),q=P(l);j=Math.floor((l+180)/6)+1,180===l&&(j=60),k>=56&&64>k&&l>=3&&12>l&&(j=32),k>=72&&84>k&&(l>=0&&9>l?j=31:l>=9&&21>l?j=33:l>=21&&33>l?j=35:l>=33&&42>l&&(j=37)),b=6*(j-1)-180+3,i=P(b),c=n/(1-n),d=m/Math.sqrt(1-n*Math.sin(p)*Math.sin(p)),e=Math.tan(p)*Math.tan(p),f=c*Math.cos(p)*Math.cos(p),g=Math.cos(p)*(q-i),h=m*((1-n/4-3*n*n/64-5*n*n*n/256)*p-(3*n/8+3*n*n/32+45*n*n*n/1024)*Math.sin(2*p)+(15*n*n/256+45*n*n*n/1024)*Math.sin(4*p)-35*n*n*n/3072*Math.sin(6*p));var r=o*d*(g+(1-e+f)*g*g*g/6+(5-18*e+e*e+72*f-58*c)*g*g*g*g*g/120)+5e5,s=o*(h+d*Math.tan(p)*(g*g/2+(5-e+9*f+4*f*f)*g*g*g*g/24+(61-58*e+e*e+600*f-330*c)*g*g*g*g*g*g/720));return 0>k&&(s+=1e7),{northing:Math.round(s),easting:Math.round(r),zoneNumber:j,zoneLetter:T(k)}}function S(a){var b=a.northing,c=a.easting,d=a.zoneLetter,e=a.zoneNumber;if(0>e||e>60)return null;var f,g,h,i,j,k,l,m,n,o,p=.9996,q=6378137,r=.00669438,s=(1-Math.sqrt(1-r))/(1+Math.sqrt(1-r)),t=c-5e5,u=b;"N">d&&(u-=1e7),m=6*(e-1)-180+3,f=r/(1-r),l=u/p,n=l/(q*(1-r/4-3*r*r/64-5*r*r*r/256)),o=n+(3*s/2-27*s*s*s/32)*Math.sin(2*n)+(21*s*s/16-55*s*s*s*s/32)*Math.sin(4*n)+151*s*s*s/96*Math.sin(6*n),g=q/Math.sqrt(1-r*Math.sin(o)*Math.sin(o)),h=Math.tan(o)*Math.tan(o),i=f*Math.cos(o)*Math.cos(o),j=q*(1-r)/Math.pow(1-r*Math.sin(o)*Math.sin(o),1.5),k=t/(g*p);var v=o-g*Math.tan(o)/j*(k*k/2-(5+3*h+10*i-4*i*i-9*f)*k*k*k*k/24+(61+90*h+298*i+45*h*h-252*f-3*i*i)*k*k*k*k*k*k/720);v=Q(v);var w=(k-(1+2*h+i)*k*k*k/6+(5-2*i+28*h-3*i*i+8*f+24*h*h)*k*k*k*k*k/120)/Math.cos(o);w=m+Q(w);var x;if(a.accuracy){var y=S({northing:a.northing+a.accuracy,easting:a.easting+a.accuracy,zoneLetter:a.zoneLetter,zoneNumber:a.zoneNumber});x={top:y.lat,right:y.lon,bottom:v,left:w}}else x={lat:v,lon:w};return x}function T(a){var b="Z";return 84>=a&&a>=72?b="X":72>a&&a>=64?b="W":64>a&&a>=56?b="V":56>a&&a>=48?b="U":48>a&&a>=40?b="T":40>a&&a>=32?b="S":32>a&&a>=24?b="R":24>a&&a>=16?b="Q":16>a&&a>=8?b="P":8>a&&a>=0?b="N":0>a&&a>=-8?b="M":-8>a&&a>=-16?b="L":-16>a&&a>=-24?b="K":-24>a&&a>=-32?b="J":-32>a&&a>=-40?b="H":-40>a&&a>=-48?b="G":-48>a&&a>=-56?b="F":-56>a&&a>=-64?b="E":-64>a&&a>=-72?b="D":-72>a&&a>=-80&&(b="C"),b}function U(a,b){var c="00000"+a.easting,d="00000"+a.northing;return a.zoneNumber+a.zoneLetter+V(a.easting,a.northing,a.zoneNumber)+c.substr(c.length-5,b)+d.substr(d.length-5,b)}function V(a,b,c){var d=W(c),e=Math.floor(a/1e5),f=Math.floor(b/1e5)%20;return X(e,f,d)}function W(a){var b=a%Ec;return 0===b&&(b=Ec),b}function X(a,b,c){var d=c-1,e=Fc.charCodeAt(d),f=Gc.charCodeAt(d),g=e+a-1,h=f+b,i=!1;g>Lc&&(g=g-Lc+Hc-1,i=!0),(g===Ic||Ic>e&&g>Ic||(g>Ic||Ic>e)&&i)&&g++,(g===Jc||Jc>e&&g>Jc||(g>Jc||Jc>e)&&i)&&(g++,g===Ic&&g++),g>Lc&&(g=g-Lc+Hc-1),h>Kc?(h=h-Kc+Hc-1,i=!0):i=!1,(h===Ic||Ic>f&&h>Ic||(h>Ic||Ic>f)&&i)&&h++,(h===Jc||Jc>f&&h>Jc||(h>Jc||Jc>f)&&i)&&(h++,h===Ic&&h++),h>Kc&&(h=h-Kc+Hc-1);var j=String.fromCharCode(g)+String.fromCharCode(h);return j}function Y(a){if(a&&0===a.length)throw"MGRSPoint coverting from nothing";for(var b,c=a.length,d=null,e="",f=0;!/[A-Z]/.test(b=a.charAt(f));){if(f>=2)throw"MGRSPoint bad conversion from: "+a;e+=b,f++}var g=parseInt(e,10);if(0===f||f+3>c)throw"MGRSPoint bad conversion from: "+a;var h=a.charAt(f++);if("A">=h||"B"===h||"Y"===h||h>="Z"||"I"===h||"O"===h)throw"MGRSPoint zone letter "+h+" not handled: "+a;d=a.substring(f,f+=2);for(var i=W(g),j=Z(d.charAt(0),i),k=$(d.charAt(1),i);k<_(h);)k+=2e6;var l=c-f;if(l%2!==0)throw"MGRSPoint has to have an even number \nof digits after the zone letter and two 100km letters - front \nhalf for easting meters, second half for \nnorthing meters"+a;var m,n,o,p,q,r=l/2,s=0,t=0;return r>0&&(m=1e5/Math.pow(10,r),n=a.substring(f,f+r),s=parseFloat(n)*m,o=a.substring(f+r),t=parseFloat(o)*m),p=s+j,q=t+k,{easting:p,northing:q,zoneLetter:h,zoneNumber:g,accuracy:m}}function Z(a,b){for(var c=Fc.charCodeAt(b-1),d=1e5,e=!1;c!==a.charCodeAt(0);){if(c++,c===Ic&&c++,c===Jc&&c++,c>Lc){if(e)throw"Bad character: "+a;c=Hc,e=!0}d+=1e5}return d}function $(a,b){if(a>"V")throw"MGRSPoint given invalid Northing "+a;for(var c=Gc.charCodeAt(b-1),d=0,e=!1;c!==a.charCodeAt(0);){if(c++,c===Ic&&c++,c===Jc&&c++,c>Kc){if(e)throw"Bad character: "+a;c=Hc,e=!0}d+=1e5}return d}function _(a){var b;switch(a){case"C":b=11e5;break;case"D":b=2e6;break;case"E":b=28e5;break;case"F":b=37e5;break;case"G":b=46e5;break;case"H":b=55e5;break;case"J":b=64e5;break;case"K":b=73e5;break;case"L":b=82e5;break;case"M":b=91e5;break;case"N":b=0;break;case"P":b=8e5;break;case"Q":b=17e5;break;case"R":b=26e5;break;case"S":b=35e5;break;case"T":b=44e5;break;case"U":b=53e5;break;case"V":b=62e5;break;case"W":b=7e6;break;case"X":b=79e5;break;default:b=-1}if(b>=0)return b;throw"Invalid zone letter: "+a}function Point(a,b,c){if(!(this instanceof Point))return new Point(a,b,c);if(Array.isArray(a))this.x=a[0],this.y=a[1],this.z=a[2]||0;else if("object"==typeof a)this.x=a.x,this.y=a.y,this.z=a.z||0;else if("string"==typeof a&&"undefined"==typeof b){var d=a.split(",");this.x=parseFloat(d[0],10),this.y=parseFloat(d[1],10),this.z=parseFloat(d[2],10)||0}else this.x=a,this.y=b,this.z=c||0;console.warn("proj4.Point will be removed in version 3, use proj4.toPoint")}function aa(){this.x0=void 0!==this.x0?this.x0:0,this.y0=void 0!==this.y0?this.y0:0,this.long0=void 0!==this.long0?this.long0:0,this.lat0=void 0!==this.lat0?this.lat0:0,this.es&&(this.en=$c(this.es),this.ml0=_c(this.lat0,Math.sin(this.lat0),Math.cos(this.lat0),this.en))}function ba(a){var b,c,d,e=a.x,f=a.y,g=lc(e-this.long0),h=Math.sin(f),i=Math.cos(f);if(this.es){var j=i*g,k=Math.pow(j,2),l=this.ep2*Math.pow(i,2),m=Math.pow(l,2),n=Math.abs(i)>Mb?Math.tan(f):0,o=Math.pow(n,2),p=Math.pow(o,2);b=1-this.es*Math.pow(h,2),j/=Math.sqrt(b);var q=_c(f,h,i,this.en);c=this.a*(this.k0*j*(1+k/6*(1-o+l+k/20*(5-18*o+p+14*l-58*o*l+k/42*(61+179*p-p*o-479*o)))))+this.x0,d=this.a*(this.k0*(q-this.ml0+h*g*j/2*(1+k/12*(5-o+9*l+4*m+k/30*(61+p-58*o+270*l-330*o*l+k/56*(1385+543*p-p*o-3111*o))))))+this.y0}else{var r=i*Math.sin(g);if(Math.abs(Math.abs(r)-1)<Mb)return 93;if(c=.5*this.a*this.k0*Math.log((1+r)/(1-r))+this.x0,d=i*Math.cos(g)/Math.sqrt(1-Math.pow(r,2)),r=Math.abs(d),r>=1){if(r-1>Mb)return 93;d=0}else d=Math.acos(d);0>f&&(d=-d),d=this.a*this.k0*(d-this.lat0)+this.y0}return a.x=c,a.y=d,a}function ca(a){var b,c,d,e,f=(a.x-this.x0)*(1/this.a),g=(a.y-this.y0)*(1/this.a);if(this.es)if(b=this.ml0+g/this.k0,c=bd(b,this.es,this.en),Math.abs(c)<Ib){var h=Math.sin(c),i=Math.cos(c),j=Math.abs(i)>Mb?Math.tan(c):0,k=this.ep2*Math.pow(i,2),l=Math.pow(k,2),m=Math.pow(j,2),n=Math.pow(m,2);b=1-this.es*Math.pow(h,2);var o=f*Math.sqrt(b)/this.k0,p=Math.pow(o,2);b*=j,d=c-b*p/(1-this.es)*.5*(1-p/12*(5+3*m-9*k*m+k-4*l-p/30*(61+90*m-252*k*m+45*n+46*k-p/56*(1385+3633*m+4095*n+1574*n*m)))),e=lc(this.long0+o*(1-p/6*(1+2*m+k-p/20*(5+28*m+24*n+8*k*m+6*k-p/42*(61+662*m+1320*n+720*n*m))))/i)}else d=Ib*kc(g),e=0;else{var q=Math.exp(f/this.k0),r=.5*(q-1/q),s=this.lat0+g/this.k0,t=Math.cos(s);b=Math.sqrt((1-Math.pow(t,2))/(1+Math.pow(r,2))),d=Math.asin(b),0>g&&(d=-d),e=0===r&&0===t?0:lc(Math.atan2(r,t)+this.long0)}return a.x=e,a.y=d,a}function da(){if(void 0===this.es||this.es<=0)throw new Error("incorrect elliptical usage");this.x0=void 0!==this.x0?this.x0:0,this.y0=void 0!==this.y0?this.y0:0,this.long0=void 0!==this.long0?this.long0:0,this.lat0=void 0!==this.lat0?this.lat0:0,this.cgb=[],this.cbg=[],this.utg=[],this.gtu=[];var a=this.es/(1+Math.sqrt(1-this.es)),b=a/(2-a),c=b;this.cgb[0]=b*(2+b*(-2/3+b*(-2+b*(116/45+b*(26/45+b*(-2854/675)))))),this.cbg[0]=b*(-2+b*(2/3+b*(4/3+b*(-82/45+b*(32/45+b*(4642/4725)))))),c*=b,this.cgb[1]=c*(7/3+b*(-1.6+b*(-227/45+b*(2704/315+b*(2323/945))))),this.cbg[1]=c*(5/3+b*(-16/15+b*(-13/9+b*(904/315+b*(-1522/945))))),c*=b,this.cgb[2]=c*(56/15+b*(-136/35+b*(-1262/105+b*(73814/2835)))),this.cbg[2]=c*(-26/15+b*(34/21+b*(1.6+b*(-12686/2835)))),c*=b,this.cgb[3]=c*(4279/630+b*(-332/35+b*(-399572/14175))),this.cbg[3]=c*(1237/630+b*(-2.4+b*(-24832/14175))),c*=b,this.cgb[4]=c*(4174/315+b*(-144838/6237)),this.cbg[4]=c*(-734/315+b*(109598/31185)),c*=b,this.cgb[5]=c*(601676/22275),this.cbg[5]=c*(444337/155925),c=Math.pow(b,2),this.Qn=this.k0/(1+b)*(1+c*(.25+c*(1/64+c/256))),this.utg[0]=b*(-.5+b*(2/3+b*(-37/96+b*(1/360+b*(81/512+b*(-96199/604800)))))),this.gtu[0]=b*(.5+b*(-2/3+b*(5/16+b*(41/180+b*(-127/288+b*(7891/37800)))))),this.utg[1]=c*(-1/48+b*(-1/15+b*(437/1440+b*(-46/105+b*(1118711/3870720))))),this.gtu[1]=c*(13/48+b*(-0.6+b*(557/1440+b*(281/630+b*(-1983433/1935360))))),c*=b,this.utg[2]=c*(-17/480+b*(37/840+b*(209/4480+b*(-5569/90720)))),this.gtu[2]=c*(61/240+b*(-103/140+b*(15061/26880+b*(167603/181440)))),c*=b,this.utg[3]=c*(-4397/161280+b*(11/504+b*(830251/7257600))),this.gtu[3]=c*(49561/161280+b*(-179/168+b*(6601661/7257600))),c*=b,this.utg[4]=c*(-4583/161280+b*(108847/3991680)),this.gtu[4]=c*(34729/80640+b*(-3418889/1995840)),c*=b,this.utg[5]=c*(-20648693/638668800),this.gtu[5]=.6650675310896665*c;var d=id(this.cbg,this.lat0);this.Zb=-this.Qn*(d+jd(this.gtu,2*d))}function ea(a){var b=lc(a.x-this.long0),c=a.y;c=id(this.cbg,c);var d=Math.sin(c),e=Math.cos(c),f=Math.sin(b),g=Math.cos(b);c=Math.atan2(d,g*e),b=Math.atan2(f*e,fd(d,e*g)),b=hd(Math.tan(b));var h=ld(this.gtu,2*c,2*b);c+=h[0],b+=h[1];var i,j;return Math.abs(b)<=2.623395162778?(i=this.a*(this.Qn*b)+this.x0,j=this.a*(this.Qn*c+this.Zb)+this.y0):(i=1/0,j=1/0),a.x=i,a.y=j,a}function fa(a){var b=(a.x-this.x0)*(1/this.a),c=(a.y-this.y0)*(1/this.a);c=(c-this.Zb)/this.Qn,b/=this.Qn;var d,e;if(Math.abs(b)<=2.623395162778){var f=ld(this.utg,2*c,2*b);c+=f[0],b+=f[1],b=Math.atan(ed(b));var g=Math.sin(c),h=Math.cos(c),i=Math.sin(b),j=Math.cos(b);c=Math.atan2(g*j,fd(i,j*h)),b=Math.atan2(i,j*h),d=lc(b+this.long0),e=id(this.cgb,c)}else d=1/0,e=1/0;return a.x=d,a.y=e,a}function ga(){var a=od(this.zone,this.long0);if(void 0===a)throw new Error("unknown utm zone");this.lat0=0,this.long0=(6*Math.abs(a)-183)*Nb,this.x0=5e5,this.y0=this.utmSouth?1e7:0,this.k0=.9996,nd.init.apply(this),this.forward=nd.forward,this.inverse=nd.inverse}function ha(){var a=Math.sin(this.lat0),b=Math.cos(this.lat0);b*=b,this.rc=Math.sqrt(1-this.es)/(1-this.es*a*a),this.C=Math.sqrt(1+this.es*b*b/(1-this.es)),this.phic0=Math.asin(a/this.C),this.ratexp=.5*this.C*this.e,this.K=Math.tan(.5*this.phic0+Pb)/(Math.pow(Math.tan(.5*this.lat0+Pb),this.C)*sd(this.e*a,this.ratexp))}function ia(a){var b=a.x,c=a.y;return a.y=2*Math.atan(this.K*Math.pow(Math.tan(.5*c+Pb),this.C)*sd(this.e*Math.sin(c),this.ratexp))-Ib,a.x=this.C*b,a}function ja(a){for(var b=1e-14,c=a.x/this.C,d=a.y,e=Math.pow(Math.tan(.5*d+Pb)/this.K,1/this.C),f=td;f>0&&(d=2*Math.atan(e*sd(this.e*Math.sin(a.y),-.5*this.e))-Ib,!(Math.abs(d-a.y)<b));--f)a.y=d;return f?(a.x=c,a.y=d,a):null}function ka(){vd.init.apply(this),this.rc&&(this.sinc0=Math.sin(this.phic0),this.cosc0=Math.cos(this.phic0),this.R2=2*this.rc,this.title||(this.title="Oblique Stereographic Alternative"))}function la(a){var b,c,d,e;return a.x=lc(a.x-this.long0),vd.forward.apply(this,[a]),b=Math.sin(a.y),c=Math.cos(a.y),d=Math.cos(a.x),e=this.k0*this.R2/(1+this.sinc0*b+this.cosc0*c*d),a.x=e*c*Math.sin(a.x),a.y=e*(this.cosc0*b-this.sinc0*c*d),a.x=this.a*a.x+this.x0,a.y=this.a*a.y+this.y0,a}function ma(a){var b,c,d,e,f;if(a.x=(a.x-this.x0)/this.a,a.y=(a.y-this.y0)/this.a,a.x/=this.k0,a.y/=this.k0,f=Math.sqrt(a.x*a.x+a.y*a.y)){var g=2*Math.atan2(f,this.R2);b=Math.sin(g),c=Math.cos(g),e=Math.asin(c*this.sinc0+a.y*b*this.cosc0/f),d=Math.atan2(a.x*b,f*this.cosc0*c-a.y*this.sinc0*b)}else e=this.phic0,d=0;return a.x=d,a.y=e,vd.inverse.apply(this,[a]),a.x=lc(a.x+this.long0),a}function na(a,b,c){return b*=c,Math.tan(.5*(Ib+a))*Math.pow((1-b)/(1+b),.5*c)}function oa(){this.coslat0=Math.cos(this.lat0),this.sinlat0=Math.sin(this.lat0),this.sphere?1===this.k0&&!isNaN(this.lat_ts)&&Math.abs(this.coslat0)<=Mb&&(this.k0=.5*(1+kc(this.lat0)*Math.sin(this.lat_ts))):(Math.abs(this.coslat0)<=Mb&&(this.lat0>0?this.con=1:this.con=-1),this.cons=Math.sqrt(Math.pow(1+this.e,1+this.e)*Math.pow(1-this.e,1-this.e)),1===this.k0&&!isNaN(this.lat_ts)&&Math.abs(this.coslat0)<=Mb&&(this.k0=.5*this.cons*jc(this.e,Math.sin(this.lat_ts),Math.cos(this.lat_ts))/mc(this.e,this.con*this.lat_ts,this.con*Math.sin(this.lat_ts))),this.ms1=jc(this.e,this.sinlat0,this.coslat0),this.X0=2*Math.atan(this.ssfn_(this.lat0,this.sinlat0,this.e))-Ib,this.cosX0=Math.cos(this.X0),this.sinX0=Math.sin(this.X0))}function pa(a){var b,c,d,e,f,g,h=a.x,i=a.y,j=Math.sin(i),k=Math.cos(i),l=lc(h-this.long0);return Math.abs(Math.abs(h-this.long0)-Math.PI)<=Mb&&Math.abs(i+this.lat0)<=Mb?(a.x=NaN,a.y=NaN,a):this.sphere?(b=2*this.k0/(1+this.sinlat0*j+this.coslat0*k*Math.cos(l)),a.x=this.a*b*k*Math.sin(l)+this.x0,a.y=this.a*b*(this.coslat0*j-this.sinlat0*k*Math.cos(l))+this.y0,a):(c=2*Math.atan(this.ssfn_(i,j,this.e))-Ib,e=Math.cos(c),d=Math.sin(c),Math.abs(this.coslat0)<=Mb?(f=mc(this.e,i*this.con,this.con*j),g=2*this.a*this.k0*f/this.cons,a.x=this.x0+g*Math.sin(h-this.long0),a.y=this.y0-this.con*g*Math.cos(h-this.long0),a):(Math.abs(this.sinlat0)<Mb?(b=2*this.a*this.k0/(1+e*Math.cos(l)),a.y=b*d):(b=2*this.a*this.k0*this.ms1/(this.cosX0*(1+this.sinX0*d+this.cosX0*e*Math.cos(l))),a.y=b*(this.cosX0*d-this.sinX0*e*Math.cos(l))+this.y0),a.x=b*e*Math.sin(l)+this.x0,a))}function qa(a){a.x-=this.x0,a.y-=this.y0;var b,c,d,e,f,g=Math.sqrt(a.x*a.x+a.y*a.y);if(this.sphere){var h=2*Math.atan(g/(.5*this.a*this.k0));return b=this.long0,c=this.lat0,Mb>=g?(a.x=b,a.y=c,a):(c=Math.asin(Math.cos(h)*this.sinlat0+a.y*Math.sin(h)*this.coslat0/g),b=lc(Math.abs(this.coslat0)<Mb?this.lat0>0?this.long0+Math.atan2(a.x,-1*a.y):this.long0+Math.atan2(a.x,a.y):this.long0+Math.atan2(a.x*Math.sin(h),g*this.coslat0*Math.cos(h)-a.y*this.sinlat0*Math.sin(h))),a.x=b,a.y=c,a)}if(Math.abs(this.coslat0)<=Mb){if(Mb>=g)return c=this.lat0,b=this.long0,a.x=b,a.y=c,a;a.x*=this.con,a.y*=this.con,d=g*this.cons/(2*this.a*this.k0),c=this.con*nc(this.e,d),b=this.con*lc(this.con*this.long0+Math.atan2(a.x,-1*a.y))}else e=2*Math.atan(g*this.cosX0/(2*this.a*this.k0*this.ms1)),b=this.long0,Mb>=g?f=this.X0:(f=Math.asin(Math.cos(e)*this.sinX0+a.y*Math.sin(e)*this.cosX0/g),b=lc(this.long0+Math.atan2(a.x*Math.sin(e),g*this.cosX0*Math.cos(e)-a.y*this.sinX0*Math.sin(e)))),c=-1*nc(this.e,Math.tan(.5*(Ib+f)));return a.x=b,a.y=c,a}function ra(){var a=this.lat0;this.lambda0=this.long0;var b=Math.sin(a),c=this.a,d=this.rf,e=1/d,f=2*e-Math.pow(e,2),g=this.e=Math.sqrt(f);this.R=this.k0*c*Math.sqrt(1-f)/(1-f*Math.pow(b,2)),this.alpha=Math.sqrt(1+f/(1-f)*Math.pow(Math.cos(a),4)),this.b0=Math.asin(b/this.alpha);var h=Math.log(Math.tan(Math.PI/4+this.b0/2)),i=Math.log(Math.tan(Math.PI/4+a/2)),j=Math.log((1+g*b)/(1-g*b));this.K=h-this.alpha*i+this.alpha*g/2*j}function sa(a){var b=Math.log(Math.tan(Math.PI/4-a.y/2)),c=this.e/2*Math.log((1+this.e*Math.sin(a.y))/(1-this.e*Math.sin(a.y))),d=-this.alpha*(b+c)+this.K,e=2*(Math.atan(Math.exp(d))-Math.PI/4),f=this.alpha*(a.x-this.lambda0),g=Math.atan(Math.sin(f)/(Math.sin(this.b0)*Math.tan(e)+Math.cos(this.b0)*Math.cos(f))),h=Math.asin(Math.cos(this.b0)*Math.sin(e)-Math.sin(this.b0)*Math.cos(e)*Math.cos(f));return a.y=this.R/2*Math.log((1+Math.sin(h))/(1-Math.sin(h)))+this.y0,a.x=this.R*g+this.x0,a}function ta(a){for(var b=a.x-this.x0,c=a.y-this.y0,d=b/this.R,e=2*(Math.atan(Math.exp(c/this.R))-Math.PI/4),f=Math.asin(Math.cos(this.b0)*Math.sin(e)+Math.sin(this.b0)*Math.cos(e)*Math.cos(d)),g=Math.atan(Math.sin(d)/(Math.cos(this.b0)*Math.cos(d)-Math.sin(this.b0)*Math.tan(e))),h=this.lambda0+g/this.alpha,i=0,j=f,k=-1e3,l=0;Math.abs(j-k)>1e-7;){if(++l>20)return;i=1/this.alpha*(Math.log(Math.tan(Math.PI/4+f/2))-this.K)+this.e*Math.log(Math.tan(Math.PI/4+Math.asin(this.e*Math.sin(j))/2)),k=j,j=2*Math.atan(Math.exp(i))-Math.PI/2}return a.x=h,a.y=j,a}function ua(){this.no_off=this.no_off||!1,this.no_rot=this.no_rot||!1,isNaN(this.k0)&&(this.k0=1);var a=Math.sin(this.lat0),b=Math.cos(this.lat0),c=this.e*a;this.bl=Math.sqrt(1+this.es/(1-this.es)*Math.pow(b,4)),this.al=this.a*this.bl*this.k0*Math.sqrt(1-this.es)/(1-c*c);var d=mc(this.e,this.lat0,a),e=this.bl/b*Math.sqrt((1-this.es)/(1-c*c));1>e*e&&(e=1);var f,g;if(isNaN(this.longc)){var h=mc(this.e,this.lat1,Math.sin(this.lat1)),i=mc(this.e,this.lat2,Math.sin(this.lat2));this.lat0>=0?this.el=(e+Math.sqrt(e*e-1))*Math.pow(d,this.bl):this.el=(e-Math.sqrt(e*e-1))*Math.pow(d,this.bl);var j=Math.pow(h,this.bl),k=Math.pow(i,this.bl);f=this.el/j,g=.5*(f-1/f);var l=(this.el*this.el-k*j)/(this.el*this.el+k*j),m=(k-j)/(k+j),n=lc(this.long1-this.long2);this.long0=.5*(this.long1+this.long2)-Math.atan(l*Math.tan(.5*this.bl*n)/m)/this.bl,this.long0=lc(this.long0);var o=lc(this.long1-this.long0);this.gamma0=Math.atan(Math.sin(this.bl*o)/g),this.alpha=Math.asin(e*Math.sin(this.gamma0))}else f=this.lat0>=0?e+Math.sqrt(e*e-1):e-Math.sqrt(e*e-1),this.el=f*Math.pow(d,this.bl),g=.5*(f-1/f),this.gamma0=Math.asin(Math.sin(this.alpha)/e),this.long0=this.longc-Math.asin(g*Math.tan(this.gamma0))/this.bl;this.no_off?this.uc=0:this.lat0>=0?this.uc=this.al/this.bl*Math.atan2(Math.sqrt(e*e-1),Math.cos(this.alpha)):this.uc=-1*this.al/this.bl*Math.atan2(Math.sqrt(e*e-1),Math.cos(this.alpha))}function va(a){var b,c,d,e=a.x,f=a.y,g=lc(e-this.long0);if(Math.abs(Math.abs(f)-Ib)<=Mb)d=f>0?-1:1,c=this.al/this.bl*Math.log(Math.tan(Pb+d*this.gamma0*.5)),b=-1*d*Ib*this.al/this.bl;else{var h=mc(this.e,f,Math.sin(f)),i=this.el/Math.pow(h,this.bl),j=.5*(i-1/i),k=.5*(i+1/i),l=Math.sin(this.bl*g),m=(j*Math.sin(this.gamma0)-l*Math.cos(this.gamma0))/k;c=Math.abs(Math.abs(m)-1)<=Mb?Number.POSITIVE_INFINITY:.5*this.al*Math.log((1-m)/(1+m))/this.bl,b=Math.abs(Math.cos(this.bl*g))<=Mb?this.al*this.bl*g:this.al*Math.atan2(j*Math.cos(this.gamma0)+l*Math.sin(this.gamma0),Math.cos(this.bl*g))/this.bl}return this.no_rot?(a.x=this.x0+b,a.y=this.y0+c):(b-=this.uc,a.x=this.x0+c*Math.cos(this.alpha)+b*Math.sin(this.alpha),a.y=this.y0+b*Math.cos(this.alpha)-c*Math.sin(this.alpha)),a}function wa(a){var b,c;this.no_rot?(c=a.y-this.y0,b=a.x-this.x0):(c=(a.x-this.x0)*Math.cos(this.alpha)-(a.y-this.y0)*Math.sin(this.alpha),b=(a.y-this.y0)*Math.cos(this.alpha)+(a.x-this.x0)*Math.sin(this.alpha),b+=this.uc);var d=Math.exp(-1*this.bl*c/this.al),e=.5*(d-1/d),f=.5*(d+1/d),g=Math.sin(this.bl*b/this.al),h=(g*Math.cos(this.gamma0)+e*Math.sin(this.gamma0))/f,i=Math.pow(this.el/Math.sqrt((1+h)/(1-h)),1/this.bl);return Math.abs(h-1)<Mb?(a.x=this.long0,a.y=Ib):Math.abs(h+1)<Mb?(a.x=this.long0,a.y=-1*Ib):(a.y=nc(this.e,i),a.x=lc(this.long0-Math.atan2(e*Math.cos(this.gamma0)-g*Math.sin(this.gamma0),Math.cos(this.bl*b/this.al))/this.bl)),a}function xa(){if(this.lat2||(this.lat2=this.lat1),this.k0||(this.k0=1),this.x0=this.x0||0,this.y0=this.y0||0,!(Math.abs(this.lat1+this.lat2)<Mb)){var a=this.b/this.a;this.e=Math.sqrt(1-a*a);var b=Math.sin(this.lat1),c=Math.cos(this.lat1),d=jc(this.e,b,c),e=mc(this.e,this.lat1,b),f=Math.sin(this.lat2),g=Math.cos(this.lat2),h=jc(this.e,f,g),i=mc(this.e,this.lat2,f),j=mc(this.e,this.lat0,Math.sin(this.lat0));Math.abs(this.lat1-this.lat2)>Mb?this.ns=Math.log(d/h)/Math.log(e/i):this.ns=b,isNaN(this.ns)&&(this.ns=b),this.f0=d/(this.ns*Math.pow(e,this.ns)),this.rh=this.a*this.f0*Math.pow(j,this.ns),this.title||(this.title="Lambert Conformal Conic")}}function ya(a){var b=a.x,c=a.y;Math.abs(2*Math.abs(c)-Math.PI)<=Mb&&(c=kc(c)*(Ib-2*Mb));var d,e,f=Math.abs(Math.abs(c)-Ib);if(f>Mb)d=mc(this.e,c,Math.sin(c)),e=this.a*this.f0*Math.pow(d,this.ns);else{if(f=c*this.ns,0>=f)return null;e=0}var g=this.ns*lc(b-this.long0);return a.x=this.k0*(e*Math.sin(g))+this.x0,a.y=this.k0*(this.rh-e*Math.cos(g))+this.y0,a}function za(a){var b,c,d,e,f,g=(a.x-this.x0)/this.k0,h=this.rh-(a.y-this.y0)/this.k0;this.ns>0?(b=Math.sqrt(g*g+h*h),c=1):(b=-Math.sqrt(g*g+h*h),c=-1);var i=0;if(0!==b&&(i=Math.atan2(c*g,c*h)),0!==b||this.ns>0){if(c=1/this.ns,d=Math.pow(b/(this.a*this.f0),c),e=nc(this.e,d),-9999===e)return null}else e=-Ib;return f=lc(i/this.ns+this.long0),a.x=f,a.y=e,a}function Aa(){this.a=6377397.155,this.es=.006674372230614,this.e=Math.sqrt(this.es),this.lat0||(this.lat0=.863937979737193),this.long0||(this.long0=.4334234309119251),this.k0||(this.k0=.9999),this.s45=.785398163397448,this.s90=2*this.s45,this.fi0=this.lat0,this.e2=this.es,this.e=Math.sqrt(this.e2),this.alfa=Math.sqrt(1+this.e2*Math.pow(Math.cos(this.fi0),4)/(1-this.e2)),this.uq=1.04216856380474,this.u0=Math.asin(Math.sin(this.fi0)/this.alfa),this.g=Math.pow((1+this.e*Math.sin(this.fi0))/(1-this.e*Math.sin(this.fi0)),this.alfa*this.e/2),this.k=Math.tan(this.u0/2+this.s45)/Math.pow(Math.tan(this.fi0/2+this.s45),this.alfa)*this.g,
this.k1=this.k0,this.n0=this.a*Math.sqrt(1-this.e2)/(1-this.e2*Math.pow(Math.sin(this.fi0),2)),this.s0=1.37008346281555,this.n=Math.sin(this.s0),this.ro0=this.k1*this.n0/Math.tan(this.s0),this.ad=this.s90-this.uq}function Ba(a){var b,c,d,e,f,g,h,i=a.x,j=a.y,k=lc(i-this.long0);return b=Math.pow((1+this.e*Math.sin(j))/(1-this.e*Math.sin(j)),this.alfa*this.e/2),c=2*(Math.atan(this.k*Math.pow(Math.tan(j/2+this.s45),this.alfa)/b)-this.s45),d=-k*this.alfa,e=Math.asin(Math.cos(this.ad)*Math.sin(c)+Math.sin(this.ad)*Math.cos(c)*Math.cos(d)),f=Math.asin(Math.cos(c)*Math.sin(d)/Math.cos(e)),g=this.n*f,h=this.ro0*Math.pow(Math.tan(this.s0/2+this.s45),this.n)/Math.pow(Math.tan(e/2+this.s45),this.n),a.y=h*Math.cos(g)/1,a.x=h*Math.sin(g)/1,this.czech||(a.y*=-1,a.x*=-1),a}function Ca(a){var b,c,d,e,f,g,h,i,j=a.x;a.x=a.y,a.y=j,this.czech||(a.y*=-1,a.x*=-1),g=Math.sqrt(a.x*a.x+a.y*a.y),f=Math.atan2(a.y,a.x),e=f/Math.sin(this.s0),d=2*(Math.atan(Math.pow(this.ro0/g,1/this.n)*Math.tan(this.s0/2+this.s45))-this.s45),b=Math.asin(Math.cos(this.ad)*Math.sin(d)-Math.sin(this.ad)*Math.cos(d)*Math.cos(e)),c=Math.asin(Math.cos(d)*Math.sin(e)/Math.cos(b)),a.x=this.long0-c/this.alfa,h=b,i=0;var k=0;do a.y=2*(Math.atan(Math.pow(this.k,-1/this.alfa)*Math.pow(Math.tan(b/2+this.s45),1/this.alfa)*Math.pow((1+this.e*Math.sin(h))/(1-this.e*Math.sin(h)),this.e/2))-this.s45),Math.abs(h-a.y)<1e-10&&(i=1),h=a.y,k+=1;while(0===i&&15>k);return k>=15?null:a}function Da(){this.sphere||(this.e0=Jd(this.es),this.e1=Kd(this.es),this.e2=Ld(this.es),this.e3=Md(this.es),this.ml0=this.a*Id(this.e0,this.e1,this.e2,this.e3,this.lat0))}function Ea(a){var b,c,d=a.x,e=a.y;if(d=lc(d-this.long0),this.sphere)b=this.a*Math.asin(Math.cos(e)*Math.sin(d)),c=this.a*(Math.atan2(Math.tan(e),Math.cos(d))-this.lat0);else{var f=Math.sin(e),g=Math.cos(e),h=Nd(this.a,this.e,f),i=Math.tan(e)*Math.tan(e),j=d*Math.cos(e),k=j*j,l=this.es*g*g/(1-this.es),m=this.a*Id(this.e0,this.e1,this.e2,this.e3,e);b=h*j*(1-k*i*(1/6-(8-i+8*l)*k/120)),c=m-this.ml0+h*f/g*k*(.5+(5-i+6*l)*k/24)}return a.x=b+this.x0,a.y=c+this.y0,a}function Fa(a){a.x-=this.x0,a.y-=this.y0;var b,c,d=a.x/this.a,e=a.y/this.a;if(this.sphere){var f=e+this.lat0;b=Math.asin(Math.sin(f)*Math.cos(d)),c=Math.atan2(Math.tan(d),Math.cos(f))}else{var g=this.ml0/this.a+e,h=Pd(g,this.e0,this.e1,this.e2,this.e3);if(Math.abs(Math.abs(h)-Ib)<=Mb)return a.x=this.long0,a.y=Ib,0>e&&(a.y*=-1),a;var i=Nd(this.a,this.e,Math.sin(h)),j=i*i*i/this.a/this.a*(1-this.es),k=Math.pow(Math.tan(h),2),l=d*this.a/i,m=l*l;b=h-i*Math.tan(h)/j*l*l*(.5-(1+3*k)*l*l/24),c=l*(1-m*(k/3+(1+3*k)*k*m/15))/Math.cos(h)}return a.x=lc(c+this.long0),a.y=Od(b),a}function Ga(){var a=Math.abs(this.lat0);if(Math.abs(a-Ib)<Mb?this.mode=this.lat0<0?this.S_POLE:this.N_POLE:Math.abs(a)<Mb?this.mode=this.EQUIT:this.mode=this.OBLIQ,this.es>0){var b;switch(this.qp=Sd(this.e,1),this.mmf=.5/(1-this.es),this.apa=Ja(this.es),this.mode){case this.N_POLE:this.dd=1;break;case this.S_POLE:this.dd=1;break;case this.EQUIT:this.rq=Math.sqrt(.5*this.qp),this.dd=1/this.rq,this.xmf=1,this.ymf=.5*this.qp;break;case this.OBLIQ:this.rq=Math.sqrt(.5*this.qp),b=Math.sin(this.lat0),this.sinb1=Sd(this.e,b)/this.qp,this.cosb1=Math.sqrt(1-this.sinb1*this.sinb1),this.dd=Math.cos(this.lat0)/(Math.sqrt(1-this.es*b*b)*this.rq*this.cosb1),this.ymf=(this.xmf=this.rq)/this.dd,this.xmf*=this.dd}}else this.mode===this.OBLIQ&&(this.sinph0=Math.sin(this.lat0),this.cosph0=Math.cos(this.lat0))}function Ha(a){var b,c,d,e,f,g,h,i,j,k,l=a.x,m=a.y;if(l=lc(l-this.long0),this.sphere){if(f=Math.sin(m),k=Math.cos(m),d=Math.cos(l),this.mode===this.OBLIQ||this.mode===this.EQUIT){if(c=this.mode===this.EQUIT?1+k*d:1+this.sinph0*f+this.cosph0*k*d,Mb>=c)return null;c=Math.sqrt(2/c),b=c*k*Math.sin(l),c*=this.mode===this.EQUIT?f:this.cosph0*f-this.sinph0*k*d}else if(this.mode===this.N_POLE||this.mode===this.S_POLE){if(this.mode===this.N_POLE&&(d=-d),Math.abs(m+this.phi0)<Mb)return null;c=Pb-.5*m,c=2*(this.mode===this.S_POLE?Math.cos(c):Math.sin(c)),b=c*Math.sin(l),c*=d}}else{switch(h=0,i=0,j=0,d=Math.cos(l),e=Math.sin(l),f=Math.sin(m),g=Sd(this.e,f),this.mode!==this.OBLIQ&&this.mode!==this.EQUIT||(h=g/this.qp,i=Math.sqrt(1-h*h)),this.mode){case this.OBLIQ:j=1+this.sinb1*h+this.cosb1*i*d;break;case this.EQUIT:j=1+i*d;break;case this.N_POLE:j=Ib+m,g=this.qp-g;break;case this.S_POLE:j=m-Ib,g=this.qp+g}if(Math.abs(j)<Mb)return null;switch(this.mode){case this.OBLIQ:case this.EQUIT:j=Math.sqrt(2/j),c=this.mode===this.OBLIQ?this.ymf*j*(this.cosb1*h-this.sinb1*i*d):(j=Math.sqrt(2/(1+i*d)))*h*this.ymf,b=this.xmf*j*i*e;break;case this.N_POLE:case this.S_POLE:g>=0?(b=(j=Math.sqrt(g))*e,c=d*(this.mode===this.S_POLE?j:-j)):b=c=0}}return a.x=this.a*b+this.x0,a.y=this.a*c+this.y0,a}function Ia(a){a.x-=this.x0,a.y-=this.y0;var b,c,d,e,f,g,h,i=a.x/this.a,j=a.y/this.a;if(this.sphere){var k,l=0,m=0;if(k=Math.sqrt(i*i+j*j),c=.5*k,c>1)return null;switch(c=2*Math.asin(c),this.mode!==this.OBLIQ&&this.mode!==this.EQUIT||(m=Math.sin(c),l=Math.cos(c)),this.mode){case this.EQUIT:c=Math.abs(k)<=Mb?0:Math.asin(j*m/k),i*=m,j=l*k;break;case this.OBLIQ:c=Math.abs(k)<=Mb?this.phi0:Math.asin(l*this.sinph0+j*m*this.cosph0/k),i*=m*this.cosph0,j=(l-Math.sin(c)*this.sinph0)*k;break;case this.N_POLE:j=-j,c=Ib-c;break;case this.S_POLE:c-=Ib}b=0!==j||this.mode!==this.EQUIT&&this.mode!==this.OBLIQ?Math.atan2(i,j):0}else{if(h=0,this.mode===this.OBLIQ||this.mode===this.EQUIT){if(i/=this.dd,j*=this.dd,g=Math.sqrt(i*i+j*j),Mb>g)return a.x=0,a.y=this.phi0,a;e=2*Math.asin(.5*g/this.rq),d=Math.cos(e),i*=e=Math.sin(e),this.mode===this.OBLIQ?(h=d*this.sinb1+j*e*this.cosb1/g,f=this.qp*h,j=g*this.cosb1*d-j*this.sinb1*e):(h=j*e/g,f=this.qp*h,j=g*d)}else if(this.mode===this.N_POLE||this.mode===this.S_POLE){if(this.mode===this.N_POLE&&(j=-j),f=i*i+j*j,!f)return a.x=0,a.y=this.phi0,a;h=1-f/this.qp,this.mode===this.S_POLE&&(h=-h)}b=Math.atan2(i,j),c=Ka(Math.asin(h),this.apa)}return a.x=lc(this.long0+b),a.y=c,a}function Ja(a){var b,c=[];return c[0]=a*Xd,b=a*a,c[0]+=b*Yd,c[1]=b*$d,b*=a,c[0]+=b*Zd,c[1]+=b*_d,c[2]=b*ae,c}function Ka(a,b){var c=a+a;return a+b[0]*Math.sin(c)+b[1]*Math.sin(c+c)+b[2]*Math.sin(c+c+c)}function La(){Math.abs(this.lat1+this.lat2)<Mb||(this.temp=this.b/this.a,this.es=1-Math.pow(this.temp,2),this.e3=Math.sqrt(this.es),this.sin_po=Math.sin(this.lat1),this.cos_po=Math.cos(this.lat1),this.t1=this.sin_po,this.con=this.sin_po,this.ms1=jc(this.e3,this.sin_po,this.cos_po),this.qs1=Sd(this.e3,this.sin_po,this.cos_po),this.sin_po=Math.sin(this.lat2),this.cos_po=Math.cos(this.lat2),this.t2=this.sin_po,this.ms2=jc(this.e3,this.sin_po,this.cos_po),this.qs2=Sd(this.e3,this.sin_po,this.cos_po),this.sin_po=Math.sin(this.lat0),this.cos_po=Math.cos(this.lat0),this.t3=this.sin_po,this.qs0=Sd(this.e3,this.sin_po,this.cos_po),Math.abs(this.lat1-this.lat2)>Mb?this.ns0=(this.ms1*this.ms1-this.ms2*this.ms2)/(this.qs2-this.qs1):this.ns0=this.con,this.c=this.ms1*this.ms1+this.ns0*this.qs1,this.rh=this.a*Math.sqrt(this.c-this.ns0*this.qs0)/this.ns0)}function Ma(a){var b=a.x,c=a.y;this.sin_phi=Math.sin(c),this.cos_phi=Math.cos(c);var d=Sd(this.e3,this.sin_phi,this.cos_phi),e=this.a*Math.sqrt(this.c-this.ns0*d)/this.ns0,f=this.ns0*lc(b-this.long0),g=e*Math.sin(f)+this.x0,h=this.rh-e*Math.cos(f)+this.y0;return a.x=g,a.y=h,a}function Na(a){var b,c,d,e,f,g;return a.x-=this.x0,a.y=this.rh-a.y+this.y0,this.ns0>=0?(b=Math.sqrt(a.x*a.x+a.y*a.y),d=1):(b=-Math.sqrt(a.x*a.x+a.y*a.y),d=-1),e=0,0!==b&&(e=Math.atan2(d*a.x,d*a.y)),d=b*this.ns0/this.a,this.sphere?g=Math.asin((this.c-d*d)/(2*this.ns0)):(c=(this.c-d*d)/this.ns0,g=this.phi1z(this.e3,c)),f=lc(e/this.ns0+this.long0),a.x=f,a.y=g,a}function Oa(a,b){var c,d,e,f,g,h=de(.5*b);if(Mb>a)return h;for(var i=a*a,j=1;25>=j;j++)if(c=Math.sin(h),d=Math.cos(h),e=a*c,f=1-e*e,g=.5*f*f/d*(b/(1-i)-c/f+.5/a*Math.log((1-e)/(1+e))),h+=g,Math.abs(g)<=1e-7)return h;return null}function Pa(){this.sin_p14=Math.sin(this.lat0),this.cos_p14=Math.cos(this.lat0),this.infinity_dist=1e3*this.a,this.rc=1}function Qa(a){var b,c,d,e,f,g,h,i,j=a.x,k=a.y;return d=lc(j-this.long0),b=Math.sin(k),c=Math.cos(k),e=Math.cos(d),g=this.sin_p14*b+this.cos_p14*c*e,f=1,g>0||Math.abs(g)<=Mb?(h=this.x0+this.a*f*c*Math.sin(d)/g,i=this.y0+this.a*f*(this.cos_p14*b-this.sin_p14*c*e)/g):(h=this.x0+this.infinity_dist*c*Math.sin(d),i=this.y0+this.infinity_dist*(this.cos_p14*b-this.sin_p14*c*e)),a.x=h,a.y=i,a}function Ra(a){var b,c,d,e,f,g;return a.x=(a.x-this.x0)/this.a,a.y=(a.y-this.y0)/this.a,a.x/=this.k0,a.y/=this.k0,(b=Math.sqrt(a.x*a.x+a.y*a.y))?(e=Math.atan2(b,this.rc),c=Math.sin(e),d=Math.cos(e),g=de(d*this.sin_p14+a.y*c*this.cos_p14/b),f=Math.atan2(a.x*c,b*this.cos_p14*d-a.y*this.sin_p14*c),f=lc(this.long0+f)):(g=this.phic0,f=0),a.x=f,a.y=g,a}function Sa(){this.sphere||(this.k0=jc(this.e,Math.sin(this.lat_ts),Math.cos(this.lat_ts)))}function Ta(a){var b,c,d=a.x,e=a.y,f=lc(d-this.long0);if(this.sphere)b=this.x0+this.a*f*Math.cos(this.lat_ts),c=this.y0+this.a*Math.sin(e)/Math.cos(this.lat_ts);else{var g=Sd(this.e,Math.sin(e));b=this.x0+this.a*this.k0*f,c=this.y0+this.a*g*.5/this.k0}return a.x=b,a.y=c,a}function Ua(a){a.x-=this.x0,a.y-=this.y0;var b,c;return this.sphere?(b=lc(this.long0+a.x/this.a/Math.cos(this.lat_ts)),c=Math.asin(a.y/this.a*Math.cos(this.lat_ts))):(c=ie(this.e,2*a.y*this.k0/this.a),b=lc(this.long0+a.x/(this.a*this.k0))),a.x=b,a.y=c,a}function Va(){this.x0=this.x0||0,this.y0=this.y0||0,this.lat0=this.lat0||0,this.long0=this.long0||0,this.lat_ts=this.lat_ts||0,this.title=this.title||"Equidistant Cylindrical (Plate Carre)",this.rc=Math.cos(this.lat_ts)}function Wa(a){var b=a.x,c=a.y,d=lc(b-this.long0),e=Od(c-this.lat0);return a.x=this.x0+this.a*d*this.rc,a.y=this.y0+this.a*e,a}function Xa(a){var b=a.x,c=a.y;return a.x=lc(this.long0+(b-this.x0)/(this.a*this.rc)),a.y=Od(this.lat0+(c-this.y0)/this.a),a}function Ya(){this.temp=this.b/this.a,this.es=1-Math.pow(this.temp,2),this.e=Math.sqrt(this.es),this.e0=Jd(this.es),this.e1=Kd(this.es),this.e2=Ld(this.es),this.e3=Md(this.es),this.ml0=this.a*Id(this.e0,this.e1,this.e2,this.e3,this.lat0)}function Za(a){var b,c,d,e=a.x,f=a.y,g=lc(e-this.long0);if(d=g*Math.sin(f),this.sphere)Math.abs(f)<=Mb?(b=this.a*g,c=-1*this.a*this.lat0):(b=this.a*Math.sin(d)/Math.tan(f),c=this.a*(Od(f-this.lat0)+(1-Math.cos(d))/Math.tan(f)));else if(Math.abs(f)<=Mb)b=this.a*g,c=-1*this.ml0;else{var h=Nd(this.a,this.e,Math.sin(f))/Math.tan(f);b=h*Math.sin(d),c=this.a*Id(this.e0,this.e1,this.e2,this.e3,f)-this.ml0+h*(1-Math.cos(d))}return a.x=b+this.x0,a.y=c+this.y0,a}function $a(a){var b,c,d,e,f,g,h,i,j;if(d=a.x-this.x0,e=a.y-this.y0,this.sphere)if(Math.abs(e+this.a*this.lat0)<=Mb)b=lc(d/this.a+this.long0),c=0;else{g=this.lat0+e/this.a,h=d*d/this.a/this.a+g*g,i=g;var k;for(f=ne;f;--f)if(k=Math.tan(i),j=-1*(g*(i*k+1)-i-.5*(i*i+h)*k)/((i-g)/k-1),i+=j,Math.abs(j)<=Mb){c=i;break}b=lc(this.long0+Math.asin(d*Math.tan(i)/this.a)/Math.sin(c))}else if(Math.abs(e+this.ml0)<=Mb)c=0,b=lc(this.long0+d/this.a);else{g=(this.ml0+e)/this.a,h=d*d/this.a/this.a+g*g,i=g;var l,m,n,o,p;for(f=ne;f;--f)if(p=this.e*Math.sin(i),l=Math.sqrt(1-p*p)*Math.tan(i),m=this.a*Id(this.e0,this.e1,this.e2,this.e3,i),n=this.e0-2*this.e1*Math.cos(2*i)+4*this.e2*Math.cos(4*i)-6*this.e3*Math.cos(6*i),o=m/this.a,j=(g*(l*o+1)-o-.5*l*(o*o+h))/(this.es*Math.sin(2*i)*(o*o+h-2*g*o)/(4*l)+(g-o)*(l*n-2/Math.sin(2*i))-n),i-=j,Math.abs(j)<=Mb){c=i;break}l=Math.sqrt(1-this.es*Math.pow(Math.sin(c),2))*Math.tan(c),b=lc(this.long0+Math.asin(d*l/this.a)/Math.sin(c))}return a.x=b,a.y=c,a}function _a(){this.A=[],this.A[1]=.6399175073,this.A[2]=-.1358797613,this.A[3]=.063294409,this.A[4]=-.02526853,this.A[5]=.0117879,this.A[6]=-.0055161,this.A[7]=.0026906,this.A[8]=-.001333,this.A[9]=67e-5,this.A[10]=-34e-5,this.B_re=[],this.B_im=[],this.B_re[1]=.7557853228,this.B_im[1]=0,this.B_re[2]=.249204646,this.B_im[2]=.003371507,this.B_re[3]=-.001541739,this.B_im[3]=.04105856,this.B_re[4]=-.10162907,this.B_im[4]=.01727609,this.B_re[5]=-.26623489,this.B_im[5]=-.36249218,this.B_re[6]=-.6870983,this.B_im[6]=-1.1651967,this.C_re=[],this.C_im=[],this.C_re[1]=1.3231270439,this.C_im[1]=0,this.C_re[2]=-.577245789,this.C_im[2]=-.007809598,this.C_re[3]=.508307513,this.C_im[3]=-.112208952,this.C_re[4]=-.15094762,this.C_im[4]=.18200602,this.C_re[5]=1.01418179,this.C_im[5]=1.64497696,this.C_re[6]=1.9660549,this.C_im[6]=2.5127645,this.D=[],this.D[1]=1.5627014243,this.D[2]=.5185406398,this.D[3]=-.03333098,this.D[4]=-.1052906,this.D[5]=-.0368594,this.D[6]=.007317,this.D[7]=.0122,this.D[8]=.00394,this.D[9]=-.0013}function ab(a){var b,c=a.x,d=a.y,e=d-this.lat0,f=c-this.long0,g=e/Hb*1e-5,h=f,i=1,j=0;for(b=1;10>=b;b++)i*=g,j+=this.A[b]*i;var k,l,m=j,n=h,o=1,p=0,q=0,r=0;for(b=1;6>=b;b++)k=o*m-p*n,l=p*m+o*n,o=k,p=l,q=q+this.B_re[b]*o-this.B_im[b]*p,r=r+this.B_im[b]*o+this.B_re[b]*p;return a.x=r*this.a+this.x0,a.y=q*this.a+this.y0,a}function bb(a){var b,c,d,e=a.x,f=a.y,g=e-this.x0,h=f-this.y0,i=h/this.a,j=g/this.a,k=1,l=0,m=0,n=0;for(b=1;6>=b;b++)c=k*i-l*j,d=l*i+k*j,k=c,l=d,m=m+this.C_re[b]*k-this.C_im[b]*l,n=n+this.C_im[b]*k+this.C_re[b]*l;for(var o=0;o<this.iterations;o++){var p,q,r=m,s=n,t=i,u=j;for(b=2;6>=b;b++)p=r*m-s*n,q=s*m+r*n,r=p,s=q,t+=(b-1)*(this.B_re[b]*r-this.B_im[b]*s),u+=(b-1)*(this.B_im[b]*r+this.B_re[b]*s);r=1,s=0;var v=this.B_re[1],w=this.B_im[1];for(b=2;6>=b;b++)p=r*m-s*n,q=s*m+r*n,r=p,s=q,v+=b*(this.B_re[b]*r-this.B_im[b]*s),w+=b*(this.B_im[b]*r+this.B_re[b]*s);var x=v*v+w*w;m=(t*v+u*w)/x,n=(u*v-t*w)/x}var y=m,z=n,A=1,B=0;for(b=1;9>=b;b++)A*=y,B+=this.D[b]*A;var C=this.lat0+B*Hb*1e5,D=this.long0+z;return a.x=D,a.y=C,a}function cb(){}function db(a){var b=a.x,c=a.y,d=lc(b-this.long0),e=this.x0+this.a*d,f=this.y0+this.a*Math.log(Math.tan(Math.PI/4+c/2.5))*1.25;return a.x=e,a.y=f,a}function eb(a){a.x-=this.x0,a.y-=this.y0;var b=lc(this.long0+a.x/this.a),c=2.5*(Math.atan(Math.exp(.8*a.y/this.a))-Math.PI/4);return a.x=b,a.y=c,a}function fb(){this.sphere?(this.n=1,this.m=0,this.es=0,this.C_y=Math.sqrt((this.m+1)/this.n),this.C_x=this.C_y/(this.m+1)):this.en=$c(this.es)}function gb(a){var b,c,d=a.x,e=a.y;if(d=lc(d-this.long0),this.sphere){if(this.m)for(var f=this.n*Math.sin(e),g=ue;g;--g){var h=(this.m*e+Math.sin(e)-f)/(this.m+Math.cos(e));if(e-=h,Math.abs(h)<Mb)break}else e=1!==this.n?Math.asin(this.n*Math.sin(e)):e;b=this.a*this.C_x*d*(this.m+Math.cos(e)),c=this.a*this.C_y*e}else{var i=Math.sin(e),j=Math.cos(e);c=this.a*_c(e,i,j,this.en),b=this.a*d*j/Math.sqrt(1-this.es*i*i)}return a.x=b,a.y=c,a}function hb(a){var b,c,d,e;return a.x-=this.x0,d=a.x/this.a,a.y-=this.y0,b=a.y/this.a,this.sphere?(b/=this.C_y,d/=this.C_x*(this.m+Math.cos(b)),this.m?b=de((this.m*b+Math.sin(b))/this.n):1!==this.n&&(b=de(Math.sin(b)/this.n)),d=lc(d+this.long0),b=Od(b)):(b=bd(a.y/this.a,this.es,this.en),e=Math.abs(b),Ib>e?(e=Math.sin(b),c=this.long0+a.x*Math.sqrt(1-this.es*e*e)/(this.a*Math.cos(b)),d=lc(c)):Ib>e-Mb&&(d=this.long0)),a.x=d,a.y=b,a}function ib(){}function jb(a){for(var b=a.x,c=a.y,d=lc(b-this.long0),e=c,f=Math.PI*Math.sin(c);;){var g=-(e+Math.sin(e)-f)/(1+Math.cos(e));if(e+=g,Math.abs(g)<Mb)break}e/=2,Math.PI/2-Math.abs(c)<Mb&&(d=0);var h=.900316316158*this.a*d*Math.cos(e)+this.x0,i=1.4142135623731*this.a*Math.sin(e)+this.y0;return a.x=h,a.y=i,a}function kb(a){var b,c;a.x-=this.x0,a.y-=this.y0,c=a.y/(1.4142135623731*this.a),Math.abs(c)>.999999999999&&(c=.999999999999),b=Math.asin(c);var d=lc(this.long0+a.x/(.900316316158*this.a*Math.cos(b)));d<-Math.PI&&(d=-Math.PI),d>Math.PI&&(d=Math.PI),c=(2*b+Math.sin(2*b))/Math.PI,Math.abs(c)>1&&(c=1);var e=Math.asin(c);return a.x=d,a.y=e,a}function lb(){Math.abs(this.lat1+this.lat2)<Mb||(this.lat2=this.lat2||this.lat1,this.temp=this.b/this.a,this.es=1-Math.pow(this.temp,2),this.e=Math.sqrt(this.es),this.e0=Jd(this.es),this.e1=Kd(this.es),this.e2=Ld(this.es),this.e3=Md(this.es),this.sinphi=Math.sin(this.lat1),this.cosphi=Math.cos(this.lat1),this.ms1=jc(this.e,this.sinphi,this.cosphi),this.ml1=Id(this.e0,this.e1,this.e2,this.e3,this.lat1),Math.abs(this.lat1-this.lat2)<Mb?this.ns=this.sinphi:(this.sinphi=Math.sin(this.lat2),this.cosphi=Math.cos(this.lat2),this.ms2=jc(this.e,this.sinphi,this.cosphi),this.ml2=Id(this.e0,this.e1,this.e2,this.e3,this.lat2),this.ns=(this.ms1-this.ms2)/(this.ml2-this.ml1)),this.g=this.ml1+this.ms1/this.ns,this.ml0=Id(this.e0,this.e1,this.e2,this.e3,this.lat0),this.rh=this.a*(this.g-this.ml0))}function mb(a){var b,c=a.x,d=a.y;if(this.sphere)b=this.a*(this.g-d);else{var e=Id(this.e0,this.e1,this.e2,this.e3,d);b=this.a*(this.g-e)}var f=this.ns*lc(c-this.long0),g=this.x0+b*Math.sin(f),h=this.y0+this.rh-b*Math.cos(f);return a.x=g,a.y=h,a}function nb(a){a.x-=this.x0,a.y=this.rh-a.y+this.y0;var b,c,d,e;this.ns>=0?(c=Math.sqrt(a.x*a.x+a.y*a.y),b=1):(c=-Math.sqrt(a.x*a.x+a.y*a.y),b=-1);var f=0;if(0!==c&&(f=Math.atan2(b*a.x,b*a.y)),this.sphere)return e=lc(this.long0+f/this.ns),d=Od(this.g-c/this.a),a.x=e,a.y=d,a;var g=this.g-c/this.a;return d=Pd(g,this.e0,this.e1,this.e2,this.e3),e=lc(this.long0+f/this.ns),a.x=e,a.y=d,a}function ob(){this.R=this.a}function pb(a){var b,c,d=a.x,e=a.y,f=lc(d-this.long0);Math.abs(e)<=Mb&&(b=this.x0+this.R*f,c=this.y0);var g=de(2*Math.abs(e/Math.PI));(Math.abs(f)<=Mb||Math.abs(Math.abs(e)-Ib)<=Mb)&&(b=this.x0,c=e>=0?this.y0+Math.PI*this.R*Math.tan(.5*g):this.y0+Math.PI*this.R*-Math.tan(.5*g));var h=.5*Math.abs(Math.PI/f-f/Math.PI),i=h*h,j=Math.sin(g),k=Math.cos(g),l=k/(j+k-1),m=l*l,n=l*(2/j-1),o=n*n,p=Math.PI*this.R*(h*(l-o)+Math.sqrt(i*(l-o)*(l-o)-(o+i)*(m-o)))/(o+i);0>f&&(p=-p),b=this.x0+p;var q=i+l;return p=Math.PI*this.R*(n*q-h*Math.sqrt((o+i)*(i+1)-q*q))/(o+i),c=e>=0?this.y0+p:this.y0-p,a.x=b,a.y=c,a}function qb(a){var b,c,d,e,f,g,h,i,j,k,l,m,n;return a.x-=this.x0,a.y-=this.y0,l=Math.PI*this.R,d=a.x/l,e=a.y/l,f=d*d+e*e,g=-Math.abs(e)*(1+f),h=g-2*e*e+d*d,i=-2*g+1+2*e*e+f*f,n=e*e/i+(2*h*h*h/i/i/i-9*g*h/i/i)/27,j=(g-h*h/3/i)/i,k=2*Math.sqrt(-j/3),l=3*n/j/k,Math.abs(l)>1&&(l=l>=0?1:-1),m=Math.acos(l)/3,c=a.y>=0?(-k*Math.cos(m+Math.PI/3)-h/3/i)*Math.PI:-(-k*Math.cos(m+Math.PI/3)-h/3/i)*Math.PI,b=Math.abs(d)<Mb?this.long0:lc(this.long0+Math.PI*(f-1+Math.sqrt(1+2*(d*d-e*e)+f*f))/2/d),a.x=b,a.y=c,a}function rb(){this.sin_p12=Math.sin(this.lat0),this.cos_p12=Math.cos(this.lat0)}function sb(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y=a.x,z=a.y,A=Math.sin(a.y),B=Math.cos(a.y),C=lc(y-this.long0);return this.sphere?Math.abs(this.sin_p12-1)<=Mb?(a.x=this.x0+this.a*(Ib-z)*Math.sin(C),a.y=this.y0-this.a*(Ib-z)*Math.cos(C),a):Math.abs(this.sin_p12+1)<=Mb?(a.x=this.x0+this.a*(Ib+z)*Math.sin(C),a.y=this.y0+this.a*(Ib+z)*Math.cos(C),a):(s=this.sin_p12*A+this.cos_p12*B*Math.cos(C),q=Math.acos(s),r=q/Math.sin(q),a.x=this.x0+this.a*r*B*Math.sin(C),a.y=this.y0+this.a*r*(this.cos_p12*A-this.sin_p12*B*Math.cos(C)),a):(b=Jd(this.es),c=Kd(this.es),d=Ld(this.es),e=Md(this.es),Math.abs(this.sin_p12-1)<=Mb?(f=this.a*Id(b,c,d,e,Ib),g=this.a*Id(b,c,d,e,z),a.x=this.x0+(f-g)*Math.sin(C),a.y=this.y0-(f-g)*Math.cos(C),a):Math.abs(this.sin_p12+1)<=Mb?(f=this.a*Id(b,c,d,e,Ib),g=this.a*Id(b,c,d,e,z),a.x=this.x0+(f+g)*Math.sin(C),a.y=this.y0+(f+g)*Math.cos(C),a):(h=A/B,i=Nd(this.a,this.e,this.sin_p12),j=Nd(this.a,this.e,A),k=Math.atan((1-this.es)*h+this.es*i*this.sin_p12/(j*B)),l=Math.atan2(Math.sin(C),this.cos_p12*Math.tan(k)-this.sin_p12*Math.cos(C)),t=0===l?Math.asin(this.cos_p12*Math.sin(k)-this.sin_p12*Math.cos(k)):Math.abs(Math.abs(l)-Math.PI)<=Mb?-Math.asin(this.cos_p12*Math.sin(k)-this.sin_p12*Math.cos(k)):Math.asin(Math.sin(C)*Math.cos(k)/Math.sin(l)),m=this.e*this.sin_p12/Math.sqrt(1-this.es),n=this.e*this.cos_p12*Math.cos(l)/Math.sqrt(1-this.es),o=m*n,p=n*n,u=t*t,v=u*t,w=v*t,x=w*t,q=i*t*(1-u*p*(1-p)/6+v/8*o*(1-2*p)+w/120*(p*(4-7*p)-3*m*m*(1-7*p))-x/48*o),a.x=this.x0+q*Math.sin(l),a.y=this.y0+q*Math.cos(l),a))}function tb(a){a.x-=this.x0,a.y-=this.y0;var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x;if(this.sphere){if(b=Math.sqrt(a.x*a.x+a.y*a.y),b>2*Ib*this.a)return;return c=b/this.a,d=Math.sin(c),e=Math.cos(c),f=this.long0,Math.abs(b)<=Mb?g=this.lat0:(g=de(e*this.sin_p12+a.y*d*this.cos_p12/b),h=Math.abs(this.lat0)-Ib,f=lc(Math.abs(h)<=Mb?this.lat0>=0?this.long0+Math.atan2(a.x,-a.y):this.long0-Math.atan2(-a.x,a.y):this.long0+Math.atan2(a.x*d,b*this.cos_p12*e-a.y*this.sin_p12*d))),a.x=f,a.y=g,a}return i=Jd(this.es),j=Kd(this.es),k=Ld(this.es),l=Md(this.es),Math.abs(this.sin_p12-1)<=Mb?(m=this.a*Id(i,j,k,l,Ib),b=Math.sqrt(a.x*a.x+a.y*a.y),n=m-b,g=Pd(n/this.a,i,j,k,l),f=lc(this.long0+Math.atan2(a.x,-1*a.y)),a.x=f,a.y=g,a):Math.abs(this.sin_p12+1)<=Mb?(m=this.a*Id(i,j,k,l,Ib),b=Math.sqrt(a.x*a.x+a.y*a.y),n=b-m,g=Pd(n/this.a,i,j,k,l),f=lc(this.long0+Math.atan2(a.x,a.y)),a.x=f,a.y=g,a):(b=Math.sqrt(a.x*a.x+a.y*a.y),q=Math.atan2(a.x,a.y),o=Nd(this.a,this.e,this.sin_p12),r=Math.cos(q),s=this.e*this.cos_p12*r,t=-s*s/(1-this.es),u=3*this.es*(1-t)*this.sin_p12*this.cos_p12*r/(1-this.es),v=b/o,w=v-t*(1+t)*Math.pow(v,3)/6-u*(1+3*t)*Math.pow(v,4)/24,x=1-t*w*w/2-v*w*w*w/6,p=Math.asin(this.sin_p12*Math.cos(w)+this.cos_p12*Math.sin(w)*r),f=lc(this.long0+Math.asin(Math.sin(q)*Math.sin(w)/Math.cos(p))),g=Math.atan((1-this.es*x*this.sin_p12/Math.sin(p))*Math.tan(p)/(1-this.es)),a.x=f,a.y=g,a)}function ub(){this.sin_p14=Math.sin(this.lat0),this.cos_p14=Math.cos(this.lat0)}function vb(a){var b,c,d,e,f,g,h,i,j=a.x,k=a.y;return d=lc(j-this.long0),b=Math.sin(k),c=Math.cos(k),e=Math.cos(d),g=this.sin_p14*b+this.cos_p14*c*e,f=1,(g>0||Math.abs(g)<=Mb)&&(h=this.a*f*c*Math.sin(d),i=this.y0+this.a*f*(this.cos_p14*b-this.sin_p14*c*e)),a.x=h,a.y=i,a}function wb(a){var b,c,d,e,f,g,h;return a.x-=this.x0,a.y-=this.y0,b=Math.sqrt(a.x*a.x+a.y*a.y),c=de(b/this.a),d=Math.sin(c),e=Math.cos(c),g=this.long0,Math.abs(b)<=Mb?(h=this.lat0,a.x=g,a.y=h,a):(h=de(e*this.sin_p14+a.y*d*this.cos_p14/b),f=Math.abs(this.lat0)-Ib,Math.abs(f)<=Mb?(g=lc(this.lat0>=0?this.long0+Math.atan2(a.x,-a.y):this.long0-Math.atan2(-a.x,a.y)),a.x=g,a.y=h,a):(g=lc(this.long0+Math.atan2(a.x*d,b*this.cos_p14*e-a.y*this.sin_p14*d)),a.x=g,a.y=h,a))}function xb(){this.x0=this.x0||0,this.y0=this.y0||0,this.lat0=this.lat0||0,this.long0=this.long0||0,this.lat_ts=this.lat_ts||0,this.title=this.title||"Quadrilateralized Spherical Cube",this.lat0>=Ib-Pb/2?this.face=He.TOP:this.lat0<=-(Ib-Pb/2)?this.face=He.BOTTOM:Math.abs(this.long0)<=Pb?this.face=He.FRONT:Math.abs(this.long0)<=Ib+Pb?this.face=this.long0>0?He.RIGHT:He.LEFT:this.face=He.BACK,0!==this.es&&(this.one_minus_f=1-(this.a-this.b)/this.a,this.one_minus_f_squared=this.one_minus_f*this.one_minus_f)}function yb(a){var b,c,d,e,f,g,h={x:0,y:0},i={value:0};if(a.x-=this.long0,b=0!==this.es?Math.atan(this.one_minus_f_squared*Math.tan(a.y)):a.y,c=a.x,this.face===He.TOP)e=Ib-b,c>=Pb&&Ib+Pb>=c?(i.value=Ie.AREA_0,d=c-Ib):c>Ib+Pb||-(Ib+Pb)>=c?(i.value=Ie.AREA_1,d=c>0?c-Rb:c+Rb):c>-(Ib+Pb)&&-Pb>=c?(i.value=Ie.AREA_2,d=c+Ib):(i.value=Ie.AREA_3,d=c);else if(this.face===He.BOTTOM)e=Ib+b,c>=Pb&&Ib+Pb>=c?(i.value=Ie.AREA_0,d=-c+Ib):Pb>c&&c>=-Pb?(i.value=Ie.AREA_1,d=-c):-Pb>c&&c>=-(Ib+Pb)?(i.value=Ie.AREA_2,d=-c-Ib):(i.value=Ie.AREA_3,d=c>0?-c+Rb:-c-Rb);else{var j,k,l,m,n,o,p;this.face===He.RIGHT?c=Bb(c,+Ib):this.face===He.BACK?c=Bb(c,+Rb):this.face===He.LEFT&&(c=Bb(c,-Ib)),m=Math.sin(b),n=Math.cos(b),o=Math.sin(c),p=Math.cos(c),j=n*p,k=n*o,l=m,this.face===He.FRONT?(e=Math.acos(j),d=Ab(e,l,k,i)):this.face===He.RIGHT?(e=Math.acos(k),d=Ab(e,l,-j,i)):this.face===He.BACK?(e=Math.acos(-j),d=Ab(e,l,-k,i)):this.face===He.LEFT?(e=Math.acos(-k),d=Ab(e,l,j,i)):(e=d=0,i.value=Ie.AREA_0)}return g=Math.atan(12/Rb*(d+Math.acos(Math.sin(d)*Math.cos(Pb))-Ib)),f=Math.sqrt((1-Math.cos(e))/(Math.cos(g)*Math.cos(g))/(1-Math.cos(Math.atan(1/Math.cos(d))))),i.value===Ie.AREA_1?g+=Ib:i.value===Ie.AREA_2?g+=Rb:i.value===Ie.AREA_3&&(g+=1.5*Rb),h.x=f*Math.cos(g),h.y=f*Math.sin(g),h.x=h.x*this.a+this.x0,h.y=h.y*this.a+this.y0,a.x=h.x,a.y=h.y,a}function zb(a){var b,c,d,e,f,g,h,i,j,k={lam:0,phi:0},l={value:0};if(a.x=(a.x-this.x0)/this.a,a.y=(a.y-this.y0)/this.a,c=Math.atan(Math.sqrt(a.x*a.x+a.y*a.y)),b=Math.atan2(a.y,a.x),a.x>=0&&a.x>=Math.abs(a.y)?l.value=Ie.AREA_0:a.y>=0&&a.y>=Math.abs(a.x)?(l.value=Ie.AREA_1,b-=Ib):a.x<0&&-a.x>=Math.abs(a.y)?(l.value=Ie.AREA_2,b=0>b?b+Rb:b-Rb):(l.value=Ie.AREA_3,b+=Ib),j=Rb/12*Math.tan(b),f=Math.sin(j)/(Math.cos(j)-1/Math.sqrt(2)),g=Math.atan(f),d=Math.cos(b),e=Math.tan(c),h=1-d*d*e*e*(1-Math.cos(Math.atan(1/Math.cos(g)))),-1>h?h=-1:h>1&&(h=1),this.face===He.TOP)i=Math.acos(h),k.phi=Ib-i,l.value===Ie.AREA_0?k.lam=g+Ib:l.value===Ie.AREA_1?k.lam=0>g?g+Rb:g-Rb:l.value===Ie.AREA_2?k.lam=g-Ib:k.lam=g;else if(this.face===He.BOTTOM)i=Math.acos(h),k.phi=i-Ib,l.value===Ie.AREA_0?k.lam=-g+Ib:l.value===Ie.AREA_1?k.lam=-g:l.value===Ie.AREA_2?k.lam=-g-Ib:k.lam=0>g?-g-Rb:-g+Rb;else{var m,n,o;m=h,j=m*m,o=j>=1?0:Math.sqrt(1-j)*Math.sin(g),j+=o*o,n=j>=1?0:Math.sqrt(1-j),l.value===Ie.AREA_1?(j=n,n=-o,o=j):l.value===Ie.AREA_2?(n=-n,o=-o):l.value===Ie.AREA_3&&(j=n,n=o,o=-j),this.face===He.RIGHT?(j=m,m=-n,n=j):this.face===He.BACK?(m=-m,n=-n):this.face===He.LEFT&&(j=m,m=n,n=-j),k.phi=Math.acos(-o)-Ib,k.lam=Math.atan2(n,m),this.face===He.RIGHT?k.lam=Bb(k.lam,-Ib):this.face===He.BACK?k.lam=Bb(k.lam,-Rb):this.face===He.LEFT&&(k.lam=Bb(k.lam,+Ib))}if(0!==this.es){var p,q,r;p=k.phi<0?1:0,q=Math.tan(k.phi),r=this.b/Math.sqrt(q*q+this.one_minus_f_squared),k.phi=Math.atan(Math.sqrt(this.a*this.a-r*r)/(this.one_minus_f*r)),p&&(k.phi=-k.phi)}return k.lam+=this.long0,a.x=k.lam,a.y=k.phi,a}function Ab(a,b,c,d){var e;return Mb>a?(d.value=Ie.AREA_0,e=0):(e=Math.atan2(b,c),Math.abs(e)<=Pb?d.value=Ie.AREA_0:e>Pb&&Ib+Pb>=e?(d.value=Ie.AREA_1,e-=Ib):e>Ib+Pb||-(Ib+Pb)>=e?(d.value=Ie.AREA_2,e=e>=0?e-Rb:e+Rb):(d.value=Ie.AREA_3,e+=Ib)),e}function Bb(a,b){var c=a+b;return-Rb>c?c+=Qb:c>+Rb&&(c-=Qb),c}var Cb=function(a){a("EPSG:4326","+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees"),a("EPSG:4269","+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees"),a("EPSG:3857","+title=WGS 84 / Pseudo-Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"),a.WGS84=a["EPSG:4326"],a["EPSG:3785"]=a["EPSG:3857"],a.GOOGLE=a["EPSG:3857"],a["EPSG:900913"]=a["EPSG:3857"],a["EPSG:102113"]=a["EPSG:3857"]},Db=1,Eb=2,Fb=4,Gb=5,Hb=484813681109536e-20,Ib=Math.PI/2,Jb=.16666666666666666,Kb=.04722222222222222,Lb=.022156084656084655,Mb=1e-10,Nb=.017453292519943295,Ob=57.29577951308232,Pb=Math.PI/4,Qb=2*Math.PI,Rb=3.14159265359,Sb={};Sb.greenwich=0,Sb.lisbon=-9.131906111111,Sb.paris=2.337229166667,Sb.bogota=-74.080916666667,Sb.madrid=-3.687938888889,Sb.rome=12.452333333333,Sb.bern=7.439583333333,Sb.jakarta=106.807719444444,Sb.ferro=-17.666666666667,Sb.brussels=4.367975,Sb.stockholm=18.058277777778,Sb.athens=23.7163375,Sb.oslo=10.722916666667;var Tb={ft:{to_meter:.3048},"us-ft":{to_meter:1200/3937}},Ub=/[\s_\-\/\(\)]/g,Vb=function(b){var c,d,e,f={},g=b.split("+").map(function(a){return a.trim()}).filter(function(a){return a}).reduce(function(a,b){var c=b.split("=");return c.push(!0),a[c[0].toLowerCase()]=c[1],a},{}),h={proj:"projName",datum:"datumCode",rf:function(a){f.rf=parseFloat(a)},lat_0:function(a){f.lat0=a*Nb},lat_1:function(a){f.lat1=a*Nb},lat_2:function(a){f.lat2=a*Nb},lat_ts:function(a){f.lat_ts=a*Nb},lon_0:function(a){f.long0=a*Nb},lon_1:function(a){f.long1=a*Nb},lon_2:function(a){f.long2=a*Nb},alpha:function(a){f.alpha=parseFloat(a)*Nb},lonc:function(a){f.longc=a*Nb},x_0:function(a){f.x0=parseFloat(a)},y_0:function(a){f.y0=parseFloat(a)},k_0:function(a){f.k0=parseFloat(a)},k:function(a){f.k0=parseFloat(a)},a:function(a){f.a=parseFloat(a)},b:function(a){f.b=parseFloat(a)},r_a:function(){f.R_A=!0},zone:function(a){f.zone=parseInt(a,10)},south:function(){f.utmSouth=!0},towgs84:function(a){f.datum_params=a.split(",").map(function(a){return parseFloat(a)})},to_meter:function(a){f.to_meter=parseFloat(a)},units:function(b){f.units=b;var c=a(Tb,b);c&&(f.to_meter=c.to_meter)},from_greenwich:function(a){f.from_greenwich=a*Nb},pm:function(b){var c=a(Sb,b);f.from_greenwich=(c?c:parseFloat(b))*Nb},nadgrids:function(a){"@null"===a?f.datumCode="none":f.nadgrids=a},axis:function(a){var b="ewnsud";3===a.length&&-1!==b.indexOf(a.substr(0,1))&&-1!==b.indexOf(a.substr(1,1))&&-1!==b.indexOf(a.substr(2,1))&&(f.axis=a)}};for(c in g)d=g[c],c in h?(e=h[c],"function"==typeof e?e(d):f[e]=d):f[c]=d;return"string"==typeof f.datumCode&&"WGS84"!==f.datumCode&&(f.datumCode=f.datumCode.toLowerCase()),f},Wb=1,Xb=2,Yb=3,Zb=4,$b=5,_b=-1,ac=/\s/,bc=/[A-Za-z]/,cc=/[A-Za-z84]/,dc=/[,\]]/,ec=/[\d\.E\-\+]/;b.prototype.readCharicter=function(){var a=this.text[this.place++];if(this.state!==Zb)for(;ac.test(a);){if(this.place>=this.text.length)return;a=this.text[this.place++]}switch(this.state){case Wb:return this.neutral(a);case Xb:return this.keyword(a);case Zb:return this.quoted(a);case $b:return this.afterquote(a);case Yb:return this.number(a);case _b:return}},b.prototype.afterquote=function(a){if('"'===a)return this.word+='"',void(this.state=Zb);if(dc.test(a))return this.word=this.word.trim(),void this.afterItem(a);throw new Error("havn't handled \""+a+'" in afterquote yet, index '+this.place)},b.prototype.afterItem=function(a){return","===a?(null!==this.word&&this.currentObject.push(this.word),this.word=null,void(this.state=Wb)):"]"===a?(this.level--,null!==this.word&&(this.currentObject.push(this.word),this.word=null),this.state=Wb,this.currentObject=this.stack.pop(),void(this.currentObject||(this.state=_b))):void 0},b.prototype.number=function(a){if(ec.test(a))return void(this.word+=a);if(dc.test(a))return this.word=parseFloat(this.word),void this.afterItem(a);throw new Error("havn't handled \""+a+'" in number yet, index '+this.place)},b.prototype.quoted=function(a){return'"'===a?void(this.state=$b):void(this.word+=a)},b.prototype.keyword=function(a){if(cc.test(a))return void(this.word+=a);if("["===a){var b=[];return b.push(this.word),this.level++,null===this.root?this.root=b:this.currentObject.push(b),this.stack.push(this.currentObject),this.currentObject=b,void(this.state=Wb)}if(dc.test(a))return void this.afterItem(a);throw new Error("havn't handled \""+a+'" in keyword yet, index '+this.place)},b.prototype.neutral=function(a){if(bc.test(a))return this.word=a,void(this.state=Xb);if('"'===a)return this.word="",void(this.state=Zb);if(ec.test(a))return this.word=a,void(this.state=Yb);if(dc.test(a))return void this.afterItem(a);throw new Error("havn't handled \""+a+'" in neutral yet, index '+this.place)},b.prototype.output=function(){for(;this.place<this.text.length;)this.readCharicter();if(this.state===_b)return this.root;throw new Error('unable to parse string "'+this.text+'". State is '+this.state)};var fc=.017453292519943295,gc=function(a){var b=c(a),d=b.shift(),f=b.shift();b.unshift(["name",f]),b.unshift(["type",d]);var g={};return e(b,g),h(g),g};Cb(i);var hc=["PROJECTEDCRS","PROJCRS","GEOGCS","GEOCCS","PROJCS","LOCAL_CS","GEODCRS","GEODETICCRS","GEODETICDATUM","ENGCRS","ENGINEERINGCRS"],ic=function(a,b){a=a||{};var c,d;if(!b)return a;for(d in b)c=b[d],void 0!==c&&(a[d]=c);return a},jc=function(a,b,c){var d=a*b;return c/Math.sqrt(1-d*d)},kc=function(a){return 0>a?-1:1},lc=function(a){return Math.abs(a)<=Rb?a:a-kc(a)*Qb},mc=function(a,b,c){var d=a*c,e=.5*a;return d=Math.pow((1-d)/(1+d),e),Math.tan(.5*(Ib-b))/d},nc=function(a,b){for(var c,d,e=.5*a,f=Ib-2*Math.atan(b),g=0;15>=g;g++)if(c=a*Math.sin(f),d=Ib-2*Math.atan(b*Math.pow((1-c)/(1+c),e))-f,f+=d,Math.abs(d)<=1e-10)return f;return-9999},oc=["Mercator","Popular Visualisation Pseudo Mercator","Mercator_1SP","Mercator_Auxiliary_Sphere","merc"],pc={init:o,forward:p,inverse:q,names:oc},qc=["longlat","identity"],rc={init:r,forward:s,inverse:s,names:qc},sc=[pc,rc],tc={},uc=[],vc={start:v,add:t,get:u},wc={};wc.MERIT={a:6378137,rf:298.257,ellipseName:"MERIT 1983"},wc.SGS85={a:6378136,rf:298.257,ellipseName:"Soviet Geodetic System 85"},wc.GRS80={a:6378137,rf:298.257222101,ellipseName:"GRS 1980(IUGG, 1980)"},wc.IAU76={a:6378140,rf:298.257,ellipseName:"IAU 1976"},wc.airy={a:6377563.396,b:6356256.91,ellipseName:"Airy 1830"
},wc.APL4={a:6378137,rf:298.25,ellipseName:"Appl. Physics. 1965"},wc.NWL9D={a:6378145,rf:298.25,ellipseName:"Naval Weapons Lab., 1965"},wc.mod_airy={a:6377340.189,b:6356034.446,ellipseName:"Modified Airy"},wc.andrae={a:6377104.43,rf:300,ellipseName:"Andrae 1876 (Den., Iclnd.)"},wc.aust_SA={a:6378160,rf:298.25,ellipseName:"Australian Natl & S. Amer. 1969"},wc.GRS67={a:6378160,rf:298.247167427,ellipseName:"GRS 67(IUGG 1967)"},wc.bessel={a:6377397.155,rf:299.1528128,ellipseName:"Bessel 1841"},wc.bess_nam={a:6377483.865,rf:299.1528128,ellipseName:"Bessel 1841 (Namibia)"},wc.clrk66={a:6378206.4,b:6356583.8,ellipseName:"Clarke 1866"},wc.clrk80={a:6378249.145,rf:293.4663,ellipseName:"Clarke 1880 mod."},wc.clrk58={a:6378293.645208759,rf:294.2606763692654,ellipseName:"Clarke 1858"},wc.CPM={a:6375738.7,rf:334.29,ellipseName:"Comm. des Poids et Mesures 1799"},wc.delmbr={a:6376428,rf:311.5,ellipseName:"Delambre 1810 (Belgium)"},wc.engelis={a:6378136.05,rf:298.2566,ellipseName:"Engelis 1985"},wc.evrst30={a:6377276.345,rf:300.8017,ellipseName:"Everest 1830"},wc.evrst48={a:6377304.063,rf:300.8017,ellipseName:"Everest 1948"},wc.evrst56={a:6377301.243,rf:300.8017,ellipseName:"Everest 1956"},wc.evrst69={a:6377295.664,rf:300.8017,ellipseName:"Everest 1969"},wc.evrstSS={a:6377298.556,rf:300.8017,ellipseName:"Everest (Sabah & Sarawak)"},wc.fschr60={a:6378166,rf:298.3,ellipseName:"Fischer (Mercury Datum) 1960"},wc.fschr60m={a:6378155,rf:298.3,ellipseName:"Fischer 1960"},wc.fschr68={a:6378150,rf:298.3,ellipseName:"Fischer 1968"},wc.helmert={a:6378200,rf:298.3,ellipseName:"Helmert 1906"},wc.hough={a:6378270,rf:297,ellipseName:"Hough"},wc.intl={a:6378388,rf:297,ellipseName:"International 1909 (Hayford)"},wc.kaula={a:6378163,rf:298.24,ellipseName:"Kaula 1961"},wc.lerch={a:6378139,rf:298.257,ellipseName:"Lerch 1979"},wc.mprts={a:6397300,rf:191,ellipseName:"Maupertius 1738"},wc.new_intl={a:6378157.5,b:6356772.2,ellipseName:"New International 1967"},wc.plessis={a:6376523,rf:6355863,ellipseName:"Plessis 1817 (France)"},wc.krass={a:6378245,rf:298.3,ellipseName:"Krassovsky, 1942"},wc.SEasia={a:6378155,b:6356773.3205,ellipseName:"Southeast Asia"},wc.walbeck={a:6376896,b:6355834.8467,ellipseName:"Walbeck"},wc.WGS60={a:6378165,rf:298.3,ellipseName:"WGS 60"},wc.WGS66={a:6378145,rf:298.25,ellipseName:"WGS 66"},wc.WGS7={a:6378135,rf:298.26,ellipseName:"WGS 72"};var xc=wc.WGS84={a:6378137,rf:298.257223563,ellipseName:"WGS 84"};wc.sphere={a:6370997,b:6370997,ellipseName:"Normal Sphere (r=6370997)"};var yc={};yc.wgs84={towgs84:"0,0,0",ellipse:"WGS84",datumName:"WGS84"},yc.ch1903={towgs84:"674.374,15.056,405.346",ellipse:"bessel",datumName:"swiss"},yc.ggrs87={towgs84:"-199.87,74.79,246.62",ellipse:"GRS80",datumName:"Greek_Geodetic_Reference_System_1987"},yc.nad83={towgs84:"0,0,0",ellipse:"GRS80",datumName:"North_American_Datum_1983"},yc.nad27={nadgrids:"@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat",ellipse:"clrk66",datumName:"North_American_Datum_1927"},yc.potsdam={towgs84:"606.0,23.0,413.0",ellipse:"bessel",datumName:"Potsdam Rauenberg 1950 DHDN"},yc.carthage={towgs84:"-263.0,6.0,431.0",ellipse:"clark80",datumName:"Carthage 1934 Tunisia"},yc.hermannskogel={towgs84:"653.0,-212.0,449.0",ellipse:"bessel",datumName:"Hermannskogel"},yc.osni52={towgs84:"482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15",ellipse:"airy",datumName:"Irish National"},yc.ire65={towgs84:"482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15",ellipse:"mod_airy",datumName:"Ireland 1965"},yc.rassadiran={towgs84:"-133.63,-157.5,-158.62",ellipse:"intl",datumName:"Rassadiran"},yc.nzgd49={towgs84:"59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993",ellipse:"intl",datumName:"New Zealand Geodetic Datum 1949"},yc.osgb36={towgs84:"446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894",ellipse:"airy",datumName:"Airy 1830"},yc.s_jtsk={towgs84:"589,76,480",ellipse:"bessel",datumName:"S-JTSK (Ferro)"},yc.beduaram={towgs84:"-106,-87,188",ellipse:"clrk80",datumName:"Beduaram"},yc.gunung_segara={towgs84:"-403,684,41",ellipse:"bessel",datumName:"Gunung Segara Jakarta"},yc.rnb72={towgs84:"106.869,-52.2978,103.724,-0.33657,0.456955,-1.84218,1",ellipse:"intl",datumName:"Reseau National Belge 1972"},z.projections=vc,z.projections.start();var zc=function(a,b,c){return A(a,b)?c:a.datum_type===Gb||b.datum_type===Gb?c:a.es!==b.es||a.a!==b.a||F(a.datum_type)||F(b.datum_type)?(c=B(c,a.es,a.a),F(a.datum_type)&&(c=D(c,a.datum_type,a.datum_params)),F(b.datum_type)&&(c=E(c,b.datum_type,b.datum_params)),C(c,b.es,b.a,b.b)):c},Ac=function(a,b,c){var d,e,f,g=c.x,h=c.y,i=c.z||0,j={};for(f=0;3>f;f++)if(!b||2!==f||void 0!==c.z)switch(0===f?(d=g,e="x"):1===f?(d=h,e="y"):(d=i,e="z"),a.axis[f]){case"e":j[e]=d;break;case"w":j[e]=-d;break;case"n":j[e]=d;break;case"s":j[e]=-d;break;case"u":void 0!==c[e]&&(j.z=d);break;case"d":void 0!==c[e]&&(j.z=-d);break;default:return null}return j},Bc=function(a){var b={x:a[0],y:a[1]};return a.length>2&&(b.z=a[2]),a.length>3&&(b.m=a[3]),b},Cc=function(a){G(a.x),G(a.y)},Dc=z("WGS84"),Ec=6,Fc="AJSAJS",Gc="AFAFAF",Hc=65,Ic=73,Jc=79,Kc=86,Lc=90,Mc={forward:M,inverse:N,toPoint:O};Point.fromMGRS=function(a){return new Point(O(a))},Point.prototype.toMGRS=function(a){return M([this.x,this.y],a)};var Nc="2.4.4",Oc=1,Pc=.25,Qc=.046875,Rc=.01953125,Sc=.01068115234375,Tc=.75,Uc=.46875,Vc=.013020833333333334,Wc=.007120768229166667,Xc=.3645833333333333,Yc=.005696614583333333,Zc=.3076171875,$c=function(a){var b=[];b[0]=Oc-a*(Pc+a*(Qc+a*(Rc+a*Sc))),b[1]=a*(Tc-a*(Qc+a*(Rc+a*Sc)));var c=a*a;return b[2]=c*(Uc-a*(Vc+a*Wc)),c*=a,b[3]=c*(Xc-a*Yc),b[4]=c*a*Zc,b},_c=function(a,b,c,d){return c*=b,b*=b,d[0]*a-c*(d[1]+b*(d[2]+b*(d[3]+b*d[4])))},ad=20,bd=function(a,b,c){for(var d=1/(1-b),e=a,f=ad;f;--f){var g=Math.sin(e),h=1-b*g*g;if(h=(_c(e,g,Math.cos(e),c)-a)*(h*Math.sqrt(h))*d,e-=h,Math.abs(h)<Mb)return e}return e},cd=["Transverse_Mercator","Transverse Mercator","tmerc"],dd={init:aa,forward:ba,inverse:ca,names:cd},ed=function(a){var b=Math.exp(a);return b=(b-1/b)/2},fd=function(a,b){a=Math.abs(a),b=Math.abs(b);var c=Math.max(a,b),d=Math.min(a,b)/(c?c:1);return c*Math.sqrt(1+Math.pow(d,2))},gd=function(a){var b=1+a,c=b-1;return 0===c?a:a*Math.log(b)/c},hd=function(a){var b=Math.abs(a);return b=gd(b*(1+b/(fd(1,b)+1))),0>a?-b:b},id=function(a,b){for(var c,d=2*Math.cos(2*b),e=a.length-1,f=a[e],g=0;--e>=0;)c=-g+d*f+a[e],g=f,f=c;return b+c*Math.sin(2*b)},jd=function(a,b){for(var c,d=2*Math.cos(b),e=a.length-1,f=a[e],g=0;--e>=0;)c=-g+d*f+a[e],g=f,f=c;return Math.sin(b)*c},kd=function(a){var b=Math.exp(a);return b=(b+1/b)/2},ld=function(a,b,c){for(var d,e,f=Math.sin(b),g=Math.cos(b),h=ed(c),i=kd(c),j=2*g*i,k=-2*f*h,l=a.length-1,m=a[l],n=0,o=0,p=0;--l>=0;)d=o,e=n,o=m,n=p,m=-d+j*o-k*n+a[l],p=-e+k*o+j*n;return j=f*i,k=g*h,[j*m-k*p,j*p+k*m]},md=["Extended_Transverse_Mercator","Extended Transverse Mercator","etmerc"],nd={init:da,forward:ea,inverse:fa,names:md},od=function(a,b){if(void 0===a){if(a=Math.floor(30*(lc(b)+Math.PI)/Math.PI)+1,0>a)return 0;if(a>60)return 60}return a},pd="etmerc",qd=["Universal Transverse Mercator System","utm"],rd={init:ga,names:qd,dependsOn:pd},sd=function(a,b){return Math.pow((1-a)/(1+a),b)},td=20,ud=["gauss"],vd={init:ha,forward:ia,inverse:ja,names:ud},wd=["Stereographic_North_Pole","Oblique_Stereographic","Polar_Stereographic","sterea","Oblique Stereographic Alternative"],xd={init:ka,forward:la,inverse:ma,names:wd},yd=["stere","Stereographic_South_Pole","Polar Stereographic (variant B)"],zd={init:oa,forward:pa,inverse:qa,names:yd,ssfn_:na},Ad=["somerc"],Bd={init:ra,forward:sa,inverse:ta,names:Ad},Cd=["Hotine_Oblique_Mercator","Hotine Oblique Mercator","Hotine_Oblique_Mercator_Azimuth_Natural_Origin","Hotine_Oblique_Mercator_Azimuth_Center","omerc"],Dd={init:ua,forward:va,inverse:wa,names:Cd},Ed=["Lambert Tangential Conformal Conic Projection","Lambert_Conformal_Conic","Lambert_Conformal_Conic_2SP","lcc"],Fd={init:xa,forward:ya,inverse:za,names:Ed},Gd=["Krovak","krovak"],Hd={init:Aa,forward:Ba,inverse:Ca,names:Gd},Id=function(a,b,c,d,e){return a*e-b*Math.sin(2*e)+c*Math.sin(4*e)-d*Math.sin(6*e)},Jd=function(a){return 1-.25*a*(1+a/16*(3+1.25*a))},Kd=function(a){return.375*a*(1+.25*a*(1+.46875*a))},Ld=function(a){return.05859375*a*a*(1+.75*a)},Md=function(a){return a*a*a*(35/3072)},Nd=function(a,b,c){var d=b*c;return a/Math.sqrt(1-d*d)},Od=function(a){return Math.abs(a)<Ib?a:a-kc(a)*Math.PI},Pd=function(a,b,c,d,e){var f,g;f=a/b;for(var h=0;15>h;h++)if(g=(a-(b*f-c*Math.sin(2*f)+d*Math.sin(4*f)-e*Math.sin(6*f)))/(b-2*c*Math.cos(2*f)+4*d*Math.cos(4*f)-6*e*Math.cos(6*f)),f+=g,Math.abs(g)<=1e-10)return f;return NaN},Qd=["Cassini","Cassini_Soldner","cass"],Rd={init:Da,forward:Ea,inverse:Fa,names:Qd},Sd=function(a,b){var c;return a>1e-7?(c=a*b,(1-a*a)*(b/(1-c*c)-.5/a*Math.log((1-c)/(1+c)))):2*b},Td=1,Ud=2,Vd=3,Wd=4,Xd=.3333333333333333,Yd=.17222222222222222,Zd=.10257936507936508,$d=.06388888888888888,_d=.0664021164021164,ae=.016415012942191543,be=["Lambert Azimuthal Equal Area","Lambert_Azimuthal_Equal_Area","laea"],ce={init:Ga,forward:Ha,inverse:Ia,names:be,S_POLE:Td,N_POLE:Ud,EQUIT:Vd,OBLIQ:Wd},de=function(a){return Math.abs(a)>1&&(a=a>1?1:-1),Math.asin(a)},ee=["Albers_Conic_Equal_Area","Albers","aea"],fe={init:La,forward:Ma,inverse:Na,names:ee,phi1z:Oa},ge=["gnom"],he={init:Pa,forward:Qa,inverse:Ra,names:ge},ie=function(a,b){var c=1-(1-a*a)/(2*a)*Math.log((1-a)/(1+a));if(Math.abs(Math.abs(b)-c)<1e-6)return 0>b?-1*Ib:Ib;for(var d,e,f,g,h=Math.asin(.5*b),i=0;30>i;i++)if(e=Math.sin(h),f=Math.cos(h),g=a*e,d=Math.pow(1-g*g,2)/(2*f)*(b/(1-a*a)-e/(1-g*g)+.5/a*Math.log((1-g)/(1+g))),h+=d,Math.abs(d)<=1e-10)return h;return NaN},je=["cea"],ke={init:Sa,forward:Ta,inverse:Ua,names:je},le=["Equirectangular","Equidistant_Cylindrical","eqc"],me={init:Va,forward:Wa,inverse:Xa,names:le},ne=20,oe=["Polyconic","poly"],pe={init:Ya,forward:Za,inverse:$a,names:oe},qe=["New_Zealand_Map_Grid","nzmg"],re={init:_a,forward:ab,inverse:bb,names:qe},se=["Miller_Cylindrical","mill"],te={init:cb,forward:db,inverse:eb,names:se},ue=20,ve=["Sinusoidal","sinu"],we={init:fb,forward:gb,inverse:hb,names:ve},xe=["Mollweide","moll"],ye={init:ib,forward:jb,inverse:kb,names:xe},ze=["Equidistant_Conic","eqdc"],Ae={init:lb,forward:mb,inverse:nb,names:ze},Be=["Van_der_Grinten_I","VanDerGrinten","vandg"],Ce={init:ob,forward:pb,inverse:qb,names:Be},De=["Azimuthal_Equidistant","aeqd"],Ee={init:rb,forward:sb,inverse:tb,names:De},Fe=["ortho"],Ge={init:ub,forward:vb,inverse:wb,names:Fe},He={FRONT:1,RIGHT:2,BACK:3,LEFT:4,TOP:5,BOTTOM:6},Ie={AREA_0:1,AREA_1:2,AREA_2:3,AREA_3:4},Je=["Quadrilateralized Spherical Cube","Quadrilateralized_Spherical_Cube","qsc"],Ke={init:xb,forward:yb,inverse:zb,names:Je},Le=function(proj4){proj4.Proj.projections.add(dd),proj4.Proj.projections.add(nd),proj4.Proj.projections.add(rd),proj4.Proj.projections.add(xd),proj4.Proj.projections.add(zd),proj4.Proj.projections.add(Bd),proj4.Proj.projections.add(Dd),proj4.Proj.projections.add(Fd),proj4.Proj.projections.add(Hd),proj4.Proj.projections.add(Rd),proj4.Proj.projections.add(ce),proj4.Proj.projections.add(fe),proj4.Proj.projections.add(he),proj4.Proj.projections.add(ke),proj4.Proj.projections.add(me),proj4.Proj.projections.add(pe),proj4.Proj.projections.add(re),proj4.Proj.projections.add(te),proj4.Proj.projections.add(we),proj4.Proj.projections.add(ye),proj4.Proj.projections.add(Ae),proj4.Proj.projections.add(Ce),proj4.Proj.projections.add(Ee),proj4.Proj.projections.add(Ge),proj4.Proj.projections.add(Ke)};return L.defaultDatum="WGS84",L.Proj=z,L.WGS84=new L.Proj("WGS84"),L.Point=Point,L.toPoint=Bc,L.defs=i,L.transform=I,L.mgrs=Mc,L.version=Nc,Le(L),L});;
(function(){var COMPILED=false;var goog=goog||{};goog.global=this;goog.global.CLOSURE_UNCOMPILED_DEFINES;goog.global.CLOSURE_DEFINES;goog.isDef=function(val){return val!==void 0};goog.isString=function(val){return typeof val=="string"};goog.isBoolean=function(val){return typeof val=="boolean"};goog.isNumber=function(val){return typeof val=="number"};
goog.exportPath_=function(name,opt_object,opt_objectToExportTo){var parts=name.split(".");var cur=opt_objectToExportTo||goog.global;if(!(parts[0]in cur)&&cur.execScript)cur.execScript("var "+parts[0]);for(var part;parts.length&&(part=parts.shift());)if(!parts.length&&goog.isDef(opt_object))cur[part]=opt_object;else if(cur[part]&&cur[part]!==Object.prototype[part])cur=cur[part];else cur=cur[part]={}};
goog.define=function(name,defaultValue){var value=defaultValue;if(!COMPILED)if(goog.global.CLOSURE_UNCOMPILED_DEFINES&&goog.global.CLOSURE_UNCOMPILED_DEFINES.nodeType===undefined&&Object.prototype.hasOwnProperty.call(goog.global.CLOSURE_UNCOMPILED_DEFINES,name))value=goog.global.CLOSURE_UNCOMPILED_DEFINES[name];else if(goog.global.CLOSURE_DEFINES&&goog.global.CLOSURE_DEFINES.nodeType===undefined&&Object.prototype.hasOwnProperty.call(goog.global.CLOSURE_DEFINES,name))value=goog.global.CLOSURE_DEFINES[name];
goog.exportPath_(name,value)};goog.define("goog.DEBUG",true);goog.define("goog.LOCALE","en");goog.define("goog.TRUSTED_SITE",true);goog.define("goog.STRICT_MODE_COMPATIBLE",false);goog.define("goog.DISALLOW_TEST_ONLY_CODE",COMPILED&&!goog.DEBUG);goog.define("goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING",false);
goog.provide=function(name){if(goog.isInModuleLoader_())throw new Error("goog.provide can not be used within a goog.module.");if(!COMPILED)if(goog.isProvided_(name))throw new Error('Namespace "'+name+'" already declared.');goog.constructNamespace_(name)};
goog.constructNamespace_=function(name,opt_obj){if(!COMPILED){delete goog.implicitNamespaces_[name];var namespace=name;while(namespace=namespace.substring(0,namespace.lastIndexOf("."))){if(goog.getObjectByName(namespace))break;goog.implicitNamespaces_[namespace]=true}}goog.exportPath_(name,opt_obj)};goog.VALID_MODULE_RE_=/^[a-zA-Z_$][a-zA-Z0-9._$]*$/;
goog.module=function(name){if(!goog.isString(name)||!name||name.search(goog.VALID_MODULE_RE_)==-1)throw new Error("Invalid module identifier");if(!goog.isInModuleLoader_())throw new Error("Module "+name+" has been loaded incorrectly. Note, "+"modules cannot be loaded as normal scripts. They require some kind of "+"pre-processing step. You're likely trying to load a module via a "+"script tag or as a part of a concatenated bundle without rewriting the "+"module. For more info see: "+"https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.");
if(goog.moduleLoaderState_.moduleName)throw new Error("goog.module may only be called once per module.");goog.moduleLoaderState_.moduleName=name;if(!COMPILED){if(goog.isProvided_(name))throw new Error('Namespace "'+name+'" already declared.');delete goog.implicitNamespaces_[name]}};goog.module.get=function(name){return goog.module.getInternal_(name)};
goog.module.getInternal_=function(name){if(!COMPILED)if(name in goog.loadedModules_)return goog.loadedModules_[name];else if(!goog.implicitNamespaces_[name]){var ns=goog.getObjectByName(name);return ns!=null?ns:null}return null};goog.moduleLoaderState_=null;goog.isInModuleLoader_=function(){return goog.moduleLoaderState_!=null};
goog.module.declareLegacyNamespace=function(){if(!COMPILED&&!goog.isInModuleLoader_())throw new Error("goog.module.declareLegacyNamespace must be called from "+"within a goog.module");if(!COMPILED&&!goog.moduleLoaderState_.moduleName)throw new Error("goog.module must be called prior to "+"goog.module.declareLegacyNamespace.");goog.moduleLoaderState_.declareLegacyNamespace=true};
goog.setTestOnly=function(opt_message){if(goog.DISALLOW_TEST_ONLY_CODE){opt_message=opt_message||"";throw new Error("Importing test-only code into non-debug environment"+(opt_message?": "+opt_message:"."));}};goog.forwardDeclare=function(name){};goog.forwardDeclare("Document");goog.forwardDeclare("HTMLScriptElement");goog.forwardDeclare("XMLHttpRequest");
if(!COMPILED){goog.isProvided_=function(name){return name in goog.loadedModules_||!goog.implicitNamespaces_[name]&&goog.isDefAndNotNull(goog.getObjectByName(name))};goog.implicitNamespaces_={"goog.module":true}}goog.getObjectByName=function(name,opt_obj){var parts=name.split(".");var cur=opt_obj||goog.global;for(var i=0;i<parts.length;i++){cur=cur[parts[i]];if(!goog.isDefAndNotNull(cur))return null}return cur};
goog.globalize=function(obj,opt_global){var global=opt_global||goog.global;for(var x in obj)global[x]=obj[x]};
goog.addDependency=function(relPath,provides,requires,opt_loadFlags){if(goog.DEPENDENCIES_ENABLED){var provide,require;var path=relPath.replace(/\\/g,"/");var deps=goog.dependencies_;if(!opt_loadFlags||typeof opt_loadFlags==="boolean")opt_loadFlags=opt_loadFlags?{"module":"goog"}:{};for(var i=0;provide=provides[i];i++){deps.nameToPath[provide]=path;deps.loadFlags[path]=opt_loadFlags}for(var j=0;require=requires[j];j++){if(!(path in deps.requires))deps.requires[path]={};deps.requires[path][require]=
true}}};goog.define("goog.ENABLE_DEBUG_LOADER",true);goog.logToConsole_=function(msg){if(goog.global.console)goog.global.console["error"](msg)};
goog.require=function(name){if(!COMPILED){if(goog.ENABLE_DEBUG_LOADER&&goog.IS_OLD_IE_)goog.maybeProcessDeferredDep_(name);if(goog.isProvided_(name)){if(goog.isInModuleLoader_())return goog.module.getInternal_(name)}else if(goog.ENABLE_DEBUG_LOADER){var path=goog.getPathFromDeps_(name);if(path)goog.writeScripts_(path);else{var errorMessage="goog.require could not find: "+name;goog.logToConsole_(errorMessage);throw new Error(errorMessage);}}return null}};goog.basePath="";goog.global.CLOSURE_BASE_PATH;
goog.global.CLOSURE_NO_DEPS;goog.global.CLOSURE_IMPORT_SCRIPT;goog.nullFunction=function(){};goog.abstractMethod=function(){throw new Error("unimplemented abstract method");};goog.addSingletonGetter=function(ctor){ctor.instance_=undefined;ctor.getInstance=function(){if(ctor.instance_)return ctor.instance_;if(goog.DEBUG)goog.instantiatedSingletons_[goog.instantiatedSingletons_.length]=ctor;return ctor.instance_=new ctor}};goog.instantiatedSingletons_=[];goog.define("goog.LOAD_MODULE_USING_EVAL",true);
goog.define("goog.SEAL_MODULE_EXPORTS",goog.DEBUG);goog.loadedModules_={};goog.DEPENDENCIES_ENABLED=!COMPILED&&goog.ENABLE_DEBUG_LOADER;goog.define("goog.TRANSPILE","detect");goog.define("goog.TRANSPILER","transpile.js");
if(goog.DEPENDENCIES_ENABLED){goog.dependencies_={loadFlags:{},nameToPath:{},requires:{},visited:{},written:{},deferred:{}};goog.inHtmlDocument_=function(){var doc=goog.global.document;return doc!=null&&"write"in doc};goog.findBasePath_=function(){if(goog.isDef(goog.global.CLOSURE_BASE_PATH)&&goog.isString(goog.global.CLOSURE_BASE_PATH)){goog.basePath=goog.global.CLOSURE_BASE_PATH;return}else if(!goog.inHtmlDocument_())return;var doc=goog.global.document;var currentScript=doc.currentScript;if(currentScript)var scripts=
[currentScript];else var scripts=doc.getElementsByTagName("SCRIPT");for(var i=scripts.length-1;i>=0;--i){var script=scripts[i];var src=script.src;var qmark=src.lastIndexOf("?");var l=qmark==-1?src.length:qmark;if(src.substr(l-7,7)=="base.js"){goog.basePath=src.substr(0,l-7);return}}};goog.importScript_=function(src,opt_sourceText){var importScript=goog.global.CLOSURE_IMPORT_SCRIPT||goog.writeScriptTag_;if(importScript(src,opt_sourceText))goog.dependencies_.written[src]=true};goog.IS_OLD_IE_=!!(!goog.global.atob&&
goog.global.document&&goog.global.document.all);goog.oldIeWaiting_=false;goog.importProcessedScript_=function(src,isModule,needsTranspile){var bootstrap='goog.retrieveAndExec_("'+src+'", '+isModule+", "+needsTranspile+");";goog.importScript_("",bootstrap)};goog.queuedModules_=[];goog.wrapModule_=function(srcUrl,scriptText){if(!goog.LOAD_MODULE_USING_EVAL||!goog.isDef(goog.global.JSON))return""+"goog.loadModule(function(exports) {"+'"use strict";'+scriptText+"\n"+";return exports"+"});"+"\n//# sourceURL="+
srcUrl+"\n";else return""+"goog.loadModule("+goog.global.JSON.stringify(scriptText+"\n//# sourceURL="+srcUrl+"\n")+");"};goog.loadQueuedModules_=function(){var count=goog.queuedModules_.length;if(count>0){var queue=goog.queuedModules_;goog.queuedModules_=[];for(var i=0;i<count;i++){var path=queue[i];goog.maybeProcessDeferredPath_(path)}}goog.oldIeWaiting_=false};goog.maybeProcessDeferredDep_=function(name){if(goog.isDeferredModule_(name)&&goog.allDepsAreAvailable_(name)){var path=goog.getPathFromDeps_(name);
goog.maybeProcessDeferredPath_(goog.basePath+path)}};goog.isDeferredModule_=function(name){var path=goog.getPathFromDeps_(name);var loadFlags=path&&goog.dependencies_.loadFlags[path]||{};var languageLevel=loadFlags["lang"]||"es3";if(path&&(loadFlags["module"]=="goog"||goog.needsTranspile_(languageLevel))){var abspath=goog.basePath+path;return abspath in goog.dependencies_.deferred}return false};goog.allDepsAreAvailable_=function(name){var path=goog.getPathFromDeps_(name);if(path&&path in goog.dependencies_.requires)for(var requireName in goog.dependencies_.requires[path])if(!goog.isProvided_(requireName)&&
!goog.isDeferredModule_(requireName))return false;return true};goog.maybeProcessDeferredPath_=function(abspath){if(abspath in goog.dependencies_.deferred){var src=goog.dependencies_.deferred[abspath];delete goog.dependencies_.deferred[abspath];goog.globalEval(src)}};goog.loadModuleFromUrl=function(url){goog.retrieveAndExec_(url,true,false)};goog.writeScriptSrcNode_=function(src){goog.global.document.write('<script type="text/javascript" src="'+src+'"></'+"script>")};goog.appendScriptSrcNode_=function(src){var doc=
goog.global.document;var scriptEl=doc.createElement("script");scriptEl.type="text/javascript";scriptEl.src=src;scriptEl.defer=false;scriptEl.async=false;doc.head.appendChild(scriptEl)};goog.writeScriptTag_=function(src,opt_sourceText){if(goog.inHtmlDocument_()){var doc=goog.global.document;if(!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING&&doc.readyState=="complete"){var isDeps=/\bdeps.js$/.test(src);if(isDeps)return false;else throw new Error('Cannot write "'+src+'" after document load');}if(opt_sourceText===
undefined)if(!goog.IS_OLD_IE_)if(goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING)goog.appendScriptSrcNode_(src);else goog.writeScriptSrcNode_(src);else{goog.oldIeWaiting_=true;var state=" onreadystatechange='goog.onScriptLoad_(this, "+ ++goog.lastNonModuleScriptIndex_+")' ";doc.write('<script type="text/javascript" src="'+src+'"'+state+"></"+"script>")}else doc.write('<script type="text/javascript">'+goog.protectScriptTag_(opt_sourceText)+"</"+"script>");return true}else return false};goog.protectScriptTag_=
function(str){return str.replace(/<\/(SCRIPT)/ig,"\\x3c/$1")};goog.needsTranspile_=function(lang){if(goog.TRANSPILE=="always")return true;else if(goog.TRANSPILE=="never")return false;else if(!goog.requiresTranspilation_)goog.requiresTranspilation_=goog.createRequiresTranspilation_();if(lang in goog.requiresTranspilation_)return goog.requiresTranspilation_[lang];else throw new Error("Unknown language mode: "+lang);};goog.requiresTranspilation_=null;goog.lastNonModuleScriptIndex_=0;goog.onScriptLoad_=
function(script,scriptIndex){if(script.readyState=="complete"&&goog.lastNonModuleScriptIndex_==scriptIndex)goog.loadQueuedModules_();return true};goog.writeScripts_=function(pathToLoad){var scripts=[];var seenScript={};var deps=goog.dependencies_;function visitNode(path){if(path in deps.written)return;if(path in deps.visited)return;deps.visited[path]=true;if(path in deps.requires)for(var requireName in deps.requires[path])if(!goog.isProvided_(requireName))if(requireName in deps.nameToPath)visitNode(deps.nameToPath[requireName]);
else throw new Error("Undefined nameToPath for "+requireName);if(!(path in seenScript)){seenScript[path]=true;scripts.push(path)}}visitNode(pathToLoad);for(var i=0;i<scripts.length;i++){var path=scripts[i];goog.dependencies_.written[path]=true}var moduleState=goog.moduleLoaderState_;goog.moduleLoaderState_=null;for(var i=0;i<scripts.length;i++){var path=scripts[i];if(path){var loadFlags=deps.loadFlags[path]||{};var languageLevel=loadFlags["lang"]||"es3";var needsTranspile=goog.needsTranspile_(languageLevel);
if(loadFlags["module"]=="goog"||needsTranspile)goog.importProcessedScript_(goog.basePath+path,loadFlags["module"]=="goog",needsTranspile);else goog.importScript_(goog.basePath+path)}else{goog.moduleLoaderState_=moduleState;throw new Error("Undefined script input");}}goog.moduleLoaderState_=moduleState};goog.getPathFromDeps_=function(rule){if(rule in goog.dependencies_.nameToPath)return goog.dependencies_.nameToPath[rule];else return null};goog.findBasePath_();if(!goog.global.CLOSURE_NO_DEPS)goog.importScript_(goog.basePath+
"deps.js")}goog.hasBadLetScoping=null;goog.useSafari10Workaround=function(){if(goog.hasBadLetScoping==null){var hasBadLetScoping;try{hasBadLetScoping=!eval('"use strict";'+"let x = 1; function f() { return typeof x; };"+'f() == "number";')}catch(e){hasBadLetScoping=false}goog.hasBadLetScoping=hasBadLetScoping}return goog.hasBadLetScoping};goog.workaroundSafari10EvalBug=function(moduleDef){return"(function(){"+moduleDef+"\n"+";"+"})();\n"};
goog.loadModule=function(moduleDef){var previousState=goog.moduleLoaderState_;try{goog.moduleLoaderState_={moduleName:undefined,declareLegacyNamespace:false};var exports;if(goog.isFunction(moduleDef))exports=moduleDef.call(undefined,{});else if(goog.isString(moduleDef)){if(goog.useSafari10Workaround())moduleDef=goog.workaroundSafari10EvalBug(moduleDef);exports=goog.loadModuleFromSource_.call(undefined,moduleDef)}else throw new Error("Invalid module definition");var moduleName=goog.moduleLoaderState_.moduleName;
if(!goog.isString(moduleName)||!moduleName)throw new Error('Invalid module name "'+moduleName+'"');if(goog.moduleLoaderState_.declareLegacyNamespace)goog.constructNamespace_(moduleName,exports);else if(goog.SEAL_MODULE_EXPORTS&&Object.seal&&typeof exports=="object"&&exports!=null)Object.seal(exports);goog.loadedModules_[moduleName]=exports}finally{goog.moduleLoaderState_=previousState}};goog.loadModuleFromSource_=function(){var exports={};eval(arguments[0]);return exports};
goog.normalizePath_=function(path){var components=path.split("/");var i=0;while(i<components.length)if(components[i]==".")components.splice(i,1);else if(i&&components[i]==".."&&components[i-1]&&components[i-1]!="..")components.splice(--i,2);else i++;return components.join("/")};goog.global.CLOSURE_LOAD_FILE_SYNC;
goog.loadFileSync_=function(src){if(goog.global.CLOSURE_LOAD_FILE_SYNC)return goog.global.CLOSURE_LOAD_FILE_SYNC(src);else try{var xhr=new goog.global["XMLHttpRequest"];xhr.open("get",src,false);xhr.send();return xhr.status==0||xhr.status==200?xhr.responseText:null}catch(err){return null}};
goog.retrieveAndExec_=function(src,isModule,needsTranspile){if(!COMPILED){var originalPath=src;src=goog.normalizePath_(src);var importScript=goog.global.CLOSURE_IMPORT_SCRIPT||goog.writeScriptTag_;var scriptText=goog.loadFileSync_(src);if(scriptText==null)throw new Error('Load of "'+src+'" failed');if(needsTranspile)scriptText=goog.transpile_.call(goog.global,scriptText,src);if(isModule)scriptText=goog.wrapModule_(src,scriptText);else scriptText+="\n//# sourceURL="+src;var isOldIE=goog.IS_OLD_IE_;
if(isOldIE&&goog.oldIeWaiting_){goog.dependencies_.deferred[originalPath]=scriptText;goog.queuedModules_.push(originalPath)}else importScript(src,scriptText)}};
goog.transpile_=function(code,path){var jscomp=goog.global["$jscomp"];if(!jscomp)goog.global["$jscomp"]=jscomp={};var transpile=jscomp.transpile;if(!transpile){var transpilerPath=goog.basePath+goog.TRANSPILER;var transpilerCode=goog.loadFileSync_(transpilerPath);if(transpilerCode){eval(transpilerCode+"\n//# sourceURL="+transpilerPath);if(goog.global["$gwtExport"]&&goog.global["$gwtExport"]["$jscomp"]&&!goog.global["$gwtExport"]["$jscomp"]["transpile"])throw new Error('The transpiler did not properly export the "transpile" '+
"method. $gwtExport: "+JSON.stringify(goog.global["$gwtExport"]));goog.global["$jscomp"].transpile=goog.global["$gwtExport"]["$jscomp"]["transpile"];jscomp=goog.global["$jscomp"];transpile=jscomp.transpile}}if(!transpile){var suffix=" requires transpilation but no transpiler was found.";transpile=jscomp.transpile=function(code,path){goog.logToConsole_(path+suffix);return code}}return transpile(code,path)};
goog.typeOf=function(value){var s=typeof value;if(s=="object")if(value){if(value instanceof Array)return"array";else if(value instanceof Object)return s;var className=Object.prototype.toString.call(value);if(className=="[object Window]")return"object";if(className=="[object Array]"||typeof value.length=="number"&&typeof value.splice!="undefined"&&typeof value.propertyIsEnumerable!="undefined"&&!value.propertyIsEnumerable("splice"))return"array";if(className=="[object Function]"||typeof value.call!=
"undefined"&&typeof value.propertyIsEnumerable!="undefined"&&!value.propertyIsEnumerable("call"))return"function"}else return"null";else if(s=="function"&&typeof value.call=="undefined")return"object";return s};goog.isNull=function(val){return val===null};goog.isDefAndNotNull=function(val){return val!=null};goog.isArray=function(val){return goog.typeOf(val)=="array"};goog.isArrayLike=function(val){var type=goog.typeOf(val);return type=="array"||type=="object"&&typeof val.length=="number"};
goog.isDateLike=function(val){return goog.isObject(val)&&typeof val.getFullYear=="function"};goog.isFunction=function(val){return goog.typeOf(val)=="function"};goog.isObject=function(val){var type=typeof val;return type=="object"&&val!=null||type=="function"};goog.getUid=function(obj){return obj[goog.UID_PROPERTY_]||(obj[goog.UID_PROPERTY_]=++goog.uidCounter_)};goog.hasUid=function(obj){return!!obj[goog.UID_PROPERTY_]};
goog.removeUid=function(obj){if(obj!==null&&"removeAttribute"in obj)obj.removeAttribute(goog.UID_PROPERTY_);try{delete obj[goog.UID_PROPERTY_]}catch(ex){}};goog.UID_PROPERTY_="closure_uid_"+(Math.random()*1E9>>>0);goog.uidCounter_=0;goog.getHashCode=goog.getUid;goog.removeHashCode=goog.removeUid;
goog.cloneObject=function(obj){var type=goog.typeOf(obj);if(type=="object"||type=="array"){if(obj.clone)return obj.clone();var clone=type=="array"?[]:{};for(var key in obj)clone[key]=goog.cloneObject(obj[key]);return clone}return obj};goog.bindNative_=function(fn,selfObj,var_args){return fn.call.apply(fn.bind,arguments)};
goog.bindJs_=function(fn,selfObj,var_args){if(!fn)throw new Error;if(arguments.length>2){var boundArgs=Array.prototype.slice.call(arguments,2);return function(){var newArgs=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(newArgs,boundArgs);return fn.apply(selfObj,newArgs)}}else return function(){return fn.apply(selfObj,arguments)}};
goog.bind=function(fn,selfObj,var_args){if(Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1)goog.bind=goog.bindNative_;else goog.bind=goog.bindJs_;return goog.bind.apply(null,arguments)};goog.partial=function(fn,var_args){var args=Array.prototype.slice.call(arguments,1);return function(){var newArgs=args.slice();newArgs.push.apply(newArgs,arguments);return fn.apply(this,newArgs)}};goog.mixin=function(target,source){for(var x in source)target[x]=source[x]};
goog.now=goog.TRUSTED_SITE&&Date.now||function(){return+new Date};
goog.globalEval=function(script){if(goog.global.execScript)goog.global.execScript(script,"JavaScript");else if(goog.global.eval){if(goog.evalWorksForGlobals_==null){goog.global.eval("var _evalTest_ = 1;");if(typeof goog.global["_evalTest_"]!="undefined"){try{delete goog.global["_evalTest_"]}catch(ignore){}goog.evalWorksForGlobals_=true}else goog.evalWorksForGlobals_=false}if(goog.evalWorksForGlobals_)goog.global.eval(script);else{var doc=goog.global.document;var scriptElt=doc.createElement("SCRIPT");
scriptElt.type="text/javascript";scriptElt.defer=false;scriptElt.appendChild(doc.createTextNode(script));doc.body.appendChild(scriptElt);doc.body.removeChild(scriptElt)}}else throw new Error("goog.globalEval not available");};goog.evalWorksForGlobals_=null;goog.cssNameMapping_;goog.cssNameMappingStyle_;goog.global.CLOSURE_CSS_NAME_MAP_FN;
goog.getCssName=function(className,opt_modifier){if(String(className).charAt(0)==".")throw new Error('className passed in goog.getCssName must not start with ".".'+" You passed: "+className);var getMapping=function(cssName){return goog.cssNameMapping_[cssName]||cssName};var renameByParts=function(cssName){var parts=cssName.split("-");var mapped=[];for(var i=0;i<parts.length;i++)mapped.push(getMapping(parts[i]));return mapped.join("-")};var rename;if(goog.cssNameMapping_)rename=goog.cssNameMappingStyle_==
"BY_WHOLE"?getMapping:renameByParts;else rename=function(a){return a};var result=opt_modifier?className+"-"+rename(opt_modifier):rename(className);if(goog.global.CLOSURE_CSS_NAME_MAP_FN)return goog.global.CLOSURE_CSS_NAME_MAP_FN(result);return result};goog.setCssNameMapping=function(mapping,opt_style){goog.cssNameMapping_=mapping;goog.cssNameMappingStyle_=opt_style};goog.global.CLOSURE_CSS_NAME_MAPPING;if(!COMPILED&&goog.global.CLOSURE_CSS_NAME_MAPPING)goog.cssNameMapping_=goog.global.CLOSURE_CSS_NAME_MAPPING;
goog.getMsg=function(str,opt_values){if(opt_values)str=str.replace(/\{\$([^}]+)}/g,function(match,key){return opt_values!=null&&key in opt_values?opt_values[key]:match});return str};goog.getMsgWithFallback=function(a,b){return a};goog.exportSymbol=function(publicPath,object,opt_objectToExportTo){goog.exportPath_(publicPath,object,opt_objectToExportTo)};goog.exportProperty=function(object,publicName,symbol){object[publicName]=symbol};
goog.inherits=function(childCtor,parentCtor){function tempCtor(){}tempCtor.prototype=parentCtor.prototype;childCtor.superClass_=parentCtor.prototype;childCtor.prototype=new tempCtor;childCtor.prototype.constructor=childCtor;childCtor.base=function(me,methodName,var_args){var args=new Array(arguments.length-2);for(var i=2;i<arguments.length;i++)args[i-2]=arguments[i];return parentCtor.prototype[methodName].apply(me,args)}};
goog.base=function(me,opt_methodName,var_args){var caller=arguments.callee.caller;if(goog.STRICT_MODE_COMPATIBLE||goog.DEBUG&&!caller)throw new Error("arguments.caller not defined.  goog.base() cannot be used "+"with strict mode code. See "+"http://www.ecma-international.org/ecma-262/5.1/#sec-C");if(caller.superClass_){var ctorArgs=new Array(arguments.length-1);for(var i=1;i<arguments.length;i++)ctorArgs[i-1]=arguments[i];return caller.superClass_.constructor.apply(me,ctorArgs)}var args=new Array(arguments.length-
2);for(var i=2;i<arguments.length;i++)args[i-2]=arguments[i];var foundCaller=false;for(var ctor=me.constructor;ctor;ctor=ctor.superClass_&&ctor.superClass_.constructor)if(ctor.prototype[opt_methodName]===caller)foundCaller=true;else if(foundCaller)return ctor.prototype[opt_methodName].apply(me,args);if(me[opt_methodName]===caller)return me.constructor.prototype[opt_methodName].apply(me,args);else throw new Error("goog.base called from a method of one name "+"to a method of a different name");};
goog.scope=function(fn){if(goog.isInModuleLoader_())throw new Error("goog.scope is not supported within a goog.module.");fn.call(goog.global)};if(!COMPILED)goog.global["COMPILED"]=COMPILED;
goog.defineClass=function(superClass,def){var constructor=def.constructor;var statics=def.statics;if(!constructor||constructor==Object.prototype.constructor)constructor=function(){throw new Error("cannot instantiate an interface (no constructor defined).");};var cls=goog.defineClass.createSealingConstructor_(constructor,superClass);if(superClass)goog.inherits(cls,superClass);delete def.constructor;delete def.statics;goog.defineClass.applyProperties_(cls.prototype,def);if(statics!=null)if(statics instanceof
Function)statics(cls);else goog.defineClass.applyProperties_(cls,statics);return cls};goog.defineClass.ClassDescriptor;goog.define("goog.defineClass.SEAL_CLASS_INSTANCES",goog.DEBUG);
goog.defineClass.createSealingConstructor_=function(ctr,superClass){if(!goog.defineClass.SEAL_CLASS_INSTANCES)return ctr;var superclassSealable=!goog.defineClass.isUnsealable_(superClass);var wrappedCtr=function(){var instance=ctr.apply(this,arguments)||this;instance[goog.UID_PROPERTY_]=instance[goog.UID_PROPERTY_];if(this.constructor===wrappedCtr&&superclassSealable&&Object.seal instanceof Function)Object.seal(instance);return instance};return wrappedCtr};
goog.defineClass.isUnsealable_=function(ctr){return ctr&&ctr.prototype&&ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_]};goog.defineClass.OBJECT_PROTOTYPE_FIELDS_=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"];
goog.defineClass.applyProperties_=function(target,source){var key;for(key in source)if(Object.prototype.hasOwnProperty.call(source,key))target[key]=source[key];for(var i=0;i<goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length;i++){key=goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];if(Object.prototype.hasOwnProperty.call(source,key))target[key]=source[key]}};goog.tagUnsealableClass=function(ctr){if(!COMPILED&&goog.defineClass.SEAL_CLASS_INSTANCES)ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_]=true};
goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_="goog_defineClass_legacy_unsealable";
goog.createRequiresTranspilation_=function(){var requiresTranspilation={"es3":false};var transpilationRequiredForAllLaterModes=false;function addNewerLanguageTranspilationCheck(modeName,isSupported){if(transpilationRequiredForAllLaterModes)requiresTranspilation[modeName]=true;else if(isSupported())requiresTranspilation[modeName]=false;else{requiresTranspilation[modeName]=true;transpilationRequiredForAllLaterModes=true}}function evalCheck(code){try{return!!eval(code)}catch(ignored){return false}}var userAgent=
goog.global.navigator&&goog.global.navigator.userAgent?goog.global.navigator.userAgent:"";addNewerLanguageTranspilationCheck("es5",function(){return evalCheck("[1,].length==1")});addNewerLanguageTranspilationCheck("es6",function(){var re=/Edge\/(\d+)(\.\d)*/i;var edgeUserAgent=userAgent.match(re);if(edgeUserAgent&&Number(edgeUserAgent[1])<15)return false;var es6fullTest="class X{constructor(){if(new.target!=String)throw 1;this.x=42}}"+"let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof "+
"String))throw 1;for(const a of[2,3]){if(a==2)continue;function "+"f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()"+"==3}";return evalCheck('(()=>{"use strict";'+es6fullTest+"})()")});addNewerLanguageTranspilationCheck("es6-impl",function(){return true});addNewerLanguageTranspilationCheck("es7",function(){return evalCheck("2 ** 2 == 4")});addNewerLanguageTranspilationCheck("es8",function(){return evalCheck("async () => 1, true")});return requiresTranspilation};goog.provide("ol.array");ol.array.binarySearch=function(haystack,needle,opt_comparator){var mid,cmp;var comparator=opt_comparator||ol.array.numberSafeCompareFunction;var low=0;var high=haystack.length;var found=false;while(low<high){mid=low+(high-low>>1);cmp=+comparator(haystack[mid],needle);if(cmp<0)low=mid+1;else{high=mid;found=!cmp}}return found?low:~low};ol.array.numberSafeCompareFunction=function(a,b){return a>b?1:a<b?-1:0};ol.array.includes=function(arr,obj){return arr.indexOf(obj)>=0};
ol.array.linearFindNearest=function(arr,target,direction){var n=arr.length;if(arr[0]<=target)return 0;else if(target<=arr[n-1])return n-1;else{var i;if(direction>0)for(i=1;i<n;++i){if(arr[i]<target)return i-1}else if(direction<0)for(i=1;i<n;++i){if(arr[i]<=target)return i}else for(i=1;i<n;++i)if(arr[i]==target)return i;else if(arr[i]<target)if(arr[i-1]-target<target-arr[i])return i-1;else return i;return n-1}};
ol.array.reverseSubArray=function(arr,begin,end){while(begin<end){var tmp=arr[begin];arr[begin]=arr[end];arr[end]=tmp;++begin;--end}};ol.array.extend=function(arr,data){var i;var extension=Array.isArray(data)?data:[data];var length=extension.length;for(i=0;i<length;i++)arr[arr.length]=extension[i]};ol.array.remove=function(arr,obj){var i=arr.indexOf(obj);var found=i>-1;if(found)arr.splice(i,1);return found};
ol.array.find=function(arr,func){var length=arr.length>>>0;var value;for(var i=0;i<length;i++){value=arr[i];if(func(value,i,arr))return value}return null};ol.array.equals=function(arr1,arr2){var len1=arr1.length;if(len1!==arr2.length)return false;for(var i=0;i<len1;i++)if(arr1[i]!==arr2[i])return false;return true};
ol.array.stableSort=function(arr,compareFnc){var length=arr.length;var tmp=Array(arr.length);var i;for(i=0;i<length;i++)tmp[i]={index:i,value:arr[i]};tmp.sort(function(a,b){return compareFnc(a.value,b.value)||a.index-b.index});for(i=0;i<arr.length;i++)arr[i]=tmp[i].value};ol.array.findIndex=function(arr,func){var index;var found=!arr.every(function(el,idx){index=idx;return!func(el,idx,arr)});return found?index:-1};
ol.array.isSorted=function(arr,opt_func,opt_strict){var compare=opt_func||ol.array.numberSafeCompareFunction;return arr.every(function(currentVal,index){if(index===0)return true;var res=compare(arr[index-1],currentVal);return!(res>0||opt_strict&&res===0)})};goog.provide("ol");ol.ASSUME_TOUCH=false;ol.DEFAULT_MAX_ZOOM=42;ol.DEFAULT_MIN_ZOOM=0;ol.DEFAULT_RASTER_REPROJECTION_ERROR_THRESHOLD=.5;ol.DEFAULT_TILE_SIZE=256;ol.DEFAULT_WMS_VERSION="1.3.0";ol.ENABLE_CANVAS=true;ol.ENABLE_PROJ4JS=true;ol.ENABLE_RASTER_REPROJECTION=true;ol.ENABLE_WEBGL=true;ol.DEBUG_WEBGL=true;ol.INITIAL_ATLAS_SIZE=256;ol.MAX_ATLAS_SIZE=-1;ol.MOUSEWHEELZOOM_MAXDELTA=1;ol.OVERVIEWMAP_MAX_RATIO=.75;ol.OVERVIEWMAP_MIN_RATIO=.1;ol.RASTER_REPROJECTION_MAX_SOURCE_TILES=100;
ol.RASTER_REPROJECTION_MAX_SUBDIVISION=10;ol.RASTER_REPROJECTION_MAX_TRIANGLE_WIDTH=.25;ol.SIMPLIFY_TOLERANCE=.5;ol.WEBGL_TEXTURE_CACHE_HIGH_WATER_MARK=1024;ol.VERSION="";ol.WEBGL_MAX_TEXTURE_SIZE;ol.WEBGL_EXTENSIONS;ol.inherits=function(childCtor,parentCtor){childCtor.prototype=Object.create(parentCtor.prototype);childCtor.prototype.constructor=childCtor};ol.nullFunction=function(){};ol.getUid=function(obj){return obj.ol_uid||(obj.ol_uid=++ol.uidCounter_)};ol.uidCounter_=0;goog.provide("ol.AssertionError");goog.require("ol");ol.AssertionError=function(code){var path=ol.VERSION?ol.VERSION.split("-")[0]:"latest";this.message="Assertion failed. See https://openlayers.org/en/"+path+"/doc/errors/#"+code+" for details.";this.code=code;this.name="AssertionError"};ol.inherits(ol.AssertionError,Error);goog.provide("ol.asserts");goog.require("ol.AssertionError");ol.asserts.assert=function(assertion,errorCode){if(!assertion)throw new ol.AssertionError(errorCode);};goog.provide("ol.TileRange");ol.TileRange=function(minX,maxX,minY,maxY){this.minX=minX;this.maxX=maxX;this.minY=minY;this.maxY=maxY};ol.TileRange.createOrUpdate=function(minX,maxX,minY,maxY,tileRange){if(tileRange!==undefined){tileRange.minX=minX;tileRange.maxX=maxX;tileRange.minY=minY;tileRange.maxY=maxY;return tileRange}else return new ol.TileRange(minX,maxX,minY,maxY)};ol.TileRange.prototype.contains=function(tileCoord){return this.containsXY(tileCoord[1],tileCoord[2])};
ol.TileRange.prototype.containsTileRange=function(tileRange){return this.minX<=tileRange.minX&&tileRange.maxX<=this.maxX&&this.minY<=tileRange.minY&&tileRange.maxY<=this.maxY};ol.TileRange.prototype.containsXY=function(x,y){return this.minX<=x&&x<=this.maxX&&this.minY<=y&&y<=this.maxY};ol.TileRange.prototype.equals=function(tileRange){return this.minX==tileRange.minX&&this.minY==tileRange.minY&&this.maxX==tileRange.maxX&&this.maxY==tileRange.maxY};
ol.TileRange.prototype.extend=function(tileRange){if(tileRange.minX<this.minX)this.minX=tileRange.minX;if(tileRange.maxX>this.maxX)this.maxX=tileRange.maxX;if(tileRange.minY<this.minY)this.minY=tileRange.minY;if(tileRange.maxY>this.maxY)this.maxY=tileRange.maxY};ol.TileRange.prototype.getHeight=function(){return this.maxY-this.minY+1};ol.TileRange.prototype.getSize=function(){return[this.getWidth(),this.getHeight()]};ol.TileRange.prototype.getWidth=function(){return this.maxX-this.minX+1};
ol.TileRange.prototype.intersects=function(tileRange){return this.minX<=tileRange.maxX&&this.maxX>=tileRange.minX&&this.minY<=tileRange.maxY&&this.maxY>=tileRange.minY};goog.provide("ol.math");goog.require("ol.asserts");ol.math.clamp=function(value,min,max){return Math.min(Math.max(value,min),max)};ol.math.cosh=function(){var cosh;if("cosh"in Math)cosh=Math.cosh;else cosh=function(x){var y=Math.exp(x);return(y+1/y)/2};return cosh}();ol.math.roundUpToPowerOfTwo=function(x){ol.asserts.assert(0<x,29);return Math.pow(2,Math.ceil(Math.log(x)/Math.LN2))};
ol.math.squaredSegmentDistance=function(x,y,x1,y1,x2,y2){var dx=x2-x1;var dy=y2-y1;if(dx!==0||dy!==0){var t=((x-x1)*dx+(y-y1)*dy)/(dx*dx+dy*dy);if(t>1){x1=x2;y1=y2}else if(t>0){x1+=dx*t;y1+=dy*t}}return ol.math.squaredDistance(x,y,x1,y1)};ol.math.squaredDistance=function(x1,y1,x2,y2){var dx=x2-x1;var dy=y2-y1;return dx*dx+dy*dy};
ol.math.solveLinearSystem=function(mat){var n=mat.length;for(var i=0;i<n;i++){var maxRow=i;var maxEl=Math.abs(mat[i][i]);for(var r=i+1;r<n;r++){var absValue=Math.abs(mat[r][i]);if(absValue>maxEl){maxEl=absValue;maxRow=r}}if(maxEl===0)return null;var tmp=mat[maxRow];mat[maxRow]=mat[i];mat[i]=tmp;for(var j=i+1;j<n;j++){var coef=-mat[j][i]/mat[i][i];for(var k=i;k<n+1;k++)if(i==k)mat[j][k]=0;else mat[j][k]+=coef*mat[i][k]}}var x=new Array(n);for(var l=n-1;l>=0;l--){x[l]=mat[l][n]/mat[l][l];for(var m=
l-1;m>=0;m--)mat[m][n]-=mat[m][l]*x[l]}return x};ol.math.toDegrees=function(angleInRadians){return angleInRadians*180/Math.PI};ol.math.toRadians=function(angleInDegrees){return angleInDegrees*Math.PI/180};ol.math.modulo=function(a,b){var r=a%b;return r*b<0?r+b:r};ol.math.lerp=function(a,b,x){return a+x*(b-a)};goog.provide("ol.size");ol.size.buffer=function(size,buffer,opt_size){if(opt_size===undefined)opt_size=[0,0];opt_size[0]=size[0]+2*buffer;opt_size[1]=size[1]+2*buffer;return opt_size};ol.size.hasArea=function(size){return size[0]>0&&size[1]>0};ol.size.scale=function(size,ratio,opt_size){if(opt_size===undefined)opt_size=[0,0];opt_size[0]=size[0]*ratio+.5|0;opt_size[1]=size[1]*ratio+.5|0;return opt_size};
ol.size.toSize=function(size,opt_size){if(Array.isArray(size))return size;else{if(opt_size===undefined)opt_size=[size,size];else opt_size[0]=opt_size[1]=size;return opt_size}};goog.provide("ol.extent.Corner");ol.extent.Corner={BOTTOM_LEFT:"bottom-left",BOTTOM_RIGHT:"bottom-right",TOP_LEFT:"top-left",TOP_RIGHT:"top-right"};goog.provide("ol.extent.Relationship");ol.extent.Relationship={UNKNOWN:0,INTERSECTING:1,ABOVE:2,RIGHT:4,BELOW:8,LEFT:16};goog.provide("ol.extent");goog.require("ol.asserts");goog.require("ol.extent.Corner");goog.require("ol.extent.Relationship");ol.extent.boundingExtent=function(coordinates){var extent=ol.extent.createEmpty();for(var i=0,ii=coordinates.length;i<ii;++i)ol.extent.extendCoordinate(extent,coordinates[i]);return extent};
ol.extent.boundingExtentXYs_=function(xs,ys,opt_extent){var minX=Math.min.apply(null,xs);var minY=Math.min.apply(null,ys);var maxX=Math.max.apply(null,xs);var maxY=Math.max.apply(null,ys);return ol.extent.createOrUpdate(minX,minY,maxX,maxY,opt_extent)};
ol.extent.buffer=function(extent,value,opt_extent){if(opt_extent){opt_extent[0]=extent[0]-value;opt_extent[1]=extent[1]-value;opt_extent[2]=extent[2]+value;opt_extent[3]=extent[3]+value;return opt_extent}else return[extent[0]-value,extent[1]-value,extent[2]+value,extent[3]+value]};ol.extent.clone=function(extent,opt_extent){if(opt_extent){opt_extent[0]=extent[0];opt_extent[1]=extent[1];opt_extent[2]=extent[2];opt_extent[3]=extent[3];return opt_extent}else return extent.slice()};
ol.extent.closestSquaredDistanceXY=function(extent,x,y){var dx,dy;if(x<extent[0])dx=extent[0]-x;else if(extent[2]<x)dx=x-extent[2];else dx=0;if(y<extent[1])dy=extent[1]-y;else if(extent[3]<y)dy=y-extent[3];else dy=0;return dx*dx+dy*dy};ol.extent.containsCoordinate=function(extent,coordinate){return ol.extent.containsXY(extent,coordinate[0],coordinate[1])};ol.extent.containsExtent=function(extent1,extent2){return extent1[0]<=extent2[0]&&extent2[2]<=extent1[2]&&extent1[1]<=extent2[1]&&extent2[3]<=extent1[3]};
ol.extent.containsXY=function(extent,x,y){return extent[0]<=x&&x<=extent[2]&&extent[1]<=y&&y<=extent[3]};
ol.extent.coordinateRelationship=function(extent,coordinate){var minX=extent[0];var minY=extent[1];var maxX=extent[2];var maxY=extent[3];var x=coordinate[0];var y=coordinate[1];var relationship=ol.extent.Relationship.UNKNOWN;if(x<minX)relationship=relationship|ol.extent.Relationship.LEFT;else if(x>maxX)relationship=relationship|ol.extent.Relationship.RIGHT;if(y<minY)relationship=relationship|ol.extent.Relationship.BELOW;else if(y>maxY)relationship=relationship|ol.extent.Relationship.ABOVE;if(relationship===
ol.extent.Relationship.UNKNOWN)relationship=ol.extent.Relationship.INTERSECTING;return relationship};ol.extent.createEmpty=function(){return[Infinity,Infinity,-Infinity,-Infinity]};ol.extent.createOrUpdate=function(minX,minY,maxX,maxY,opt_extent){if(opt_extent){opt_extent[0]=minX;opt_extent[1]=minY;opt_extent[2]=maxX;opt_extent[3]=maxY;return opt_extent}else return[minX,minY,maxX,maxY]};
ol.extent.createOrUpdateEmpty=function(opt_extent){return ol.extent.createOrUpdate(Infinity,Infinity,-Infinity,-Infinity,opt_extent)};ol.extent.createOrUpdateFromCoordinate=function(coordinate,opt_extent){var x=coordinate[0];var y=coordinate[1];return ol.extent.createOrUpdate(x,y,x,y,opt_extent)};ol.extent.createOrUpdateFromCoordinates=function(coordinates,opt_extent){var extent=ol.extent.createOrUpdateEmpty(opt_extent);return ol.extent.extendCoordinates(extent,coordinates)};
ol.extent.createOrUpdateFromFlatCoordinates=function(flatCoordinates,offset,end,stride,opt_extent){var extent=ol.extent.createOrUpdateEmpty(opt_extent);return ol.extent.extendFlatCoordinates(extent,flatCoordinates,offset,end,stride)};ol.extent.createOrUpdateFromRings=function(rings,opt_extent){var extent=ol.extent.createOrUpdateEmpty(opt_extent);return ol.extent.extendRings(extent,rings)};
ol.extent.equals=function(extent1,extent2){return extent1[0]==extent2[0]&&extent1[2]==extent2[2]&&extent1[1]==extent2[1]&&extent1[3]==extent2[3]};ol.extent.extend=function(extent1,extent2){if(extent2[0]<extent1[0])extent1[0]=extent2[0];if(extent2[2]>extent1[2])extent1[2]=extent2[2];if(extent2[1]<extent1[1])extent1[1]=extent2[1];if(extent2[3]>extent1[3])extent1[3]=extent2[3];return extent1};
ol.extent.extendCoordinate=function(extent,coordinate){if(coordinate[0]<extent[0])extent[0]=coordinate[0];if(coordinate[0]>extent[2])extent[2]=coordinate[0];if(coordinate[1]<extent[1])extent[1]=coordinate[1];if(coordinate[1]>extent[3])extent[3]=coordinate[1]};ol.extent.extendCoordinates=function(extent,coordinates){var i,ii;for(i=0,ii=coordinates.length;i<ii;++i)ol.extent.extendCoordinate(extent,coordinates[i]);return extent};
ol.extent.extendFlatCoordinates=function(extent,flatCoordinates,offset,end,stride){for(;offset<end;offset+=stride)ol.extent.extendXY(extent,flatCoordinates[offset],flatCoordinates[offset+1]);return extent};ol.extent.extendRings=function(extent,rings){var i,ii;for(i=0,ii=rings.length;i<ii;++i)ol.extent.extendCoordinates(extent,rings[i]);return extent};
ol.extent.extendXY=function(extent,x,y){extent[0]=Math.min(extent[0],x);extent[1]=Math.min(extent[1],y);extent[2]=Math.max(extent[2],x);extent[3]=Math.max(extent[3],y)};
ol.extent.forEachCorner=function(extent,callback,opt_this){var val;val=callback.call(opt_this,ol.extent.getBottomLeft(extent));if(val)return val;val=callback.call(opt_this,ol.extent.getBottomRight(extent));if(val)return val;val=callback.call(opt_this,ol.extent.getTopRight(extent));if(val)return val;val=callback.call(opt_this,ol.extent.getTopLeft(extent));if(val)return val;return false};
ol.extent.getArea=function(extent){var area=0;if(!ol.extent.isEmpty(extent))area=ol.extent.getWidth(extent)*ol.extent.getHeight(extent);return area};ol.extent.getBottomLeft=function(extent){return[extent[0],extent[1]]};ol.extent.getBottomRight=function(extent){return[extent[2],extent[1]]};ol.extent.getCenter=function(extent){return[(extent[0]+extent[2])/2,(extent[1]+extent[3])/2]};
ol.extent.getCorner=function(extent,corner){var coordinate;if(corner===ol.extent.Corner.BOTTOM_LEFT)coordinate=ol.extent.getBottomLeft(extent);else if(corner===ol.extent.Corner.BOTTOM_RIGHT)coordinate=ol.extent.getBottomRight(extent);else if(corner===ol.extent.Corner.TOP_LEFT)coordinate=ol.extent.getTopLeft(extent);else if(corner===ol.extent.Corner.TOP_RIGHT)coordinate=ol.extent.getTopRight(extent);else ol.asserts.assert(false,13);return coordinate};
ol.extent.getEnlargedArea=function(extent1,extent2){var minX=Math.min(extent1[0],extent2[0]);var minY=Math.min(extent1[1],extent2[1]);var maxX=Math.max(extent1[2],extent2[2]);var maxY=Math.max(extent1[3],extent2[3]);return(maxX-minX)*(maxY-minY)};
ol.extent.getForViewAndSize=function(center,resolution,rotation,size,opt_extent){var dx=resolution*size[0]/2;var dy=resolution*size[1]/2;var cosRotation=Math.cos(rotation);var sinRotation=Math.sin(rotation);var xCos=dx*cosRotation;var xSin=dx*sinRotation;var yCos=dy*cosRotation;var ySin=dy*sinRotation;var x=center[0];var y=center[1];var x0=x-xCos+ySin;var x1=x-xCos-ySin;var x2=x+xCos-ySin;var x3=x+xCos+ySin;var y0=y-xSin-yCos;var y1=y-xSin+yCos;var y2=y+xSin+yCos;var y3=y+xSin-yCos;return ol.extent.createOrUpdate(Math.min(x0,
x1,x2,x3),Math.min(y0,y1,y2,y3),Math.max(x0,x1,x2,x3),Math.max(y0,y1,y2,y3),opt_extent)};ol.extent.getHeight=function(extent){return extent[3]-extent[1]};ol.extent.getIntersectionArea=function(extent1,extent2){var intersection=ol.extent.getIntersection(extent1,extent2);return ol.extent.getArea(intersection)};
ol.extent.getIntersection=function(extent1,extent2,opt_extent){var intersection=opt_extent?opt_extent:ol.extent.createEmpty();if(ol.extent.intersects(extent1,extent2)){if(extent1[0]>extent2[0])intersection[0]=extent1[0];else intersection[0]=extent2[0];if(extent1[1]>extent2[1])intersection[1]=extent1[1];else intersection[1]=extent2[1];if(extent1[2]<extent2[2])intersection[2]=extent1[2];else intersection[2]=extent2[2];if(extent1[3]<extent2[3])intersection[3]=extent1[3];else intersection[3]=extent2[3]}return intersection};
ol.extent.getMargin=function(extent){return ol.extent.getWidth(extent)+ol.extent.getHeight(extent)};ol.extent.getSize=function(extent){return[extent[2]-extent[0],extent[3]-extent[1]]};ol.extent.getTopLeft=function(extent){return[extent[0],extent[3]]};ol.extent.getTopRight=function(extent){return[extent[2],extent[3]]};ol.extent.getWidth=function(extent){return extent[2]-extent[0]};
ol.extent.intersects=function(extent1,extent2){return extent1[0]<=extent2[2]&&extent1[2]>=extent2[0]&&extent1[1]<=extent2[3]&&extent1[3]>=extent2[1]};ol.extent.isEmpty=function(extent){return extent[2]<extent[0]||extent[3]<extent[1]};ol.extent.returnOrUpdate=function(extent,opt_extent){if(opt_extent){opt_extent[0]=extent[0];opt_extent[1]=extent[1];opt_extent[2]=extent[2];opt_extent[3]=extent[3];return opt_extent}else return extent};
ol.extent.scaleFromCenter=function(extent,value){var deltaX=(extent[2]-extent[0])/2*(value-1);var deltaY=(extent[3]-extent[1])/2*(value-1);extent[0]-=deltaX;extent[2]+=deltaX;extent[1]-=deltaY;extent[3]+=deltaY};
ol.extent.intersectsSegment=function(extent,start,end){var intersects=false;var startRel=ol.extent.coordinateRelationship(extent,start);var endRel=ol.extent.coordinateRelationship(extent,end);if(startRel===ol.extent.Relationship.INTERSECTING||endRel===ol.extent.Relationship.INTERSECTING)intersects=true;else{var minX=extent[0];var minY=extent[1];var maxX=extent[2];var maxY=extent[3];var startX=start[0];var startY=start[1];var endX=end[0];var endY=end[1];var slope=(endY-startY)/(endX-startX);var x,
y;if(!!(endRel&ol.extent.Relationship.ABOVE)&&!(startRel&ol.extent.Relationship.ABOVE)){x=endX-(endY-maxY)/slope;intersects=x>=minX&&x<=maxX}if(!intersects&&!!(endRel&ol.extent.Relationship.RIGHT)&&!(startRel&ol.extent.Relationship.RIGHT)){y=endY-(endX-maxX)*slope;intersects=y>=minY&&y<=maxY}if(!intersects&&!!(endRel&ol.extent.Relationship.BELOW)&&!(startRel&ol.extent.Relationship.BELOW)){x=endX-(endY-minY)/slope;intersects=x>=minX&&x<=maxX}if(!intersects&&!!(endRel&ol.extent.Relationship.LEFT)&&
!(startRel&ol.extent.Relationship.LEFT)){y=endY-(endX-minX)*slope;intersects=y>=minY&&y<=maxY}}return intersects};ol.extent.applyTransform=function(extent,transformFn,opt_extent){var coordinates=[extent[0],extent[1],extent[0],extent[3],extent[2],extent[1],extent[2],extent[3]];transformFn(coordinates,coordinates,2);var xs=[coordinates[0],coordinates[2],coordinates[4],coordinates[6]];var ys=[coordinates[1],coordinates[3],coordinates[5],coordinates[7]];return ol.extent.boundingExtentXYs_(xs,ys,opt_extent)};goog.provide("ol.obj");ol.obj.assign=typeof Object.assign==="function"?Object.assign:function(target,var_sources){if(target===undefined||target===null)throw new TypeError("Cannot convert undefined or null to object");var output=Object(target);for(var i=1,ii=arguments.length;i<ii;++i){var source=arguments[i];if(source!==undefined&&source!==null)for(var key in source)if(source.hasOwnProperty(key))output[key]=source[key]}return output};ol.obj.clear=function(object){for(var property in object)delete object[property]};
ol.obj.getValues=function(object){var values=[];for(var property in object)values.push(object[property]);return values};ol.obj.isEmpty=function(object){var property;for(property in object)return false;return!property};goog.provide("ol.geom.GeometryType");ol.geom.GeometryType={POINT:"Point",LINE_STRING:"LineString",LINEAR_RING:"LinearRing",POLYGON:"Polygon",MULTI_POINT:"MultiPoint",MULTI_LINE_STRING:"MultiLineString",MULTI_POLYGON:"MultiPolygon",GEOMETRY_COLLECTION:"GeometryCollection",CIRCLE:"Circle"};/*

 Latitude/longitude spherical geodesy formulae taken from
 http://www.movable-type.co.uk/scripts/latlong.html
 Licensed under CC-BY-3.0.
*/
goog.provide("ol.Sphere");goog.require("ol.math");goog.require("ol.geom.GeometryType");ol.Sphere=function(radius){this.radius=radius};ol.Sphere.prototype.geodesicArea=function(coordinates){return ol.Sphere.getArea_(coordinates,this.radius)};ol.Sphere.prototype.haversineDistance=function(c1,c2){return ol.Sphere.getDistance_(c1,c2,this.radius)};
ol.Sphere.prototype.offset=function(c1,distance,bearing){var lat1=ol.math.toRadians(c1[1]);var lon1=ol.math.toRadians(c1[0]);var dByR=distance/this.radius;var lat=Math.asin(Math.sin(lat1)*Math.cos(dByR)+Math.cos(lat1)*Math.sin(dByR)*Math.cos(bearing));var lon=lon1+Math.atan2(Math.sin(bearing)*Math.sin(dByR)*Math.cos(lat1),Math.cos(dByR)-Math.sin(lat1)*Math.sin(lat));return[ol.math.toDegrees(lon),ol.math.toDegrees(lat)]};ol.Sphere.DEFAULT_RADIUS=6371008.8;
ol.Sphere.getLength=function(geometry,opt_options){var options=opt_options||{};var radius=options.radius||ol.Sphere.DEFAULT_RADIUS;var projection=options.projection||"EPSG:3857";geometry=geometry.clone().transform(projection,"EPSG:4326");var type=geometry.getType();var length=0;var coordinates,coords,i,ii,j,jj;switch(type){case ol.geom.GeometryType.POINT:case ol.geom.GeometryType.MULTI_POINT:{break}case ol.geom.GeometryType.LINE_STRING:case ol.geom.GeometryType.LINEAR_RING:{coordinates=geometry.getCoordinates();
length=ol.Sphere.getLength_(coordinates,radius);break}case ol.geom.GeometryType.MULTI_LINE_STRING:case ol.geom.GeometryType.POLYGON:{coordinates=geometry.getCoordinates();for(i=0,ii=coordinates.length;i<ii;++i)length+=ol.Sphere.getLength_(coordinates[i],radius);break}case ol.geom.GeometryType.MULTI_POLYGON:{coordinates=geometry.getCoordinates();for(i=0,ii=coordinates.length;i<ii;++i){coords=coordinates[i];for(j=0,jj=coords.length;j<jj;++j)length+=ol.Sphere.getLength_(coords[j],radius)}break}case ol.geom.GeometryType.GEOMETRY_COLLECTION:{var geometries=
geometry.getGeometries();for(i=0,ii=geometries.length;i<ii;++i)length+=ol.Sphere.getLength(geometries[i],opt_options);break}default:{throw new Error("Unsupported geometry type: "+type);}}return length};ol.Sphere.getLength_=function(coordinates,radius){var length=0;for(var i=0,ii=coordinates.length;i<ii-1;++i)length+=ol.Sphere.getDistance_(coordinates[i],coordinates[i+1],radius);return length};
ol.Sphere.getDistance_=function(c1,c2,radius){var lat1=ol.math.toRadians(c1[1]);var lat2=ol.math.toRadians(c2[1]);var deltaLatBy2=(lat2-lat1)/2;var deltaLonBy2=ol.math.toRadians(c2[0]-c1[0])/2;var a=Math.sin(deltaLatBy2)*Math.sin(deltaLatBy2)+Math.sin(deltaLonBy2)*Math.sin(deltaLonBy2)*Math.cos(lat1)*Math.cos(lat2);return 2*radius*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))};
ol.Sphere.getArea=function(geometry,opt_options){var options=opt_options||{};var radius=options.radius||ol.Sphere.DEFAULT_RADIUS;var projection=options.projection||"EPSG:3857";geometry=geometry.clone().transform(projection,"EPSG:4326");var type=geometry.getType();var area=0;var coordinates,coords,i,ii,j,jj;switch(type){case ol.geom.GeometryType.POINT:case ol.geom.GeometryType.MULTI_POINT:case ol.geom.GeometryType.LINE_STRING:case ol.geom.GeometryType.MULTI_LINE_STRING:case ol.geom.GeometryType.LINEAR_RING:{break}case ol.geom.GeometryType.POLYGON:{coordinates=
geometry.getCoordinates();area=Math.abs(ol.Sphere.getArea_(coordinates[0],radius));for(i=1,ii=coordinates.length;i<ii;++i)area-=Math.abs(ol.Sphere.getArea_(coordinates[i],radius));break}case ol.geom.GeometryType.MULTI_POLYGON:{coordinates=geometry.getCoordinates();for(i=0,ii=coordinates.length;i<ii;++i){coords=coordinates[i];area+=Math.abs(ol.Sphere.getArea_(coords[0],radius));for(j=1,jj=coords.length;j<jj;++j)area-=Math.abs(ol.Sphere.getArea_(coords[j],radius))}break}case ol.geom.GeometryType.GEOMETRY_COLLECTION:{var geometries=
geometry.getGeometries();for(i=0,ii=geometries.length;i<ii;++i)area+=ol.Sphere.getArea(geometries[i],opt_options);break}default:{throw new Error("Unsupported geometry type: "+type);}}return area};
ol.Sphere.getArea_=function(coordinates,radius){var area=0,len=coordinates.length;var x1=coordinates[len-1][0];var y1=coordinates[len-1][1];for(var i=0;i<len;i++){var x2=coordinates[i][0],y2=coordinates[i][1];area+=ol.math.toRadians(x2-x1)*(2+Math.sin(ol.math.toRadians(y1))+Math.sin(ol.math.toRadians(y2)));x1=x2;y1=y2}return area*radius*radius/2};goog.provide("ol.proj.Units");ol.proj.Units={DEGREES:"degrees",FEET:"ft",METERS:"m",PIXELS:"pixels",TILE_PIXELS:"tile-pixels",USFEET:"us-ft"};ol.proj.Units.METERS_PER_UNIT={};ol.proj.Units.METERS_PER_UNIT[ol.proj.Units.DEGREES]=2*Math.PI*6370997/360;ol.proj.Units.METERS_PER_UNIT[ol.proj.Units.FEET]=.3048;ol.proj.Units.METERS_PER_UNIT[ol.proj.Units.METERS]=1;ol.proj.Units.METERS_PER_UNIT[ol.proj.Units.USFEET]=1200/3937;goog.provide("ol.proj.proj4");ol.proj.proj4.cache_=null;ol.proj.proj4.set=function(proj4){ol.proj.proj4.cache_=proj4};ol.proj.proj4.get=function(){return ol.proj.proj4.cache_||window["proj4"]};goog.provide("ol.proj.Projection");goog.require("ol");goog.require("ol.proj.Units");goog.require("ol.proj.proj4");
ol.proj.Projection=function(options){this.code_=options.code;this.units_=options.units;this.extent_=options.extent!==undefined?options.extent:null;this.worldExtent_=options.worldExtent!==undefined?options.worldExtent:null;this.axisOrientation_=options.axisOrientation!==undefined?options.axisOrientation:"enu";this.global_=options.global!==undefined?options.global:false;this.canWrapX_=!!(this.global_&&this.extent_);this.getPointResolutionFunc_=options.getPointResolution;this.defaultTileGrid_=null;this.metersPerUnit_=
options.metersPerUnit;var code=options.code;if(ol.ENABLE_PROJ4JS){var proj4js=ol.proj.proj4.get();if(typeof proj4js=="function"){var def=proj4js.defs(code);if(def!==undefined){if(def.axis!==undefined&&options.axisOrientation===undefined)this.axisOrientation_=def.axis;if(options.metersPerUnit===undefined)this.metersPerUnit_=def.to_meter;if(options.units===undefined)this.units_=def.units}}}};ol.proj.Projection.prototype.canWrapX=function(){return this.canWrapX_};
ol.proj.Projection.prototype.getCode=function(){return this.code_};ol.proj.Projection.prototype.getExtent=function(){return this.extent_};ol.proj.Projection.prototype.getUnits=function(){return this.units_};ol.proj.Projection.prototype.getMetersPerUnit=function(){return this.metersPerUnit_||ol.proj.Units.METERS_PER_UNIT[this.units_]};ol.proj.Projection.prototype.getWorldExtent=function(){return this.worldExtent_};ol.proj.Projection.prototype.getAxisOrientation=function(){return this.axisOrientation_};
ol.proj.Projection.prototype.isGlobal=function(){return this.global_};ol.proj.Projection.prototype.setGlobal=function(global){this.global_=global;this.canWrapX_=!!(global&&this.extent_)};ol.proj.Projection.prototype.getDefaultTileGrid=function(){return this.defaultTileGrid_};ol.proj.Projection.prototype.setDefaultTileGrid=function(tileGrid){this.defaultTileGrid_=tileGrid};ol.proj.Projection.prototype.setExtent=function(extent){this.extent_=extent;this.canWrapX_=!!(this.global_&&extent)};
ol.proj.Projection.prototype.setWorldExtent=function(worldExtent){this.worldExtent_=worldExtent};ol.proj.Projection.prototype.setGetPointResolution=function(func){this.getPointResolutionFunc_=func};ol.proj.Projection.prototype.getPointResolutionFunc=function(){return this.getPointResolutionFunc_};goog.provide("ol.proj.EPSG3857");goog.require("ol");goog.require("ol.math");goog.require("ol.proj.Projection");goog.require("ol.proj.Units");ol.proj.EPSG3857.Projection_=function(code){ol.proj.Projection.call(this,{code:code,units:ol.proj.Units.METERS,extent:ol.proj.EPSG3857.EXTENT,global:true,worldExtent:ol.proj.EPSG3857.WORLD_EXTENT,getPointResolution:function(resolution,point){return resolution/ol.math.cosh(point[1]/ol.proj.EPSG3857.RADIUS)}})};ol.inherits(ol.proj.EPSG3857.Projection_,ol.proj.Projection);
ol.proj.EPSG3857.RADIUS=6378137;ol.proj.EPSG3857.HALF_SIZE=Math.PI*ol.proj.EPSG3857.RADIUS;ol.proj.EPSG3857.EXTENT=[-ol.proj.EPSG3857.HALF_SIZE,-ol.proj.EPSG3857.HALF_SIZE,ol.proj.EPSG3857.HALF_SIZE,ol.proj.EPSG3857.HALF_SIZE];ol.proj.EPSG3857.WORLD_EXTENT=[-180,-85,180,85];
ol.proj.EPSG3857.PROJECTIONS=[new ol.proj.EPSG3857.Projection_("EPSG:3857"),new ol.proj.EPSG3857.Projection_("EPSG:102100"),new ol.proj.EPSG3857.Projection_("EPSG:102113"),new ol.proj.EPSG3857.Projection_("EPSG:900913"),new ol.proj.EPSG3857.Projection_("urn:ogc:def:crs:EPSG:6.18:3:3857"),new ol.proj.EPSG3857.Projection_("urn:ogc:def:crs:EPSG::3857"),new ol.proj.EPSG3857.Projection_("http://www.opengis.net/gml/srs/epsg.xml#3857")];
ol.proj.EPSG3857.fromEPSG4326=function(input,opt_output,opt_dimension){var length=input.length,dimension=opt_dimension>1?opt_dimension:2,output=opt_output;if(output===undefined)if(dimension>2)output=input.slice();else output=new Array(length);var halfSize=ol.proj.EPSG3857.HALF_SIZE;for(var i=0;i<length;i+=dimension){output[i]=halfSize*input[i]/180;var y=ol.proj.EPSG3857.RADIUS*Math.log(Math.tan(Math.PI*(input[i+1]+90)/360));if(y>halfSize)y=halfSize;else if(y<-halfSize)y=-halfSize;output[i+1]=y}return output};
ol.proj.EPSG3857.toEPSG4326=function(input,opt_output,opt_dimension){var length=input.length,dimension=opt_dimension>1?opt_dimension:2,output=opt_output;if(output===undefined)if(dimension>2)output=input.slice();else output=new Array(length);for(var i=0;i<length;i+=dimension){output[i]=180*input[i]/ol.proj.EPSG3857.HALF_SIZE;output[i+1]=360*Math.atan(Math.exp(input[i+1]/ol.proj.EPSG3857.RADIUS))/Math.PI-90}return output};goog.provide("ol.proj.EPSG4326");goog.require("ol");goog.require("ol.proj.Projection");goog.require("ol.proj.Units");ol.proj.EPSG4326.Projection_=function(code,opt_axisOrientation){ol.proj.Projection.call(this,{code:code,units:ol.proj.Units.DEGREES,extent:ol.proj.EPSG4326.EXTENT,axisOrientation:opt_axisOrientation,global:true,metersPerUnit:ol.proj.EPSG4326.METERS_PER_UNIT,worldExtent:ol.proj.EPSG4326.EXTENT})};ol.inherits(ol.proj.EPSG4326.Projection_,ol.proj.Projection);ol.proj.EPSG4326.RADIUS=6378137;
ol.proj.EPSG4326.EXTENT=[-180,-90,180,90];ol.proj.EPSG4326.METERS_PER_UNIT=Math.PI*ol.proj.EPSG4326.RADIUS/180;
ol.proj.EPSG4326.PROJECTIONS=[new ol.proj.EPSG4326.Projection_("CRS:84"),new ol.proj.EPSG4326.Projection_("EPSG:4326","neu"),new ol.proj.EPSG4326.Projection_("urn:ogc:def:crs:EPSG::4326","neu"),new ol.proj.EPSG4326.Projection_("urn:ogc:def:crs:EPSG:6.6:4326","neu"),new ol.proj.EPSG4326.Projection_("urn:ogc:def:crs:OGC:1.3:CRS84"),new ol.proj.EPSG4326.Projection_("urn:ogc:def:crs:OGC:2:84"),new ol.proj.EPSG4326.Projection_("http://www.opengis.net/gml/srs/epsg.xml#4326","neu"),new ol.proj.EPSG4326.Projection_("urn:x-ogc:def:crs:EPSG:4326",
"neu")];goog.provide("ol.proj.projections");ol.proj.projections.cache_={};ol.proj.projections.clear=function(){ol.proj.projections.cache_={}};ol.proj.projections.get=function(code){var projections=ol.proj.projections.cache_;return projections[code]||null};ol.proj.projections.add=function(code,projection){var projections=ol.proj.projections.cache_;projections[code]=projection};goog.provide("ol.proj.transforms");goog.require("ol.obj");ol.proj.transforms.cache_={};ol.proj.transforms.clear=function(){ol.proj.transforms.cache_={}};ol.proj.transforms.add=function(source,destination,transformFn){var sourceCode=source.getCode();var destinationCode=destination.getCode();var transforms=ol.proj.transforms.cache_;if(!(sourceCode in transforms))transforms[sourceCode]={};transforms[sourceCode][destinationCode]=transformFn};
ol.proj.transforms.remove=function(source,destination){var sourceCode=source.getCode();var destinationCode=destination.getCode();var transforms=ol.proj.transforms.cache_;var transform=transforms[sourceCode][destinationCode];delete transforms[sourceCode][destinationCode];if(ol.obj.isEmpty(transforms[sourceCode]))delete transforms[sourceCode];return transform};
ol.proj.transforms.get=function(sourceCode,destinationCode){var transform;var transforms=ol.proj.transforms.cache_;if(sourceCode in transforms&&destinationCode in transforms[sourceCode])transform=transforms[sourceCode][destinationCode];return transform};goog.provide("ol.proj");goog.require("ol");goog.require("ol.Sphere");goog.require("ol.extent");goog.require("ol.math");goog.require("ol.proj.EPSG3857");goog.require("ol.proj.EPSG4326");goog.require("ol.proj.Projection");goog.require("ol.proj.Units");goog.require("ol.proj.proj4");goog.require("ol.proj.projections");goog.require("ol.proj.transforms");ol.proj.METERS_PER_UNIT=ol.proj.Units.METERS_PER_UNIT;ol.proj.SPHERE_=new ol.Sphere(ol.Sphere.DEFAULT_RADIUS);if(ol.ENABLE_PROJ4JS)ol.proj.setProj4=function(proj4){ol.proj.proj4.set(proj4)};
ol.proj.getPointResolution=function(projection,resolution,point,opt_units){projection=ol.proj.get(projection);var pointResolution;var getter=projection.getPointResolutionFunc();if(getter)pointResolution=getter(resolution,point);else{var units=projection.getUnits();if(units==ol.proj.Units.DEGREES&&!opt_units||opt_units==ol.proj.Units.DEGREES)pointResolution=resolution;else{var toEPSG4326=ol.proj.getTransformFromProjections(projection,ol.proj.get("EPSG:4326"));var vertices=[point[0]-resolution/2,point[1],
point[0]+resolution/2,point[1],point[0],point[1]-resolution/2,point[0],point[1]+resolution/2];vertices=toEPSG4326(vertices,vertices,2);var width=ol.proj.SPHERE_.haversineDistance(vertices.slice(0,2),vertices.slice(2,4));var height=ol.proj.SPHERE_.haversineDistance(vertices.slice(4,6),vertices.slice(6,8));pointResolution=(width+height)/2;var metersPerUnit=opt_units?ol.proj.Units.METERS_PER_UNIT[opt_units]:projection.getMetersPerUnit();if(metersPerUnit!==undefined)pointResolution/=metersPerUnit}}return pointResolution};
ol.proj.addEquivalentProjections=function(projections){ol.proj.addProjections(projections);projections.forEach(function(source){projections.forEach(function(destination){if(source!==destination)ol.proj.transforms.add(source,destination,ol.proj.cloneTransform)})})};
ol.proj.addEquivalentTransforms=function(projections1,projections2,forwardTransform,inverseTransform){projections1.forEach(function(projection1){projections2.forEach(function(projection2){ol.proj.transforms.add(projection1,projection2,forwardTransform);ol.proj.transforms.add(projection2,projection1,inverseTransform)})})};ol.proj.addProjection=function(projection){ol.proj.projections.add(projection.getCode(),projection);ol.proj.transforms.add(projection,projection,ol.proj.cloneTransform)};
ol.proj.addProjections=function(projections){projections.forEach(ol.proj.addProjection)};ol.proj.clearAllProjections=function(){ol.proj.projections.clear();ol.proj.transforms.clear()};ol.proj.createProjection=function(projection,defaultCode){if(!projection)return ol.proj.get(defaultCode);else if(typeof projection==="string")return ol.proj.get(projection);else return projection};
ol.proj.addCoordinateTransforms=function(source,destination,forward,inverse){var sourceProj=ol.proj.get(source);var destProj=ol.proj.get(destination);ol.proj.transforms.add(sourceProj,destProj,ol.proj.createTransformFromCoordinateTransform(forward));ol.proj.transforms.add(destProj,sourceProj,ol.proj.createTransformFromCoordinateTransform(inverse))};
ol.proj.createTransformFromCoordinateTransform=function(transform){return function(input,opt_output,opt_dimension){var length=input.length;var dimension=opt_dimension!==undefined?opt_dimension:2;var output=opt_output!==undefined?opt_output:new Array(length);var point,i,j;for(i=0;i<length;i+=dimension){point=transform([input[i],input[i+1]]);output[i]=point[0];output[i+1]=point[1];for(j=dimension-1;j>=2;--j)output[i+j]=input[i+j]}return output}};
ol.proj.fromLonLat=function(coordinate,opt_projection){return ol.proj.transform(coordinate,"EPSG:4326",opt_projection!==undefined?opt_projection:"EPSG:3857")};ol.proj.toLonLat=function(coordinate,opt_projection){var lonLat=ol.proj.transform(coordinate,opt_projection!==undefined?opt_projection:"EPSG:3857","EPSG:4326");var lon=lonLat[0];if(lon<-180||lon>180)lonLat[0]=ol.math.modulo(lon+180,360)-180;return lonLat};
ol.proj.get=function(projectionLike){var projection=null;if(projectionLike instanceof ol.proj.Projection)projection=projectionLike;else if(typeof projectionLike==="string"){var code=projectionLike;projection=ol.proj.projections.get(code);if(ol.ENABLE_PROJ4JS&&!projection){var proj4js=ol.proj.proj4.get();if(typeof proj4js=="function"&&proj4js.defs(code)!==undefined){projection=new ol.proj.Projection({code:code});ol.proj.addProjection(projection)}}}return projection};
ol.proj.equivalent=function(projection1,projection2){if(projection1===projection2)return true;var equalUnits=projection1.getUnits()===projection2.getUnits();if(projection1.getCode()===projection2.getCode())return equalUnits;else{var transformFn=ol.proj.getTransformFromProjections(projection1,projection2);return transformFn===ol.proj.cloneTransform&&equalUnits}};
ol.proj.getTransform=function(source,destination){var sourceProjection=ol.proj.get(source);var destinationProjection=ol.proj.get(destination);return ol.proj.getTransformFromProjections(sourceProjection,destinationProjection)};
ol.proj.getTransformFromProjections=function(sourceProjection,destinationProjection){var sourceCode=sourceProjection.getCode();var destinationCode=destinationProjection.getCode();var transform=ol.proj.transforms.get(sourceCode,destinationCode);if(ol.ENABLE_PROJ4JS&&!transform){var proj4js=ol.proj.proj4.get();if(typeof proj4js=="function"){var sourceDef=proj4js.defs(sourceCode);var destinationDef=proj4js.defs(destinationCode);if(sourceDef!==undefined&&destinationDef!==undefined){if(sourceDef===destinationDef)ol.proj.addEquivalentProjections([destinationProjection,
sourceProjection]);else{var proj4Transform=proj4js(destinationCode,sourceCode);ol.proj.addCoordinateTransforms(destinationProjection,sourceProjection,proj4Transform.forward,proj4Transform.inverse)}transform=ol.proj.transforms.get(sourceCode,destinationCode)}}}if(!transform)transform=ol.proj.identityTransform;return transform};
ol.proj.identityTransform=function(input,opt_output,opt_dimension){if(opt_output!==undefined&&input!==opt_output){for(var i=0,ii=input.length;i<ii;++i)opt_output[i]=input[i];input=opt_output}return input};ol.proj.cloneTransform=function(input,opt_output,opt_dimension){var output;if(opt_output!==undefined){for(var i=0,ii=input.length;i<ii;++i)opt_output[i]=input[i];output=opt_output}else output=input.slice();return output};
ol.proj.transform=function(coordinate,source,destination){var transformFn=ol.proj.getTransform(source,destination);return transformFn(coordinate,undefined,coordinate.length)};ol.proj.transformExtent=function(extent,source,destination){var transformFn=ol.proj.getTransform(source,destination);return ol.extent.applyTransform(extent,transformFn)};
ol.proj.transformWithProjections=function(point,sourceProjection,destinationProjection){var transformFn=ol.proj.getTransformFromProjections(sourceProjection,destinationProjection);return transformFn(point)};ol.proj.addCommon=function(){ol.proj.addEquivalentProjections(ol.proj.EPSG3857.PROJECTIONS);ol.proj.addEquivalentProjections(ol.proj.EPSG4326.PROJECTIONS);ol.proj.addEquivalentTransforms(ol.proj.EPSG4326.PROJECTIONS,ol.proj.EPSG3857.PROJECTIONS,ol.proj.EPSG3857.fromEPSG4326,ol.proj.EPSG3857.toEPSG4326)};
ol.proj.addCommon();goog.provide("ol.tilecoord");ol.tilecoord.createOrUpdate=function(z,x,y,opt_tileCoord){if(opt_tileCoord!==undefined){opt_tileCoord[0]=z;opt_tileCoord[1]=x;opt_tileCoord[2]=y;return opt_tileCoord}else return[z,x,y]};ol.tilecoord.getKeyZXY=function(z,x,y){return z+"/"+x+"/"+y};ol.tilecoord.getKey=function(tileCoord){return ol.tilecoord.getKeyZXY(tileCoord[0],tileCoord[1],tileCoord[2])};ol.tilecoord.fromKey=function(key){return key.split("/").map(Number)};
ol.tilecoord.hash=function(tileCoord){return(tileCoord[1]<<tileCoord[0])+tileCoord[2]};ol.tilecoord.quadKey=function(tileCoord){var z=tileCoord[0];var digits=new Array(z);var mask=1<<z-1;var i,charCode;for(i=0;i<z;++i){charCode=48;if(tileCoord[1]&mask)charCode+=1;if(tileCoord[2]&mask)charCode+=2;digits[i]=String.fromCharCode(charCode);mask>>=1}return digits.join("")};
ol.tilecoord.withinExtentAndZ=function(tileCoord,tileGrid){var z=tileCoord[0];var x=tileCoord[1];var y=tileCoord[2];if(tileGrid.getMinZoom()>z||z>tileGrid.getMaxZoom())return false;var extent=tileGrid.getExtent();var tileRange;if(!extent)tileRange=tileGrid.getFullTileRange(z);else tileRange=tileGrid.getTileRangeForExtentAndZ(extent,z);if(!tileRange)return true;else return tileRange.containsXY(x,y)};goog.provide("ol.tilegrid.TileGrid");goog.require("ol");goog.require("ol.asserts");goog.require("ol.TileRange");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.math");goog.require("ol.size");goog.require("ol.tilecoord");
ol.tilegrid.TileGrid=function(options){this.minZoom=options.minZoom!==undefined?options.minZoom:0;this.resolutions_=options.resolutions;ol.asserts.assert(ol.array.isSorted(this.resolutions_,function(a,b){return b-a},true),17);var zoomFactor;if(!options.origins)for(var i=0,ii=this.resolutions_.length-1;i<ii;++i)if(!zoomFactor)zoomFactor=this.resolutions_[i]/this.resolutions_[i+1];else if(this.resolutions_[i]/this.resolutions_[i+1]!==zoomFactor){zoomFactor=undefined;break}this.zoomFactor_=zoomFactor;
this.maxZoom=this.resolutions_.length-1;this.origin_=options.origin!==undefined?options.origin:null;this.origins_=null;if(options.origins!==undefined){this.origins_=options.origins;ol.asserts.assert(this.origins_.length==this.resolutions_.length,20)}var extent=options.extent;if(extent!==undefined&&!this.origin_&&!this.origins_)this.origin_=ol.extent.getTopLeft(extent);ol.asserts.assert(!this.origin_&&this.origins_||this.origin_&&!this.origins_,18);this.tileSizes_=null;if(options.tileSizes!==undefined){this.tileSizes_=
options.tileSizes;ol.asserts.assert(this.tileSizes_.length==this.resolutions_.length,19)}this.tileSize_=options.tileSize!==undefined?options.tileSize:!this.tileSizes_?ol.DEFAULT_TILE_SIZE:null;ol.asserts.assert(!this.tileSize_&&this.tileSizes_||this.tileSize_&&!this.tileSizes_,22);this.extent_=extent!==undefined?extent:null;this.fullTileRanges_=null;this.tmpSize_=[0,0];if(options.sizes!==undefined)this.fullTileRanges_=options.sizes.map(function(size,z){var tileRange=new ol.TileRange(Math.min(0,size[0]),
Math.max(size[0]-1,-1),Math.min(0,size[1]),Math.max(size[1]-1,-1));return tileRange},this);else if(extent)this.calculateTileRanges_(extent)};ol.tilegrid.TileGrid.tmpTileCoord_=[0,0,0];ol.tilegrid.TileGrid.prototype.forEachTileCoord=function(extent,zoom,callback){var tileRange=this.getTileRangeForExtentAndZ(extent,zoom);for(var i=tileRange.minX,ii=tileRange.maxX;i<=ii;++i)for(var j=tileRange.minY,jj=tileRange.maxY;j<=jj;++j)callback([zoom,i,j])};
ol.tilegrid.TileGrid.prototype.forEachTileCoordParentTileRange=function(tileCoord,callback,opt_this,opt_tileRange,opt_extent){var tileRange,x,y;var tileCoordExtent=null;var z=tileCoord[0]-1;if(this.zoomFactor_===2){x=tileCoord[1];y=tileCoord[2]}else tileCoordExtent=this.getTileCoordExtent(tileCoord,opt_extent);while(z>=this.minZoom){if(this.zoomFactor_===2){x=Math.floor(x/2);y=Math.floor(y/2);tileRange=ol.TileRange.createOrUpdate(x,x,y,y,opt_tileRange)}else tileRange=this.getTileRangeForExtentAndZ(tileCoordExtent,
z,opt_tileRange);if(callback.call(opt_this,z,tileRange))return true;--z}return false};ol.tilegrid.TileGrid.prototype.getExtent=function(){return this.extent_};ol.tilegrid.TileGrid.prototype.getMaxZoom=function(){return this.maxZoom};ol.tilegrid.TileGrid.prototype.getMinZoom=function(){return this.minZoom};ol.tilegrid.TileGrid.prototype.getOrigin=function(z){if(this.origin_)return this.origin_;else return this.origins_[z]};ol.tilegrid.TileGrid.prototype.getResolution=function(z){return this.resolutions_[z]};
ol.tilegrid.TileGrid.prototype.getResolutions=function(){return this.resolutions_};ol.tilegrid.TileGrid.prototype.getTileCoordChildTileRange=function(tileCoord,opt_tileRange,opt_extent){if(tileCoord[0]<this.maxZoom){if(this.zoomFactor_===2){var minX=tileCoord[1]*2;var minY=tileCoord[2]*2;return ol.TileRange.createOrUpdate(minX,minX+1,minY,minY+1,opt_tileRange)}var tileCoordExtent=this.getTileCoordExtent(tileCoord,opt_extent);return this.getTileRangeForExtentAndZ(tileCoordExtent,tileCoord[0]+1,opt_tileRange)}return null};
ol.tilegrid.TileGrid.prototype.getTileRangeExtent=function(z,tileRange,opt_extent){var origin=this.getOrigin(z);var resolution=this.getResolution(z);var tileSize=ol.size.toSize(this.getTileSize(z),this.tmpSize_);var minX=origin[0]+tileRange.minX*tileSize[0]*resolution;var maxX=origin[0]+(tileRange.maxX+1)*tileSize[0]*resolution;var minY=origin[1]+tileRange.minY*tileSize[1]*resolution;var maxY=origin[1]+(tileRange.maxY+1)*tileSize[1]*resolution;return ol.extent.createOrUpdate(minX,minY,maxX,maxY,opt_extent)};
ol.tilegrid.TileGrid.prototype.getTileRangeForExtentAndZ=function(extent,z,opt_tileRange){var tileCoord=ol.tilegrid.TileGrid.tmpTileCoord_;this.getTileCoordForXYAndZ_(extent[0],extent[1],z,false,tileCoord);var minX=tileCoord[1];var minY=tileCoord[2];this.getTileCoordForXYAndZ_(extent[2],extent[3],z,true,tileCoord);return ol.TileRange.createOrUpdate(minX,tileCoord[1],minY,tileCoord[2],opt_tileRange)};
ol.tilegrid.TileGrid.prototype.getTileCoordCenter=function(tileCoord){var origin=this.getOrigin(tileCoord[0]);var resolution=this.getResolution(tileCoord[0]);var tileSize=ol.size.toSize(this.getTileSize(tileCoord[0]),this.tmpSize_);return[origin[0]+(tileCoord[1]+.5)*tileSize[0]*resolution,origin[1]+(tileCoord[2]+.5)*tileSize[1]*resolution]};
ol.tilegrid.TileGrid.prototype.getTileCoordExtent=function(tileCoord,opt_extent){var origin=this.getOrigin(tileCoord[0]);var resolution=this.getResolution(tileCoord[0]);var tileSize=ol.size.toSize(this.getTileSize(tileCoord[0]),this.tmpSize_);var minX=origin[0]+tileCoord[1]*tileSize[0]*resolution;var minY=origin[1]+tileCoord[2]*tileSize[1]*resolution;var maxX=minX+tileSize[0]*resolution;var maxY=minY+tileSize[1]*resolution;return ol.extent.createOrUpdate(minX,minY,maxX,maxY,opt_extent)};
ol.tilegrid.TileGrid.prototype.getTileCoordForCoordAndResolution=function(coordinate,resolution,opt_tileCoord){return this.getTileCoordForXYAndResolution_(coordinate[0],coordinate[1],resolution,false,opt_tileCoord)};
ol.tilegrid.TileGrid.prototype.getTileCoordForXYAndResolution_=function(x,y,resolution,reverseIntersectionPolicy,opt_tileCoord){var z=this.getZForResolution(resolution);var scale=resolution/this.getResolution(z);var origin=this.getOrigin(z);var tileSize=ol.size.toSize(this.getTileSize(z),this.tmpSize_);var adjustX=reverseIntersectionPolicy?.5:0;var adjustY=reverseIntersectionPolicy?0:.5;var xFromOrigin=Math.floor((x-origin[0])/resolution+adjustX);var yFromOrigin=Math.floor((y-origin[1])/resolution+
adjustY);var tileCoordX=scale*xFromOrigin/tileSize[0];var tileCoordY=scale*yFromOrigin/tileSize[1];if(reverseIntersectionPolicy){tileCoordX=Math.ceil(tileCoordX)-1;tileCoordY=Math.ceil(tileCoordY)-1}else{tileCoordX=Math.floor(tileCoordX);tileCoordY=Math.floor(tileCoordY)}return ol.tilecoord.createOrUpdate(z,tileCoordX,tileCoordY,opt_tileCoord)};
ol.tilegrid.TileGrid.prototype.getTileCoordForXYAndZ_=function(x,y,z,reverseIntersectionPolicy,opt_tileCoord){var origin=this.getOrigin(z);var resolution=this.getResolution(z);var tileSize=ol.size.toSize(this.getTileSize(z),this.tmpSize_);var adjustX=reverseIntersectionPolicy?.5:0;var adjustY=reverseIntersectionPolicy?0:.5;var xFromOrigin=Math.floor((x-origin[0])/resolution+adjustX);var yFromOrigin=Math.floor((y-origin[1])/resolution+adjustY);var tileCoordX=xFromOrigin/tileSize[0];var tileCoordY=
yFromOrigin/tileSize[1];if(reverseIntersectionPolicy){tileCoordX=Math.ceil(tileCoordX)-1;tileCoordY=Math.ceil(tileCoordY)-1}else{tileCoordX=Math.floor(tileCoordX);tileCoordY=Math.floor(tileCoordY)}return ol.tilecoord.createOrUpdate(z,tileCoordX,tileCoordY,opt_tileCoord)};ol.tilegrid.TileGrid.prototype.getTileCoordForCoordAndZ=function(coordinate,z,opt_tileCoord){return this.getTileCoordForXYAndZ_(coordinate[0],coordinate[1],z,false,opt_tileCoord)};
ol.tilegrid.TileGrid.prototype.getTileCoordResolution=function(tileCoord){return this.resolutions_[tileCoord[0]]};ol.tilegrid.TileGrid.prototype.getTileSize=function(z){if(this.tileSize_)return this.tileSize_;else return this.tileSizes_[z]};ol.tilegrid.TileGrid.prototype.getFullTileRange=function(z){if(!this.fullTileRanges_)return null;else return this.fullTileRanges_[z]};
ol.tilegrid.TileGrid.prototype.getZForResolution=function(resolution,opt_direction){var z=ol.array.linearFindNearest(this.resolutions_,resolution,opt_direction||0);return ol.math.clamp(z,this.minZoom,this.maxZoom)};ol.tilegrid.TileGrid.prototype.calculateTileRanges_=function(extent){var length=this.resolutions_.length;var fullTileRanges=new Array(length);for(var z=this.minZoom;z<length;++z)fullTileRanges[z]=this.getTileRangeForExtentAndZ(extent,z);this.fullTileRanges_=fullTileRanges};goog.provide("ol.tilegrid");goog.require("ol");goog.require("ol.size");goog.require("ol.extent");goog.require("ol.extent.Corner");goog.require("ol.obj");goog.require("ol.proj");goog.require("ol.proj.Units");goog.require("ol.tilegrid.TileGrid");ol.tilegrid.getForProjection=function(projection){var tileGrid=projection.getDefaultTileGrid();if(!tileGrid){tileGrid=ol.tilegrid.createForProjection(projection);projection.setDefaultTileGrid(tileGrid)}return tileGrid};
ol.tilegrid.wrapX=function(tileGrid,tileCoord,projection){var z=tileCoord[0];var center=tileGrid.getTileCoordCenter(tileCoord);var projectionExtent=ol.tilegrid.extentFromProjection(projection);if(!ol.extent.containsCoordinate(projectionExtent,center)){var worldWidth=ol.extent.getWidth(projectionExtent);var worldsAway=Math.ceil((projectionExtent[0]-center[0])/worldWidth);center[0]+=worldWidth*worldsAway;return tileGrid.getTileCoordForCoordAndZ(center,z)}else return tileCoord};
ol.tilegrid.createForExtent=function(extent,opt_maxZoom,opt_tileSize,opt_corner){var corner=opt_corner!==undefined?opt_corner:ol.extent.Corner.TOP_LEFT;var resolutions=ol.tilegrid.resolutionsFromExtent(extent,opt_maxZoom,opt_tileSize);return new ol.tilegrid.TileGrid({extent:extent,origin:ol.extent.getCorner(extent,corner),resolutions:resolutions,tileSize:opt_tileSize})};
ol.tilegrid.createXYZ=function(opt_options){var options={};ol.obj.assign(options,opt_options!==undefined?opt_options:{});if(options.extent===undefined)options.extent=ol.proj.get("EPSG:3857").getExtent();options.resolutions=ol.tilegrid.resolutionsFromExtent(options.extent,options.maxZoom,options.tileSize);delete options.maxZoom;return new ol.tilegrid.TileGrid(options)};
ol.tilegrid.resolutionsFromExtent=function(extent,opt_maxZoom,opt_tileSize){var maxZoom=opt_maxZoom!==undefined?opt_maxZoom:ol.DEFAULT_MAX_ZOOM;var height=ol.extent.getHeight(extent);var width=ol.extent.getWidth(extent);var tileSize=ol.size.toSize(opt_tileSize!==undefined?opt_tileSize:ol.DEFAULT_TILE_SIZE);var maxResolution=Math.max(width/tileSize[0],height/tileSize[1]);var length=maxZoom+1;var resolutions=new Array(length);for(var z=0;z<length;++z)resolutions[z]=maxResolution/Math.pow(2,z);return resolutions};
ol.tilegrid.createForProjection=function(projection,opt_maxZoom,opt_tileSize,opt_corner){var extent=ol.tilegrid.extentFromProjection(projection);return ol.tilegrid.createForExtent(extent,opt_maxZoom,opt_tileSize,opt_corner)};ol.tilegrid.extentFromProjection=function(projection){projection=ol.proj.get(projection);var extent=projection.getExtent();if(!extent){var half=180*ol.proj.METERS_PER_UNIT[ol.proj.Units.DEGREES]/projection.getMetersPerUnit();extent=ol.extent.createOrUpdate(-half,-half,half,half)}return extent};goog.provide("ol.Attribution");goog.require("ol.TileRange");goog.require("ol.math");goog.require("ol.tilegrid");ol.Attribution=function(options){this.html_=options.html;this.tileRanges_=options.tileRanges?options.tileRanges:null};ol.Attribution.prototype.getHTML=function(){return this.html_};
ol.Attribution.prototype.intersectsAnyTileRange=function(tileRanges,tileGrid,projection){if(!this.tileRanges_)return true;var i,ii,tileRange,zKey;for(zKey in tileRanges){if(!(zKey in this.tileRanges_))continue;tileRange=tileRanges[zKey];var testTileRange;for(i=0,ii=this.tileRanges_[zKey].length;i<ii;++i){testTileRange=this.tileRanges_[zKey][i];if(testTileRange.intersects(tileRange))return true;var extentTileRange=tileGrid.getTileRangeForExtentAndZ(ol.tilegrid.extentFromProjection(projection),parseInt(zKey,
10));var width=extentTileRange.getWidth();if(tileRange.minX<extentTileRange.minX||tileRange.maxX>extentTileRange.maxX){if(testTileRange.intersects(new ol.TileRange(ol.math.modulo(tileRange.minX,width),ol.math.modulo(tileRange.maxX,width),tileRange.minY,tileRange.maxY)))return true;if(tileRange.getWidth()>width&&testTileRange.intersects(extentTileRange))return true}}}return false};goog.provide("ol.CollectionEventType");ol.CollectionEventType={ADD:"add",REMOVE:"remove"};goog.provide("ol.ObjectEventType");ol.ObjectEventType={PROPERTYCHANGE:"propertychange"};goog.provide("ol.events");goog.require("ol.obj");ol.events.bindListener_=function(listenerObj){var boundListener=function(evt){var listener=listenerObj.listener;var bindTo=listenerObj.bindTo||listenerObj.target;if(listenerObj.callOnce)ol.events.unlistenByKey(listenerObj);return listener.call(bindTo,evt)};listenerObj.boundListener=boundListener;return boundListener};
ol.events.findListener_=function(listeners,listener,opt_this,opt_setDeleteIndex){var listenerObj;for(var i=0,ii=listeners.length;i<ii;++i){listenerObj=listeners[i];if(listenerObj.listener===listener&&listenerObj.bindTo===opt_this){if(opt_setDeleteIndex)listenerObj.deleteIndex=i;return listenerObj}}return undefined};ol.events.getListeners=function(target,type){var listenerMap=target.ol_lm;return listenerMap?listenerMap[type]:undefined};
ol.events.getListenerMap_=function(target){var listenerMap=target.ol_lm;if(!listenerMap)listenerMap=target.ol_lm={};return listenerMap};
ol.events.removeListeners_=function(target,type){var listeners=ol.events.getListeners(target,type);if(listeners){for(var i=0,ii=listeners.length;i<ii;++i){target.removeEventListener(type,listeners[i].boundListener);ol.obj.clear(listeners[i])}listeners.length=0;var listenerMap=target.ol_lm;if(listenerMap){delete listenerMap[type];if(Object.keys(listenerMap).length===0)delete target.ol_lm}}};
ol.events.listen=function(target,type,listener,opt_this,opt_once){var listenerMap=ol.events.getListenerMap_(target);var listeners=listenerMap[type];if(!listeners)listeners=listenerMap[type]=[];var listenerObj=ol.events.findListener_(listeners,listener,opt_this,false);if(listenerObj){if(!opt_once)listenerObj.callOnce=false}else{listenerObj={bindTo:opt_this,callOnce:!!opt_once,listener:listener,target:target,type:type};target.addEventListener(type,ol.events.bindListener_(listenerObj));listeners.push(listenerObj)}return listenerObj};
ol.events.listenOnce=function(target,type,listener,opt_this){return ol.events.listen(target,type,listener,opt_this,true)};ol.events.unlisten=function(target,type,listener,opt_this){var listeners=ol.events.getListeners(target,type);if(listeners){var listenerObj=ol.events.findListener_(listeners,listener,opt_this,true);if(listenerObj)ol.events.unlistenByKey(listenerObj)}};
ol.events.unlistenByKey=function(key){if(key&&key.target){key.target.removeEventListener(key.type,key.boundListener);var listeners=ol.events.getListeners(key.target,key.type);if(listeners){var i="deleteIndex"in key?key.deleteIndex:listeners.indexOf(key);if(i!==-1)listeners.splice(i,1);if(listeners.length===0)ol.events.removeListeners_(key.target,key.type)}ol.obj.clear(key)}};
ol.events.unlistenAll=function(target){var listenerMap=ol.events.getListenerMap_(target);for(var type in listenerMap)ol.events.removeListeners_(target,type)};goog.provide("ol.Disposable");goog.require("ol");ol.Disposable=function(){};ol.Disposable.prototype.disposed_=false;ol.Disposable.prototype.dispose=function(){if(!this.disposed_){this.disposed_=true;this.disposeInternal()}};ol.Disposable.prototype.disposeInternal=ol.nullFunction;goog.provide("ol.events.Event");ol.events.Event=function(type){this.propagationStopped;this.type=type;this.target=null};ol.events.Event.prototype.preventDefault=ol.events.Event.prototype.stopPropagation=function(){this.propagationStopped=true};ol.events.Event.stopPropagation=function(evt){evt.stopPropagation()};ol.events.Event.preventDefault=function(evt){evt.preventDefault()};goog.provide("ol.events.EventTarget");goog.require("ol");goog.require("ol.Disposable");goog.require("ol.events");goog.require("ol.events.Event");ol.events.EventTarget=function(){ol.Disposable.call(this);this.pendingRemovals_={};this.dispatching_={};this.listeners_={}};ol.inherits(ol.events.EventTarget,ol.Disposable);
ol.events.EventTarget.prototype.addEventListener=function(type,listener){var listeners=this.listeners_[type];if(!listeners)listeners=this.listeners_[type]=[];if(listeners.indexOf(listener)===-1)listeners.push(listener)};
ol.events.EventTarget.prototype.dispatchEvent=function(event){var evt=typeof event==="string"?new ol.events.Event(event):event;var type=evt.type;evt.target=this;var listeners=this.listeners_[type];var propagate;if(listeners){if(!(type in this.dispatching_)){this.dispatching_[type]=0;this.pendingRemovals_[type]=0}++this.dispatching_[type];for(var i=0,ii=listeners.length;i<ii;++i)if(listeners[i].call(this,evt)===false||evt.propagationStopped){propagate=false;break}--this.dispatching_[type];if(this.dispatching_[type]===
0){var pendingRemovals=this.pendingRemovals_[type];delete this.pendingRemovals_[type];while(pendingRemovals--)this.removeEventListener(type,ol.nullFunction);delete this.dispatching_[type]}return propagate}};ol.events.EventTarget.prototype.disposeInternal=function(){ol.events.unlistenAll(this)};ol.events.EventTarget.prototype.getListeners=function(type){return this.listeners_[type]};
ol.events.EventTarget.prototype.hasListener=function(opt_type){return opt_type?opt_type in this.listeners_:Object.keys(this.listeners_).length>0};ol.events.EventTarget.prototype.removeEventListener=function(type,listener){var listeners=this.listeners_[type];if(listeners){var index=listeners.indexOf(listener);if(type in this.pendingRemovals_){listeners[index]=ol.nullFunction;++this.pendingRemovals_[type]}else{listeners.splice(index,1);if(listeners.length===0)delete this.listeners_[type]}}};goog.provide("ol.events.EventType");ol.events.EventType={CHANGE:"change",CLEAR:"clear",CLICK:"click",DBLCLICK:"dblclick",DRAGENTER:"dragenter",DRAGOVER:"dragover",DROP:"drop",ERROR:"error",KEYDOWN:"keydown",KEYPRESS:"keypress",LOAD:"load",MOUSEDOWN:"mousedown",MOUSEMOVE:"mousemove",MOUSEOUT:"mouseout",MOUSEUP:"mouseup",MOUSEWHEEL:"mousewheel",MSPOINTERDOWN:"MSPointerDown",RESIZE:"resize",TOUCHSTART:"touchstart",TOUCHMOVE:"touchmove",TOUCHEND:"touchend",WHEEL:"wheel"};goog.provide("ol.Observable");goog.require("ol");goog.require("ol.events");goog.require("ol.events.EventTarget");goog.require("ol.events.EventType");ol.Observable=function(){ol.events.EventTarget.call(this);this.revision_=0};ol.inherits(ol.Observable,ol.events.EventTarget);ol.Observable.unByKey=function(key){if(Array.isArray(key))for(var i=0,ii=key.length;i<ii;++i)ol.events.unlistenByKey(key[i]);else ol.events.unlistenByKey(key)};ol.Observable.prototype.changed=function(){++this.revision_;this.dispatchEvent(ol.events.EventType.CHANGE)};
ol.Observable.prototype.dispatchEvent;ol.Observable.prototype.getRevision=function(){return this.revision_};ol.Observable.prototype.on=function(type,listener,opt_this){if(Array.isArray(type)){var len=type.length;var keys=new Array(len);for(var i=0;i<len;++i)keys[i]=ol.events.listen(this,type[i],listener,opt_this);return keys}else return ol.events.listen(this,type,listener,opt_this)};
ol.Observable.prototype.once=function(type,listener,opt_this){if(Array.isArray(type)){var len=type.length;var keys=new Array(len);for(var i=0;i<len;++i)keys[i]=ol.events.listenOnce(this,type[i],listener,opt_this);return keys}else return ol.events.listenOnce(this,type,listener,opt_this)};
ol.Observable.prototype.un=function(type,listener,opt_this){if(Array.isArray(type)){for(var i=0,ii=type.length;i<ii;++i)ol.events.unlisten(this,type[i],listener,opt_this);return}else ol.events.unlisten(this,type,listener,opt_this)};goog.provide("ol.Object");goog.require("ol");goog.require("ol.ObjectEventType");goog.require("ol.Observable");goog.require("ol.events.Event");goog.require("ol.obj");ol.Object=function(opt_values){ol.Observable.call(this);ol.getUid(this);this.values_={};if(opt_values!==undefined)this.setProperties(opt_values)};ol.inherits(ol.Object,ol.Observable);ol.Object.changeEventTypeCache_={};
ol.Object.getChangeEventType=function(key){return ol.Object.changeEventTypeCache_.hasOwnProperty(key)?ol.Object.changeEventTypeCache_[key]:ol.Object.changeEventTypeCache_[key]="change:"+key};ol.Object.prototype.get=function(key){var value;if(this.values_.hasOwnProperty(key))value=this.values_[key];return value};ol.Object.prototype.getKeys=function(){return Object.keys(this.values_)};ol.Object.prototype.getProperties=function(){return ol.obj.assign({},this.values_)};
ol.Object.prototype.notify=function(key,oldValue){var eventType;eventType=ol.Object.getChangeEventType(key);this.dispatchEvent(new ol.Object.Event(eventType,key,oldValue));eventType=ol.ObjectEventType.PROPERTYCHANGE;this.dispatchEvent(new ol.Object.Event(eventType,key,oldValue))};ol.Object.prototype.set=function(key,value,opt_silent){if(opt_silent)this.values_[key]=value;else{var oldValue=this.values_[key];this.values_[key]=value;if(oldValue!==value)this.notify(key,oldValue)}};
ol.Object.prototype.setProperties=function(values,opt_silent){var key;for(key in values)this.set(key,values[key],opt_silent)};ol.Object.prototype.unset=function(key,opt_silent){if(key in this.values_){var oldValue=this.values_[key];delete this.values_[key];if(!opt_silent)this.notify(key,oldValue)}};ol.Object.Event=function(type,key,oldValue){ol.events.Event.call(this,type);this.key=key;this.oldValue=oldValue};ol.inherits(ol.Object.Event,ol.events.Event);goog.provide("ol.Collection");goog.require("ol");goog.require("ol.AssertionError");goog.require("ol.CollectionEventType");goog.require("ol.Object");goog.require("ol.events.Event");ol.Collection=function(opt_array,opt_options){ol.Object.call(this);var options=opt_options||{};this.unique_=!!options.unique;this.array_=opt_array?opt_array:[];if(this.unique_)for(var i=0,ii=this.array_.length;i<ii;++i)this.assertUnique_(this.array_[i],i);this.updateLength_()};ol.inherits(ol.Collection,ol.Object);
ol.Collection.prototype.clear=function(){while(this.getLength()>0)this.pop()};ol.Collection.prototype.extend=function(arr){var i,ii;for(i=0,ii=arr.length;i<ii;++i)this.push(arr[i]);return this};ol.Collection.prototype.forEach=function(f,opt_this){var fn=opt_this?f.bind(opt_this):f;var array=this.array_;for(var i=0,ii=array.length;i<ii;++i)fn(array[i],i,array)};ol.Collection.prototype.getArray=function(){return this.array_};ol.Collection.prototype.item=function(index){return this.array_[index]};
ol.Collection.prototype.getLength=function(){return this.get(ol.Collection.Property_.LENGTH)};ol.Collection.prototype.insertAt=function(index,elem){if(this.unique_)this.assertUnique_(elem);this.array_.splice(index,0,elem);this.updateLength_();this.dispatchEvent(new ol.Collection.Event(ol.CollectionEventType.ADD,elem))};ol.Collection.prototype.pop=function(){return this.removeAt(this.getLength()-1)};
ol.Collection.prototype.push=function(elem){if(this.unique_)this.assertUnique_(elem);var n=this.getLength();this.insertAt(n,elem);return this.getLength()};ol.Collection.prototype.remove=function(elem){var arr=this.array_;var i,ii;for(i=0,ii=arr.length;i<ii;++i)if(arr[i]===elem)return this.removeAt(i);return undefined};
ol.Collection.prototype.removeAt=function(index){var prev=this.array_[index];this.array_.splice(index,1);this.updateLength_();this.dispatchEvent(new ol.Collection.Event(ol.CollectionEventType.REMOVE,prev));return prev};
ol.Collection.prototype.setAt=function(index,elem){var n=this.getLength();if(index<n){if(this.unique_)this.assertUnique_(elem,index);var prev=this.array_[index];this.array_[index]=elem;this.dispatchEvent(new ol.Collection.Event(ol.CollectionEventType.REMOVE,prev));this.dispatchEvent(new ol.Collection.Event(ol.CollectionEventType.ADD,elem))}else{var j;for(j=n;j<index;++j)this.insertAt(j,undefined);this.insertAt(index,elem)}};
ol.Collection.prototype.updateLength_=function(){this.set(ol.Collection.Property_.LENGTH,this.array_.length)};ol.Collection.prototype.assertUnique_=function(elem,opt_except){for(var i=0,ii=this.array_.length;i<ii;++i)if(this.array_[i]===elem&&i!==opt_except)throw new ol.AssertionError(58);};ol.Collection.Property_={LENGTH:"length"};ol.Collection.Event=function(type,opt_element){ol.events.Event.call(this,type);this.element=opt_element};ol.inherits(ol.Collection.Event,ol.events.Event);goog.provide("ol.MapEvent");goog.require("ol");goog.require("ol.events.Event");ol.MapEvent=function(type,map,opt_frameState){ol.events.Event.call(this,type);this.map=map;this.frameState=opt_frameState!==undefined?opt_frameState:null};ol.inherits(ol.MapEvent,ol.events.Event);goog.provide("ol.MapBrowserEvent");goog.require("ol");goog.require("ol.MapEvent");ol.MapBrowserEvent=function(type,map,browserEvent,opt_dragging,opt_frameState){ol.MapEvent.call(this,type,map,opt_frameState);this.originalEvent=browserEvent;this.pixel=map.getEventPixel(browserEvent);this.coordinate=map.getCoordinateFromPixel(this.pixel);this.dragging=opt_dragging!==undefined?opt_dragging:false};ol.inherits(ol.MapBrowserEvent,ol.MapEvent);
ol.MapBrowserEvent.prototype.preventDefault=function(){ol.MapEvent.prototype.preventDefault.call(this);this.originalEvent.preventDefault()};ol.MapBrowserEvent.prototype.stopPropagation=function(){ol.MapEvent.prototype.stopPropagation.call(this);this.originalEvent.stopPropagation()};goog.provide("ol.webgl");ol.webgl.ONE=1;ol.webgl.SRC_ALPHA=770;ol.webgl.COLOR_ATTACHMENT0=36064;ol.webgl.COLOR_BUFFER_BIT=16384;ol.webgl.TRIANGLES=4;ol.webgl.TRIANGLE_STRIP=5;ol.webgl.ONE_MINUS_SRC_ALPHA=771;ol.webgl.ARRAY_BUFFER=34962;ol.webgl.ELEMENT_ARRAY_BUFFER=34963;ol.webgl.STREAM_DRAW=35040;ol.webgl.STATIC_DRAW=35044;ol.webgl.DYNAMIC_DRAW=35048;ol.webgl.CULL_FACE=2884;ol.webgl.BLEND=3042;ol.webgl.STENCIL_TEST=2960;ol.webgl.DEPTH_TEST=2929;ol.webgl.SCISSOR_TEST=3089;ol.webgl.UNSIGNED_BYTE=5121;
ol.webgl.UNSIGNED_SHORT=5123;ol.webgl.UNSIGNED_INT=5125;ol.webgl.FLOAT=5126;ol.webgl.RGBA=6408;ol.webgl.FRAGMENT_SHADER=35632;ol.webgl.VERTEX_SHADER=35633;ol.webgl.LINK_STATUS=35714;ol.webgl.LINEAR=9729;ol.webgl.TEXTURE_MAG_FILTER=10240;ol.webgl.TEXTURE_MIN_FILTER=10241;ol.webgl.TEXTURE_WRAP_S=10242;ol.webgl.TEXTURE_WRAP_T=10243;ol.webgl.TEXTURE_2D=3553;ol.webgl.TEXTURE0=33984;ol.webgl.CLAMP_TO_EDGE=33071;ol.webgl.COMPILE_STATUS=35713;ol.webgl.FRAMEBUFFER=36160;
ol.webgl.CONTEXT_IDS_=["experimental-webgl","webgl","webkit-3d","moz-webgl"];ol.webgl.getContext=function(canvas,opt_attributes){var context,i,ii=ol.webgl.CONTEXT_IDS_.length;for(i=0;i<ii;++i)try{context=canvas.getContext(ol.webgl.CONTEXT_IDS_[i],opt_attributes);if(context)return context}catch(e){}return null};goog.provide("ol.has");goog.require("ol");goog.require("ol.webgl");var ua=typeof navigator!=="undefined"?navigator.userAgent.toLowerCase():"";ol.has.FIREFOX=ua.indexOf("firefox")!==-1;ol.has.SAFARI=ua.indexOf("safari")!==-1&&ua.indexOf("chrom")==-1;ol.has.WEBKIT=ua.indexOf("webkit")!==-1&&ua.indexOf("edge")==-1;ol.has.MAC=ua.indexOf("macintosh")!==-1;ol.has.DEVICE_PIXEL_RATIO=window.devicePixelRatio||1;ol.has.CANVAS_LINE_DASH=false;
ol.has.CANVAS=ol.ENABLE_CANVAS&&function(){if(!("HTMLCanvasElement"in window))return false;try{var context=document.createElement("CANVAS").getContext("2d");if(!context)return false;else{if(context.setLineDash!==undefined)ol.has.CANVAS_LINE_DASH=true;return true}}catch(e){return false}}();ol.has.DEVICE_ORIENTATION="DeviceOrientationEvent"in window;ol.has.GEOLOCATION="geolocation"in navigator;ol.has.TOUCH=ol.ASSUME_TOUCH||"ontouchstart"in window;ol.has.POINTER="PointerEvent"in window;
ol.has.MSPOINTER=!!navigator.msPointerEnabled;ol.has.WEBGL;(function(){if(ol.ENABLE_WEBGL){var hasWebGL=false;var textureSize;var extensions=[];if("WebGLRenderingContext"in window)try{var canvas=document.createElement("CANVAS");var gl=ol.webgl.getContext(canvas,{failIfMajorPerformanceCaveat:true});if(gl){hasWebGL=true;textureSize=gl.getParameter(gl.MAX_TEXTURE_SIZE);extensions=gl.getSupportedExtensions()}}catch(e){}ol.has.WEBGL=hasWebGL;ol.WEBGL_EXTENSIONS=extensions;ol.WEBGL_MAX_TEXTURE_SIZE=textureSize}})();goog.provide("ol.MapBrowserEventType");goog.require("ol.events.EventType");ol.MapBrowserEventType={SINGLECLICK:"singleclick",CLICK:ol.events.EventType.CLICK,DBLCLICK:ol.events.EventType.DBLCLICK,POINTERDRAG:"pointerdrag",POINTERMOVE:"pointermove",POINTERDOWN:"pointerdown",POINTERUP:"pointerup",POINTEROVER:"pointerover",POINTEROUT:"pointerout",POINTERENTER:"pointerenter",POINTERLEAVE:"pointerleave",POINTERCANCEL:"pointercancel"};goog.provide("ol.MapBrowserPointerEvent");goog.require("ol");goog.require("ol.MapBrowserEvent");ol.MapBrowserPointerEvent=function(type,map,pointerEvent,opt_dragging,opt_frameState){ol.MapBrowserEvent.call(this,type,map,pointerEvent.originalEvent,opt_dragging,opt_frameState);this.pointerEvent=pointerEvent};ol.inherits(ol.MapBrowserPointerEvent,ol.MapBrowserEvent);goog.provide("ol.pointer.EventType");ol.pointer.EventType={POINTERMOVE:"pointermove",POINTERDOWN:"pointerdown",POINTERUP:"pointerup",POINTEROVER:"pointerover",POINTEROUT:"pointerout",POINTERENTER:"pointerenter",POINTERLEAVE:"pointerleave",POINTERCANCEL:"pointercancel"};goog.provide("ol.pointer.EventSource");ol.pointer.EventSource=function(dispatcher,mapping){this.dispatcher=dispatcher;this.mapping_=mapping};ol.pointer.EventSource.prototype.getEvents=function(){return Object.keys(this.mapping_)};ol.pointer.EventSource.prototype.getHandlerForEvent=function(eventType){return this.mapping_[eventType]};goog.provide("ol.pointer.MouseSource");goog.require("ol");goog.require("ol.pointer.EventSource");ol.pointer.MouseSource=function(dispatcher){var mapping={"mousedown":this.mousedown,"mousemove":this.mousemove,"mouseup":this.mouseup,"mouseover":this.mouseover,"mouseout":this.mouseout};ol.pointer.EventSource.call(this,dispatcher,mapping);this.pointerMap=dispatcher.pointerMap;this.lastTouches=[]};ol.inherits(ol.pointer.MouseSource,ol.pointer.EventSource);ol.pointer.MouseSource.POINTER_ID=1;
ol.pointer.MouseSource.POINTER_TYPE="mouse";ol.pointer.MouseSource.DEDUP_DIST=25;ol.pointer.MouseSource.prototype.isEventSimulatedFromTouch_=function(inEvent){var lts=this.lastTouches;var x=inEvent.clientX,y=inEvent.clientY;for(var i=0,l=lts.length,t;i<l&&(t=lts[i]);i++){var dx=Math.abs(x-t[0]),dy=Math.abs(y-t[1]);if(dx<=ol.pointer.MouseSource.DEDUP_DIST&&dy<=ol.pointer.MouseSource.DEDUP_DIST)return true}return false};
ol.pointer.MouseSource.prepareEvent=function(inEvent,dispatcher){var e=dispatcher.cloneEvent(inEvent,inEvent);var pd=e.preventDefault;e.preventDefault=function(){inEvent.preventDefault();pd()};e.pointerId=ol.pointer.MouseSource.POINTER_ID;e.isPrimary=true;e.pointerType=ol.pointer.MouseSource.POINTER_TYPE;return e};
ol.pointer.MouseSource.prototype.mousedown=function(inEvent){if(!this.isEventSimulatedFromTouch_(inEvent)){if(ol.pointer.MouseSource.POINTER_ID.toString()in this.pointerMap)this.cancel(inEvent);var e=ol.pointer.MouseSource.prepareEvent(inEvent,this.dispatcher);this.pointerMap[ol.pointer.MouseSource.POINTER_ID.toString()]=inEvent;this.dispatcher.down(e,inEvent)}};
ol.pointer.MouseSource.prototype.mousemove=function(inEvent){if(!this.isEventSimulatedFromTouch_(inEvent)){var e=ol.pointer.MouseSource.prepareEvent(inEvent,this.dispatcher);this.dispatcher.move(e,inEvent)}};
ol.pointer.MouseSource.prototype.mouseup=function(inEvent){if(!this.isEventSimulatedFromTouch_(inEvent)){var p=this.pointerMap[ol.pointer.MouseSource.POINTER_ID.toString()];if(p&&p.button===inEvent.button){var e=ol.pointer.MouseSource.prepareEvent(inEvent,this.dispatcher);this.dispatcher.up(e,inEvent);this.cleanupMouse()}}};
ol.pointer.MouseSource.prototype.mouseover=function(inEvent){if(!this.isEventSimulatedFromTouch_(inEvent)){var e=ol.pointer.MouseSource.prepareEvent(inEvent,this.dispatcher);this.dispatcher.enterOver(e,inEvent)}};ol.pointer.MouseSource.prototype.mouseout=function(inEvent){if(!this.isEventSimulatedFromTouch_(inEvent)){var e=ol.pointer.MouseSource.prepareEvent(inEvent,this.dispatcher);this.dispatcher.leaveOut(e,inEvent)}};
ol.pointer.MouseSource.prototype.cancel=function(inEvent){var e=ol.pointer.MouseSource.prepareEvent(inEvent,this.dispatcher);this.dispatcher.cancel(e,inEvent);this.cleanupMouse()};ol.pointer.MouseSource.prototype.cleanupMouse=function(){delete this.pointerMap[ol.pointer.MouseSource.POINTER_ID.toString()]};goog.provide("ol.pointer.MsSource");goog.require("ol");goog.require("ol.pointer.EventSource");
ol.pointer.MsSource=function(dispatcher){var mapping={"MSPointerDown":this.msPointerDown,"MSPointerMove":this.msPointerMove,"MSPointerUp":this.msPointerUp,"MSPointerOut":this.msPointerOut,"MSPointerOver":this.msPointerOver,"MSPointerCancel":this.msPointerCancel,"MSGotPointerCapture":this.msGotPointerCapture,"MSLostPointerCapture":this.msLostPointerCapture};ol.pointer.EventSource.call(this,dispatcher,mapping);this.pointerMap=dispatcher.pointerMap;this.POINTER_TYPES=["","unavailable","touch","pen",
"mouse"]};ol.inherits(ol.pointer.MsSource,ol.pointer.EventSource);ol.pointer.MsSource.prototype.prepareEvent_=function(inEvent){var e=inEvent;if(typeof inEvent.pointerType==="number"){e=this.dispatcher.cloneEvent(inEvent,inEvent);e.pointerType=this.POINTER_TYPES[inEvent.pointerType]}return e};ol.pointer.MsSource.prototype.cleanup=function(pointerId){delete this.pointerMap[pointerId.toString()]};
ol.pointer.MsSource.prototype.msPointerDown=function(inEvent){this.pointerMap[inEvent.pointerId.toString()]=inEvent;var e=this.prepareEvent_(inEvent);this.dispatcher.down(e,inEvent)};ol.pointer.MsSource.prototype.msPointerMove=function(inEvent){var e=this.prepareEvent_(inEvent);this.dispatcher.move(e,inEvent)};ol.pointer.MsSource.prototype.msPointerUp=function(inEvent){var e=this.prepareEvent_(inEvent);this.dispatcher.up(e,inEvent);this.cleanup(inEvent.pointerId)};
ol.pointer.MsSource.prototype.msPointerOut=function(inEvent){var e=this.prepareEvent_(inEvent);this.dispatcher.leaveOut(e,inEvent)};ol.pointer.MsSource.prototype.msPointerOver=function(inEvent){var e=this.prepareEvent_(inEvent);this.dispatcher.enterOver(e,inEvent)};ol.pointer.MsSource.prototype.msPointerCancel=function(inEvent){var e=this.prepareEvent_(inEvent);this.dispatcher.cancel(e,inEvent);this.cleanup(inEvent.pointerId)};
ol.pointer.MsSource.prototype.msLostPointerCapture=function(inEvent){var e=this.dispatcher.makeEvent("lostpointercapture",inEvent,inEvent);this.dispatcher.dispatchEvent(e)};ol.pointer.MsSource.prototype.msGotPointerCapture=function(inEvent){var e=this.dispatcher.makeEvent("gotpointercapture",inEvent,inEvent);this.dispatcher.dispatchEvent(e)};goog.provide("ol.pointer.NativeSource");goog.require("ol");goog.require("ol.pointer.EventSource");ol.pointer.NativeSource=function(dispatcher){var mapping={"pointerdown":this.pointerDown,"pointermove":this.pointerMove,"pointerup":this.pointerUp,"pointerout":this.pointerOut,"pointerover":this.pointerOver,"pointercancel":this.pointerCancel,"gotpointercapture":this.gotPointerCapture,"lostpointercapture":this.lostPointerCapture};ol.pointer.EventSource.call(this,dispatcher,mapping)};
ol.inherits(ol.pointer.NativeSource,ol.pointer.EventSource);ol.pointer.NativeSource.prototype.pointerDown=function(inEvent){this.dispatcher.fireNativeEvent(inEvent)};ol.pointer.NativeSource.prototype.pointerMove=function(inEvent){this.dispatcher.fireNativeEvent(inEvent)};ol.pointer.NativeSource.prototype.pointerUp=function(inEvent){this.dispatcher.fireNativeEvent(inEvent)};ol.pointer.NativeSource.prototype.pointerOut=function(inEvent){this.dispatcher.fireNativeEvent(inEvent)};
ol.pointer.NativeSource.prototype.pointerOver=function(inEvent){this.dispatcher.fireNativeEvent(inEvent)};ol.pointer.NativeSource.prototype.pointerCancel=function(inEvent){this.dispatcher.fireNativeEvent(inEvent)};ol.pointer.NativeSource.prototype.lostPointerCapture=function(inEvent){this.dispatcher.fireNativeEvent(inEvent)};ol.pointer.NativeSource.prototype.gotPointerCapture=function(inEvent){this.dispatcher.fireNativeEvent(inEvent)};goog.provide("ol.pointer.PointerEvent");goog.require("ol");goog.require("ol.events.Event");
ol.pointer.PointerEvent=function(type,originalEvent,opt_eventDict){ol.events.Event.call(this,type);this.originalEvent=originalEvent;var eventDict=opt_eventDict?opt_eventDict:{};this.buttons=this.getButtons_(eventDict);this.pressure=this.getPressure_(eventDict,this.buttons);this.bubbles="bubbles"in eventDict?eventDict["bubbles"]:false;this.cancelable="cancelable"in eventDict?eventDict["cancelable"]:false;this.view="view"in eventDict?eventDict["view"]:null;this.detail="detail"in eventDict?eventDict["detail"]:
null;this.screenX="screenX"in eventDict?eventDict["screenX"]:0;this.screenY="screenY"in eventDict?eventDict["screenY"]:0;this.clientX="clientX"in eventDict?eventDict["clientX"]:0;this.clientY="clientY"in eventDict?eventDict["clientY"]:0;this.ctrlKey="ctrlKey"in eventDict?eventDict["ctrlKey"]:false;this.altKey="altKey"in eventDict?eventDict["altKey"]:false;this.shiftKey="shiftKey"in eventDict?eventDict["shiftKey"]:false;this.metaKey="metaKey"in eventDict?eventDict["metaKey"]:false;this.button="button"in
eventDict?eventDict["button"]:0;this.relatedTarget="relatedTarget"in eventDict?eventDict["relatedTarget"]:null;this.pointerId="pointerId"in eventDict?eventDict["pointerId"]:0;this.width="width"in eventDict?eventDict["width"]:0;this.height="height"in eventDict?eventDict["height"]:0;this.tiltX="tiltX"in eventDict?eventDict["tiltX"]:0;this.tiltY="tiltY"in eventDict?eventDict["tiltY"]:0;this.pointerType="pointerType"in eventDict?eventDict["pointerType"]:"";this.hwTimestamp="hwTimestamp"in eventDict?eventDict["hwTimestamp"]:
0;this.isPrimary="isPrimary"in eventDict?eventDict["isPrimary"]:false;if(originalEvent.preventDefault)this.preventDefault=function(){originalEvent.preventDefault()}};ol.inherits(ol.pointer.PointerEvent,ol.events.Event);ol.pointer.PointerEvent.prototype.getButtons_=function(eventDict){var buttons;if(eventDict.buttons||ol.pointer.PointerEvent.HAS_BUTTONS)buttons=eventDict.buttons;else switch(eventDict.which){case 1:buttons=1;break;case 2:buttons=4;break;case 3:buttons=2;break;default:buttons=0}return buttons};
ol.pointer.PointerEvent.prototype.getPressure_=function(eventDict,buttons){var pressure=0;if(eventDict.pressure)pressure=eventDict.pressure;else pressure=buttons?.5:0;return pressure};ol.pointer.PointerEvent.HAS_BUTTONS=false;(function(){try{var ev=new MouseEvent("click",{buttons:1});ol.pointer.PointerEvent.HAS_BUTTONS=ev.buttons===1}catch(e){}})();goog.provide("ol.pointer.TouchSource");goog.require("ol");goog.require("ol.array");goog.require("ol.pointer.EventSource");goog.require("ol.pointer.MouseSource");
ol.pointer.TouchSource=function(dispatcher,mouseSource){var mapping={"touchstart":this.touchstart,"touchmove":this.touchmove,"touchend":this.touchend,"touchcancel":this.touchcancel};ol.pointer.EventSource.call(this,dispatcher,mapping);this.pointerMap=dispatcher.pointerMap;this.mouseSource=mouseSource;this.firstTouchId_=undefined;this.clickCount_=0;this.resetId_=undefined};ol.inherits(ol.pointer.TouchSource,ol.pointer.EventSource);ol.pointer.TouchSource.DEDUP_TIMEOUT=2500;
ol.pointer.TouchSource.CLICK_COUNT_TIMEOUT=200;ol.pointer.TouchSource.POINTER_TYPE="touch";ol.pointer.TouchSource.prototype.isPrimaryTouch_=function(inTouch){return this.firstTouchId_===inTouch.identifier};ol.pointer.TouchSource.prototype.setPrimaryTouch_=function(inTouch){var count=Object.keys(this.pointerMap).length;if(count===0||count===1&&ol.pointer.MouseSource.POINTER_ID.toString()in this.pointerMap){this.firstTouchId_=inTouch.identifier;this.cancelResetClickCount_()}};
ol.pointer.TouchSource.prototype.removePrimaryPointer_=function(inPointer){if(inPointer.isPrimary){this.firstTouchId_=undefined;this.resetClickCount_()}};ol.pointer.TouchSource.prototype.resetClickCount_=function(){this.resetId_=setTimeout(this.resetClickCountHandler_.bind(this),ol.pointer.TouchSource.CLICK_COUNT_TIMEOUT)};ol.pointer.TouchSource.prototype.resetClickCountHandler_=function(){this.clickCount_=0;this.resetId_=undefined};
ol.pointer.TouchSource.prototype.cancelResetClickCount_=function(){if(this.resetId_!==undefined)clearTimeout(this.resetId_)};
ol.pointer.TouchSource.prototype.touchToPointer_=function(browserEvent,inTouch){var e=this.dispatcher.cloneEvent(browserEvent,inTouch);e.pointerId=inTouch.identifier+2;e.bubbles=true;e.cancelable=true;e.detail=this.clickCount_;e.button=0;e.buttons=1;e.width=inTouch.webkitRadiusX||inTouch.radiusX||0;e.height=inTouch.webkitRadiusY||inTouch.radiusY||0;e.pressure=inTouch.webkitForce||inTouch.force||.5;e.isPrimary=this.isPrimaryTouch_(inTouch);e.pointerType=ol.pointer.TouchSource.POINTER_TYPE;e.clientX=
inTouch.clientX;e.clientY=inTouch.clientY;e.screenX=inTouch.screenX;e.screenY=inTouch.screenY;return e};ol.pointer.TouchSource.prototype.processTouches_=function(inEvent,inFunction){var touches=Array.prototype.slice.call(inEvent.changedTouches);var count=touches.length;function preventDefault(){inEvent.preventDefault()}var i,pointer;for(i=0;i<count;++i){pointer=this.touchToPointer_(inEvent,touches[i]);pointer.preventDefault=preventDefault;inFunction.call(this,inEvent,pointer)}};
ol.pointer.TouchSource.prototype.findTouch_=function(touchList,searchId){var l=touchList.length;var touch;for(var i=0;i<l;i++){touch=touchList[i];if(touch.identifier===searchId)return true}return false};
ol.pointer.TouchSource.prototype.vacuumTouches_=function(inEvent){var touchList=inEvent.touches;var keys=Object.keys(this.pointerMap);var count=keys.length;if(count>=touchList.length){var d=[];var i,key,value;for(i=0;i<count;++i){key=keys[i];value=this.pointerMap[key];if(key!=ol.pointer.MouseSource.POINTER_ID&&!this.findTouch_(touchList,key-2))d.push(value.out)}for(i=0;i<d.length;++i)this.cancelOut_(inEvent,d[i])}};
ol.pointer.TouchSource.prototype.touchstart=function(inEvent){this.vacuumTouches_(inEvent);this.setPrimaryTouch_(inEvent.changedTouches[0]);this.dedupSynthMouse_(inEvent);this.clickCount_++;this.processTouches_(inEvent,this.overDown_)};
ol.pointer.TouchSource.prototype.overDown_=function(browserEvent,inPointer){this.pointerMap[inPointer.pointerId]={target:inPointer.target,out:inPointer,outTarget:inPointer.target};this.dispatcher.over(inPointer,browserEvent);this.dispatcher.enter(inPointer,browserEvent);this.dispatcher.down(inPointer,browserEvent)};ol.pointer.TouchSource.prototype.touchmove=function(inEvent){inEvent.preventDefault();this.processTouches_(inEvent,this.moveOverOut_)};
ol.pointer.TouchSource.prototype.moveOverOut_=function(browserEvent,inPointer){var event=inPointer;var pointer=this.pointerMap[event.pointerId];if(!pointer)return;var outEvent=pointer.out;var outTarget=pointer.outTarget;this.dispatcher.move(event,browserEvent);if(outEvent&&outTarget!==event.target){outEvent.relatedTarget=event.target;event.relatedTarget=outTarget;outEvent.target=outTarget;if(event.target){this.dispatcher.leaveOut(outEvent,browserEvent);this.dispatcher.enterOver(event,browserEvent)}else{event.target=
outTarget;event.relatedTarget=null;this.cancelOut_(browserEvent,event)}}pointer.out=event;pointer.outTarget=event.target};ol.pointer.TouchSource.prototype.touchend=function(inEvent){this.dedupSynthMouse_(inEvent);this.processTouches_(inEvent,this.upOut_)};ol.pointer.TouchSource.prototype.upOut_=function(browserEvent,inPointer){this.dispatcher.up(inPointer,browserEvent);this.dispatcher.out(inPointer,browserEvent);this.dispatcher.leave(inPointer,browserEvent);this.cleanUpPointer_(inPointer)};
ol.pointer.TouchSource.prototype.touchcancel=function(inEvent){this.processTouches_(inEvent,this.cancelOut_)};ol.pointer.TouchSource.prototype.cancelOut_=function(browserEvent,inPointer){this.dispatcher.cancel(inPointer,browserEvent);this.dispatcher.out(inPointer,browserEvent);this.dispatcher.leave(inPointer,browserEvent);this.cleanUpPointer_(inPointer)};ol.pointer.TouchSource.prototype.cleanUpPointer_=function(inPointer){delete this.pointerMap[inPointer.pointerId];this.removePrimaryPointer_(inPointer)};
ol.pointer.TouchSource.prototype.dedupSynthMouse_=function(inEvent){var lts=this.mouseSource.lastTouches;var t=inEvent.changedTouches[0];if(this.isPrimaryTouch_(t)){var lt=[t.clientX,t.clientY];lts.push(lt);setTimeout(function(){ol.array.remove(lts,lt)},ol.pointer.TouchSource.DEDUP_TIMEOUT)}};goog.provide("ol.pointer.PointerEventHandler");goog.require("ol");goog.require("ol.events");goog.require("ol.events.EventTarget");goog.require("ol.has");goog.require("ol.pointer.EventType");goog.require("ol.pointer.MouseSource");goog.require("ol.pointer.MsSource");goog.require("ol.pointer.NativeSource");goog.require("ol.pointer.PointerEvent");goog.require("ol.pointer.TouchSource");
ol.pointer.PointerEventHandler=function(element){ol.events.EventTarget.call(this);this.element_=element;this.pointerMap={};this.eventMap_={};this.eventSourceList_=[];this.registerSources()};ol.inherits(ol.pointer.PointerEventHandler,ol.events.EventTarget);
ol.pointer.PointerEventHandler.prototype.registerSources=function(){if(ol.has.POINTER)this.registerSource("native",new ol.pointer.NativeSource(this));else if(ol.has.MSPOINTER)this.registerSource("ms",new ol.pointer.MsSource(this));else{var mouseSource=new ol.pointer.MouseSource(this);this.registerSource("mouse",mouseSource);if(ol.has.TOUCH)this.registerSource("touch",new ol.pointer.TouchSource(this,mouseSource))}this.register_()};
ol.pointer.PointerEventHandler.prototype.registerSource=function(name,source){var s=source;var newEvents=s.getEvents();if(newEvents){newEvents.forEach(function(e){var handler=s.getHandlerForEvent(e);if(handler)this.eventMap_[e]=handler.bind(s)},this);this.eventSourceList_.push(s)}};ol.pointer.PointerEventHandler.prototype.register_=function(){var l=this.eventSourceList_.length;var eventSource;for(var i=0;i<l;i++){eventSource=this.eventSourceList_[i];this.addEvents_(eventSource.getEvents())}};
ol.pointer.PointerEventHandler.prototype.unregister_=function(){var l=this.eventSourceList_.length;var eventSource;for(var i=0;i<l;i++){eventSource=this.eventSourceList_[i];this.removeEvents_(eventSource.getEvents())}};ol.pointer.PointerEventHandler.prototype.eventHandler_=function(inEvent){var type=inEvent.type;var handler=this.eventMap_[type];if(handler)handler(inEvent)};
ol.pointer.PointerEventHandler.prototype.addEvents_=function(events){events.forEach(function(eventName){ol.events.listen(this.element_,eventName,this.eventHandler_,this)},this)};ol.pointer.PointerEventHandler.prototype.removeEvents_=function(events){events.forEach(function(e){ol.events.unlisten(this.element_,e,this.eventHandler_,this)},this)};
ol.pointer.PointerEventHandler.prototype.cloneEvent=function(event,inEvent){var eventCopy={},p;for(var i=0,ii=ol.pointer.PointerEventHandler.CLONE_PROPS.length;i<ii;i++){p=ol.pointer.PointerEventHandler.CLONE_PROPS[i][0];eventCopy[p]=event[p]||inEvent[p]||ol.pointer.PointerEventHandler.CLONE_PROPS[i][1]}return eventCopy};ol.pointer.PointerEventHandler.prototype.down=function(data,event){this.fireEvent(ol.pointer.EventType.POINTERDOWN,data,event)};
ol.pointer.PointerEventHandler.prototype.move=function(data,event){this.fireEvent(ol.pointer.EventType.POINTERMOVE,data,event)};ol.pointer.PointerEventHandler.prototype.up=function(data,event){this.fireEvent(ol.pointer.EventType.POINTERUP,data,event)};ol.pointer.PointerEventHandler.prototype.enter=function(data,event){data.bubbles=false;this.fireEvent(ol.pointer.EventType.POINTERENTER,data,event)};
ol.pointer.PointerEventHandler.prototype.leave=function(data,event){data.bubbles=false;this.fireEvent(ol.pointer.EventType.POINTERLEAVE,data,event)};ol.pointer.PointerEventHandler.prototype.over=function(data,event){data.bubbles=true;this.fireEvent(ol.pointer.EventType.POINTEROVER,data,event)};ol.pointer.PointerEventHandler.prototype.out=function(data,event){data.bubbles=true;this.fireEvent(ol.pointer.EventType.POINTEROUT,data,event)};
ol.pointer.PointerEventHandler.prototype.cancel=function(data,event){this.fireEvent(ol.pointer.EventType.POINTERCANCEL,data,event)};ol.pointer.PointerEventHandler.prototype.leaveOut=function(data,event){this.out(data,event);if(!this.contains_(data.target,data.relatedTarget))this.leave(data,event)};ol.pointer.PointerEventHandler.prototype.enterOver=function(data,event){this.over(data,event);if(!this.contains_(data.target,data.relatedTarget))this.enter(data,event)};
ol.pointer.PointerEventHandler.prototype.contains_=function(container,contained){if(!container||!contained)return false;return container.contains(contained)};ol.pointer.PointerEventHandler.prototype.makeEvent=function(inType,data,event){return new ol.pointer.PointerEvent(inType,event,data)};ol.pointer.PointerEventHandler.prototype.fireEvent=function(inType,data,event){var e=this.makeEvent(inType,data,event);this.dispatchEvent(e)};
ol.pointer.PointerEventHandler.prototype.fireNativeEvent=function(event){var e=this.makeEvent(event.type,event,event);this.dispatchEvent(e)};ol.pointer.PointerEventHandler.prototype.wrapMouseEvent=function(eventType,event){var pointerEvent=this.makeEvent(eventType,ol.pointer.MouseSource.prepareEvent(event,this),event);return pointerEvent};ol.pointer.PointerEventHandler.prototype.disposeInternal=function(){this.unregister_();ol.events.EventTarget.prototype.disposeInternal.call(this)};
ol.pointer.PointerEventHandler.CLONE_PROPS=[["bubbles",false],["cancelable",false],["view",null],["detail",null],["screenX",0],["screenY",0],["clientX",0],["clientY",0],["ctrlKey",false],["altKey",false],["shiftKey",false],["metaKey",false],["button",0],["relatedTarget",null],["buttons",0],["pointerId",0],["width",0],["height",0],["pressure",0],["tiltX",0],["tiltY",0],["pointerType",""],["hwTimestamp",0],["isPrimary",false],["type",""],["target",null],["currentTarget",null],["which",0]];goog.provide("ol.MapBrowserEventHandler");goog.require("ol");goog.require("ol.has");goog.require("ol.MapBrowserEventType");goog.require("ol.MapBrowserPointerEvent");goog.require("ol.events");goog.require("ol.events.EventTarget");goog.require("ol.pointer.EventType");goog.require("ol.pointer.PointerEventHandler");
ol.MapBrowserEventHandler=function(map,moveTolerance){ol.events.EventTarget.call(this);this.map_=map;this.clickTimeoutId_=0;this.dragging_=false;this.dragListenerKeys_=[];this.moveTolerance_=moveTolerance?moveTolerance*ol.has.DEVICE_PIXEL_RATIO:ol.has.DEVICE_PIXEL_RATIO;this.down_=null;var element=this.map_.getViewport();this.activePointers_=0;this.trackedTouches_={};this.pointerEventHandler_=new ol.pointer.PointerEventHandler(element);this.documentPointerEventHandler_=null;this.pointerdownListenerKey_=
ol.events.listen(this.pointerEventHandler_,ol.pointer.EventType.POINTERDOWN,this.handlePointerDown_,this);this.relayedListenerKey_=ol.events.listen(this.pointerEventHandler_,ol.pointer.EventType.POINTERMOVE,this.relayEvent_,this)};ol.inherits(ol.MapBrowserEventHandler,ol.events.EventTarget);
ol.MapBrowserEventHandler.prototype.emulateClick_=function(pointerEvent){var newEvent=new ol.MapBrowserPointerEvent(ol.MapBrowserEventType.CLICK,this.map_,pointerEvent);this.dispatchEvent(newEvent);if(this.clickTimeoutId_!==0){clearTimeout(this.clickTimeoutId_);this.clickTimeoutId_=0;newEvent=new ol.MapBrowserPointerEvent(ol.MapBrowserEventType.DBLCLICK,this.map_,pointerEvent);this.dispatchEvent(newEvent)}else this.clickTimeoutId_=setTimeout(function(){this.clickTimeoutId_=0;var newEvent=new ol.MapBrowserPointerEvent(ol.MapBrowserEventType.SINGLECLICK,
this.map_,pointerEvent);this.dispatchEvent(newEvent)}.bind(this),250)};ol.MapBrowserEventHandler.prototype.updateActivePointers_=function(pointerEvent){var event=pointerEvent;if(event.type==ol.MapBrowserEventType.POINTERUP||event.type==ol.MapBrowserEventType.POINTERCANCEL)delete this.trackedTouches_[event.pointerId];else if(event.type==ol.MapBrowserEventType.POINTERDOWN)this.trackedTouches_[event.pointerId]=true;this.activePointers_=Object.keys(this.trackedTouches_).length};
ol.MapBrowserEventHandler.prototype.handlePointerUp_=function(pointerEvent){this.updateActivePointers_(pointerEvent);var newEvent=new ol.MapBrowserPointerEvent(ol.MapBrowserEventType.POINTERUP,this.map_,pointerEvent);this.dispatchEvent(newEvent);if(!newEvent.propagationStopped&&!this.dragging_&&this.isMouseActionButton_(pointerEvent))this.emulateClick_(this.down_);if(this.activePointers_===0){this.dragListenerKeys_.forEach(ol.events.unlistenByKey);this.dragListenerKeys_.length=0;this.dragging_=false;
this.down_=null;this.documentPointerEventHandler_.dispose();this.documentPointerEventHandler_=null}};ol.MapBrowserEventHandler.prototype.isMouseActionButton_=function(pointerEvent){return pointerEvent.button===0};
ol.MapBrowserEventHandler.prototype.handlePointerDown_=function(pointerEvent){this.updateActivePointers_(pointerEvent);var newEvent=new ol.MapBrowserPointerEvent(ol.MapBrowserEventType.POINTERDOWN,this.map_,pointerEvent);this.dispatchEvent(newEvent);this.down_=pointerEvent;if(this.dragListenerKeys_.length===0){this.documentPointerEventHandler_=new ol.pointer.PointerEventHandler(document);this.dragListenerKeys_.push(ol.events.listen(this.documentPointerEventHandler_,ol.MapBrowserEventType.POINTERMOVE,
this.handlePointerMove_,this),ol.events.listen(this.documentPointerEventHandler_,ol.MapBrowserEventType.POINTERUP,this.handlePointerUp_,this),ol.events.listen(this.pointerEventHandler_,ol.MapBrowserEventType.POINTERCANCEL,this.handlePointerUp_,this))}};
ol.MapBrowserEventHandler.prototype.handlePointerMove_=function(pointerEvent){if(this.isMoving_(pointerEvent)){this.dragging_=true;var newEvent=new ol.MapBrowserPointerEvent(ol.MapBrowserEventType.POINTERDRAG,this.map_,pointerEvent,this.dragging_);this.dispatchEvent(newEvent)}pointerEvent.preventDefault()};
ol.MapBrowserEventHandler.prototype.relayEvent_=function(pointerEvent){var dragging=!!(this.down_&&this.isMoving_(pointerEvent));this.dispatchEvent(new ol.MapBrowserPointerEvent(pointerEvent.type,this.map_,pointerEvent,dragging))};ol.MapBrowserEventHandler.prototype.isMoving_=function(pointerEvent){return Math.abs(pointerEvent.clientX-this.down_.clientX)>this.moveTolerance_||Math.abs(pointerEvent.clientY-this.down_.clientY)>this.moveTolerance_};
ol.MapBrowserEventHandler.prototype.disposeInternal=function(){if(this.relayedListenerKey_){ol.events.unlistenByKey(this.relayedListenerKey_);this.relayedListenerKey_=null}if(this.pointerdownListenerKey_){ol.events.unlistenByKey(this.pointerdownListenerKey_);this.pointerdownListenerKey_=null}this.dragListenerKeys_.forEach(ol.events.unlistenByKey);this.dragListenerKeys_.length=0;if(this.documentPointerEventHandler_){this.documentPointerEventHandler_.dispose();this.documentPointerEventHandler_=null}if(this.pointerEventHandler_){this.pointerEventHandler_.dispose();
this.pointerEventHandler_=null}ol.events.EventTarget.prototype.disposeInternal.call(this)};goog.provide("ol.MapEventType");ol.MapEventType={POSTRENDER:"postrender",MOVESTART:"movestart",MOVEEND:"moveend"};goog.provide("ol.MapProperty");ol.MapProperty={LAYERGROUP:"layergroup",SIZE:"size",TARGET:"target",VIEW:"view"};goog.provide("ol.TileState");ol.TileState={IDLE:0,LOADING:1,LOADED:2,ERROR:3,EMPTY:4,ABORT:5};goog.provide("ol.structs.PriorityQueue");goog.require("ol.asserts");goog.require("ol.obj");ol.structs.PriorityQueue=function(priorityFunction,keyFunction){this.priorityFunction_=priorityFunction;this.keyFunction_=keyFunction;this.elements_=[];this.priorities_=[];this.queuedElements_={}};ol.structs.PriorityQueue.DROP=Infinity;ol.structs.PriorityQueue.prototype.clear=function(){this.elements_.length=0;this.priorities_.length=0;ol.obj.clear(this.queuedElements_)};
ol.structs.PriorityQueue.prototype.dequeue=function(){var elements=this.elements_;var priorities=this.priorities_;var element=elements[0];if(elements.length==1){elements.length=0;priorities.length=0}else{elements[0]=elements.pop();priorities[0]=priorities.pop();this.siftUp_(0)}var elementKey=this.keyFunction_(element);delete this.queuedElements_[elementKey];return element};
ol.structs.PriorityQueue.prototype.enqueue=function(element){ol.asserts.assert(!(this.keyFunction_(element)in this.queuedElements_),31);var priority=this.priorityFunction_(element);if(priority!=ol.structs.PriorityQueue.DROP){this.elements_.push(element);this.priorities_.push(priority);this.queuedElements_[this.keyFunction_(element)]=true;this.siftDown_(0,this.elements_.length-1);return true}return false};ol.structs.PriorityQueue.prototype.getCount=function(){return this.elements_.length};
ol.structs.PriorityQueue.prototype.getLeftChildIndex_=function(index){return index*2+1};ol.structs.PriorityQueue.prototype.getRightChildIndex_=function(index){return index*2+2};ol.structs.PriorityQueue.prototype.getParentIndex_=function(index){return index-1>>1};ol.structs.PriorityQueue.prototype.heapify_=function(){var i;for(i=(this.elements_.length>>1)-1;i>=0;i--)this.siftUp_(i)};ol.structs.PriorityQueue.prototype.isEmpty=function(){return this.elements_.length===0};
ol.structs.PriorityQueue.prototype.isKeyQueued=function(key){return key in this.queuedElements_};ol.structs.PriorityQueue.prototype.isQueued=function(element){return this.isKeyQueued(this.keyFunction_(element))};
ol.structs.PriorityQueue.prototype.siftUp_=function(index){var elements=this.elements_;var priorities=this.priorities_;var count=elements.length;var element=elements[index];var priority=priorities[index];var startIndex=index;while(index<count>>1){var lIndex=this.getLeftChildIndex_(index);var rIndex=this.getRightChildIndex_(index);var smallerChildIndex=rIndex<count&&priorities[rIndex]<priorities[lIndex]?rIndex:lIndex;elements[index]=elements[smallerChildIndex];priorities[index]=priorities[smallerChildIndex];
index=smallerChildIndex}elements[index]=element;priorities[index]=priority;this.siftDown_(startIndex,index)};
ol.structs.PriorityQueue.prototype.siftDown_=function(startIndex,index){var elements=this.elements_;var priorities=this.priorities_;var element=elements[index];var priority=priorities[index];while(index>startIndex){var parentIndex=this.getParentIndex_(index);if(priorities[parentIndex]>priority){elements[index]=elements[parentIndex];priorities[index]=priorities[parentIndex];index=parentIndex}else break}elements[index]=element;priorities[index]=priority};
ol.structs.PriorityQueue.prototype.reprioritize=function(){var priorityFunction=this.priorityFunction_;var elements=this.elements_;var priorities=this.priorities_;var index=0;var n=elements.length;var element,i,priority;for(i=0;i<n;++i){element=elements[i];priority=priorityFunction(element);if(priority==ol.structs.PriorityQueue.DROP)delete this.queuedElements_[this.keyFunction_(element)];else{priorities[index]=priority;elements[index++]=element}}elements.length=index;priorities.length=index;this.heapify_()};goog.provide("ol.TileQueue");goog.require("ol");goog.require("ol.TileState");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.structs.PriorityQueue");ol.TileQueue=function(tilePriorityFunction,tileChangeCallback){ol.structs.PriorityQueue.call(this,function(element){return tilePriorityFunction.apply(null,element)},function(element){return element[0].getKey()});this.tileChangeCallback_=tileChangeCallback;this.tilesLoading_=0;this.tilesLoadingKeys_={}};
ol.inherits(ol.TileQueue,ol.structs.PriorityQueue);ol.TileQueue.prototype.enqueue=function(element){var added=ol.structs.PriorityQueue.prototype.enqueue.call(this,element);if(added){var tile=element[0];ol.events.listen(tile,ol.events.EventType.CHANGE,this.handleTileChange,this)}return added};ol.TileQueue.prototype.getTilesLoading=function(){return this.tilesLoading_};
ol.TileQueue.prototype.handleTileChange=function(event){var tile=event.target;var state=tile.getState();if(state===ol.TileState.LOADED||state===ol.TileState.ERROR||state===ol.TileState.EMPTY||state===ol.TileState.ABORT){ol.events.unlisten(tile,ol.events.EventType.CHANGE,this.handleTileChange,this);var tileKey=tile.getKey();if(tileKey in this.tilesLoadingKeys_){delete this.tilesLoadingKeys_[tileKey];--this.tilesLoading_}this.tileChangeCallback_()}};
ol.TileQueue.prototype.loadMoreTiles=function(maxTotalLoading,maxNewLoads){var newLoads=0;var abortedTiles=false;var state,tile,tileKey;while(this.tilesLoading_<maxTotalLoading&&newLoads<maxNewLoads&&this.getCount()>0){tile=this.dequeue()[0];tileKey=tile.getKey();state=tile.getState();if(state===ol.TileState.ABORT)abortedTiles=true;else if(state===ol.TileState.IDLE&&!(tileKey in this.tilesLoadingKeys_)){this.tilesLoadingKeys_[tileKey]=true;++this.tilesLoading_;++newLoads;tile.load()}}if(newLoads===
0&&abortedTiles)this.tileChangeCallback_()};goog.provide("ol.CenterConstraint");goog.require("ol.math");ol.CenterConstraint.createExtent=function(extent){return function(center){if(center)return[ol.math.clamp(center[0],extent[0],extent[2]),ol.math.clamp(center[1],extent[1],extent[3])];else return undefined}};ol.CenterConstraint.none=function(center){return center};goog.provide("ol.ResolutionConstraint");goog.require("ol.array");goog.require("ol.math");
ol.ResolutionConstraint.createSnapToResolutions=function(resolutions){return function(resolution,delta,direction){if(resolution!==undefined){var z=ol.array.linearFindNearest(resolutions,resolution,direction);z=ol.math.clamp(z+delta,0,resolutions.length-1);var index=Math.floor(z);if(z!=index&&index<resolutions.length-1){var power=resolutions[index]/resolutions[index+1];return resolutions[index]/Math.pow(power,z-index)}else return resolutions[index]}else return undefined}};
ol.ResolutionConstraint.createSnapToPower=function(power,maxResolution,opt_maxLevel){return function(resolution,delta,direction){if(resolution!==undefined){var offset=-direction/2+.5;var oldLevel=Math.floor(Math.log(maxResolution/resolution)/Math.log(power)+offset);var newLevel=Math.max(oldLevel+delta,0);if(opt_maxLevel!==undefined)newLevel=Math.min(newLevel,opt_maxLevel);return maxResolution/Math.pow(power,newLevel)}else return undefined}};goog.provide("ol.RotationConstraint");goog.require("ol.math");ol.RotationConstraint.disable=function(rotation,delta){if(rotation!==undefined)return 0;else return undefined};ol.RotationConstraint.none=function(rotation,delta){if(rotation!==undefined)return rotation+delta;else return undefined};ol.RotationConstraint.createSnapToN=function(n){var theta=2*Math.PI/n;return function(rotation,delta){if(rotation!==undefined){rotation=Math.floor((rotation+delta)/theta+.5)*theta;return rotation}else return undefined}};
ol.RotationConstraint.createSnapToZero=function(opt_tolerance){var tolerance=opt_tolerance||ol.math.toRadians(5);return function(rotation,delta){if(rotation!==undefined)if(Math.abs(rotation+delta)<=tolerance)return 0;else return rotation+delta;else return undefined}};goog.provide("ol.ViewHint");ol.ViewHint={ANIMATING:0,INTERACTING:1};goog.provide("ol.ViewProperty");ol.ViewProperty={CENTER:"center",RESOLUTION:"resolution",ROTATION:"rotation"};goog.provide("ol.string");ol.string.padNumber=function(number,width,opt_precision){var numberString=opt_precision!==undefined?number.toFixed(opt_precision):""+number;var decimal=numberString.indexOf(".");decimal=decimal===-1?numberString.length:decimal;return decimal>width?numberString:(new Array(1+width-decimal)).join("0")+numberString};
ol.string.compareVersions=function(v1,v2){var s1=(""+v1).split(".");var s2=(""+v2).split(".");for(var i=0;i<Math.max(s1.length,s2.length);i++){var n1=parseInt(s1[i]||"0",10);var n2=parseInt(s2[i]||"0",10);if(n1>n2)return 1;if(n2>n1)return-1}return 0};goog.provide("ol.coordinate");goog.require("ol.math");goog.require("ol.string");ol.coordinate.add=function(coordinate,delta){coordinate[0]+=delta[0];coordinate[1]+=delta[1];return coordinate};ol.coordinate.closestOnCircle=function(coordinate,circle){var r=circle.getRadius();var center=circle.getCenter();var x0=center[0];var y0=center[1];var x1=coordinate[0];var y1=coordinate[1];var dx=x1-x0;var dy=y1-y0;if(dx===0&&dy===0)dx=1;var d=Math.sqrt(dx*dx+dy*dy);var x,y;x=x0+r*dx/d;y=y0+r*dy/d;return[x,y]};
ol.coordinate.closestOnSegment=function(coordinate,segment){var x0=coordinate[0];var y0=coordinate[1];var start=segment[0];var end=segment[1];var x1=start[0];var y1=start[1];var x2=end[0];var y2=end[1];var dx=x2-x1;var dy=y2-y1;var along=dx===0&&dy===0?0:(dx*(x0-x1)+dy*(y0-y1))/(dx*dx+dy*dy||0);var x,y;if(along<=0){x=x1;y=y1}else if(along>=1){x=x2;y=y2}else{x=x1+along*dx;y=y1+along*dy}return[x,y]};
ol.coordinate.createStringXY=function(opt_fractionDigits){return function(coordinate){return ol.coordinate.toStringXY(coordinate,opt_fractionDigits)}};
ol.coordinate.degreesToStringHDMS=function(hemispheres,degrees,opt_fractionDigits){var normalizedDegrees=ol.math.modulo(degrees+180,360)-180;var x=Math.abs(3600*normalizedDegrees);var dflPrecision=opt_fractionDigits||0;var precision=Math.pow(10,dflPrecision);var deg=Math.floor(x/3600);var min=Math.floor((x-deg*3600)/60);var sec=x-deg*3600-min*60;sec=Math.ceil(sec*precision)/precision;if(sec>=60){sec=0;min+=1}if(min>=60){min=0;deg+=1}return deg+"\u00b0 "+ol.string.padNumber(min,2)+"\u2032 "+ol.string.padNumber(sec,
2,dflPrecision)+"\u2033"+(normalizedDegrees==0?"":" "+hemispheres.charAt(normalizedDegrees<0?1:0))};ol.coordinate.format=function(coordinate,template,opt_fractionDigits){if(coordinate)return template.replace("{x}",coordinate[0].toFixed(opt_fractionDigits)).replace("{y}",coordinate[1].toFixed(opt_fractionDigits));else return""};ol.coordinate.equals=function(coordinate1,coordinate2){var equals=true;for(var i=coordinate1.length-1;i>=0;--i)if(coordinate1[i]!=coordinate2[i]){equals=false;break}return equals};
ol.coordinate.rotate=function(coordinate,angle){var cosAngle=Math.cos(angle);var sinAngle=Math.sin(angle);var x=coordinate[0]*cosAngle-coordinate[1]*sinAngle;var y=coordinate[1]*cosAngle+coordinate[0]*sinAngle;coordinate[0]=x;coordinate[1]=y;return coordinate};ol.coordinate.scale=function(coordinate,scale){coordinate[0]*=scale;coordinate[1]*=scale;return coordinate};ol.coordinate.sub=function(coordinate,delta){coordinate[0]-=delta[0];coordinate[1]-=delta[1];return coordinate};
ol.coordinate.squaredDistance=function(coord1,coord2){var dx=coord1[0]-coord2[0];var dy=coord1[1]-coord2[1];return dx*dx+dy*dy};ol.coordinate.distance=function(coord1,coord2){return Math.sqrt(ol.coordinate.squaredDistance(coord1,coord2))};ol.coordinate.squaredDistanceToSegment=function(coordinate,segment){return ol.coordinate.squaredDistance(coordinate,ol.coordinate.closestOnSegment(coordinate,segment))};
ol.coordinate.toStringHDMS=function(coordinate,opt_fractionDigits){if(coordinate)return ol.coordinate.degreesToStringHDMS("NS",coordinate[1],opt_fractionDigits)+" "+ol.coordinate.degreesToStringHDMS("EW",coordinate[0],opt_fractionDigits);else return""};ol.coordinate.toStringXY=function(coordinate,opt_fractionDigits){return ol.coordinate.format(coordinate,"{x}, {y}",opt_fractionDigits)};goog.provide("ol.easing");ol.easing.easeIn=function(t){return Math.pow(t,3)};ol.easing.easeOut=function(t){return 1-ol.easing.easeIn(1-t)};ol.easing.inAndOut=function(t){return 3*t*t-2*t*t*t};ol.easing.linear=function(t){return t};ol.easing.upAndDown=function(t){if(t<.5)return ol.easing.inAndOut(2*t);else return 1-ol.easing.inAndOut(2*(t-.5))};goog.provide("ol.geom.GeometryLayout");ol.geom.GeometryLayout={XY:"XY",XYZ:"XYZ",XYM:"XYM",XYZM:"XYZM"};goog.provide("ol.functions");ol.functions.TRUE=function(){return true};ol.functions.FALSE=function(){return false};goog.provide("ol.geom.flat.transform");ol.geom.flat.transform.transform2D=function(flatCoordinates,offset,end,stride,transform,opt_dest){var dest=opt_dest?opt_dest:[];var i=0;var j;for(j=offset;j<end;j+=stride){var x=flatCoordinates[j];var y=flatCoordinates[j+1];dest[i++]=transform[0]*x+transform[2]*y+transform[4];dest[i++]=transform[1]*x+transform[3]*y+transform[5]}if(opt_dest&&dest.length!=i)dest.length=i;return dest};
ol.geom.flat.transform.rotate=function(flatCoordinates,offset,end,stride,angle,anchor,opt_dest){var dest=opt_dest?opt_dest:[];var cos=Math.cos(angle);var sin=Math.sin(angle);var anchorX=anchor[0];var anchorY=anchor[1];var i=0;for(var j=offset;j<end;j+=stride){var deltaX=flatCoordinates[j]-anchorX;var deltaY=flatCoordinates[j+1]-anchorY;dest[i++]=anchorX+deltaX*cos-deltaY*sin;dest[i++]=anchorY+deltaX*sin+deltaY*cos;for(var k=j+2;k<j+stride;++k)dest[i++]=flatCoordinates[k]}if(opt_dest&&dest.length!=
i)dest.length=i;return dest};ol.geom.flat.transform.scale=function(flatCoordinates,offset,end,stride,sx,sy,anchor,opt_dest){var dest=opt_dest?opt_dest:[];var anchorX=anchor[0];var anchorY=anchor[1];var i=0;for(var j=offset;j<end;j+=stride){var deltaX=flatCoordinates[j]-anchorX;var deltaY=flatCoordinates[j+1]-anchorY;dest[i++]=anchorX+sx*deltaX;dest[i++]=anchorY+sy*deltaY;for(var k=j+2;k<j+stride;++k)dest[i++]=flatCoordinates[k]}if(opt_dest&&dest.length!=i)dest.length=i;return dest};
ol.geom.flat.transform.translate=function(flatCoordinates,offset,end,stride,deltaX,deltaY,opt_dest){var dest=opt_dest?opt_dest:[];var i=0;var j,k;for(j=offset;j<end;j+=stride){dest[i++]=flatCoordinates[j]+deltaX;dest[i++]=flatCoordinates[j+1]+deltaY;for(k=j+2;k<j+stride;++k)dest[i++]=flatCoordinates[k]}if(opt_dest&&dest.length!=i)dest.length=i;return dest};goog.provide("ol.transform");goog.require("ol.asserts");ol.transform.tmp_=new Array(6);ol.transform.create=function(){return[1,0,0,1,0,0]};ol.transform.reset=function(transform){return ol.transform.set(transform,1,0,0,1,0,0)};
ol.transform.multiply=function(transform1,transform2){var a1=transform1[0];var b1=transform1[1];var c1=transform1[2];var d1=transform1[3];var e1=transform1[4];var f1=transform1[5];var a2=transform2[0];var b2=transform2[1];var c2=transform2[2];var d2=transform2[3];var e2=transform2[4];var f2=transform2[5];transform1[0]=a1*a2+c1*b2;transform1[1]=b1*a2+d1*b2;transform1[2]=a1*c2+c1*d2;transform1[3]=b1*c2+d1*d2;transform1[4]=a1*e2+c1*f2+e1;transform1[5]=b1*e2+d1*f2+f1;return transform1};
ol.transform.set=function(transform,a,b,c,d,e,f){transform[0]=a;transform[1]=b;transform[2]=c;transform[3]=d;transform[4]=e;transform[5]=f;return transform};ol.transform.setFromArray=function(transform1,transform2){transform1[0]=transform2[0];transform1[1]=transform2[1];transform1[2]=transform2[2];transform1[3]=transform2[3];transform1[4]=transform2[4];transform1[5]=transform2[5];return transform1};
ol.transform.apply=function(transform,coordinate){var x=coordinate[0],y=coordinate[1];coordinate[0]=transform[0]*x+transform[2]*y+transform[4];coordinate[1]=transform[1]*x+transform[3]*y+transform[5];return coordinate};ol.transform.rotate=function(transform,angle){var cos=Math.cos(angle);var sin=Math.sin(angle);return ol.transform.multiply(transform,ol.transform.set(ol.transform.tmp_,cos,sin,-sin,cos,0,0))};
ol.transform.scale=function(transform,x,y){return ol.transform.multiply(transform,ol.transform.set(ol.transform.tmp_,x,0,0,y,0,0))};ol.transform.translate=function(transform,dx,dy){return ol.transform.multiply(transform,ol.transform.set(ol.transform.tmp_,1,0,0,1,dx,dy))};
ol.transform.compose=function(transform,dx1,dy1,sx,sy,angle,dx2,dy2){var sin=Math.sin(angle);var cos=Math.cos(angle);transform[0]=sx*cos;transform[1]=sy*sin;transform[2]=-sx*sin;transform[3]=sy*cos;transform[4]=dx2*sx*cos-dy2*sx*sin+dx1;transform[5]=dx2*sy*sin+dy2*sy*cos+dy1;return transform};
ol.transform.invert=function(transform){var det=ol.transform.determinant(transform);ol.asserts.assert(det!==0,32);var a=transform[0];var b=transform[1];var c=transform[2];var d=transform[3];var e=transform[4];var f=transform[5];transform[0]=d/det;transform[1]=-b/det;transform[2]=-c/det;transform[3]=a/det;transform[4]=(c*f-d*e)/det;transform[5]=-(a*f-b*e)/det;return transform};ol.transform.determinant=function(mat){return mat[0]*mat[3]-mat[1]*mat[2]};goog.provide("ol.geom.Geometry");goog.require("ol");goog.require("ol.Object");goog.require("ol.extent");goog.require("ol.functions");goog.require("ol.geom.flat.transform");goog.require("ol.proj");goog.require("ol.proj.Units");goog.require("ol.transform");ol.geom.Geometry=function(){ol.Object.call(this);this.extent_=ol.extent.createEmpty();this.extentRevision_=-1;this.simplifiedGeometryCache={};this.simplifiedGeometryMaxMinSquaredTolerance=0;this.simplifiedGeometryRevision=0;this.tmpTransform_=ol.transform.create()};
ol.inherits(ol.geom.Geometry,ol.Object);ol.geom.Geometry.prototype.clone=function(){};ol.geom.Geometry.prototype.closestPointXY=function(x,y,closestPoint,minSquaredDistance){};ol.geom.Geometry.prototype.getClosestPoint=function(point,opt_closestPoint){var closestPoint=opt_closestPoint?opt_closestPoint:[NaN,NaN];this.closestPointXY(point[0],point[1],closestPoint,Infinity);return closestPoint};
ol.geom.Geometry.prototype.intersectsCoordinate=function(coordinate){return this.containsXY(coordinate[0],coordinate[1])};ol.geom.Geometry.prototype.computeExtent=function(extent){};ol.geom.Geometry.prototype.containsXY=ol.functions.FALSE;ol.geom.Geometry.prototype.getExtent=function(opt_extent){if(this.extentRevision_!=this.getRevision()){this.extent_=this.computeExtent(this.extent_);this.extentRevision_=this.getRevision()}return ol.extent.returnOrUpdate(this.extent_,opt_extent)};
ol.geom.Geometry.prototype.rotate=function(angle,anchor){};ol.geom.Geometry.prototype.scale=function(sx,opt_sy,opt_anchor){};ol.geom.Geometry.prototype.simplify=function(tolerance){return this.getSimplifiedGeometry(tolerance*tolerance)};ol.geom.Geometry.prototype.getSimplifiedGeometry=function(squaredTolerance){};ol.geom.Geometry.prototype.getType=function(){};ol.geom.Geometry.prototype.applyTransform=function(transformFn){};ol.geom.Geometry.prototype.intersectsExtent=function(extent){};
ol.geom.Geometry.prototype.translate=function(deltaX,deltaY){};
ol.geom.Geometry.prototype.transform=function(source,destination){var tmpTransform=this.tmpTransform_;source=ol.proj.get(source);var transformFn=source.getUnits()==ol.proj.Units.TILE_PIXELS?function(inCoordinates,outCoordinates,stride){var pixelExtent=source.getExtent();var projectedExtent=source.getWorldExtent();var scale=ol.extent.getHeight(projectedExtent)/ol.extent.getHeight(pixelExtent);ol.transform.compose(tmpTransform,projectedExtent[0],projectedExtent[3],scale,-scale,0,0,0);ol.geom.flat.transform.transform2D(inCoordinates,
0,inCoordinates.length,stride,tmpTransform,outCoordinates);return ol.proj.getTransform(source,destination)(inCoordinates,outCoordinates,stride)}:ol.proj.getTransform(source,destination);this.applyTransform(transformFn);return this};goog.provide("ol.geom.SimpleGeometry");goog.require("ol");goog.require("ol.functions");goog.require("ol.extent");goog.require("ol.geom.Geometry");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.flat.transform");goog.require("ol.obj");ol.geom.SimpleGeometry=function(){ol.geom.Geometry.call(this);this.layout=ol.geom.GeometryLayout.XY;this.stride=2;this.flatCoordinates=null};ol.inherits(ol.geom.SimpleGeometry,ol.geom.Geometry);
ol.geom.SimpleGeometry.getLayoutForStride_=function(stride){var layout;if(stride==2)layout=ol.geom.GeometryLayout.XY;else if(stride==3)layout=ol.geom.GeometryLayout.XYZ;else if(stride==4)layout=ol.geom.GeometryLayout.XYZM;return layout};ol.geom.SimpleGeometry.getStrideForLayout=function(layout){var stride;if(layout==ol.geom.GeometryLayout.XY)stride=2;else if(layout==ol.geom.GeometryLayout.XYZ||layout==ol.geom.GeometryLayout.XYM)stride=3;else if(layout==ol.geom.GeometryLayout.XYZM)stride=4;return stride};
ol.geom.SimpleGeometry.prototype.containsXY=ol.functions.FALSE;ol.geom.SimpleGeometry.prototype.computeExtent=function(extent){return ol.extent.createOrUpdateFromFlatCoordinates(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,extent)};ol.geom.SimpleGeometry.prototype.getCoordinates=function(){};ol.geom.SimpleGeometry.prototype.getFirstCoordinate=function(){return this.flatCoordinates.slice(0,this.stride)};ol.geom.SimpleGeometry.prototype.getFlatCoordinates=function(){return this.flatCoordinates};
ol.geom.SimpleGeometry.prototype.getLastCoordinate=function(){return this.flatCoordinates.slice(this.flatCoordinates.length-this.stride)};ol.geom.SimpleGeometry.prototype.getLayout=function(){return this.layout};
ol.geom.SimpleGeometry.prototype.getSimplifiedGeometry=function(squaredTolerance){if(this.simplifiedGeometryRevision!=this.getRevision()){ol.obj.clear(this.simplifiedGeometryCache);this.simplifiedGeometryMaxMinSquaredTolerance=0;this.simplifiedGeometryRevision=this.getRevision()}if(squaredTolerance<0||this.simplifiedGeometryMaxMinSquaredTolerance!==0&&squaredTolerance<=this.simplifiedGeometryMaxMinSquaredTolerance)return this;var key=squaredTolerance.toString();if(this.simplifiedGeometryCache.hasOwnProperty(key))return this.simplifiedGeometryCache[key];
else{var simplifiedGeometry=this.getSimplifiedGeometryInternal(squaredTolerance);var simplifiedFlatCoordinates=simplifiedGeometry.getFlatCoordinates();if(simplifiedFlatCoordinates.length<this.flatCoordinates.length){this.simplifiedGeometryCache[key]=simplifiedGeometry;return simplifiedGeometry}else{this.simplifiedGeometryMaxMinSquaredTolerance=squaredTolerance;return this}}};ol.geom.SimpleGeometry.prototype.getSimplifiedGeometryInternal=function(squaredTolerance){return this};
ol.geom.SimpleGeometry.prototype.getStride=function(){return this.stride};ol.geom.SimpleGeometry.prototype.setFlatCoordinatesInternal=function(layout,flatCoordinates){this.stride=ol.geom.SimpleGeometry.getStrideForLayout(layout);this.layout=layout;this.flatCoordinates=flatCoordinates};ol.geom.SimpleGeometry.prototype.setCoordinates=function(coordinates,opt_layout){};
ol.geom.SimpleGeometry.prototype.setLayout=function(layout,coordinates,nesting){var stride;if(layout)stride=ol.geom.SimpleGeometry.getStrideForLayout(layout);else{var i;for(i=0;i<nesting;++i)if(coordinates.length===0){this.layout=ol.geom.GeometryLayout.XY;this.stride=2;return}else coordinates=coordinates[0];stride=coordinates.length;layout=ol.geom.SimpleGeometry.getLayoutForStride_(stride)}this.layout=layout;this.stride=stride};
ol.geom.SimpleGeometry.prototype.applyTransform=function(transformFn){if(this.flatCoordinates){transformFn(this.flatCoordinates,this.flatCoordinates,this.stride);this.changed()}};ol.geom.SimpleGeometry.prototype.rotate=function(angle,anchor){var flatCoordinates=this.getFlatCoordinates();if(flatCoordinates){var stride=this.getStride();ol.geom.flat.transform.rotate(flatCoordinates,0,flatCoordinates.length,stride,angle,anchor,flatCoordinates);this.changed()}};
ol.geom.SimpleGeometry.prototype.scale=function(sx,opt_sy,opt_anchor){var sy=opt_sy;if(sy===undefined)sy=sx;var anchor=opt_anchor;if(!anchor)anchor=ol.extent.getCenter(this.getExtent());var flatCoordinates=this.getFlatCoordinates();if(flatCoordinates){var stride=this.getStride();ol.geom.flat.transform.scale(flatCoordinates,0,flatCoordinates.length,stride,sx,sy,anchor,flatCoordinates);this.changed()}};
ol.geom.SimpleGeometry.prototype.translate=function(deltaX,deltaY){var flatCoordinates=this.getFlatCoordinates();if(flatCoordinates){var stride=this.getStride();ol.geom.flat.transform.translate(flatCoordinates,0,flatCoordinates.length,stride,deltaX,deltaY,flatCoordinates);this.changed()}};
ol.geom.SimpleGeometry.transform2D=function(simpleGeometry,transform,opt_dest){var flatCoordinates=simpleGeometry.getFlatCoordinates();if(!flatCoordinates)return null;else{var stride=simpleGeometry.getStride();return ol.geom.flat.transform.transform2D(flatCoordinates,0,flatCoordinates.length,stride,transform,opt_dest)}};goog.provide("ol.geom.flat.area");ol.geom.flat.area.linearRing=function(flatCoordinates,offset,end,stride){var twiceArea=0;var x1=flatCoordinates[end-stride];var y1=flatCoordinates[end-stride+1];for(;offset<end;offset+=stride){var x2=flatCoordinates[offset];var y2=flatCoordinates[offset+1];twiceArea+=y1*x2-x1*y2;x1=x2;y1=y2}return twiceArea/2};
ol.geom.flat.area.linearRings=function(flatCoordinates,offset,ends,stride){var area=0;var i,ii;for(i=0,ii=ends.length;i<ii;++i){var end=ends[i];area+=ol.geom.flat.area.linearRing(flatCoordinates,offset,end,stride);offset=end}return area};ol.geom.flat.area.linearRingss=function(flatCoordinates,offset,endss,stride){var area=0;var i,ii;for(i=0,ii=endss.length;i<ii;++i){var ends=endss[i];area+=ol.geom.flat.area.linearRings(flatCoordinates,offset,ends,stride);offset=ends[ends.length-1]}return area};goog.provide("ol.geom.flat.closest");goog.require("ol.math");
ol.geom.flat.closest.point=function(flatCoordinates,offset1,offset2,stride,x,y,closestPoint){var x1=flatCoordinates[offset1];var y1=flatCoordinates[offset1+1];var dx=flatCoordinates[offset2]-x1;var dy=flatCoordinates[offset2+1]-y1;var i,offset;if(dx===0&&dy===0)offset=offset1;else{var t=((x-x1)*dx+(y-y1)*dy)/(dx*dx+dy*dy);if(t>1)offset=offset2;else if(t>0){for(i=0;i<stride;++i)closestPoint[i]=ol.math.lerp(flatCoordinates[offset1+i],flatCoordinates[offset2+i],t);closestPoint.length=stride;return}else offset=
offset1}for(i=0;i<stride;++i)closestPoint[i]=flatCoordinates[offset+i];closestPoint.length=stride};ol.geom.flat.closest.getMaxSquaredDelta=function(flatCoordinates,offset,end,stride,maxSquaredDelta){var x1=flatCoordinates[offset];var y1=flatCoordinates[offset+1];for(offset+=stride;offset<end;offset+=stride){var x2=flatCoordinates[offset];var y2=flatCoordinates[offset+1];var squaredDelta=ol.math.squaredDistance(x1,y1,x2,y2);if(squaredDelta>maxSquaredDelta)maxSquaredDelta=squaredDelta;x1=x2;y1=y2}return maxSquaredDelta};
ol.geom.flat.closest.getsMaxSquaredDelta=function(flatCoordinates,offset,ends,stride,maxSquaredDelta){var i,ii;for(i=0,ii=ends.length;i<ii;++i){var end=ends[i];maxSquaredDelta=ol.geom.flat.closest.getMaxSquaredDelta(flatCoordinates,offset,end,stride,maxSquaredDelta);offset=end}return maxSquaredDelta};
ol.geom.flat.closest.getssMaxSquaredDelta=function(flatCoordinates,offset,endss,stride,maxSquaredDelta){var i,ii;for(i=0,ii=endss.length;i<ii;++i){var ends=endss[i];maxSquaredDelta=ol.geom.flat.closest.getsMaxSquaredDelta(flatCoordinates,offset,ends,stride,maxSquaredDelta);offset=ends[ends.length-1]}return maxSquaredDelta};
ol.geom.flat.closest.getClosestPoint=function(flatCoordinates,offset,end,stride,maxDelta,isRing,x,y,closestPoint,minSquaredDistance,opt_tmpPoint){if(offset==end)return minSquaredDistance;var i,squaredDistance;if(maxDelta===0){squaredDistance=ol.math.squaredDistance(x,y,flatCoordinates[offset],flatCoordinates[offset+1]);if(squaredDistance<minSquaredDistance){for(i=0;i<stride;++i)closestPoint[i]=flatCoordinates[offset+i];closestPoint.length=stride;return squaredDistance}else return minSquaredDistance}var tmpPoint=
opt_tmpPoint?opt_tmpPoint:[NaN,NaN];var index=offset+stride;while(index<end){ol.geom.flat.closest.point(flatCoordinates,index-stride,index,stride,x,y,tmpPoint);squaredDistance=ol.math.squaredDistance(x,y,tmpPoint[0],tmpPoint[1]);if(squaredDistance<minSquaredDistance){minSquaredDistance=squaredDistance;for(i=0;i<stride;++i)closestPoint[i]=tmpPoint[i];closestPoint.length=stride;index+=stride}else index+=stride*Math.max((Math.sqrt(squaredDistance)-Math.sqrt(minSquaredDistance))/maxDelta|0,1)}if(isRing){ol.geom.flat.closest.point(flatCoordinates,
end-stride,offset,stride,x,y,tmpPoint);squaredDistance=ol.math.squaredDistance(x,y,tmpPoint[0],tmpPoint[1]);if(squaredDistance<minSquaredDistance){minSquaredDistance=squaredDistance;for(i=0;i<stride;++i)closestPoint[i]=tmpPoint[i];closestPoint.length=stride}}return minSquaredDistance};
ol.geom.flat.closest.getsClosestPoint=function(flatCoordinates,offset,ends,stride,maxDelta,isRing,x,y,closestPoint,minSquaredDistance,opt_tmpPoint){var tmpPoint=opt_tmpPoint?opt_tmpPoint:[NaN,NaN];var i,ii;for(i=0,ii=ends.length;i<ii;++i){var end=ends[i];minSquaredDistance=ol.geom.flat.closest.getClosestPoint(flatCoordinates,offset,end,stride,maxDelta,isRing,x,y,closestPoint,minSquaredDistance,tmpPoint);offset=end}return minSquaredDistance};
ol.geom.flat.closest.getssClosestPoint=function(flatCoordinates,offset,endss,stride,maxDelta,isRing,x,y,closestPoint,minSquaredDistance,opt_tmpPoint){var tmpPoint=opt_tmpPoint?opt_tmpPoint:[NaN,NaN];var i,ii;for(i=0,ii=endss.length;i<ii;++i){var ends=endss[i];minSquaredDistance=ol.geom.flat.closest.getsClosestPoint(flatCoordinates,offset,ends,stride,maxDelta,isRing,x,y,closestPoint,minSquaredDistance,tmpPoint);offset=ends[ends.length-1]}return minSquaredDistance};goog.provide("ol.geom.flat.deflate");ol.geom.flat.deflate.coordinate=function(flatCoordinates,offset,coordinate,stride){var i,ii;for(i=0,ii=coordinate.length;i<ii;++i)flatCoordinates[offset++]=coordinate[i];return offset};ol.geom.flat.deflate.coordinates=function(flatCoordinates,offset,coordinates,stride){var i,ii;for(i=0,ii=coordinates.length;i<ii;++i){var coordinate=coordinates[i];var j;for(j=0;j<stride;++j)flatCoordinates[offset++]=coordinate[j]}return offset};
ol.geom.flat.deflate.coordinatess=function(flatCoordinates,offset,coordinatess,stride,opt_ends){var ends=opt_ends?opt_ends:[];var i=0;var j,jj;for(j=0,jj=coordinatess.length;j<jj;++j){var end=ol.geom.flat.deflate.coordinates(flatCoordinates,offset,coordinatess[j],stride);ends[i++]=end;offset=end}ends.length=i;return ends};
ol.geom.flat.deflate.coordinatesss=function(flatCoordinates,offset,coordinatesss,stride,opt_endss){var endss=opt_endss?opt_endss:[];var i=0;var j,jj;for(j=0,jj=coordinatesss.length;j<jj;++j){var ends=ol.geom.flat.deflate.coordinatess(flatCoordinates,offset,coordinatesss[j],stride,endss[i]);endss[i++]=ends;offset=ends[ends.length-1]}endss.length=i;return endss};goog.provide("ol.geom.flat.inflate");ol.geom.flat.inflate.coordinates=function(flatCoordinates,offset,end,stride,opt_coordinates){var coordinates=opt_coordinates!==undefined?opt_coordinates:[];var i=0;var j;for(j=offset;j<end;j+=stride)coordinates[i++]=flatCoordinates.slice(j,j+stride);coordinates.length=i;return coordinates};
ol.geom.flat.inflate.coordinatess=function(flatCoordinates,offset,ends,stride,opt_coordinatess){var coordinatess=opt_coordinatess!==undefined?opt_coordinatess:[];var i=0;var j,jj;for(j=0,jj=ends.length;j<jj;++j){var end=ends[j];coordinatess[i++]=ol.geom.flat.inflate.coordinates(flatCoordinates,offset,end,stride,coordinatess[i]);offset=end}coordinatess.length=i;return coordinatess};
ol.geom.flat.inflate.coordinatesss=function(flatCoordinates,offset,endss,stride,opt_coordinatesss){var coordinatesss=opt_coordinatesss!==undefined?opt_coordinatesss:[];var i=0;var j,jj;for(j=0,jj=endss.length;j<jj;++j){var ends=endss[j];coordinatesss[i++]=ol.geom.flat.inflate.coordinatess(flatCoordinates,offset,ends,stride,coordinatesss[i]);offset=ends[ends.length-1]}coordinatesss.length=i;return coordinatesss};goog.provide("ol.geom.flat.simplify");goog.require("ol.math");
ol.geom.flat.simplify.lineString=function(flatCoordinates,offset,end,stride,squaredTolerance,highQuality,opt_simplifiedFlatCoordinates){var simplifiedFlatCoordinates=opt_simplifiedFlatCoordinates!==undefined?opt_simplifiedFlatCoordinates:[];if(!highQuality){end=ol.geom.flat.simplify.radialDistance(flatCoordinates,offset,end,stride,squaredTolerance,simplifiedFlatCoordinates,0);flatCoordinates=simplifiedFlatCoordinates;offset=0;stride=2}simplifiedFlatCoordinates.length=ol.geom.flat.simplify.douglasPeucker(flatCoordinates,
offset,end,stride,squaredTolerance,simplifiedFlatCoordinates,0);return simplifiedFlatCoordinates};
ol.geom.flat.simplify.douglasPeucker=function(flatCoordinates,offset,end,stride,squaredTolerance,simplifiedFlatCoordinates,simplifiedOffset){var n=(end-offset)/stride;if(n<3){for(;offset<end;offset+=stride){simplifiedFlatCoordinates[simplifiedOffset++]=flatCoordinates[offset];simplifiedFlatCoordinates[simplifiedOffset++]=flatCoordinates[offset+1]}return simplifiedOffset}var markers=new Array(n);markers[0]=1;markers[n-1]=1;var stack=[offset,end-stride];var index=0;var i;while(stack.length>0){var last=
stack.pop();var first=stack.pop();var maxSquaredDistance=0;var x1=flatCoordinates[first];var y1=flatCoordinates[first+1];var x2=flatCoordinates[last];var y2=flatCoordinates[last+1];for(i=first+stride;i<last;i+=stride){var x=flatCoordinates[i];var y=flatCoordinates[i+1];var squaredDistance=ol.math.squaredSegmentDistance(x,y,x1,y1,x2,y2);if(squaredDistance>maxSquaredDistance){index=i;maxSquaredDistance=squaredDistance}}if(maxSquaredDistance>squaredTolerance){markers[(index-offset)/stride]=1;if(first+
stride<index)stack.push(first,index);if(index+stride<last)stack.push(index,last)}}for(i=0;i<n;++i)if(markers[i]){simplifiedFlatCoordinates[simplifiedOffset++]=flatCoordinates[offset+i*stride];simplifiedFlatCoordinates[simplifiedOffset++]=flatCoordinates[offset+i*stride+1]}return simplifiedOffset};
ol.geom.flat.simplify.douglasPeuckers=function(flatCoordinates,offset,ends,stride,squaredTolerance,simplifiedFlatCoordinates,simplifiedOffset,simplifiedEnds){var i,ii;for(i=0,ii=ends.length;i<ii;++i){var end=ends[i];simplifiedOffset=ol.geom.flat.simplify.douglasPeucker(flatCoordinates,offset,end,stride,squaredTolerance,simplifiedFlatCoordinates,simplifiedOffset);simplifiedEnds.push(simplifiedOffset);offset=end}return simplifiedOffset};
ol.geom.flat.simplify.douglasPeuckerss=function(flatCoordinates,offset,endss,stride,squaredTolerance,simplifiedFlatCoordinates,simplifiedOffset,simplifiedEndss){var i,ii;for(i=0,ii=endss.length;i<ii;++i){var ends=endss[i];var simplifiedEnds=[];simplifiedOffset=ol.geom.flat.simplify.douglasPeuckers(flatCoordinates,offset,ends,stride,squaredTolerance,simplifiedFlatCoordinates,simplifiedOffset,simplifiedEnds);simplifiedEndss.push(simplifiedEnds);offset=ends[ends.length-1]}return simplifiedOffset};
ol.geom.flat.simplify.radialDistance=function(flatCoordinates,offset,end,stride,squaredTolerance,simplifiedFlatCoordinates,simplifiedOffset){if(end<=offset+stride){for(;offset<end;offset+=stride){simplifiedFlatCoordinates[simplifiedOffset++]=flatCoordinates[offset];simplifiedFlatCoordinates[simplifiedOffset++]=flatCoordinates[offset+1]}return simplifiedOffset}var x1=flatCoordinates[offset];var y1=flatCoordinates[offset+1];simplifiedFlatCoordinates[simplifiedOffset++]=x1;simplifiedFlatCoordinates[simplifiedOffset++]=
y1;var x2=x1;var y2=y1;for(offset+=stride;offset<end;offset+=stride){x2=flatCoordinates[offset];y2=flatCoordinates[offset+1];if(ol.math.squaredDistance(x1,y1,x2,y2)>squaredTolerance){simplifiedFlatCoordinates[simplifiedOffset++]=x2;simplifiedFlatCoordinates[simplifiedOffset++]=y2;x1=x2;y1=y2}}if(x2!=x1||y2!=y1){simplifiedFlatCoordinates[simplifiedOffset++]=x2;simplifiedFlatCoordinates[simplifiedOffset++]=y2}return simplifiedOffset};
ol.geom.flat.simplify.snap=function(value,tolerance){return tolerance*Math.round(value/tolerance)};
ol.geom.flat.simplify.quantize=function(flatCoordinates,offset,end,stride,tolerance,simplifiedFlatCoordinates,simplifiedOffset){if(offset==end)return simplifiedOffset;var x1=ol.geom.flat.simplify.snap(flatCoordinates[offset],tolerance);var y1=ol.geom.flat.simplify.snap(flatCoordinates[offset+1],tolerance);offset+=stride;simplifiedFlatCoordinates[simplifiedOffset++]=x1;simplifiedFlatCoordinates[simplifiedOffset++]=y1;var x2,y2;do{x2=ol.geom.flat.simplify.snap(flatCoordinates[offset],tolerance);y2=
ol.geom.flat.simplify.snap(flatCoordinates[offset+1],tolerance);offset+=stride;if(offset==end){simplifiedFlatCoordinates[simplifiedOffset++]=x2;simplifiedFlatCoordinates[simplifiedOffset++]=y2;return simplifiedOffset}}while(x2==x1&&y2==y1);while(offset<end){var x3,y3;x3=ol.geom.flat.simplify.snap(flatCoordinates[offset],tolerance);y3=ol.geom.flat.simplify.snap(flatCoordinates[offset+1],tolerance);offset+=stride;if(x3==x2&&y3==y2)continue;var dx1=x2-x1;var dy1=y2-y1;var dx2=x3-x1;var dy2=y3-y1;if(dx1*
dy2==dy1*dx2&&(dx1<0&&dx2<dx1||dx1==dx2||dx1>0&&dx2>dx1)&&(dy1<0&&dy2<dy1||dy1==dy2||dy1>0&&dy2>dy1)){x2=x3;y2=y3;continue}simplifiedFlatCoordinates[simplifiedOffset++]=x2;simplifiedFlatCoordinates[simplifiedOffset++]=y2;x1=x2;y1=y2;x2=x3;y2=y3}simplifiedFlatCoordinates[simplifiedOffset++]=x2;simplifiedFlatCoordinates[simplifiedOffset++]=y2;return simplifiedOffset};
ol.geom.flat.simplify.quantizes=function(flatCoordinates,offset,ends,stride,tolerance,simplifiedFlatCoordinates,simplifiedOffset,simplifiedEnds){var i,ii;for(i=0,ii=ends.length;i<ii;++i){var end=ends[i];simplifiedOffset=ol.geom.flat.simplify.quantize(flatCoordinates,offset,end,stride,tolerance,simplifiedFlatCoordinates,simplifiedOffset);simplifiedEnds.push(simplifiedOffset);offset=end}return simplifiedOffset};
ol.geom.flat.simplify.quantizess=function(flatCoordinates,offset,endss,stride,tolerance,simplifiedFlatCoordinates,simplifiedOffset,simplifiedEndss){var i,ii;for(i=0,ii=endss.length;i<ii;++i){var ends=endss[i];var simplifiedEnds=[];simplifiedOffset=ol.geom.flat.simplify.quantizes(flatCoordinates,offset,ends,stride,tolerance,simplifiedFlatCoordinates,simplifiedOffset,simplifiedEnds);simplifiedEndss.push(simplifiedEnds);offset=ends[ends.length-1]}return simplifiedOffset};goog.provide("ol.geom.LinearRing");goog.require("ol");goog.require("ol.extent");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.GeometryType");goog.require("ol.geom.SimpleGeometry");goog.require("ol.geom.flat.area");goog.require("ol.geom.flat.closest");goog.require("ol.geom.flat.deflate");goog.require("ol.geom.flat.inflate");goog.require("ol.geom.flat.simplify");
ol.geom.LinearRing=function(coordinates,opt_layout){ol.geom.SimpleGeometry.call(this);this.maxDelta_=-1;this.maxDeltaRevision_=-1;this.setCoordinates(coordinates,opt_layout)};ol.inherits(ol.geom.LinearRing,ol.geom.SimpleGeometry);ol.geom.LinearRing.prototype.clone=function(){var linearRing=new ol.geom.LinearRing(null);linearRing.setFlatCoordinates(this.layout,this.flatCoordinates.slice());return linearRing};
ol.geom.LinearRing.prototype.closestPointXY=function(x,y,closestPoint,minSquaredDistance){if(minSquaredDistance<ol.extent.closestSquaredDistanceXY(this.getExtent(),x,y))return minSquaredDistance;if(this.maxDeltaRevision_!=this.getRevision()){this.maxDelta_=Math.sqrt(ol.geom.flat.closest.getMaxSquaredDelta(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,0));this.maxDeltaRevision_=this.getRevision()}return ol.geom.flat.closest.getClosestPoint(this.flatCoordinates,0,this.flatCoordinates.length,
this.stride,this.maxDelta_,true,x,y,closestPoint,minSquaredDistance)};ol.geom.LinearRing.prototype.getArea=function(){return ol.geom.flat.area.linearRing(this.flatCoordinates,0,this.flatCoordinates.length,this.stride)};ol.geom.LinearRing.prototype.getCoordinates=function(){return ol.geom.flat.inflate.coordinates(this.flatCoordinates,0,this.flatCoordinates.length,this.stride)};
ol.geom.LinearRing.prototype.getSimplifiedGeometryInternal=function(squaredTolerance){var simplifiedFlatCoordinates=[];simplifiedFlatCoordinates.length=ol.geom.flat.simplify.douglasPeucker(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,squaredTolerance,simplifiedFlatCoordinates,0);var simplifiedLinearRing=new ol.geom.LinearRing(null);simplifiedLinearRing.setFlatCoordinates(ol.geom.GeometryLayout.XY,simplifiedFlatCoordinates);return simplifiedLinearRing};
ol.geom.LinearRing.prototype.getType=function(){return ol.geom.GeometryType.LINEAR_RING};ol.geom.LinearRing.prototype.intersectsExtent=function(extent){};
ol.geom.LinearRing.prototype.setCoordinates=function(coordinates,opt_layout){if(!coordinates)this.setFlatCoordinates(ol.geom.GeometryLayout.XY,null);else{this.setLayout(opt_layout,coordinates,1);if(!this.flatCoordinates)this.flatCoordinates=[];this.flatCoordinates.length=ol.geom.flat.deflate.coordinates(this.flatCoordinates,0,coordinates,this.stride);this.changed()}};
ol.geom.LinearRing.prototype.setFlatCoordinates=function(layout,flatCoordinates){this.setFlatCoordinatesInternal(layout,flatCoordinates);this.changed()};goog.provide("ol.geom.Point");goog.require("ol");goog.require("ol.extent");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.GeometryType");goog.require("ol.geom.SimpleGeometry");goog.require("ol.geom.flat.deflate");goog.require("ol.math");ol.geom.Point=function(coordinates,opt_layout){ol.geom.SimpleGeometry.call(this);this.setCoordinates(coordinates,opt_layout)};ol.inherits(ol.geom.Point,ol.geom.SimpleGeometry);
ol.geom.Point.prototype.clone=function(){var point=new ol.geom.Point(null);point.setFlatCoordinates(this.layout,this.flatCoordinates.slice());return point};
ol.geom.Point.prototype.closestPointXY=function(x,y,closestPoint,minSquaredDistance){var flatCoordinates=this.flatCoordinates;var squaredDistance=ol.math.squaredDistance(x,y,flatCoordinates[0],flatCoordinates[1]);if(squaredDistance<minSquaredDistance){var stride=this.stride;var i;for(i=0;i<stride;++i)closestPoint[i]=flatCoordinates[i];closestPoint.length=stride;return squaredDistance}else return minSquaredDistance};ol.geom.Point.prototype.getCoordinates=function(){return!this.flatCoordinates?[]:this.flatCoordinates.slice()};
ol.geom.Point.prototype.computeExtent=function(extent){return ol.extent.createOrUpdateFromCoordinate(this.flatCoordinates,extent)};ol.geom.Point.prototype.getType=function(){return ol.geom.GeometryType.POINT};ol.geom.Point.prototype.intersectsExtent=function(extent){return ol.extent.containsXY(extent,this.flatCoordinates[0],this.flatCoordinates[1])};
ol.geom.Point.prototype.setCoordinates=function(coordinates,opt_layout){if(!coordinates)this.setFlatCoordinates(ol.geom.GeometryLayout.XY,null);else{this.setLayout(opt_layout,coordinates,0);if(!this.flatCoordinates)this.flatCoordinates=[];this.flatCoordinates.length=ol.geom.flat.deflate.coordinate(this.flatCoordinates,0,coordinates,this.stride);this.changed()}};ol.geom.Point.prototype.setFlatCoordinates=function(layout,flatCoordinates){this.setFlatCoordinatesInternal(layout,flatCoordinates);this.changed()};goog.provide("ol.geom.flat.contains");goog.require("ol.extent");ol.geom.flat.contains.linearRingContainsExtent=function(flatCoordinates,offset,end,stride,extent){var outside=ol.extent.forEachCorner(extent,function(coordinate){return!ol.geom.flat.contains.linearRingContainsXY(flatCoordinates,offset,end,stride,coordinate[0],coordinate[1])});return!outside};
ol.geom.flat.contains.linearRingContainsXY=function(flatCoordinates,offset,end,stride,x,y){var wn=0;var x1=flatCoordinates[end-stride];var y1=flatCoordinates[end-stride+1];for(;offset<end;offset+=stride){var x2=flatCoordinates[offset];var y2=flatCoordinates[offset+1];if(y1<=y){if(y2>y&&(x2-x1)*(y-y1)-(x-x1)*(y2-y1)>0)wn++}else if(y2<=y&&(x2-x1)*(y-y1)-(x-x1)*(y2-y1)<0)wn--;x1=x2;y1=y2}return wn!==0};
ol.geom.flat.contains.linearRingsContainsXY=function(flatCoordinates,offset,ends,stride,x,y){if(ends.length===0)return false;if(!ol.geom.flat.contains.linearRingContainsXY(flatCoordinates,offset,ends[0],stride,x,y))return false;var i,ii;for(i=1,ii=ends.length;i<ii;++i)if(ol.geom.flat.contains.linearRingContainsXY(flatCoordinates,ends[i-1],ends[i],stride,x,y))return false;return true};
ol.geom.flat.contains.linearRingssContainsXY=function(flatCoordinates,offset,endss,stride,x,y){if(endss.length===0)return false;var i,ii;for(i=0,ii=endss.length;i<ii;++i){var ends=endss[i];if(ol.geom.flat.contains.linearRingsContainsXY(flatCoordinates,offset,ends,stride,x,y))return true;offset=ends[ends.length-1]}return false};goog.provide("ol.geom.flat.interiorpoint");goog.require("ol.array");goog.require("ol.geom.flat.contains");
ol.geom.flat.interiorpoint.linearRings=function(flatCoordinates,offset,ends,stride,flatCenters,flatCentersOffset,opt_dest){var i,ii,x,x1,x2,y1,y2;var y=flatCenters[flatCentersOffset+1];var intersections=[];for(var r=0,rr=ends.length;r<rr;++r){var end=ends[r];x1=flatCoordinates[end-stride];y1=flatCoordinates[end-stride+1];for(i=offset;i<end;i+=stride){x2=flatCoordinates[i];y2=flatCoordinates[i+1];if(y<=y1&&y2<=y||y1<=y&&y<=y2){x=(y-y1)/(y2-y1)*(x2-x1)+x1;intersections.push(x)}x1=x2;y1=y2}}var pointX=
NaN;var maxSegmentLength=-Infinity;intersections.sort(ol.array.numberSafeCompareFunction);x1=intersections[0];for(i=1,ii=intersections.length;i<ii;++i){x2=intersections[i];var segmentLength=Math.abs(x2-x1);if(segmentLength>maxSegmentLength){x=(x1+x2)/2;if(ol.geom.flat.contains.linearRingsContainsXY(flatCoordinates,offset,ends,stride,x,y)){pointX=x;maxSegmentLength=segmentLength}}x1=x2}if(isNaN(pointX))pointX=flatCenters[flatCentersOffset];if(opt_dest){opt_dest.push(pointX,y,maxSegmentLength);return opt_dest}else return[pointX,
y,maxSegmentLength]};ol.geom.flat.interiorpoint.linearRingss=function(flatCoordinates,offset,endss,stride,flatCenters){var interiorPoints=[];var i,ii;for(i=0,ii=endss.length;i<ii;++i){var ends=endss[i];interiorPoints=ol.geom.flat.interiorpoint.linearRings(flatCoordinates,offset,ends,stride,flatCenters,2*i,interiorPoints);offset=ends[ends.length-1]}return interiorPoints};goog.provide("ol.geom.flat.segments");ol.geom.flat.segments.forEach=function(flatCoordinates,offset,end,stride,callback,opt_this){var point1=[flatCoordinates[offset],flatCoordinates[offset+1]];var point2=[];var ret;for(;offset+stride<end;offset+=stride){point2[0]=flatCoordinates[offset+stride];point2[1]=flatCoordinates[offset+stride+1];ret=callback.call(opt_this,point1,point2);if(ret)return ret;point1[0]=point2[0];point1[1]=point2[1]}return false};goog.provide("ol.geom.flat.intersectsextent");goog.require("ol.extent");goog.require("ol.geom.flat.contains");goog.require("ol.geom.flat.segments");
ol.geom.flat.intersectsextent.lineString=function(flatCoordinates,offset,end,stride,extent){var coordinatesExtent=ol.extent.extendFlatCoordinates(ol.extent.createEmpty(),flatCoordinates,offset,end,stride);if(!ol.extent.intersects(extent,coordinatesExtent))return false;if(ol.extent.containsExtent(extent,coordinatesExtent))return true;if(coordinatesExtent[0]>=extent[0]&&coordinatesExtent[2]<=extent[2])return true;if(coordinatesExtent[1]>=extent[1]&&coordinatesExtent[3]<=extent[3])return true;return ol.geom.flat.segments.forEach(flatCoordinates,
offset,end,stride,function(point1,point2){return ol.extent.intersectsSegment(extent,point1,point2)})};ol.geom.flat.intersectsextent.lineStrings=function(flatCoordinates,offset,ends,stride,extent){var i,ii;for(i=0,ii=ends.length;i<ii;++i){if(ol.geom.flat.intersectsextent.lineString(flatCoordinates,offset,ends[i],stride,extent))return true;offset=ends[i]}return false};
ol.geom.flat.intersectsextent.linearRing=function(flatCoordinates,offset,end,stride,extent){if(ol.geom.flat.intersectsextent.lineString(flatCoordinates,offset,end,stride,extent))return true;if(ol.geom.flat.contains.linearRingContainsXY(flatCoordinates,offset,end,stride,extent[0],extent[1]))return true;if(ol.geom.flat.contains.linearRingContainsXY(flatCoordinates,offset,end,stride,extent[0],extent[3]))return true;if(ol.geom.flat.contains.linearRingContainsXY(flatCoordinates,offset,end,stride,extent[2],
extent[1]))return true;if(ol.geom.flat.contains.linearRingContainsXY(flatCoordinates,offset,end,stride,extent[2],extent[3]))return true;return false};
ol.geom.flat.intersectsextent.linearRings=function(flatCoordinates,offset,ends,stride,extent){if(!ol.geom.flat.intersectsextent.linearRing(flatCoordinates,offset,ends[0],stride,extent))return false;if(ends.length===1)return true;var i,ii;for(i=1,ii=ends.length;i<ii;++i)if(ol.geom.flat.contains.linearRingContainsExtent(flatCoordinates,ends[i-1],ends[i],stride,extent))return false;return true};
ol.geom.flat.intersectsextent.linearRingss=function(flatCoordinates,offset,endss,stride,extent){var i,ii;for(i=0,ii=endss.length;i<ii;++i){var ends=endss[i];if(ol.geom.flat.intersectsextent.linearRings(flatCoordinates,offset,ends,stride,extent))return true;offset=ends[ends.length-1]}return false};goog.provide("ol.geom.flat.reverse");ol.geom.flat.reverse.coordinates=function(flatCoordinates,offset,end,stride){while(offset<end-stride){var i;for(i=0;i<stride;++i){var tmp=flatCoordinates[offset+i];flatCoordinates[offset+i]=flatCoordinates[end-stride+i];flatCoordinates[end-stride+i]=tmp}offset+=stride;end-=stride}};goog.provide("ol.geom.flat.orient");goog.require("ol.geom.flat.reverse");ol.geom.flat.orient.linearRingIsClockwise=function(flatCoordinates,offset,end,stride){var edge=0;var x1=flatCoordinates[end-stride];var y1=flatCoordinates[end-stride+1];for(;offset<end;offset+=stride){var x2=flatCoordinates[offset];var y2=flatCoordinates[offset+1];edge+=(x2-x1)*(y2+y1);x1=x2;y1=y2}return edge>0};
ol.geom.flat.orient.linearRingsAreOriented=function(flatCoordinates,offset,ends,stride,opt_right){var right=opt_right!==undefined?opt_right:false;var i,ii;for(i=0,ii=ends.length;i<ii;++i){var end=ends[i];var isClockwise=ol.geom.flat.orient.linearRingIsClockwise(flatCoordinates,offset,end,stride);if(i===0){if(right&&isClockwise||!right&&!isClockwise)return false}else if(right&&!isClockwise||!right&&isClockwise)return false;offset=end}return true};
ol.geom.flat.orient.linearRingssAreOriented=function(flatCoordinates,offset,endss,stride,opt_right){var i,ii;for(i=0,ii=endss.length;i<ii;++i)if(!ol.geom.flat.orient.linearRingsAreOriented(flatCoordinates,offset,endss[i],stride,opt_right))return false;return true};
ol.geom.flat.orient.orientLinearRings=function(flatCoordinates,offset,ends,stride,opt_right){var right=opt_right!==undefined?opt_right:false;var i,ii;for(i=0,ii=ends.length;i<ii;++i){var end=ends[i];var isClockwise=ol.geom.flat.orient.linearRingIsClockwise(flatCoordinates,offset,end,stride);var reverse=i===0?right&&isClockwise||!right&&!isClockwise:right&&!isClockwise||!right&&isClockwise;if(reverse)ol.geom.flat.reverse.coordinates(flatCoordinates,offset,end,stride);offset=end}return offset};
ol.geom.flat.orient.orientLinearRingss=function(flatCoordinates,offset,endss,stride,opt_right){var i,ii;for(i=0,ii=endss.length;i<ii;++i)offset=ol.geom.flat.orient.orientLinearRings(flatCoordinates,offset,endss[i],stride,opt_right);return offset};goog.provide("ol.geom.Polygon");goog.require("ol");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.GeometryType");goog.require("ol.geom.LinearRing");goog.require("ol.geom.Point");goog.require("ol.geom.SimpleGeometry");goog.require("ol.geom.flat.area");goog.require("ol.geom.flat.closest");goog.require("ol.geom.flat.contains");goog.require("ol.geom.flat.deflate");goog.require("ol.geom.flat.inflate");goog.require("ol.geom.flat.interiorpoint");
goog.require("ol.geom.flat.intersectsextent");goog.require("ol.geom.flat.orient");goog.require("ol.geom.flat.simplify");goog.require("ol.math");ol.geom.Polygon=function(coordinates,opt_layout){ol.geom.SimpleGeometry.call(this);this.ends_=[];this.flatInteriorPointRevision_=-1;this.flatInteriorPoint_=null;this.maxDelta_=-1;this.maxDeltaRevision_=-1;this.orientedRevision_=-1;this.orientedFlatCoordinates_=null;this.setCoordinates(coordinates,opt_layout)};ol.inherits(ol.geom.Polygon,ol.geom.SimpleGeometry);
ol.geom.Polygon.prototype.appendLinearRing=function(linearRing){if(!this.flatCoordinates)this.flatCoordinates=linearRing.getFlatCoordinates().slice();else ol.array.extend(this.flatCoordinates,linearRing.getFlatCoordinates());this.ends_.push(this.flatCoordinates.length);this.changed()};ol.geom.Polygon.prototype.clone=function(){var polygon=new ol.geom.Polygon(null);polygon.setFlatCoordinates(this.layout,this.flatCoordinates.slice(),this.ends_.slice());return polygon};
ol.geom.Polygon.prototype.closestPointXY=function(x,y,closestPoint,minSquaredDistance){if(minSquaredDistance<ol.extent.closestSquaredDistanceXY(this.getExtent(),x,y))return minSquaredDistance;if(this.maxDeltaRevision_!=this.getRevision()){this.maxDelta_=Math.sqrt(ol.geom.flat.closest.getsMaxSquaredDelta(this.flatCoordinates,0,this.ends_,this.stride,0));this.maxDeltaRevision_=this.getRevision()}return ol.geom.flat.closest.getsClosestPoint(this.flatCoordinates,0,this.ends_,this.stride,this.maxDelta_,
true,x,y,closestPoint,minSquaredDistance)};ol.geom.Polygon.prototype.containsXY=function(x,y){return ol.geom.flat.contains.linearRingsContainsXY(this.getOrientedFlatCoordinates(),0,this.ends_,this.stride,x,y)};ol.geom.Polygon.prototype.getArea=function(){return ol.geom.flat.area.linearRings(this.getOrientedFlatCoordinates(),0,this.ends_,this.stride)};
ol.geom.Polygon.prototype.getCoordinates=function(opt_right){var flatCoordinates;if(opt_right!==undefined){flatCoordinates=this.getOrientedFlatCoordinates().slice();ol.geom.flat.orient.orientLinearRings(flatCoordinates,0,this.ends_,this.stride,opt_right)}else flatCoordinates=this.flatCoordinates;return ol.geom.flat.inflate.coordinatess(flatCoordinates,0,this.ends_,this.stride)};ol.geom.Polygon.prototype.getEnds=function(){return this.ends_};
ol.geom.Polygon.prototype.getFlatInteriorPoint=function(){if(this.flatInteriorPointRevision_!=this.getRevision()){var flatCenter=ol.extent.getCenter(this.getExtent());this.flatInteriorPoint_=ol.geom.flat.interiorpoint.linearRings(this.getOrientedFlatCoordinates(),0,this.ends_,this.stride,flatCenter,0);this.flatInteriorPointRevision_=this.getRevision()}return this.flatInteriorPoint_};ol.geom.Polygon.prototype.getInteriorPoint=function(){return new ol.geom.Point(this.getFlatInteriorPoint(),ol.geom.GeometryLayout.XYM)};
ol.geom.Polygon.prototype.getLinearRingCount=function(){return this.ends_.length};ol.geom.Polygon.prototype.getLinearRing=function(index){if(index<0||this.ends_.length<=index)return null;var linearRing=new ol.geom.LinearRing(null);linearRing.setFlatCoordinates(this.layout,this.flatCoordinates.slice(index===0?0:this.ends_[index-1],this.ends_[index]));return linearRing};
ol.geom.Polygon.prototype.getLinearRings=function(){var layout=this.layout;var flatCoordinates=this.flatCoordinates;var ends=this.ends_;var linearRings=[];var offset=0;var i,ii;for(i=0,ii=ends.length;i<ii;++i){var end=ends[i];var linearRing=new ol.geom.LinearRing(null);linearRing.setFlatCoordinates(layout,flatCoordinates.slice(offset,end));linearRings.push(linearRing);offset=end}return linearRings};
ol.geom.Polygon.prototype.getOrientedFlatCoordinates=function(){if(this.orientedRevision_!=this.getRevision()){var flatCoordinates=this.flatCoordinates;if(ol.geom.flat.orient.linearRingsAreOriented(flatCoordinates,0,this.ends_,this.stride))this.orientedFlatCoordinates_=flatCoordinates;else{this.orientedFlatCoordinates_=flatCoordinates.slice();this.orientedFlatCoordinates_.length=ol.geom.flat.orient.orientLinearRings(this.orientedFlatCoordinates_,0,this.ends_,this.stride)}this.orientedRevision_=this.getRevision()}return this.orientedFlatCoordinates_};
ol.geom.Polygon.prototype.getSimplifiedGeometryInternal=function(squaredTolerance){var simplifiedFlatCoordinates=[];var simplifiedEnds=[];simplifiedFlatCoordinates.length=ol.geom.flat.simplify.quantizes(this.flatCoordinates,0,this.ends_,this.stride,Math.sqrt(squaredTolerance),simplifiedFlatCoordinates,0,simplifiedEnds);var simplifiedPolygon=new ol.geom.Polygon(null);simplifiedPolygon.setFlatCoordinates(ol.geom.GeometryLayout.XY,simplifiedFlatCoordinates,simplifiedEnds);return simplifiedPolygon};
ol.geom.Polygon.prototype.getType=function(){return ol.geom.GeometryType.POLYGON};ol.geom.Polygon.prototype.intersectsExtent=function(extent){return ol.geom.flat.intersectsextent.linearRings(this.getOrientedFlatCoordinates(),0,this.ends_,this.stride,extent)};
ol.geom.Polygon.prototype.setCoordinates=function(coordinates,opt_layout){if(!coordinates)this.setFlatCoordinates(ol.geom.GeometryLayout.XY,null,this.ends_);else{this.setLayout(opt_layout,coordinates,2);if(!this.flatCoordinates)this.flatCoordinates=[];var ends=ol.geom.flat.deflate.coordinatess(this.flatCoordinates,0,coordinates,this.stride,this.ends_);this.flatCoordinates.length=ends.length===0?0:ends[ends.length-1];this.changed()}};
ol.geom.Polygon.prototype.setFlatCoordinates=function(layout,flatCoordinates,ends){this.setFlatCoordinatesInternal(layout,flatCoordinates);this.ends_=ends;this.changed()};
ol.geom.Polygon.circular=function(sphere,center,radius,opt_n){var n=opt_n?opt_n:32;var flatCoordinates=[];var i;for(i=0;i<n;++i)ol.array.extend(flatCoordinates,sphere.offset(center,radius,2*Math.PI*i/n));flatCoordinates.push(flatCoordinates[0],flatCoordinates[1]);var polygon=new ol.geom.Polygon(null);polygon.setFlatCoordinates(ol.geom.GeometryLayout.XY,flatCoordinates,[flatCoordinates.length]);return polygon};
ol.geom.Polygon.fromExtent=function(extent){var minX=extent[0];var minY=extent[1];var maxX=extent[2];var maxY=extent[3];var flatCoordinates=[minX,minY,minX,maxY,maxX,maxY,maxX,minY,minX,minY];var polygon=new ol.geom.Polygon(null);polygon.setFlatCoordinates(ol.geom.GeometryLayout.XY,flatCoordinates,[flatCoordinates.length]);return polygon};
ol.geom.Polygon.fromCircle=function(circle,opt_sides,opt_angle){var sides=opt_sides?opt_sides:32;var stride=circle.getStride();var layout=circle.getLayout();var polygon=new ol.geom.Polygon(null,layout);var arrayLength=stride*(sides+1);var flatCoordinates=new Array(arrayLength);for(var i=0;i<arrayLength;i++)flatCoordinates[i]=0;var ends=[flatCoordinates.length];polygon.setFlatCoordinates(layout,flatCoordinates,ends);ol.geom.Polygon.makeRegular(polygon,circle.getCenter(),circle.getRadius(),opt_angle);
return polygon};
ol.geom.Polygon.makeRegular=function(polygon,center,radius,opt_angle){var flatCoordinates=polygon.getFlatCoordinates();var layout=polygon.getLayout();var stride=polygon.getStride();var ends=polygon.getEnds();var sides=flatCoordinates.length/stride-1;var startAngle=opt_angle?opt_angle:0;var angle,offset;for(var i=0;i<=sides;++i){offset=i*stride;angle=startAngle+ol.math.modulo(i,sides)*2*Math.PI/sides;flatCoordinates[offset]=center[0]+radius*Math.cos(angle);flatCoordinates[offset+1]=center[1]+radius*
Math.sin(angle)}polygon.setFlatCoordinates(layout,flatCoordinates,ends)};goog.provide("ol.View");goog.require("ol");goog.require("ol.CenterConstraint");goog.require("ol.Object");goog.require("ol.ResolutionConstraint");goog.require("ol.RotationConstraint");goog.require("ol.ViewHint");goog.require("ol.ViewProperty");goog.require("ol.array");goog.require("ol.asserts");goog.require("ol.coordinate");goog.require("ol.easing");goog.require("ol.extent");goog.require("ol.geom.GeometryType");goog.require("ol.geom.Polygon");goog.require("ol.geom.SimpleGeometry");goog.require("ol.math");
goog.require("ol.obj");goog.require("ol.proj");goog.require("ol.proj.Units");ol.View=function(opt_options){ol.Object.call(this);var options=ol.obj.assign({},opt_options);this.hints_=[0,0];this.animations_=[];this.updateAnimationKey_;this.updateAnimations_=this.updateAnimations_.bind(this);this.projection_=ol.proj.createProjection(options.projection,"EPSG:3857");this.applyOptions_(options)};ol.inherits(ol.View,ol.Object);
ol.View.prototype.applyOptions_=function(options){var properties={};properties[ol.ViewProperty.CENTER]=options.center!==undefined?options.center:null;var resolutionConstraintInfo=ol.View.createResolutionConstraint_(options);this.maxResolution_=resolutionConstraintInfo.maxResolution;this.minResolution_=resolutionConstraintInfo.minResolution;this.zoomFactor_=resolutionConstraintInfo.zoomFactor;this.resolutions_=options.resolutions;this.minZoom_=resolutionConstraintInfo.minZoom;var centerConstraint=
ol.View.createCenterConstraint_(options);var resolutionConstraint=resolutionConstraintInfo.constraint;var rotationConstraint=ol.View.createRotationConstraint_(options);this.constraints_={center:centerConstraint,resolution:resolutionConstraint,rotation:rotationConstraint};if(options.resolution!==undefined)properties[ol.ViewProperty.RESOLUTION]=options.resolution;else if(options.zoom!==undefined){properties[ol.ViewProperty.RESOLUTION]=this.constrainResolution(this.maxResolution_,options.zoom-this.minZoom_);
if(this.resolutions_)properties[ol.ViewProperty.RESOLUTION]=ol.math.clamp(Number(this.getResolution()||properties[ol.ViewProperty.RESOLUTION]),this.minResolution_,this.maxResolution_)}properties[ol.ViewProperty.ROTATION]=options.rotation!==undefined?options.rotation:0;this.setProperties(properties);this.options_=options};
ol.View.prototype.getUpdatedOptions_=function(newOptions){var options=ol.obj.assign({},this.options_);if(options.resolution!==undefined)options.resolution=this.getResolution();else options.zoom=this.getZoom();options.center=this.getCenter();options.rotation=this.getRotation();return ol.obj.assign({},options,newOptions)};
ol.View.prototype.animate=function(var_args){var animationCount=arguments.length;var callback;if(animationCount>1&&typeof arguments[animationCount-1]==="function"){callback=arguments[animationCount-1];--animationCount}if(!this.isDef()){var state=arguments[animationCount-1];if(state.center)this.setCenter(state.center);if(state.zoom!==undefined)this.setZoom(state.zoom);if(state.rotation!==undefined)this.setRotation(state.rotation);if(callback)callback(true);return}var start=Date.now();var center=this.getCenter().slice();
var resolution=this.getResolution();var rotation=this.getRotation();var series=[];for(var i=0;i<animationCount;++i){var options=arguments[i];var animation={start:start,complete:false,anchor:options.anchor,duration:options.duration!==undefined?options.duration:1E3,easing:options.easing||ol.easing.inAndOut};if(options.center){animation.sourceCenter=center;animation.targetCenter=options.center;center=animation.targetCenter}if(options.zoom!==undefined){animation.sourceResolution=resolution;animation.targetResolution=
this.constrainResolution(this.maxResolution_,options.zoom-this.minZoom_,0);resolution=animation.targetResolution}else if(options.resolution){animation.sourceResolution=resolution;animation.targetResolution=options.resolution;resolution=animation.targetResolution}if(options.rotation!==undefined){animation.sourceRotation=rotation;var delta=ol.math.modulo(options.rotation-rotation+Math.PI,2*Math.PI)-Math.PI;animation.targetRotation=rotation+delta;rotation=animation.targetRotation}animation.callback=
callback;if(ol.View.isNoopAnimation(animation))animation.complete=true;else start+=animation.duration;series.push(animation)}this.animations_.push(series);this.setHint(ol.ViewHint.ANIMATING,1);this.updateAnimations_()};ol.View.prototype.getAnimating=function(){return this.hints_[ol.ViewHint.ANIMATING]>0};ol.View.prototype.getInteracting=function(){return this.hints_[ol.ViewHint.INTERACTING]>0};
ol.View.prototype.cancelAnimations=function(){this.setHint(ol.ViewHint.ANIMATING,-this.hints_[ol.ViewHint.ANIMATING]);for(var i=0,ii=this.animations_.length;i<ii;++i){var series=this.animations_[i];if(series[0].callback)series[0].callback(false)}this.animations_.length=0};
ol.View.prototype.updateAnimations_=function(){if(this.updateAnimationKey_!==undefined){cancelAnimationFrame(this.updateAnimationKey_);this.updateAnimationKey_=undefined}if(!this.getAnimating())return;var now=Date.now();var more=false;for(var i=this.animations_.length-1;i>=0;--i){var series=this.animations_[i];var seriesComplete=true;for(var j=0,jj=series.length;j<jj;++j){var animation=series[j];if(animation.complete)continue;var elapsed=now-animation.start;var fraction=animation.duration>0?elapsed/
animation.duration:1;if(fraction>=1){animation.complete=true;fraction=1}else seriesComplete=false;var progress=animation.easing(fraction);if(animation.sourceCenter){var x0=animation.sourceCenter[0];var y0=animation.sourceCenter[1];var x1=animation.targetCenter[0];var y1=animation.targetCenter[1];var x=x0+progress*(x1-x0);var y=y0+progress*(y1-y0);this.set(ol.ViewProperty.CENTER,[x,y])}if(animation.sourceResolution&&animation.targetResolution){var resolution=progress===1?animation.targetResolution:
animation.sourceResolution+progress*(animation.targetResolution-animation.sourceResolution);if(animation.anchor)this.set(ol.ViewProperty.CENTER,this.calculateCenterZoom(resolution,animation.anchor));this.set(ol.ViewProperty.RESOLUTION,resolution)}if(animation.sourceRotation!==undefined&&animation.targetRotation!==undefined){var rotation=progress===1?ol.math.modulo(animation.targetRotation+Math.PI,2*Math.PI)-Math.PI:animation.sourceRotation+progress*(animation.targetRotation-animation.sourceRotation);
if(animation.anchor)this.set(ol.ViewProperty.CENTER,this.calculateCenterRotate(rotation,animation.anchor));this.set(ol.ViewProperty.ROTATION,rotation)}more=true;if(!animation.complete)break}if(seriesComplete){this.animations_[i]=null;this.setHint(ol.ViewHint.ANIMATING,-1);var callback=series[0].callback;if(callback)callback(true)}}this.animations_=this.animations_.filter(Boolean);if(more&&this.updateAnimationKey_===undefined)this.updateAnimationKey_=requestAnimationFrame(this.updateAnimations_)};
ol.View.prototype.calculateCenterRotate=function(rotation,anchor){var center;var currentCenter=this.getCenter();if(currentCenter!==undefined){center=[currentCenter[0]-anchor[0],currentCenter[1]-anchor[1]];ol.coordinate.rotate(center,rotation-this.getRotation());ol.coordinate.add(center,anchor)}return center};
ol.View.prototype.calculateCenterZoom=function(resolution,anchor){var center;var currentCenter=this.getCenter();var currentResolution=this.getResolution();if(currentCenter!==undefined&&currentResolution!==undefined){var x=anchor[0]-resolution*(anchor[0]-currentCenter[0])/currentResolution;var y=anchor[1]-resolution*(anchor[1]-currentCenter[1])/currentResolution;center=[x,y]}return center};
ol.View.prototype.getSizeFromViewport_=function(){var size=[100,100];var selector='.ol-viewport[data-view="'+ol.getUid(this)+'"]';var element=document.querySelector(selector);if(element){var metrics=getComputedStyle(element);size[0]=parseInt(metrics.width,10);size[1]=parseInt(metrics.height,10)}return size};ol.View.prototype.constrainCenter=function(center){return this.constraints_.center(center)};
ol.View.prototype.constrainResolution=function(resolution,opt_delta,opt_direction){var delta=opt_delta||0;var direction=opt_direction||0;return this.constraints_.resolution(resolution,delta,direction)};ol.View.prototype.constrainRotation=function(rotation,opt_delta){var delta=opt_delta||0;return this.constraints_.rotation(rotation,delta)};ol.View.prototype.getCenter=function(){return this.get(ol.ViewProperty.CENTER)};ol.View.prototype.getConstraints=function(){return this.constraints_};
ol.View.prototype.getHints=function(opt_hints){if(opt_hints!==undefined){opt_hints[0]=this.hints_[0];opt_hints[1]=this.hints_[1];return opt_hints}else return this.hints_.slice()};
ol.View.prototype.calculateExtent=function(opt_size){var size=opt_size||this.getSizeFromViewport_();var center=this.getCenter();ol.asserts.assert(center,1);var resolution=this.getResolution();ol.asserts.assert(resolution!==undefined,2);var rotation=this.getRotation();ol.asserts.assert(rotation!==undefined,3);return ol.extent.getForViewAndSize(center,resolution,rotation,size)};ol.View.prototype.getMaxResolution=function(){return this.maxResolution_};ol.View.prototype.getMinResolution=function(){return this.minResolution_};
ol.View.prototype.getMaxZoom=function(){return this.getZoomForResolution(this.minResolution_)};ol.View.prototype.setMaxZoom=function(zoom){this.applyOptions_(this.getUpdatedOptions_({maxZoom:zoom}))};ol.View.prototype.getMinZoom=function(){return this.getZoomForResolution(this.maxResolution_)};ol.View.prototype.setMinZoom=function(zoom){this.applyOptions_(this.getUpdatedOptions_({minZoom:zoom}))};ol.View.prototype.getProjection=function(){return this.projection_};ol.View.prototype.getResolution=function(){return this.get(ol.ViewProperty.RESOLUTION)};
ol.View.prototype.getResolutions=function(){return this.resolutions_};ol.View.prototype.getResolutionForExtent=function(extent,opt_size){var size=opt_size||this.getSizeFromViewport_();var xResolution=ol.extent.getWidth(extent)/size[0];var yResolution=ol.extent.getHeight(extent)/size[1];return Math.max(xResolution,yResolution)};
ol.View.prototype.getResolutionForValueFunction=function(opt_power){var power=opt_power||2;var maxResolution=this.maxResolution_;var minResolution=this.minResolution_;var max=Math.log(maxResolution/minResolution)/Math.log(power);return function(value){var resolution=maxResolution/Math.pow(power,value*max);return resolution}};ol.View.prototype.getRotation=function(){return this.get(ol.ViewProperty.ROTATION)};
ol.View.prototype.getValueForResolutionFunction=function(opt_power){var power=opt_power||2;var maxResolution=this.maxResolution_;var minResolution=this.minResolution_;var max=Math.log(maxResolution/minResolution)/Math.log(power);return function(resolution){var value=Math.log(maxResolution/resolution)/Math.log(power)/max;return value}};
ol.View.prototype.getState=function(){var center=this.getCenter();var projection=this.getProjection();var resolution=this.getResolution();var rotation=this.getRotation();return{center:center.slice(),projection:projection!==undefined?projection:null,resolution:resolution,rotation:rotation,zoom:this.getZoom()}};ol.View.prototype.getZoom=function(){var zoom;var resolution=this.getResolution();if(resolution!==undefined)zoom=this.getZoomForResolution(resolution);return zoom};
ol.View.prototype.getZoomForResolution=function(resolution){var offset=this.minZoom_||0;var max,zoomFactor;if(this.resolutions_){var nearest=ol.array.linearFindNearest(this.resolutions_,resolution,1);offset=nearest;max=this.resolutions_[nearest];if(nearest==this.resolutions_.length-1)zoomFactor=2;else zoomFactor=max/this.resolutions_[nearest+1]}else{max=this.maxResolution_;zoomFactor=this.zoomFactor_}return offset+Math.log(max/resolution)/Math.log(zoomFactor)};
ol.View.prototype.getResolutionForZoom=function(zoom){return this.constrainResolution(this.maxResolution_,zoom-this.minZoom_,0)};
ol.View.prototype.fit=function(geometryOrExtent,opt_options){var options=opt_options||{};var size=options.size;if(!size)size=this.getSizeFromViewport_();var geometry;if(!(geometryOrExtent instanceof ol.geom.SimpleGeometry)){ol.asserts.assert(Array.isArray(geometryOrExtent),24);ol.asserts.assert(!ol.extent.isEmpty(geometryOrExtent),25);geometry=ol.geom.Polygon.fromExtent(geometryOrExtent)}else if(geometryOrExtent.getType()===ol.geom.GeometryType.CIRCLE){geometryOrExtent=geometryOrExtent.getExtent();
geometry=ol.geom.Polygon.fromExtent(geometryOrExtent);geometry.rotate(this.getRotation(),ol.extent.getCenter(geometryOrExtent))}else geometry=geometryOrExtent;var padding=options.padding!==undefined?options.padding:[0,0,0,0];var constrainResolution=options.constrainResolution!==undefined?options.constrainResolution:true;var nearest=options.nearest!==undefined?options.nearest:false;var minResolution;if(options.minResolution!==undefined)minResolution=options.minResolution;else if(options.maxZoom!==
undefined)minResolution=this.constrainResolution(this.maxResolution_,options.maxZoom-this.minZoom_,0);else minResolution=0;var coords=geometry.getFlatCoordinates();var rotation=this.getRotation();var cosAngle=Math.cos(-rotation);var sinAngle=Math.sin(-rotation);var minRotX=+Infinity;var minRotY=+Infinity;var maxRotX=-Infinity;var maxRotY=-Infinity;var stride=geometry.getStride();for(var i=0,ii=coords.length;i<ii;i+=stride){var rotX=coords[i]*cosAngle-coords[i+1]*sinAngle;var rotY=coords[i]*sinAngle+
coords[i+1]*cosAngle;minRotX=Math.min(minRotX,rotX);minRotY=Math.min(minRotY,rotY);maxRotX=Math.max(maxRotX,rotX);maxRotY=Math.max(maxRotY,rotY)}var resolution=this.getResolutionForExtent([minRotX,minRotY,maxRotX,maxRotY],[size[0]-padding[1]-padding[3],size[1]-padding[0]-padding[2]]);resolution=isNaN(resolution)?minResolution:Math.max(resolution,minResolution);if(constrainResolution){var constrainedResolution=this.constrainResolution(resolution,0,0);if(!nearest&&constrainedResolution<resolution)constrainedResolution=
this.constrainResolution(constrainedResolution,-1,0);resolution=constrainedResolution}sinAngle=-sinAngle;var centerRotX=(minRotX+maxRotX)/2;var centerRotY=(minRotY+maxRotY)/2;centerRotX+=(padding[1]-padding[3])/2*resolution;centerRotY+=(padding[0]-padding[2])/2*resolution;var centerX=centerRotX*cosAngle-centerRotY*sinAngle;var centerY=centerRotY*cosAngle+centerRotX*sinAngle;var center=[centerX,centerY];var callback=options.callback?options.callback:ol.nullFunction;if(options.duration!==undefined)this.animate({resolution:resolution,
center:center,duration:options.duration,easing:options.easing},callback);else{this.setResolution(resolution);this.setCenter(center);setTimeout(callback.bind(undefined,true),0)}};
ol.View.prototype.centerOn=function(coordinate,size,position){var rotation=this.getRotation();var cosAngle=Math.cos(-rotation);var sinAngle=Math.sin(-rotation);var rotX=coordinate[0]*cosAngle-coordinate[1]*sinAngle;var rotY=coordinate[1]*cosAngle+coordinate[0]*sinAngle;var resolution=this.getResolution();rotX+=(size[0]/2-position[0])*resolution;rotY+=(position[1]-size[1]/2)*resolution;sinAngle=-sinAngle;var centerX=rotX*cosAngle-rotY*sinAngle;var centerY=rotY*cosAngle+rotX*sinAngle;this.setCenter([centerX,
centerY])};ol.View.prototype.isDef=function(){return!!this.getCenter()&&this.getResolution()!==undefined};ol.View.prototype.rotate=function(rotation,opt_anchor){if(opt_anchor!==undefined){var center=this.calculateCenterRotate(rotation,opt_anchor);this.setCenter(center)}this.setRotation(rotation)};ol.View.prototype.setCenter=function(center){this.set(ol.ViewProperty.CENTER,center);if(this.getAnimating())this.cancelAnimations()};
ol.View.prototype.setHint=function(hint,delta){this.hints_[hint]+=delta;this.changed();return this.hints_[hint]};ol.View.prototype.setResolution=function(resolution){this.set(ol.ViewProperty.RESOLUTION,resolution);if(this.getAnimating())this.cancelAnimations()};ol.View.prototype.setRotation=function(rotation){this.set(ol.ViewProperty.ROTATION,rotation);if(this.getAnimating())this.cancelAnimations()};ol.View.prototype.setZoom=function(zoom){this.setResolution(this.getResolutionForZoom(zoom))};
ol.View.createCenterConstraint_=function(options){if(options.extent!==undefined)return ol.CenterConstraint.createExtent(options.extent);else return ol.CenterConstraint.none};
ol.View.createResolutionConstraint_=function(options){var resolutionConstraint;var maxResolution;var minResolution;var defaultMaxZoom=28;var defaultZoomFactor=2;var minZoom=options.minZoom!==undefined?options.minZoom:ol.DEFAULT_MIN_ZOOM;var maxZoom=options.maxZoom!==undefined?options.maxZoom:defaultMaxZoom;var zoomFactor=options.zoomFactor!==undefined?options.zoomFactor:defaultZoomFactor;if(options.resolutions!==undefined){var resolutions=options.resolutions;maxResolution=resolutions[minZoom];minResolution=
resolutions[maxZoom]!==undefined?resolutions[maxZoom]:resolutions[resolutions.length-1];resolutionConstraint=ol.ResolutionConstraint.createSnapToResolutions(resolutions)}else{var projection=ol.proj.createProjection(options.projection,"EPSG:3857");var extent=projection.getExtent();var size=!extent?360*ol.proj.METERS_PER_UNIT[ol.proj.Units.DEGREES]/projection.getMetersPerUnit():Math.max(ol.extent.getWidth(extent),ol.extent.getHeight(extent));var defaultMaxResolution=size/ol.DEFAULT_TILE_SIZE/Math.pow(defaultZoomFactor,
ol.DEFAULT_MIN_ZOOM);var defaultMinResolution=defaultMaxResolution/Math.pow(defaultZoomFactor,defaultMaxZoom-ol.DEFAULT_MIN_ZOOM);maxResolution=options.maxResolution;if(maxResolution!==undefined)minZoom=0;else maxResolution=defaultMaxResolution/Math.pow(zoomFactor,minZoom);minResolution=options.minResolution;if(minResolution===undefined)if(options.maxZoom!==undefined)if(options.maxResolution!==undefined)minResolution=maxResolution/Math.pow(zoomFactor,maxZoom);else minResolution=defaultMaxResolution/
Math.pow(zoomFactor,maxZoom);else minResolution=defaultMinResolution;maxZoom=minZoom+Math.floor(Math.log(maxResolution/minResolution)/Math.log(zoomFactor));minResolution=maxResolution/Math.pow(zoomFactor,maxZoom-minZoom);resolutionConstraint=ol.ResolutionConstraint.createSnapToPower(zoomFactor,maxResolution,maxZoom-minZoom)}return{constraint:resolutionConstraint,maxResolution:maxResolution,minResolution:minResolution,minZoom:minZoom,zoomFactor:zoomFactor}};
ol.View.createRotationConstraint_=function(options){var enableRotation=options.enableRotation!==undefined?options.enableRotation:true;if(enableRotation){var constrainRotation=options.constrainRotation;if(constrainRotation===undefined||constrainRotation===true)return ol.RotationConstraint.createSnapToZero();else if(constrainRotation===false)return ol.RotationConstraint.none;else if(typeof constrainRotation==="number")return ol.RotationConstraint.createSnapToN(constrainRotation);else return ol.RotationConstraint.none}else return ol.RotationConstraint.disable};
ol.View.isNoopAnimation=function(animation){if(animation.sourceCenter&&animation.targetCenter)if(!ol.coordinate.equals(animation.sourceCenter,animation.targetCenter))return false;if(animation.sourceResolution!==animation.targetResolution)return false;if(animation.sourceRotation!==animation.targetRotation)return false;return true};goog.provide("ol.dom");ol.dom.createCanvasContext2D=function(opt_width,opt_height){var canvas=document.createElement("CANVAS");if(opt_width)canvas.width=opt_width;if(opt_height)canvas.height=opt_height;return canvas.getContext("2d")};ol.dom.outerWidth=function(element){var width=element.offsetWidth;var style=getComputedStyle(element);width+=parseInt(style.marginLeft,10)+parseInt(style.marginRight,10);return width};
ol.dom.outerHeight=function(element){var height=element.offsetHeight;var style=getComputedStyle(element);height+=parseInt(style.marginTop,10)+parseInt(style.marginBottom,10);return height};ol.dom.replaceNode=function(newNode,oldNode){var parent=oldNode.parentNode;if(parent)parent.replaceChild(newNode,oldNode)};ol.dom.removeNode=function(node){return node&&node.parentNode?node.parentNode.removeChild(node):null};ol.dom.removeChildren=function(node){while(node.lastChild)node.removeChild(node.lastChild)};goog.provide("ol.layer.Property");ol.layer.Property={OPACITY:"opacity",VISIBLE:"visible",EXTENT:"extent",Z_INDEX:"zIndex",MAX_RESOLUTION:"maxResolution",MIN_RESOLUTION:"minResolution",SOURCE:"source"};goog.provide("ol.layer.Base");goog.require("ol");goog.require("ol.Object");goog.require("ol.layer.Property");goog.require("ol.math");goog.require("ol.obj");
ol.layer.Base=function(options){ol.Object.call(this);var properties=ol.obj.assign({},options);properties[ol.layer.Property.OPACITY]=options.opacity!==undefined?options.opacity:1;properties[ol.layer.Property.VISIBLE]=options.visible!==undefined?options.visible:true;properties[ol.layer.Property.Z_INDEX]=options.zIndex!==undefined?options.zIndex:0;properties[ol.layer.Property.MAX_RESOLUTION]=options.maxResolution!==undefined?options.maxResolution:Infinity;properties[ol.layer.Property.MIN_RESOLUTION]=
options.minResolution!==undefined?options.minResolution:0;this.setProperties(properties);this.state_={layer:this,managed:true};this.type};ol.inherits(ol.layer.Base,ol.Object);ol.layer.Base.prototype.getType=function(){return this.type};
ol.layer.Base.prototype.getLayerState=function(){this.state_.opacity=ol.math.clamp(this.getOpacity(),0,1);this.state_.sourceState=this.getSourceState();this.state_.visible=this.getVisible();this.state_.extent=this.getExtent();this.state_.zIndex=this.getZIndex();this.state_.maxResolution=this.getMaxResolution();this.state_.minResolution=Math.max(this.getMinResolution(),0);return this.state_};ol.layer.Base.prototype.getLayersArray=function(opt_array){};ol.layer.Base.prototype.getLayerStatesArray=function(opt_states){};
ol.layer.Base.prototype.getExtent=function(){return this.get(ol.layer.Property.EXTENT)};ol.layer.Base.prototype.getMaxResolution=function(){return this.get(ol.layer.Property.MAX_RESOLUTION)};ol.layer.Base.prototype.getMinResolution=function(){return this.get(ol.layer.Property.MIN_RESOLUTION)};ol.layer.Base.prototype.getOpacity=function(){return this.get(ol.layer.Property.OPACITY)};ol.layer.Base.prototype.getSourceState=function(){};ol.layer.Base.prototype.getVisible=function(){return this.get(ol.layer.Property.VISIBLE)};
ol.layer.Base.prototype.getZIndex=function(){return this.get(ol.layer.Property.Z_INDEX)};ol.layer.Base.prototype.setExtent=function(extent){this.set(ol.layer.Property.EXTENT,extent)};ol.layer.Base.prototype.setMaxResolution=function(maxResolution){this.set(ol.layer.Property.MAX_RESOLUTION,maxResolution)};ol.layer.Base.prototype.setMinResolution=function(minResolution){this.set(ol.layer.Property.MIN_RESOLUTION,minResolution)};
ol.layer.Base.prototype.setOpacity=function(opacity){this.set(ol.layer.Property.OPACITY,opacity)};ol.layer.Base.prototype.setVisible=function(visible){this.set(ol.layer.Property.VISIBLE,visible)};ol.layer.Base.prototype.setZIndex=function(zindex){this.set(ol.layer.Property.Z_INDEX,zindex)};goog.provide("ol.source.State");ol.source.State={UNDEFINED:"undefined",LOADING:"loading",READY:"ready",ERROR:"error"};goog.provide("ol.layer.Group");goog.require("ol");goog.require("ol.Collection");goog.require("ol.CollectionEventType");goog.require("ol.Object");goog.require("ol.ObjectEventType");goog.require("ol.asserts");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.layer.Base");goog.require("ol.obj");goog.require("ol.source.State");
ol.layer.Group=function(opt_options){var options=opt_options||{};var baseOptions=ol.obj.assign({},options);delete baseOptions.layers;var layers=options.layers;ol.layer.Base.call(this,baseOptions);this.layersListenerKeys_=[];this.listenerKeys_={};ol.events.listen(this,ol.Object.getChangeEventType(ol.layer.Group.Property_.LAYERS),this.handleLayersChanged_,this);if(layers)if(Array.isArray(layers))layers=new ol.Collection(layers.slice(),{unique:true});else{ol.asserts.assert(layers instanceof ol.Collection,
43);layers=layers}else layers=new ol.Collection(undefined,{unique:true});this.setLayers(layers)};ol.inherits(ol.layer.Group,ol.layer.Base);ol.layer.Group.prototype.handleLayerChange_=function(){this.changed()};
ol.layer.Group.prototype.handleLayersChanged_=function(event){this.layersListenerKeys_.forEach(ol.events.unlistenByKey);this.layersListenerKeys_.length=0;var layers=this.getLayers();this.layersListenerKeys_.push(ol.events.listen(layers,ol.CollectionEventType.ADD,this.handleLayersAdd_,this),ol.events.listen(layers,ol.CollectionEventType.REMOVE,this.handleLayersRemove_,this));for(var id in this.listenerKeys_)this.listenerKeys_[id].forEach(ol.events.unlistenByKey);ol.obj.clear(this.listenerKeys_);var layersArray=
layers.getArray();var i,ii,layer;for(i=0,ii=layersArray.length;i<ii;i++){layer=layersArray[i];this.listenerKeys_[ol.getUid(layer).toString()]=[ol.events.listen(layer,ol.ObjectEventType.PROPERTYCHANGE,this.handleLayerChange_,this),ol.events.listen(layer,ol.events.EventType.CHANGE,this.handleLayerChange_,this)]}this.changed()};
ol.layer.Group.prototype.handleLayersAdd_=function(collectionEvent){var layer=collectionEvent.element;var key=ol.getUid(layer).toString();this.listenerKeys_[key]=[ol.events.listen(layer,ol.ObjectEventType.PROPERTYCHANGE,this.handleLayerChange_,this),ol.events.listen(layer,ol.events.EventType.CHANGE,this.handleLayerChange_,this)];this.changed()};
ol.layer.Group.prototype.handleLayersRemove_=function(collectionEvent){var layer=collectionEvent.element;var key=ol.getUid(layer).toString();this.listenerKeys_[key].forEach(ol.events.unlistenByKey);delete this.listenerKeys_[key];this.changed()};ol.layer.Group.prototype.getLayers=function(){return this.get(ol.layer.Group.Property_.LAYERS)};ol.layer.Group.prototype.setLayers=function(layers){this.set(ol.layer.Group.Property_.LAYERS,layers)};
ol.layer.Group.prototype.getLayersArray=function(opt_array){var array=opt_array!==undefined?opt_array:[];this.getLayers().forEach(function(layer){layer.getLayersArray(array)});return array};
ol.layer.Group.prototype.getLayerStatesArray=function(opt_states){var states=opt_states!==undefined?opt_states:[];var pos=states.length;this.getLayers().forEach(function(layer){layer.getLayerStatesArray(states)});var ownLayerState=this.getLayerState();var i,ii,layerState;for(i=pos,ii=states.length;i<ii;i++){layerState=states[i];layerState.opacity*=ownLayerState.opacity;layerState.visible=layerState.visible&&ownLayerState.visible;layerState.maxResolution=Math.min(layerState.maxResolution,ownLayerState.maxResolution);
layerState.minResolution=Math.max(layerState.minResolution,ownLayerState.minResolution);if(ownLayerState.extent!==undefined)if(layerState.extent!==undefined)layerState.extent=ol.extent.getIntersection(layerState.extent,ownLayerState.extent);else layerState.extent=ownLayerState.extent}return states};ol.layer.Group.prototype.getSourceState=function(){return ol.source.State.READY};ol.layer.Group.Property_={LAYERS:"layers"};goog.provide("ol.PluginType");ol.PluginType={MAP_RENDERER:"MAP_RENDERER",LAYER_RENDERER:"LAYER_RENDERER"};goog.provide("ol.plugins");goog.require("ol.PluginType");ol.plugins.mapRendererPlugins_=[];ol.plugins.getMapRendererPlugins=function(){return ol.plugins.mapRendererPlugins_};ol.plugins.layerRendererPlugins_=[];ol.plugins.getLayerRendererPlugins=function(){return ol.plugins.layerRendererPlugins_};
ol.plugins.register=function(type,plugin){var plugins;switch(type){case ol.PluginType.MAP_RENDERER:{plugins=ol.plugins.mapRendererPlugins_;plugins.push(plugin);break}case ol.PluginType.LAYER_RENDERER:{plugins=ol.plugins.layerRendererPlugins_;plugins.push(plugin);break}default:{throw new Error("Unsupported plugin type: "+type);}}};ol.plugins.registerMultiple=function(type,plugins){for(var i=0,ii=plugins.length;i<ii;++i)ol.plugins.register(type,plugins[i])};goog.provide("ol.renderer.Type");ol.renderer.Type={CANVAS:"canvas",WEBGL:"webgl"};goog.provide("ol.PluggableMap");goog.require("ol");goog.require("ol.Collection");goog.require("ol.CollectionEventType");goog.require("ol.MapBrowserEvent");goog.require("ol.MapBrowserEventHandler");goog.require("ol.MapBrowserEventType");goog.require("ol.MapEvent");goog.require("ol.MapEventType");goog.require("ol.MapProperty");goog.require("ol.Object");goog.require("ol.ObjectEventType");goog.require("ol.TileQueue");goog.require("ol.View");goog.require("ol.ViewHint");goog.require("ol.asserts");goog.require("ol.dom");
goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.functions");goog.require("ol.has");goog.require("ol.layer.Group");goog.require("ol.obj");goog.require("ol.plugins");goog.require("ol.renderer.Type");goog.require("ol.size");goog.require("ol.structs.PriorityQueue");goog.require("ol.transform");
ol.PluggableMap=function(options){ol.Object.call(this);var optionsInternal=ol.PluggableMap.createOptionsInternal(options);this.loadTilesWhileAnimating_=options.loadTilesWhileAnimating!==undefined?options.loadTilesWhileAnimating:false;this.loadTilesWhileInteracting_=options.loadTilesWhileInteracting!==undefined?options.loadTilesWhileInteracting:false;this.pixelRatio_=options.pixelRatio!==undefined?options.pixelRatio:ol.has.DEVICE_PIXEL_RATIO;this.logos_=optionsInternal.logos;this.animationDelayKey_;
this.animationDelay_=function(){this.animationDelayKey_=undefined;this.renderFrame_.call(this,Date.now())}.bind(this);this.coordinateToPixelTransform_=ol.transform.create();this.pixelToCoordinateTransform_=ol.transform.create();this.frameIndex_=0;this.frameState_=null;this.previousExtent_=null;this.viewPropertyListenerKey_=null;this.viewChangeListenerKey_=null;this.layerGroupPropertyListenerKeys_=null;this.viewport_=document.createElement("DIV");this.viewport_.className="ol-viewport"+(ol.has.TOUCH?
" ol-touch":"");this.viewport_.style.position="relative";this.viewport_.style.overflow="hidden";this.viewport_.style.width="100%";this.viewport_.style.height="100%";this.viewport_.style.msTouchAction="none";this.viewport_.style.touchAction="none";this.overlayContainer_=document.createElement("DIV");this.overlayContainer_.className="ol-overlaycontainer";this.viewport_.appendChild(this.overlayContainer_);this.overlayContainerStopEvent_=document.createElement("DIV");this.overlayContainerStopEvent_.className=
"ol-overlaycontainer-stopevent";var overlayEvents=[ol.events.EventType.CLICK,ol.events.EventType.DBLCLICK,ol.events.EventType.MOUSEDOWN,ol.events.EventType.TOUCHSTART,ol.events.EventType.MSPOINTERDOWN,ol.MapBrowserEventType.POINTERDOWN,ol.events.EventType.MOUSEWHEEL,ol.events.EventType.WHEEL];for(var i=0,ii=overlayEvents.length;i<ii;++i)ol.events.listen(this.overlayContainerStopEvent_,overlayEvents[i],ol.events.Event.stopPropagation);this.viewport_.appendChild(this.overlayContainerStopEvent_);this.mapBrowserEventHandler_=
new ol.MapBrowserEventHandler(this,options.moveTolerance);for(var key in ol.MapBrowserEventType)ol.events.listen(this.mapBrowserEventHandler_,ol.MapBrowserEventType[key],this.handleMapBrowserEvent,this);this.keyboardEventTarget_=optionsInternal.keyboardEventTarget;this.keyHandlerKeys_=null;ol.events.listen(this.viewport_,ol.events.EventType.WHEEL,this.handleBrowserEvent,this);ol.events.listen(this.viewport_,ol.events.EventType.MOUSEWHEEL,this.handleBrowserEvent,this);this.controls=optionsInternal.controls||
new ol.Collection;this.interactions=optionsInternal.interactions||new ol.Collection;this.overlays_=optionsInternal.overlays;this.overlayIdIndex_={};this.renderer_=optionsInternal.mapRendererPlugin["create"](this.viewport_,this);this.handleResize_;this.focus_=null;this.postRenderFunctions_=[];this.tileQueue_=new ol.TileQueue(this.getTilePriority.bind(this),this.handleTileChange_.bind(this));this.skippedFeatureUids_={};ol.events.listen(this,ol.Object.getChangeEventType(ol.MapProperty.LAYERGROUP),this.handleLayerGroupChanged_,
this);ol.events.listen(this,ol.Object.getChangeEventType(ol.MapProperty.VIEW),this.handleViewChanged_,this);ol.events.listen(this,ol.Object.getChangeEventType(ol.MapProperty.SIZE),this.handleSizeChanged_,this);ol.events.listen(this,ol.Object.getChangeEventType(ol.MapProperty.TARGET),this.handleTargetChanged_,this);this.setProperties(optionsInternal.values);this.controls.forEach(function(control){control.setMap(this)},this);ol.events.listen(this.controls,ol.CollectionEventType.ADD,function(event){event.element.setMap(this)},
this);ol.events.listen(this.controls,ol.CollectionEventType.REMOVE,function(event){event.element.setMap(null)},this);this.interactions.forEach(function(interaction){interaction.setMap(this)},this);ol.events.listen(this.interactions,ol.CollectionEventType.ADD,function(event){event.element.setMap(this)},this);ol.events.listen(this.interactions,ol.CollectionEventType.REMOVE,function(event){event.element.setMap(null)},this);this.overlays_.forEach(this.addOverlayInternal_,this);ol.events.listen(this.overlays_,
ol.CollectionEventType.ADD,function(event){this.addOverlayInternal_(event.element)},this);ol.events.listen(this.overlays_,ol.CollectionEventType.REMOVE,function(event){var overlay=event.element;var id=overlay.getId();if(id!==undefined)delete this.overlayIdIndex_[id.toString()];event.element.setMap(null)},this)};ol.inherits(ol.PluggableMap,ol.Object);ol.PluggableMap.prototype.addControl=function(control){this.getControls().push(control)};ol.PluggableMap.prototype.addInteraction=function(interaction){this.getInteractions().push(interaction)};
ol.PluggableMap.prototype.addLayer=function(layer){var layers=this.getLayerGroup().getLayers();layers.push(layer)};ol.PluggableMap.prototype.addOverlay=function(overlay){this.getOverlays().push(overlay)};ol.PluggableMap.prototype.addOverlayInternal_=function(overlay){var id=overlay.getId();if(id!==undefined)this.overlayIdIndex_[id.toString()]=overlay;overlay.setMap(this)};
ol.PluggableMap.prototype.disposeInternal=function(){this.mapBrowserEventHandler_.dispose();ol.events.unlisten(this.viewport_,ol.events.EventType.WHEEL,this.handleBrowserEvent,this);ol.events.unlisten(this.viewport_,ol.events.EventType.MOUSEWHEEL,this.handleBrowserEvent,this);if(this.handleResize_!==undefined){window.removeEventListener(ol.events.EventType.RESIZE,this.handleResize_,false);this.handleResize_=undefined}if(this.animationDelayKey_){cancelAnimationFrame(this.animationDelayKey_);this.animationDelayKey_=
undefined}this.setTarget(null);ol.Object.prototype.disposeInternal.call(this)};
ol.PluggableMap.prototype.forEachFeatureAtPixel=function(pixel,callback,opt_options){if(!this.frameState_)return;var coordinate=this.getCoordinateFromPixel(pixel);opt_options=opt_options!==undefined?opt_options:{};var hitTolerance=opt_options.hitTolerance!==undefined?opt_options.hitTolerance*this.frameState_.pixelRatio:0;var layerFilter=opt_options.layerFilter!==undefined?opt_options.layerFilter:ol.functions.TRUE;return this.renderer_.forEachFeatureAtCoordinate(coordinate,this.frameState_,hitTolerance,
callback,null,layerFilter,null)};ol.PluggableMap.prototype.getFeaturesAtPixel=function(pixel,opt_options){var features=null;this.forEachFeatureAtPixel(pixel,function(feature){if(!features)features=[];features.push(feature)},opt_options);return features};
ol.PluggableMap.prototype.forEachLayerAtPixel=function(pixel,callback,opt_this,opt_layerFilter,opt_this2){if(!this.frameState_)return;var thisArg=opt_this!==undefined?opt_this:null;var layerFilter=opt_layerFilter!==undefined?opt_layerFilter:ol.functions.TRUE;var thisArg2=opt_this2!==undefined?opt_this2:null;return this.renderer_.forEachLayerAtPixel(pixel,this.frameState_,callback,thisArg,layerFilter,thisArg2)};
ol.PluggableMap.prototype.hasFeatureAtPixel=function(pixel,opt_options){if(!this.frameState_)return false;var coordinate=this.getCoordinateFromPixel(pixel);opt_options=opt_options!==undefined?opt_options:{};var layerFilter=opt_options.layerFilter!==undefined?opt_options.layerFilter:ol.functions.TRUE;var hitTolerance=opt_options.hitTolerance!==undefined?opt_options.hitTolerance*this.frameState_.pixelRatio:0;return this.renderer_.hasFeatureAtCoordinate(coordinate,this.frameState_,hitTolerance,layerFilter,
null)};ol.PluggableMap.prototype.getEventCoordinate=function(event){return this.getCoordinateFromPixel(this.getEventPixel(event))};ol.PluggableMap.prototype.getEventPixel=function(event){var viewportPosition=this.viewport_.getBoundingClientRect();var eventPosition=event.changedTouches?event.changedTouches[0]:event;return[eventPosition.clientX-viewportPosition.left,eventPosition.clientY-viewportPosition.top]};ol.PluggableMap.prototype.getTarget=function(){return this.get(ol.MapProperty.TARGET)};
ol.PluggableMap.prototype.getTargetElement=function(){var target=this.getTarget();if(target!==undefined)return typeof target==="string"?document.getElementById(target):target;else return null};ol.PluggableMap.prototype.getCoordinateFromPixel=function(pixel){var frameState=this.frameState_;if(!frameState)return null;else return ol.transform.apply(frameState.pixelToCoordinateTransform,pixel.slice())};ol.PluggableMap.prototype.getControls=function(){return this.controls};
ol.PluggableMap.prototype.getOverlays=function(){return this.overlays_};ol.PluggableMap.prototype.getOverlayById=function(id){var overlay=this.overlayIdIndex_[id.toString()];return overlay!==undefined?overlay:null};ol.PluggableMap.prototype.getInteractions=function(){return this.interactions};ol.PluggableMap.prototype.getLayerGroup=function(){return this.get(ol.MapProperty.LAYERGROUP)};ol.PluggableMap.prototype.getLayers=function(){var layers=this.getLayerGroup().getLayers();return layers};
ol.PluggableMap.prototype.getPixelFromCoordinate=function(coordinate){var frameState=this.frameState_;if(!frameState)return null;else return ol.transform.apply(frameState.coordinateToPixelTransform,coordinate.slice(0,2))};ol.PluggableMap.prototype.getRenderer=function(){return this.renderer_};ol.PluggableMap.prototype.getSize=function(){return this.get(ol.MapProperty.SIZE)};ol.PluggableMap.prototype.getView=function(){return this.get(ol.MapProperty.VIEW)};ol.PluggableMap.prototype.getViewport=function(){return this.viewport_};
ol.PluggableMap.prototype.getOverlayContainer=function(){return this.overlayContainer_};ol.PluggableMap.prototype.getOverlayContainerStopEvent=function(){return this.overlayContainerStopEvent_};
ol.PluggableMap.prototype.getTilePriority=function(tile,tileSourceKey,tileCenter,tileResolution){var frameState=this.frameState_;if(!frameState||!(tileSourceKey in frameState.wantedTiles))return ol.structs.PriorityQueue.DROP;if(!frameState.wantedTiles[tileSourceKey][tile.getKey()])return ol.structs.PriorityQueue.DROP;var deltaX=tileCenter[0]-frameState.focus[0];var deltaY=tileCenter[1]-frameState.focus[1];return 65536*Math.log(tileResolution)+Math.sqrt(deltaX*deltaX+deltaY*deltaY)/tileResolution};
ol.PluggableMap.prototype.handleBrowserEvent=function(browserEvent,opt_type){var type=opt_type||browserEvent.type;var mapBrowserEvent=new ol.MapBrowserEvent(type,this,browserEvent);this.handleMapBrowserEvent(mapBrowserEvent)};
ol.PluggableMap.prototype.handleMapBrowserEvent=function(mapBrowserEvent){if(!this.frameState_)return;this.focus_=mapBrowserEvent.coordinate;mapBrowserEvent.frameState=this.frameState_;var interactionsArray=this.getInteractions().getArray();var i;if(this.dispatchEvent(mapBrowserEvent)!==false)for(i=interactionsArray.length-1;i>=0;i--){var interaction=interactionsArray[i];if(!interaction.getActive())continue;var cont=interaction.handleEvent(mapBrowserEvent);if(!cont)break}};
ol.PluggableMap.prototype.handlePostRender=function(){var frameState=this.frameState_;var tileQueue=this.tileQueue_;if(!tileQueue.isEmpty()){var maxTotalLoading=16;var maxNewLoads=maxTotalLoading;if(frameState){var hints=frameState.viewHints;if(hints[ol.ViewHint.ANIMATING]){maxTotalLoading=this.loadTilesWhileAnimating_?8:0;maxNewLoads=2}if(hints[ol.ViewHint.INTERACTING]){maxTotalLoading=this.loadTilesWhileInteracting_?8:0;maxNewLoads=2}}if(tileQueue.getTilesLoading()<maxTotalLoading){tileQueue.reprioritize();
tileQueue.loadMoreTiles(maxTotalLoading,maxNewLoads)}}var postRenderFunctions=this.postRenderFunctions_;var i,ii;for(i=0,ii=postRenderFunctions.length;i<ii;++i)postRenderFunctions[i](this,frameState);postRenderFunctions.length=0};ol.PluggableMap.prototype.handleSizeChanged_=function(){this.render()};
ol.PluggableMap.prototype.handleTargetChanged_=function(){var targetElement;if(this.getTarget())targetElement=this.getTargetElement();if(this.keyHandlerKeys_){for(var i=0,ii=this.keyHandlerKeys_.length;i<ii;++i)ol.events.unlistenByKey(this.keyHandlerKeys_[i]);this.keyHandlerKeys_=null}if(!targetElement){this.renderer_.removeLayerRenderers();ol.dom.removeNode(this.viewport_);if(this.handleResize_!==undefined){window.removeEventListener(ol.events.EventType.RESIZE,this.handleResize_,false);this.handleResize_=
undefined}}else{targetElement.appendChild(this.viewport_);var keyboardEventTarget=!this.keyboardEventTarget_?targetElement:this.keyboardEventTarget_;this.keyHandlerKeys_=[ol.events.listen(keyboardEventTarget,ol.events.EventType.KEYDOWN,this.handleBrowserEvent,this),ol.events.listen(keyboardEventTarget,ol.events.EventType.KEYPRESS,this.handleBrowserEvent,this)];if(!this.handleResize_){this.handleResize_=this.updateSize.bind(this);window.addEventListener(ol.events.EventType.RESIZE,this.handleResize_,
false)}}this.updateSize()};ol.PluggableMap.prototype.handleTileChange_=function(){this.render()};ol.PluggableMap.prototype.handleViewPropertyChanged_=function(){this.render()};
ol.PluggableMap.prototype.handleViewChanged_=function(){if(this.viewPropertyListenerKey_){ol.events.unlistenByKey(this.viewPropertyListenerKey_);this.viewPropertyListenerKey_=null}if(this.viewChangeListenerKey_){ol.events.unlistenByKey(this.viewChangeListenerKey_);this.viewChangeListenerKey_=null}var view=this.getView();if(view){this.viewport_.setAttribute("data-view",ol.getUid(view));this.viewPropertyListenerKey_=ol.events.listen(view,ol.ObjectEventType.PROPERTYCHANGE,this.handleViewPropertyChanged_,
this);this.viewChangeListenerKey_=ol.events.listen(view,ol.events.EventType.CHANGE,this.handleViewPropertyChanged_,this)}this.render()};
ol.PluggableMap.prototype.handleLayerGroupChanged_=function(){if(this.layerGroupPropertyListenerKeys_){this.layerGroupPropertyListenerKeys_.forEach(ol.events.unlistenByKey);this.layerGroupPropertyListenerKeys_=null}var layerGroup=this.getLayerGroup();if(layerGroup)this.layerGroupPropertyListenerKeys_=[ol.events.listen(layerGroup,ol.ObjectEventType.PROPERTYCHANGE,this.render,this),ol.events.listen(layerGroup,ol.events.EventType.CHANGE,this.render,this)];this.render()};
ol.PluggableMap.prototype.isRendered=function(){return!!this.frameState_};ol.PluggableMap.prototype.renderSync=function(){if(this.animationDelayKey_)cancelAnimationFrame(this.animationDelayKey_);this.animationDelay_()};ol.PluggableMap.prototype.render=function(){if(this.animationDelayKey_===undefined)this.animationDelayKey_=requestAnimationFrame(this.animationDelay_)};ol.PluggableMap.prototype.removeControl=function(control){return this.getControls().remove(control)};
ol.PluggableMap.prototype.removeInteraction=function(interaction){return this.getInteractions().remove(interaction)};ol.PluggableMap.prototype.removeLayer=function(layer){var layers=this.getLayerGroup().getLayers();return layers.remove(layer)};ol.PluggableMap.prototype.removeOverlay=function(overlay){return this.getOverlays().remove(overlay)};
ol.PluggableMap.prototype.renderFrame_=function(time){var i,ii,viewState;var size=this.getSize();var view=this.getView();var extent=ol.extent.createEmpty();var previousFrameState=this.frameState_;var frameState=null;if(size!==undefined&&ol.size.hasArea(size)&&view&&view.isDef()){var viewHints=view.getHints(this.frameState_?this.frameState_.viewHints:undefined);var layerStatesArray=this.getLayerGroup().getLayerStatesArray();var layerStates={};for(i=0,ii=layerStatesArray.length;i<ii;++i)layerStates[ol.getUid(layerStatesArray[i].layer)]=
layerStatesArray[i];viewState=view.getState();var center=viewState.center;var pixelResolution=viewState.resolution/this.pixelRatio_;center[0]=Math.round(center[0]/pixelResolution)*pixelResolution;center[1]=Math.round(center[1]/pixelResolution)*pixelResolution;frameState={animate:false,coordinateToPixelTransform:this.coordinateToPixelTransform_,extent:extent,focus:!this.focus_?center:this.focus_,index:this.frameIndex_++,layerStates:layerStates,layerStatesArray:layerStatesArray,logos:ol.obj.assign({},
this.logos_),pixelRatio:this.pixelRatio_,pixelToCoordinateTransform:this.pixelToCoordinateTransform_,postRenderFunctions:[],size:size,skippedFeatureUids:this.skippedFeatureUids_,tileQueue:this.tileQueue_,time:time,usedTiles:{},viewState:viewState,viewHints:viewHints,wantedTiles:{}}}if(frameState)frameState.extent=ol.extent.getForViewAndSize(viewState.center,viewState.resolution,viewState.rotation,frameState.size,extent);this.frameState_=frameState;this.renderer_.renderFrame(frameState);if(frameState){if(frameState.animate)this.render();
Array.prototype.push.apply(this.postRenderFunctions_,frameState.postRenderFunctions);if(previousFrameState){var moveStart=!this.previousExtent_||!ol.extent.isEmpty(this.previousExtent_)&&!ol.extent.equals(frameState.extent,this.previousExtent_);if(moveStart){this.dispatchEvent(new ol.MapEvent(ol.MapEventType.MOVESTART,this,previousFrameState));this.previousExtent_=ol.extent.createOrUpdateEmpty(this.previousExtent_)}}var idle=this.previousExtent_&&!frameState.viewHints[ol.ViewHint.ANIMATING]&&!frameState.viewHints[ol.ViewHint.INTERACTING]&&
!ol.extent.equals(frameState.extent,this.previousExtent_);if(idle){this.dispatchEvent(new ol.MapEvent(ol.MapEventType.MOVEEND,this,frameState));ol.extent.clone(frameState.extent,this.previousExtent_)}}this.dispatchEvent(new ol.MapEvent(ol.MapEventType.POSTRENDER,this,frameState));setTimeout(this.handlePostRender.bind(this),0)};ol.PluggableMap.prototype.setLayerGroup=function(layerGroup){this.set(ol.MapProperty.LAYERGROUP,layerGroup)};
ol.PluggableMap.prototype.setSize=function(size){this.set(ol.MapProperty.SIZE,size)};ol.PluggableMap.prototype.setTarget=function(target){this.set(ol.MapProperty.TARGET,target)};ol.PluggableMap.prototype.setView=function(view){this.set(ol.MapProperty.VIEW,view)};ol.PluggableMap.prototype.skipFeature=function(feature){var featureUid=ol.getUid(feature).toString();this.skippedFeatureUids_[featureUid]=true;this.render()};
ol.PluggableMap.prototype.updateSize=function(){var targetElement=this.getTargetElement();if(!targetElement)this.setSize(undefined);else{var computedStyle=getComputedStyle(targetElement);this.setSize([targetElement.offsetWidth-parseFloat(computedStyle["borderLeftWidth"])-parseFloat(computedStyle["paddingLeft"])-parseFloat(computedStyle["paddingRight"])-parseFloat(computedStyle["borderRightWidth"]),targetElement.offsetHeight-parseFloat(computedStyle["borderTopWidth"])-parseFloat(computedStyle["paddingTop"])-
parseFloat(computedStyle["paddingBottom"])-parseFloat(computedStyle["borderBottomWidth"])])}};ol.PluggableMap.prototype.unskipFeature=function(feature){var featureUid=ol.getUid(feature).toString();delete this.skippedFeatureUids_[featureUid];this.render()};ol.PluggableMap.DEFAULT_RENDERER_TYPES=[ol.renderer.Type.CANVAS,ol.renderer.Type.WEBGL];
ol.PluggableMap.LOGO_URL="data:image/png;base64,"+"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAA3NCSVQICAjb4U/gAAAACXBI"+"WXMAAAHGAAABxgEXwfpGAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA"+"AhNQTFRF////AP//AICAgP//AFVVQECA////K1VVSbbbYL/fJ05idsTYJFtbbcjbJllmZszW"+"WMTOIFhoHlNiZszTa9DdUcHNHlNlV8XRIVdiasrUHlZjIVZjaMnVH1RlIFRkH1RkH1ZlasvY"+"asvXVsPQH1VkacnVa8vWIVZjIFRjVMPQa8rXIVVkXsXRsNveIFVkIFZlIVVj3eDeh6GmbMvX"+"H1ZkIFRka8rWbMvXIFVkIFVjIFVkbMvWH1VjbMvWIFVlbcvWIFVla8vVIFVkbMvWbMvVH1Vk"+"bMvWIFVlbcvWIFVkbcvVbMvWjNPbIFVkU8LPwMzNIFVkbczWIFVkbsvWbMvXIFVkRnB8bcvW"+
"2+TkW8XRIFVkIlZlJVloJlpoKlxrLl9tMmJwOWd0Omh1RXF8TneCT3iDUHiDU8LPVMLPVcLP"+"VcPQVsPPVsPQV8PQWMTQWsTQW8TQXMXSXsXRX4SNX8bSYMfTYcfTYsfTY8jUZcfSZsnUaIqT"+"acrVasrVa8jTa8rWbI2VbMvWbcvWdJObdcvUdszUd8vVeJaee87Yfc3WgJyjhqGnitDYjaar"+"ldPZnrK2oNbborW5o9bbo9fbpLa6q9ndrL3ArtndscDDutzfu8fJwN7gwt7gxc/QyuHhy+Hi"+"zeHi0NfX0+Pj19zb1+Tj2uXk29/e3uLg3+Lh3+bl4uXj4ufl4+fl5Ofl5ufl5ujm5+jmySDn"+"BAAAAFp0Uk5TAAECAgMEBAYHCA0NDg4UGRogIiMmKSssLzU7PkJJT1JTVFliY2hrdHZ3foSF"+"hYeJjY2QkpugqbG1tre5w8zQ09XY3uXn6+zx8vT09vf4+Pj5+fr6/P39/f3+gz7SsAAAAVVJ"+
"REFUOMtjYKA7EBDnwCPLrObS1BRiLoJLnte6CQy8FLHLCzs2QUG4FjZ5GbcmBDDjxJBXDWxC"+"Brb8aM4zbkIDzpLYnAcE9VXlJSWlZRU13koIeW57mGx5XjoMZEUqwxWYQaQbSzLSkYGfKFSe"+"0QMsX5WbjgY0YS4MBplemI4BdGBW+DQ11eZiymfqQuXZIjqwyadPNoSZ4L+0FVM6e+oGI6g8"+"a9iKNT3o8kVzNkzRg5lgl7p4wyRUL9Yt2jAxVh6mQCogae6GmflI8p0r13VFWTHBQ0rWPW7a"+"hgWVcPm+9cuLoyy4kCJDzCm6d8PSFoh0zvQNC5OjDJhQopPPJqph1doJBUD5tnkbZiUEqaCn"+"B3bTqLTFG1bPn71kw4b+GFdpLElKIzRxxgYgWNYc5SCENVHKeUaltHdXx0dZ8uBI1hJ2UUDg"+"q82CM2MwKeibqAvSO7MCABq0wXEPiqWEAAAAAElFTkSuQmCC";
ol.PluggableMap.createOptionsInternal=function(options){var keyboardEventTarget=null;if(options.keyboardEventTarget!==undefined)keyboardEventTarget=typeof options.keyboardEventTarget==="string"?document.getElementById(options.keyboardEventTarget):options.keyboardEventTarget;var values={};var logos={};if(options.logo===undefined||typeof options.logo==="boolean"&&options.logo)logos[ol.PluggableMap.LOGO_URL]="https://openlayers.org/";else{var logo=options.logo;if(typeof logo==="string")logos[logo]="";
else if(logo instanceof HTMLElement)logos[ol.getUid(logo).toString()]=logo;else if(logo){ol.asserts.assert(typeof logo.href=="string",44);ol.asserts.assert(typeof logo.src=="string",45);logos[logo.src]=logo.href}}var layerGroup=options.layers instanceof ol.layer.Group?options.layers:new ol.layer.Group({layers:options.layers});values[ol.MapProperty.LAYERGROUP]=layerGroup;values[ol.MapProperty.TARGET]=options.target;values[ol.MapProperty.VIEW]=options.view!==undefined?options.view:new ol.View;var rendererTypes;
if(options.renderer!==undefined){if(Array.isArray(options.renderer))rendererTypes=options.renderer;else if(typeof options.renderer==="string")rendererTypes=[options.renderer];else ol.asserts.assert(false,46);if(rendererTypes.indexOf("dom")>=0)rendererTypes=rendererTypes.concat(ol.PluggableMap.DEFAULT_RENDERER_TYPES)}else rendererTypes=ol.PluggableMap.DEFAULT_RENDERER_TYPES;var mapRendererPlugin;var mapRendererPlugins=ol.plugins.getMapRendererPlugins();outer:for(var i=0,ii=rendererTypes.length;i<ii;++i){var rendererType=
rendererTypes[i];for(var j=0,jj=mapRendererPlugins.length;j<jj;++j){var candidate=mapRendererPlugins[j];if(candidate["handles"](rendererType)){mapRendererPlugin=candidate;break outer}}}if(!mapRendererPlugin)throw new Error("Unable to create a map renderer for types: "+rendererTypes.join(", "));var controls;if(options.controls!==undefined)if(Array.isArray(options.controls))controls=new ol.Collection(options.controls.slice());else{ol.asserts.assert(options.controls instanceof ol.Collection,47);controls=
options.controls}var interactions;if(options.interactions!==undefined)if(Array.isArray(options.interactions))interactions=new ol.Collection(options.interactions.slice());else{ol.asserts.assert(options.interactions instanceof ol.Collection,48);interactions=options.interactions}var overlays;if(options.overlays!==undefined)if(Array.isArray(options.overlays))overlays=new ol.Collection(options.overlays.slice());else{ol.asserts.assert(options.overlays instanceof ol.Collection,49);overlays=options.overlays}else overlays=
new ol.Collection;return{controls:controls,interactions:interactions,keyboardEventTarget:keyboardEventTarget,logos:logos,overlays:overlays,mapRendererPlugin:mapRendererPlugin,values:values}};goog.provide("ol.control.Control");goog.require("ol");goog.require("ol.MapEventType");goog.require("ol.Object");goog.require("ol.dom");goog.require("ol.events");ol.control.Control=function(options){ol.Object.call(this);this.element=options.element?options.element:null;this.target_=null;this.map_=null;this.listenerKeys=[];this.render=options.render?options.render:ol.nullFunction;if(options.target)this.setTarget(options.target)};ol.inherits(ol.control.Control,ol.Object);
ol.control.Control.prototype.disposeInternal=function(){ol.dom.removeNode(this.element);ol.Object.prototype.disposeInternal.call(this)};ol.control.Control.prototype.getMap=function(){return this.map_};
ol.control.Control.prototype.setMap=function(map){if(this.map_)ol.dom.removeNode(this.element);for(var i=0,ii=this.listenerKeys.length;i<ii;++i)ol.events.unlistenByKey(this.listenerKeys[i]);this.listenerKeys.length=0;this.map_=map;if(this.map_){var target=this.target_?this.target_:map.getOverlayContainerStopEvent();target.appendChild(this.element);if(this.render!==ol.nullFunction)this.listenerKeys.push(ol.events.listen(map,ol.MapEventType.POSTRENDER,this.render,this));map.render()}};
ol.control.Control.prototype.setTarget=function(target){this.target_=typeof target==="string"?document.getElementById(target):target};goog.provide("ol.css");ol.css.CLASS_HIDDEN="ol-hidden";ol.css.CLASS_SELECTABLE="ol-selectable";ol.css.CLASS_UNSELECTABLE="ol-unselectable";ol.css.CLASS_UNSUPPORTED="ol-unsupported";ol.css.CLASS_CONTROL="ol-control";ol.css.getFontFamilies=function(){var style;var cache={};return function(font){if(!style)style=document.createElement("div").style;if(!(font in cache)){style.font=font;var family=style.fontFamily;style.font="";if(!family)return null;cache[font]=family.split(/,\s?/)}return cache[font]}}();goog.provide("ol.render.EventType");ol.render.EventType={POSTCOMPOSE:"postcompose",PRECOMPOSE:"precompose",RENDER:"render"};goog.provide("ol.layer.Layer");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol");goog.require("ol.Object");goog.require("ol.layer.Base");goog.require("ol.layer.Property");goog.require("ol.obj");goog.require("ol.render.EventType");goog.require("ol.source.State");
ol.layer.Layer=function(options){var baseOptions=ol.obj.assign({},options);delete baseOptions.source;ol.layer.Base.call(this,baseOptions);this.mapPrecomposeKey_=null;this.mapRenderKey_=null;this.sourceChangeKey_=null;if(options.map)this.setMap(options.map);ol.events.listen(this,ol.Object.getChangeEventType(ol.layer.Property.SOURCE),this.handleSourcePropertyChange_,this);var source=options.source?options.source:null;this.setSource(source)};ol.inherits(ol.layer.Layer,ol.layer.Base);
ol.layer.Layer.visibleAtResolution=function(layerState,resolution){return layerState.visible&&resolution>=layerState.minResolution&&resolution<layerState.maxResolution};ol.layer.Layer.prototype.getLayersArray=function(opt_array){var array=opt_array?opt_array:[];array.push(this);return array};ol.layer.Layer.prototype.getLayerStatesArray=function(opt_states){var states=opt_states?opt_states:[];states.push(this.getLayerState());return states};
ol.layer.Layer.prototype.getSource=function(){var source=this.get(ol.layer.Property.SOURCE);return source||null};ol.layer.Layer.prototype.getSourceState=function(){var source=this.getSource();return!source?ol.source.State.UNDEFINED:source.getState()};ol.layer.Layer.prototype.handleSourceChange_=function(){this.changed()};
ol.layer.Layer.prototype.handleSourcePropertyChange_=function(){if(this.sourceChangeKey_){ol.events.unlistenByKey(this.sourceChangeKey_);this.sourceChangeKey_=null}var source=this.getSource();if(source)this.sourceChangeKey_=ol.events.listen(source,ol.events.EventType.CHANGE,this.handleSourceChange_,this);this.changed()};
ol.layer.Layer.prototype.setMap=function(map){if(this.mapPrecomposeKey_){ol.events.unlistenByKey(this.mapPrecomposeKey_);this.mapPrecomposeKey_=null}if(!map)this.changed();if(this.mapRenderKey_){ol.events.unlistenByKey(this.mapRenderKey_);this.mapRenderKey_=null}if(map){this.mapPrecomposeKey_=ol.events.listen(map,ol.render.EventType.PRECOMPOSE,function(evt){var layerState=this.getLayerState();layerState.managed=false;layerState.zIndex=Infinity;evt.frameState.layerStatesArray.push(layerState);evt.frameState.layerStates[ol.getUid(this)]=
layerState},this);this.mapRenderKey_=ol.events.listen(this,ol.events.EventType.CHANGE,map.render,map);this.changed()}};ol.layer.Layer.prototype.setSource=function(source){this.set(ol.layer.Property.SOURCE,source)};goog.provide("ol.control.Attribution");goog.require("ol");goog.require("ol.array");goog.require("ol.control.Control");goog.require("ol.css");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.layer.Layer");goog.require("ol.obj");
ol.control.Attribution=function(opt_options){var options=opt_options?opt_options:{};this.ulElement_=document.createElement("UL");this.logoLi_=document.createElement("LI");this.ulElement_.appendChild(this.logoLi_);this.logoLi_.style.display="none";this.collapsed_=options.collapsed!==undefined?options.collapsed:true;this.collapsible_=options.collapsible!==undefined?options.collapsible:true;if(!this.collapsible_)this.collapsed_=false;var className=options.className!==undefined?options.className:"ol-attribution";
var tipLabel=options.tipLabel!==undefined?options.tipLabel:"Attributions";var collapseLabel=options.collapseLabel!==undefined?options.collapseLabel:"\u00bb";if(typeof collapseLabel==="string"){this.collapseLabel_=document.createElement("span");this.collapseLabel_.textContent=collapseLabel}else this.collapseLabel_=collapseLabel;var label=options.label!==undefined?options.label:"i";if(typeof label==="string"){this.label_=document.createElement("span");this.label_.textContent=label}else this.label_=
label;var activeLabel=this.collapsible_&&!this.collapsed_?this.collapseLabel_:this.label_;var button=document.createElement("button");button.setAttribute("type","button");button.title=tipLabel;button.appendChild(activeLabel);ol.events.listen(button,ol.events.EventType.CLICK,this.handleClick_,this);var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+(this.collapsed_&&this.collapsible_?" ol-collapsed":"")+(this.collapsible_?"":" ol-uncollapsible");var element=document.createElement("div");
element.className=cssClasses;element.appendChild(this.ulElement_);element.appendChild(button);var render=options.render?options.render:ol.control.Attribution.render;ol.control.Control.call(this,{element:element,render:render,target:options.target});this.renderedAttributions_=[];this.renderedVisible_=true;this.logoElements_={}};ol.inherits(ol.control.Attribution,ol.control.Control);
ol.control.Attribution.prototype.getSourceAttributions_=function(frameState){var lookup={};var visibleAttributions=[];var layerStatesArray=frameState.layerStatesArray;var resolution=frameState.viewState.resolution;for(var i=0,ii=layerStatesArray.length;i<ii;++i){var layerState=layerStatesArray[i];if(!ol.layer.Layer.visibleAtResolution(layerState,resolution))continue;var source=layerState.layer.getSource();if(!source)continue;var attributionGetter=source.getAttributions2();if(!attributionGetter)continue;
var attributions=attributionGetter(frameState);if(!attributions)continue;if(Array.isArray(attributions))for(var j=0,jj=attributions.length;j<jj;++j){if(!(attributions[j]in lookup)){visibleAttributions.push(attributions[j]);lookup[attributions[j]]=true}}else if(!(attributions in lookup)){visibleAttributions.push(attributions);lookup[attributions]=true}}return visibleAttributions};ol.control.Attribution.render=function(mapEvent){this.updateElement_(mapEvent.frameState)};
ol.control.Attribution.prototype.updateElement_=function(frameState){if(!frameState){if(this.renderedVisible_){this.element.style.display="none";this.renderedVisible_=false}return}var attributions=this.getSourceAttributions_(frameState);if(ol.array.equals(attributions,this.renderedAttributions_))return;while(this.ulElement_.lastChild!==this.logoLi_)this.ulElement_.removeChild(this.ulElement_.lastChild);for(var i=0,ii=attributions.length;i<ii;++i){var element=document.createElement("LI");element.innerHTML=
attributions[i];this.ulElement_.appendChild(element)}if(attributions.length===0&&this.renderedAttributions_.length>0)this.element.classList.add("ol-logo-only");else if(this.renderedAttributions_.length===0&&attributions.length>0)this.element.classList.remove("ol-logo-only");var visible=attributions.length>0||!ol.obj.isEmpty(frameState.logos);if(this.renderedVisible_!=visible){this.element.style.display=visible?"":"none";this.renderedVisible_=visible}this.renderedAttributions_=attributions;this.insertLogos_(frameState)};
ol.control.Attribution.prototype.insertLogos_=function(frameState){var logo;var logos=frameState.logos;var logoElements=this.logoElements_;for(logo in logoElements)if(!(logo in logos)){ol.dom.removeNode(logoElements[logo]);delete logoElements[logo]}var image,logoElement,logoKey;for(logoKey in logos){var logoValue=logos[logoKey];if(logoValue instanceof HTMLElement){this.logoLi_.appendChild(logoValue);logoElements[logoKey]=logoValue}if(!(logoKey in logoElements)){image=new Image;image.src=logoKey;if(logoValue===
"")logoElement=image;else{logoElement=document.createElement("a");logoElement.href=logoValue;logoElement.appendChild(image)}this.logoLi_.appendChild(logoElement);logoElements[logoKey]=logoElement}}this.logoLi_.style.display=!ol.obj.isEmpty(logos)?"":"none"};ol.control.Attribution.prototype.handleClick_=function(event){event.preventDefault();this.handleToggle_()};
ol.control.Attribution.prototype.handleToggle_=function(){this.element.classList.toggle("ol-collapsed");if(this.collapsed_)ol.dom.replaceNode(this.collapseLabel_,this.label_);else ol.dom.replaceNode(this.label_,this.collapseLabel_);this.collapsed_=!this.collapsed_};ol.control.Attribution.prototype.getCollapsible=function(){return this.collapsible_};
ol.control.Attribution.prototype.setCollapsible=function(collapsible){if(this.collapsible_===collapsible)return;this.collapsible_=collapsible;this.element.classList.toggle("ol-uncollapsible");if(!collapsible&&this.collapsed_)this.handleToggle_()};ol.control.Attribution.prototype.setCollapsed=function(collapsed){if(!this.collapsible_||this.collapsed_===collapsed)return;this.handleToggle_()};ol.control.Attribution.prototype.getCollapsed=function(){return this.collapsed_};goog.provide("ol.control.Rotate");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol");goog.require("ol.control.Control");goog.require("ol.css");goog.require("ol.easing");
ol.control.Rotate=function(opt_options){var options=opt_options?opt_options:{};var className=options.className!==undefined?options.className:"ol-rotate";var label=options.label!==undefined?options.label:"\u21e7";this.label_=null;if(typeof label==="string"){this.label_=document.createElement("span");this.label_.className="ol-compass";this.label_.textContent=label}else{this.label_=label;this.label_.classList.add("ol-compass")}var tipLabel=options.tipLabel?options.tipLabel:"Reset rotation";var button=
document.createElement("button");button.className=className+"-reset";button.setAttribute("type","button");button.title=tipLabel;button.appendChild(this.label_);ol.events.listen(button,ol.events.EventType.CLICK,ol.control.Rotate.prototype.handleClick_,this);var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL;var element=document.createElement("div");element.className=cssClasses;element.appendChild(button);var render=options.render?options.render:ol.control.Rotate.render;
this.callResetNorth_=options.resetNorth?options.resetNorth:undefined;ol.control.Control.call(this,{element:element,render:render,target:options.target});this.duration_=options.duration!==undefined?options.duration:250;this.autoHide_=options.autoHide!==undefined?options.autoHide:true;this.rotation_=undefined;if(this.autoHide_)this.element.classList.add(ol.css.CLASS_HIDDEN)};ol.inherits(ol.control.Rotate,ol.control.Control);
ol.control.Rotate.prototype.handleClick_=function(event){event.preventDefault();if(this.callResetNorth_!==undefined)this.callResetNorth_();else this.resetNorth_()};ol.control.Rotate.prototype.resetNorth_=function(){var map=this.getMap();var view=map.getView();if(!view)return;if(view.getRotation()!==undefined)if(this.duration_>0)view.animate({rotation:0,duration:this.duration_,easing:ol.easing.easeOut});else view.setRotation(0)};
ol.control.Rotate.render=function(mapEvent){var frameState=mapEvent.frameState;if(!frameState)return;var rotation=frameState.viewState.rotation;if(rotation!=this.rotation_){var transform="rotate("+rotation+"rad)";if(this.autoHide_){var contains=this.element.classList.contains(ol.css.CLASS_HIDDEN);if(!contains&&rotation===0)this.element.classList.add(ol.css.CLASS_HIDDEN);else if(contains&&rotation!==0)this.element.classList.remove(ol.css.CLASS_HIDDEN)}this.label_.style.msTransform=transform;this.label_.style.webkitTransform=
transform;this.label_.style.transform=transform}this.rotation_=rotation};goog.provide("ol.control.Zoom");goog.require("ol");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.control.Control");goog.require("ol.css");goog.require("ol.easing");
ol.control.Zoom=function(opt_options){var options=opt_options?opt_options:{};var className=options.className!==undefined?options.className:"ol-zoom";var delta=options.delta!==undefined?options.delta:1;var zoomInLabel=options.zoomInLabel!==undefined?options.zoomInLabel:"+";var zoomOutLabel=options.zoomOutLabel!==undefined?options.zoomOutLabel:"\u2212";var zoomInTipLabel=options.zoomInTipLabel!==undefined?options.zoomInTipLabel:"Zoom in";var zoomOutTipLabel=options.zoomOutTipLabel!==undefined?options.zoomOutTipLabel:
"Zoom out";var inElement=document.createElement("button");inElement.className=className+"-in";inElement.setAttribute("type","button");inElement.title=zoomInTipLabel;inElement.appendChild(typeof zoomInLabel==="string"?document.createTextNode(zoomInLabel):zoomInLabel);ol.events.listen(inElement,ol.events.EventType.CLICK,ol.control.Zoom.prototype.handleClick_.bind(this,delta));var outElement=document.createElement("button");outElement.className=className+"-out";outElement.setAttribute("type","button");
outElement.title=zoomOutTipLabel;outElement.appendChild(typeof zoomOutLabel==="string"?document.createTextNode(zoomOutLabel):zoomOutLabel);ol.events.listen(outElement,ol.events.EventType.CLICK,ol.control.Zoom.prototype.handleClick_.bind(this,-delta));var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL;var element=document.createElement("div");element.className=cssClasses;element.appendChild(inElement);element.appendChild(outElement);ol.control.Control.call(this,{element:element,
target:options.target});this.duration_=options.duration!==undefined?options.duration:250};ol.inherits(ol.control.Zoom,ol.control.Control);ol.control.Zoom.prototype.handleClick_=function(delta,event){event.preventDefault();this.zoomByDelta_(delta)};
ol.control.Zoom.prototype.zoomByDelta_=function(delta){var map=this.getMap();var view=map.getView();if(!view)return;var currentResolution=view.getResolution();if(currentResolution){var newResolution=view.constrainResolution(currentResolution,delta);if(this.duration_>0){if(view.getAnimating())view.cancelAnimations();view.animate({resolution:newResolution,duration:this.duration_,easing:ol.easing.easeOut})}else view.setResolution(newResolution)}};goog.provide("ol.control");goog.require("ol.Collection");goog.require("ol.control.Attribution");goog.require("ol.control.Rotate");goog.require("ol.control.Zoom");
ol.control.defaults=function(opt_options){var options=opt_options?opt_options:{};var controls=new ol.Collection;var zoomControl=options.zoom!==undefined?options.zoom:true;if(zoomControl)controls.push(new ol.control.Zoom(options.zoomOptions));var rotateControl=options.rotate!==undefined?options.rotate:true;if(rotateControl)controls.push(new ol.control.Rotate(options.rotateOptions));var attributionControl=options.attribution!==undefined?options.attribution:true;if(attributionControl)controls.push(new ol.control.Attribution(options.attributionOptions));
return controls};goog.provide("ol.Kinetic");ol.Kinetic=function(decay,minVelocity,delay){this.decay_=decay;this.minVelocity_=minVelocity;this.delay_=delay;this.points_=[];this.angle_=0;this.initialVelocity_=0};ol.Kinetic.prototype.begin=function(){this.points_.length=0;this.angle_=0;this.initialVelocity_=0};ol.Kinetic.prototype.update=function(x,y){this.points_.push(x,y,Date.now())};
ol.Kinetic.prototype.end=function(){if(this.points_.length<6)return false;var delay=Date.now()-this.delay_;var lastIndex=this.points_.length-3;if(this.points_[lastIndex+2]<delay)return false;var firstIndex=lastIndex-3;while(firstIndex>0&&this.points_[firstIndex+2]>delay)firstIndex-=3;var duration=this.points_[lastIndex+2]-this.points_[firstIndex+2];if(duration<1E3/60)return false;var dx=this.points_[lastIndex]-this.points_[firstIndex];var dy=this.points_[lastIndex+1]-this.points_[firstIndex+1];this.angle_=
Math.atan2(dy,dx);this.initialVelocity_=Math.sqrt(dx*dx+dy*dy)/duration;return this.initialVelocity_>this.minVelocity_};ol.Kinetic.prototype.getDistance=function(){return(this.minVelocity_-this.initialVelocity_)/this.decay_};ol.Kinetic.prototype.getAngle=function(){return this.angle_};goog.provide("ol.interaction.Property");ol.interaction.Property={ACTIVE:"active"};goog.provide("ol.interaction.Interaction");goog.require("ol");goog.require("ol.Object");goog.require("ol.easing");goog.require("ol.interaction.Property");goog.require("ol.math");ol.interaction.Interaction=function(options){ol.Object.call(this);this.map_=null;this.setActive(true);this.handleEvent=options.handleEvent};ol.inherits(ol.interaction.Interaction,ol.Object);ol.interaction.Interaction.prototype.getActive=function(){return this.get(ol.interaction.Property.ACTIVE)};
ol.interaction.Interaction.prototype.getMap=function(){return this.map_};ol.interaction.Interaction.prototype.setActive=function(active){this.set(ol.interaction.Property.ACTIVE,active)};ol.interaction.Interaction.prototype.setMap=function(map){this.map_=map};
ol.interaction.Interaction.pan=function(view,delta,opt_duration){var currentCenter=view.getCenter();if(currentCenter){var center=view.constrainCenter([currentCenter[0]+delta[0],currentCenter[1]+delta[1]]);if(opt_duration)view.animate({duration:opt_duration,easing:ol.easing.linear,center:center});else view.setCenter(center)}};
ol.interaction.Interaction.rotate=function(view,rotation,opt_anchor,opt_duration){rotation=view.constrainRotation(rotation,0);ol.interaction.Interaction.rotateWithoutConstraints(view,rotation,opt_anchor,opt_duration)};
ol.interaction.Interaction.rotateWithoutConstraints=function(view,rotation,opt_anchor,opt_duration){if(rotation!==undefined){var currentRotation=view.getRotation();var currentCenter=view.getCenter();if(currentRotation!==undefined&&currentCenter&&opt_duration>0)view.animate({rotation:rotation,anchor:opt_anchor,duration:opt_duration,easing:ol.easing.easeOut});else view.rotate(rotation,opt_anchor)}};
ol.interaction.Interaction.zoom=function(view,resolution,opt_anchor,opt_duration,opt_direction){resolution=view.constrainResolution(resolution,0,opt_direction);ol.interaction.Interaction.zoomWithoutConstraints(view,resolution,opt_anchor,opt_duration)};
ol.interaction.Interaction.zoomByDelta=function(view,delta,opt_anchor,opt_duration){var currentResolution=view.getResolution();var resolution=view.constrainResolution(currentResolution,delta,0);if(resolution!==undefined){var resolutions=view.getResolutions();resolution=ol.math.clamp(resolution,view.getMinResolution()||resolutions[resolutions.length-1],view.getMaxResolution()||resolutions[0])}if(opt_anchor&&resolution!==undefined&&resolution!==currentResolution){var currentCenter=view.getCenter();
var center=view.calculateCenterZoom(resolution,opt_anchor);center=view.constrainCenter(center);opt_anchor=[(resolution*currentCenter[0]-currentResolution*center[0])/(resolution-currentResolution),(resolution*currentCenter[1]-currentResolution*center[1])/(resolution-currentResolution)]}ol.interaction.Interaction.zoomWithoutConstraints(view,resolution,opt_anchor,opt_duration)};
ol.interaction.Interaction.zoomWithoutConstraints=function(view,resolution,opt_anchor,opt_duration){if(resolution){var currentResolution=view.getResolution();var currentCenter=view.getCenter();if(currentResolution!==undefined&&currentCenter&&resolution!==currentResolution&&opt_duration)view.animate({resolution:resolution,anchor:opt_anchor,duration:opt_duration,easing:ol.easing.easeOut});else{if(opt_anchor){var center=view.calculateCenterZoom(resolution,opt_anchor);view.setCenter(center)}view.setResolution(resolution)}}};goog.provide("ol.interaction.DoubleClickZoom");goog.require("ol");goog.require("ol.MapBrowserEventType");goog.require("ol.interaction.Interaction");ol.interaction.DoubleClickZoom=function(opt_options){var options=opt_options?opt_options:{};this.delta_=options.delta?options.delta:1;ol.interaction.Interaction.call(this,{handleEvent:ol.interaction.DoubleClickZoom.handleEvent});this.duration_=options.duration!==undefined?options.duration:250};ol.inherits(ol.interaction.DoubleClickZoom,ol.interaction.Interaction);
ol.interaction.DoubleClickZoom.handleEvent=function(mapBrowserEvent){var stopEvent=false;var browserEvent=mapBrowserEvent.originalEvent;if(mapBrowserEvent.type==ol.MapBrowserEventType.DBLCLICK){var map=mapBrowserEvent.map;var anchor=mapBrowserEvent.coordinate;var delta=browserEvent.shiftKey?-this.delta_:this.delta_;var view=map.getView();ol.interaction.Interaction.zoomByDelta(view,delta,anchor,this.duration_);mapBrowserEvent.preventDefault();stopEvent=true}return!stopEvent};goog.provide("ol.events.condition");goog.require("ol.MapBrowserEventType");goog.require("ol.asserts");goog.require("ol.functions");goog.require("ol.has");ol.events.condition.altKeyOnly=function(mapBrowserEvent){var originalEvent=mapBrowserEvent.originalEvent;return originalEvent.altKey&&!(originalEvent.metaKey||originalEvent.ctrlKey)&&!originalEvent.shiftKey};
ol.events.condition.altShiftKeysOnly=function(mapBrowserEvent){var originalEvent=mapBrowserEvent.originalEvent;return originalEvent.altKey&&!(originalEvent.metaKey||originalEvent.ctrlKey)&&originalEvent.shiftKey};ol.events.condition.always=ol.functions.TRUE;ol.events.condition.click=function(mapBrowserEvent){return mapBrowserEvent.type==ol.MapBrowserEventType.CLICK};
ol.events.condition.mouseActionButton=function(mapBrowserEvent){var originalEvent=mapBrowserEvent.originalEvent;return originalEvent.button==0&&!(ol.has.WEBKIT&&ol.has.MAC&&originalEvent.ctrlKey)};ol.events.condition.never=ol.functions.FALSE;ol.events.condition.pointerMove=function(mapBrowserEvent){return mapBrowserEvent.type=="pointermove"};ol.events.condition.singleClick=function(mapBrowserEvent){return mapBrowserEvent.type==ol.MapBrowserEventType.SINGLECLICK};
ol.events.condition.doubleClick=function(mapBrowserEvent){return mapBrowserEvent.type==ol.MapBrowserEventType.DBLCLICK};ol.events.condition.noModifierKeys=function(mapBrowserEvent){var originalEvent=mapBrowserEvent.originalEvent;return!originalEvent.altKey&&!(originalEvent.metaKey||originalEvent.ctrlKey)&&!originalEvent.shiftKey};
ol.events.condition.platformModifierKeyOnly=function(mapBrowserEvent){var originalEvent=mapBrowserEvent.originalEvent;return!originalEvent.altKey&&(ol.has.MAC?originalEvent.metaKey:originalEvent.ctrlKey)&&!originalEvent.shiftKey};ol.events.condition.shiftKeyOnly=function(mapBrowserEvent){var originalEvent=mapBrowserEvent.originalEvent;return!originalEvent.altKey&&!(originalEvent.metaKey||originalEvent.ctrlKey)&&originalEvent.shiftKey};
ol.events.condition.targetNotEditable=function(mapBrowserEvent){var target=mapBrowserEvent.originalEvent.target;var tagName=target.tagName;return tagName!=="INPUT"&&tagName!=="SELECT"&&tagName!=="TEXTAREA"};ol.events.condition.mouseOnly=function(mapBrowserEvent){ol.asserts.assert(mapBrowserEvent.pointerEvent,56);return mapBrowserEvent.pointerEvent.pointerType=="mouse"};
ol.events.condition.primaryAction=function(mapBrowserEvent){var pointerEvent=mapBrowserEvent.pointerEvent;return pointerEvent.isPrimary&&pointerEvent.button===0};goog.provide("ol.interaction.Pointer");goog.require("ol");goog.require("ol.functions");goog.require("ol.MapBrowserEventType");goog.require("ol.MapBrowserPointerEvent");goog.require("ol.interaction.Interaction");goog.require("ol.obj");
ol.interaction.Pointer=function(opt_options){var options=opt_options?opt_options:{};var handleEvent=options.handleEvent?options.handleEvent:ol.interaction.Pointer.handleEvent;ol.interaction.Interaction.call(this,{handleEvent:handleEvent});this.handleDownEvent_=options.handleDownEvent?options.handleDownEvent:ol.interaction.Pointer.handleDownEvent;this.handleDragEvent_=options.handleDragEvent?options.handleDragEvent:ol.interaction.Pointer.handleDragEvent;this.handleMoveEvent_=options.handleMoveEvent?
options.handleMoveEvent:ol.interaction.Pointer.handleMoveEvent;this.handleUpEvent_=options.handleUpEvent?options.handleUpEvent:ol.interaction.Pointer.handleUpEvent;this.handlingDownUpSequence=false;this.trackedPointers_={};this.targetPointers=[]};ol.inherits(ol.interaction.Pointer,ol.interaction.Interaction);
ol.interaction.Pointer.centroid=function(pointerEvents){var length=pointerEvents.length;var clientX=0;var clientY=0;for(var i=0;i<length;i++){clientX+=pointerEvents[i].clientX;clientY+=pointerEvents[i].clientY}return[clientX/length,clientY/length]};ol.interaction.Pointer.prototype.isPointerDraggingEvent_=function(mapBrowserEvent){var type=mapBrowserEvent.type;return type===ol.MapBrowserEventType.POINTERDOWN||type===ol.MapBrowserEventType.POINTERDRAG||type===ol.MapBrowserEventType.POINTERUP};
ol.interaction.Pointer.prototype.updateTrackedPointers_=function(mapBrowserEvent){if(this.isPointerDraggingEvent_(mapBrowserEvent)){var event=mapBrowserEvent.pointerEvent;var id=event.pointerId.toString();if(mapBrowserEvent.type==ol.MapBrowserEventType.POINTERUP)delete this.trackedPointers_[id];else if(mapBrowserEvent.type==ol.MapBrowserEventType.POINTERDOWN)this.trackedPointers_[id]=event;else if(id in this.trackedPointers_)this.trackedPointers_[id]=event;this.targetPointers=ol.obj.getValues(this.trackedPointers_)}};
ol.interaction.Pointer.handleDragEvent=ol.nullFunction;ol.interaction.Pointer.handleUpEvent=ol.functions.FALSE;ol.interaction.Pointer.handleDownEvent=ol.functions.FALSE;ol.interaction.Pointer.handleMoveEvent=ol.nullFunction;
ol.interaction.Pointer.handleEvent=function(mapBrowserEvent){if(!(mapBrowserEvent instanceof ol.MapBrowserPointerEvent))return true;var stopEvent=false;this.updateTrackedPointers_(mapBrowserEvent);if(this.handlingDownUpSequence)if(mapBrowserEvent.type==ol.MapBrowserEventType.POINTERDRAG)this.handleDragEvent_(mapBrowserEvent);else{if(mapBrowserEvent.type==ol.MapBrowserEventType.POINTERUP){var handledUp=this.handleUpEvent_(mapBrowserEvent);this.handlingDownUpSequence=handledUp&&this.targetPointers.length>
0}}else if(mapBrowserEvent.type==ol.MapBrowserEventType.POINTERDOWN){var handled=this.handleDownEvent_(mapBrowserEvent);this.handlingDownUpSequence=handled;stopEvent=this.shouldStopEvent(handled)}else if(mapBrowserEvent.type==ol.MapBrowserEventType.POINTERMOVE)this.handleMoveEvent_(mapBrowserEvent);return!stopEvent};ol.interaction.Pointer.prototype.shouldStopEvent=function(handled){return handled};goog.provide("ol.interaction.DragPan");goog.require("ol");goog.require("ol.ViewHint");goog.require("ol.coordinate");goog.require("ol.easing");goog.require("ol.events.condition");goog.require("ol.functions");goog.require("ol.interaction.Pointer");
ol.interaction.DragPan=function(opt_options){ol.interaction.Pointer.call(this,{handleDownEvent:ol.interaction.DragPan.handleDownEvent_,handleDragEvent:ol.interaction.DragPan.handleDragEvent_,handleUpEvent:ol.interaction.DragPan.handleUpEvent_});var options=opt_options?opt_options:{};this.kinetic_=options.kinetic;this.lastCentroid=null;this.lastPointersCount_;this.condition_=options.condition?options.condition:ol.events.condition.noModifierKeys;this.noKinetic_=false};
ol.inherits(ol.interaction.DragPan,ol.interaction.Pointer);
ol.interaction.DragPan.handleDragEvent_=function(mapBrowserEvent){var targetPointers=this.targetPointers;var centroid=ol.interaction.Pointer.centroid(targetPointers);if(targetPointers.length==this.lastPointersCount_){if(this.kinetic_)this.kinetic_.update(centroid[0],centroid[1]);if(this.lastCentroid){var deltaX=this.lastCentroid[0]-centroid[0];var deltaY=centroid[1]-this.lastCentroid[1];var map=mapBrowserEvent.map;var view=map.getView();var viewState=view.getState();var center=[deltaX,deltaY];ol.coordinate.scale(center,
viewState.resolution);ol.coordinate.rotate(center,viewState.rotation);ol.coordinate.add(center,viewState.center);center=view.constrainCenter(center);view.setCenter(center)}}else if(this.kinetic_)this.kinetic_.begin();this.lastCentroid=centroid;this.lastPointersCount_=targetPointers.length};
ol.interaction.DragPan.handleUpEvent_=function(mapBrowserEvent){var map=mapBrowserEvent.map;var view=map.getView();if(this.targetPointers.length===0){if(!this.noKinetic_&&this.kinetic_&&this.kinetic_.end()){var distance=this.kinetic_.getDistance();var angle=this.kinetic_.getAngle();var center=view.getCenter();var centerpx=map.getPixelFromCoordinate(center);var dest=map.getCoordinateFromPixel([centerpx[0]-distance*Math.cos(angle),centerpx[1]-distance*Math.sin(angle)]);view.animate({center:view.constrainCenter(dest),
duration:500,easing:ol.easing.easeOut})}view.setHint(ol.ViewHint.INTERACTING,-1);return false}else{if(this.kinetic_)this.kinetic_.begin();this.lastCentroid=null;return true}};
ol.interaction.DragPan.handleDownEvent_=function(mapBrowserEvent){if(this.targetPointers.length>0&&this.condition_(mapBrowserEvent)){var map=mapBrowserEvent.map;var view=map.getView();this.lastCentroid=null;if(!this.handlingDownUpSequence)view.setHint(ol.ViewHint.INTERACTING,1);if(view.getAnimating())view.setCenter(mapBrowserEvent.frameState.viewState.center);if(this.kinetic_)this.kinetic_.begin();this.noKinetic_=this.targetPointers.length>1;return true}else return false};
ol.interaction.DragPan.prototype.shouldStopEvent=ol.functions.FALSE;goog.provide("ol.interaction.DragRotate");goog.require("ol");goog.require("ol.RotationConstraint");goog.require("ol.ViewHint");goog.require("ol.events.condition");goog.require("ol.functions");goog.require("ol.interaction.Interaction");goog.require("ol.interaction.Pointer");
ol.interaction.DragRotate=function(opt_options){var options=opt_options?opt_options:{};ol.interaction.Pointer.call(this,{handleDownEvent:ol.interaction.DragRotate.handleDownEvent_,handleDragEvent:ol.interaction.DragRotate.handleDragEvent_,handleUpEvent:ol.interaction.DragRotate.handleUpEvent_});this.condition_=options.condition?options.condition:ol.events.condition.altShiftKeysOnly;this.lastAngle_=undefined;this.duration_=options.duration!==undefined?options.duration:250};
ol.inherits(ol.interaction.DragRotate,ol.interaction.Pointer);
ol.interaction.DragRotate.handleDragEvent_=function(mapBrowserEvent){if(!ol.events.condition.mouseOnly(mapBrowserEvent))return;var map=mapBrowserEvent.map;var view=map.getView();if(view.getConstraints().rotation===ol.RotationConstraint.disable)return;var size=map.getSize();var offset=mapBrowserEvent.pixel;var theta=Math.atan2(size[1]/2-offset[1],offset[0]-size[0]/2);if(this.lastAngle_!==undefined){var delta=theta-this.lastAngle_;var rotation=view.getRotation();ol.interaction.Interaction.rotateWithoutConstraints(view,
rotation-delta)}this.lastAngle_=theta};ol.interaction.DragRotate.handleUpEvent_=function(mapBrowserEvent){if(!ol.events.condition.mouseOnly(mapBrowserEvent))return true;var map=mapBrowserEvent.map;var view=map.getView();view.setHint(ol.ViewHint.INTERACTING,-1);var rotation=view.getRotation();ol.interaction.Interaction.rotate(view,rotation,undefined,this.duration_);return false};
ol.interaction.DragRotate.handleDownEvent_=function(mapBrowserEvent){if(!ol.events.condition.mouseOnly(mapBrowserEvent))return false;if(ol.events.condition.mouseActionButton(mapBrowserEvent)&&this.condition_(mapBrowserEvent)){var map=mapBrowserEvent.map;map.getView().setHint(ol.ViewHint.INTERACTING,1);this.lastAngle_=undefined;return true}else return false};ol.interaction.DragRotate.prototype.shouldStopEvent=ol.functions.FALSE;goog.provide("ol.render.Box");goog.require("ol");goog.require("ol.Disposable");goog.require("ol.geom.Polygon");ol.render.Box=function(className){this.geometry_=null;this.element_=document.createElement("div");this.element_.style.position="absolute";this.element_.className="ol-box "+className;this.map_=null;this.startPixel_=null;this.endPixel_=null};ol.inherits(ol.render.Box,ol.Disposable);ol.render.Box.prototype.disposeInternal=function(){this.setMap(null)};
ol.render.Box.prototype.render_=function(){var startPixel=this.startPixel_;var endPixel=this.endPixel_;var px="px";var style=this.element_.style;style.left=Math.min(startPixel[0],endPixel[0])+px;style.top=Math.min(startPixel[1],endPixel[1])+px;style.width=Math.abs(endPixel[0]-startPixel[0])+px;style.height=Math.abs(endPixel[1]-startPixel[1])+px};
ol.render.Box.prototype.setMap=function(map){if(this.map_){this.map_.getOverlayContainer().removeChild(this.element_);var style=this.element_.style;style.left=style.top=style.width=style.height="inherit"}this.map_=map;if(this.map_)this.map_.getOverlayContainer().appendChild(this.element_)};ol.render.Box.prototype.setPixels=function(startPixel,endPixel){this.startPixel_=startPixel;this.endPixel_=endPixel;this.createOrUpdateGeometry();this.render_()};
ol.render.Box.prototype.createOrUpdateGeometry=function(){var startPixel=this.startPixel_;var endPixel=this.endPixel_;var pixels=[startPixel,[startPixel[0],endPixel[1]],endPixel,[endPixel[0],startPixel[1]]];var coordinates=pixels.map(this.map_.getCoordinateFromPixel,this.map_);coordinates[4]=coordinates[0].slice();if(!this.geometry_)this.geometry_=new ol.geom.Polygon([coordinates]);else this.geometry_.setCoordinates([coordinates])};ol.render.Box.prototype.getGeometry=function(){return this.geometry_};goog.provide("ol.interaction.DragBox");goog.require("ol.events.Event");goog.require("ol");goog.require("ol.events.condition");goog.require("ol.interaction.Pointer");goog.require("ol.render.Box");
ol.interaction.DragBox=function(opt_options){ol.interaction.Pointer.call(this,{handleDownEvent:ol.interaction.DragBox.handleDownEvent_,handleDragEvent:ol.interaction.DragBox.handleDragEvent_,handleUpEvent:ol.interaction.DragBox.handleUpEvent_});var options=opt_options?opt_options:{};this.box_=new ol.render.Box(options.className||"ol-dragbox");this.minArea_=options.minArea!==undefined?options.minArea:64;this.startPixel_=null;this.condition_=options.condition?options.condition:ol.events.condition.always;
this.boxEndCondition_=options.boxEndCondition?options.boxEndCondition:ol.interaction.DragBox.defaultBoxEndCondition};ol.inherits(ol.interaction.DragBox,ol.interaction.Pointer);ol.interaction.DragBox.defaultBoxEndCondition=function(mapBrowserEvent,startPixel,endPixel){var width=endPixel[0]-startPixel[0];var height=endPixel[1]-startPixel[1];return width*width+height*height>=this.minArea_};
ol.interaction.DragBox.handleDragEvent_=function(mapBrowserEvent){if(!ol.events.condition.mouseOnly(mapBrowserEvent))return;this.box_.setPixels(this.startPixel_,mapBrowserEvent.pixel);this.dispatchEvent(new ol.interaction.DragBox.Event(ol.interaction.DragBox.EventType_.BOXDRAG,mapBrowserEvent.coordinate,mapBrowserEvent))};ol.interaction.DragBox.prototype.getGeometry=function(){return this.box_.getGeometry()};ol.interaction.DragBox.prototype.onBoxEnd=ol.nullFunction;
ol.interaction.DragBox.handleUpEvent_=function(mapBrowserEvent){if(!ol.events.condition.mouseOnly(mapBrowserEvent))return true;this.box_.setMap(null);if(this.boxEndCondition_(mapBrowserEvent,this.startPixel_,mapBrowserEvent.pixel)){this.onBoxEnd(mapBrowserEvent);this.dispatchEvent(new ol.interaction.DragBox.Event(ol.interaction.DragBox.EventType_.BOXEND,mapBrowserEvent.coordinate,mapBrowserEvent))}return false};
ol.interaction.DragBox.handleDownEvent_=function(mapBrowserEvent){if(!ol.events.condition.mouseOnly(mapBrowserEvent))return false;if(ol.events.condition.mouseActionButton(mapBrowserEvent)&&this.condition_(mapBrowserEvent)){this.startPixel_=mapBrowserEvent.pixel;this.box_.setMap(mapBrowserEvent.map);this.box_.setPixels(this.startPixel_,this.startPixel_);this.dispatchEvent(new ol.interaction.DragBox.Event(ol.interaction.DragBox.EventType_.BOXSTART,mapBrowserEvent.coordinate,mapBrowserEvent));return true}else return false};
ol.interaction.DragBox.EventType_={BOXSTART:"boxstart",BOXDRAG:"boxdrag",BOXEND:"boxend"};ol.interaction.DragBox.Event=function(type,coordinate,mapBrowserEvent){ol.events.Event.call(this,type);this.coordinate=coordinate;this.mapBrowserEvent=mapBrowserEvent};ol.inherits(ol.interaction.DragBox.Event,ol.events.Event);goog.provide("ol.interaction.DragZoom");goog.require("ol");goog.require("ol.easing");goog.require("ol.events.condition");goog.require("ol.extent");goog.require("ol.interaction.DragBox");
ol.interaction.DragZoom=function(opt_options){var options=opt_options?opt_options:{};var condition=options.condition?options.condition:ol.events.condition.shiftKeyOnly;this.duration_=options.duration!==undefined?options.duration:200;this.out_=options.out!==undefined?options.out:false;ol.interaction.DragBox.call(this,{condition:condition,className:options.className||"ol-dragzoom"})};ol.inherits(ol.interaction.DragZoom,ol.interaction.DragBox);
ol.interaction.DragZoom.prototype.onBoxEnd=function(){var map=this.getMap();var view=map.getView();var size=map.getSize();var extent=this.getGeometry().getExtent();if(this.out_){var mapExtent=view.calculateExtent(size);var boxPixelExtent=ol.extent.createOrUpdateFromCoordinates([map.getPixelFromCoordinate(ol.extent.getBottomLeft(extent)),map.getPixelFromCoordinate(ol.extent.getTopRight(extent))]);var factor=view.getResolutionForExtent(boxPixelExtent,size);ol.extent.scaleFromCenter(mapExtent,1/factor);
extent=mapExtent}var resolution=view.constrainResolution(view.getResolutionForExtent(extent,size));var center=ol.extent.getCenter(extent);center=view.constrainCenter(center);view.animate({resolution:resolution,center:center,duration:this.duration_,easing:ol.easing.easeOut})};goog.provide("ol.events.KeyCode");ol.events.KeyCode={LEFT:37,UP:38,RIGHT:39,DOWN:40};goog.provide("ol.interaction.KeyboardPan");goog.require("ol");goog.require("ol.coordinate");goog.require("ol.events.EventType");goog.require("ol.events.KeyCode");goog.require("ol.events.condition");goog.require("ol.interaction.Interaction");
ol.interaction.KeyboardPan=function(opt_options){ol.interaction.Interaction.call(this,{handleEvent:ol.interaction.KeyboardPan.handleEvent});var options=opt_options||{};this.defaultCondition_=function(mapBrowserEvent){return ol.events.condition.noModifierKeys(mapBrowserEvent)&&ol.events.condition.targetNotEditable(mapBrowserEvent)};this.condition_=options.condition!==undefined?options.condition:this.defaultCondition_;this.duration_=options.duration!==undefined?options.duration:100;this.pixelDelta_=
options.pixelDelta!==undefined?options.pixelDelta:128};ol.inherits(ol.interaction.KeyboardPan,ol.interaction.Interaction);
ol.interaction.KeyboardPan.handleEvent=function(mapBrowserEvent){var stopEvent=false;if(mapBrowserEvent.type==ol.events.EventType.KEYDOWN){var keyEvent=mapBrowserEvent.originalEvent;var keyCode=keyEvent.keyCode;if(this.condition_(mapBrowserEvent)&&(keyCode==ol.events.KeyCode.DOWN||keyCode==ol.events.KeyCode.LEFT||keyCode==ol.events.KeyCode.RIGHT||keyCode==ol.events.KeyCode.UP)){var map=mapBrowserEvent.map;var view=map.getView();var mapUnitsDelta=view.getResolution()*this.pixelDelta_;var deltaX=0,
deltaY=0;if(keyCode==ol.events.KeyCode.DOWN)deltaY=-mapUnitsDelta;else if(keyCode==ol.events.KeyCode.LEFT)deltaX=-mapUnitsDelta;else if(keyCode==ol.events.KeyCode.RIGHT)deltaX=mapUnitsDelta;else deltaY=mapUnitsDelta;var delta=[deltaX,deltaY];ol.coordinate.rotate(delta,view.getRotation());ol.interaction.Interaction.pan(view,delta,this.duration_);mapBrowserEvent.preventDefault();stopEvent=true}}return!stopEvent};goog.provide("ol.interaction.KeyboardZoom");goog.require("ol");goog.require("ol.events.EventType");goog.require("ol.events.condition");goog.require("ol.interaction.Interaction");
ol.interaction.KeyboardZoom=function(opt_options){ol.interaction.Interaction.call(this,{handleEvent:ol.interaction.KeyboardZoom.handleEvent});var options=opt_options?opt_options:{};this.condition_=options.condition?options.condition:ol.events.condition.targetNotEditable;this.delta_=options.delta?options.delta:1;this.duration_=options.duration!==undefined?options.duration:100};ol.inherits(ol.interaction.KeyboardZoom,ol.interaction.Interaction);
ol.interaction.KeyboardZoom.handleEvent=function(mapBrowserEvent){var stopEvent=false;if(mapBrowserEvent.type==ol.events.EventType.KEYDOWN||mapBrowserEvent.type==ol.events.EventType.KEYPRESS){var keyEvent=mapBrowserEvent.originalEvent;var charCode=keyEvent.charCode;if(this.condition_(mapBrowserEvent)&&(charCode=="+".charCodeAt(0)||charCode=="-".charCodeAt(0))){var map=mapBrowserEvent.map;var delta=charCode=="+".charCodeAt(0)?this.delta_:-this.delta_;var view=map.getView();ol.interaction.Interaction.zoomByDelta(view,
delta,undefined,this.duration_);mapBrowserEvent.preventDefault();stopEvent=true}}return!stopEvent};goog.provide("ol.interaction.MouseWheelZoom");goog.require("ol");goog.require("ol.ViewHint");goog.require("ol.easing");goog.require("ol.events.EventType");goog.require("ol.has");goog.require("ol.interaction.Interaction");goog.require("ol.math");
ol.interaction.MouseWheelZoom=function(opt_options){ol.interaction.Interaction.call(this,{handleEvent:ol.interaction.MouseWheelZoom.handleEvent});var options=opt_options||{};this.delta_=0;this.duration_=options.duration!==undefined?options.duration:250;this.timeout_=options.timeout!==undefined?options.timeout:80;this.useAnchor_=options.useAnchor!==undefined?options.useAnchor:true;this.constrainResolution_=options.constrainResolution||false;this.lastAnchor_=null;this.startTime_=undefined;this.timeoutId_=
undefined;this.mode_=undefined;this.trackpadEventGap_=400;this.trackpadTimeoutId_=undefined;this.trackpadDeltaPerZoom_=300;this.trackpadZoomBuffer_=1.5};ol.inherits(ol.interaction.MouseWheelZoom,ol.interaction.Interaction);
ol.interaction.MouseWheelZoom.handleEvent=function(mapBrowserEvent){var type=mapBrowserEvent.type;if(type!==ol.events.EventType.WHEEL&&type!==ol.events.EventType.MOUSEWHEEL)return true;mapBrowserEvent.preventDefault();var map=mapBrowserEvent.map;var wheelEvent=mapBrowserEvent.originalEvent;if(this.useAnchor_)this.lastAnchor_=mapBrowserEvent.coordinate;var delta;if(mapBrowserEvent.type==ol.events.EventType.WHEEL){delta=wheelEvent.deltaY;if(ol.has.FIREFOX&&wheelEvent.deltaMode===WheelEvent.DOM_DELTA_PIXEL)delta/=
ol.has.DEVICE_PIXEL_RATIO;if(wheelEvent.deltaMode===WheelEvent.DOM_DELTA_LINE)delta*=40}else if(mapBrowserEvent.type==ol.events.EventType.MOUSEWHEEL){delta=-wheelEvent.wheelDeltaY;if(ol.has.SAFARI)delta/=3}if(delta===0)return false;var now=Date.now();if(this.startTime_===undefined)this.startTime_=now;if(!this.mode_||now-this.startTime_>this.trackpadEventGap_)this.mode_=Math.abs(delta)<4?ol.interaction.MouseWheelZoom.Mode_.TRACKPAD:ol.interaction.MouseWheelZoom.Mode_.WHEEL;if(this.mode_===ol.interaction.MouseWheelZoom.Mode_.TRACKPAD){var view=
map.getView();if(this.trackpadTimeoutId_)clearTimeout(this.trackpadTimeoutId_);else view.setHint(ol.ViewHint.INTERACTING,1);this.trackpadTimeoutId_=setTimeout(this.decrementInteractingHint_.bind(this),this.trackpadEventGap_);var resolution=view.getResolution()*Math.pow(2,delta/this.trackpadDeltaPerZoom_);var minResolution=view.getMinResolution();var maxResolution=view.getMaxResolution();var rebound=0;if(resolution<minResolution){resolution=Math.max(resolution,minResolution/this.trackpadZoomBuffer_);
rebound=1}else if(resolution>maxResolution){resolution=Math.min(resolution,maxResolution*this.trackpadZoomBuffer_);rebound=-1}if(this.lastAnchor_){var center=view.calculateCenterZoom(resolution,this.lastAnchor_);view.setCenter(view.constrainCenter(center))}view.setResolution(resolution);if(rebound===0&&this.constrainResolution_)view.animate({resolution:view.constrainResolution(resolution,delta>0?-1:1),easing:ol.easing.easeOut,anchor:this.lastAnchor_,duration:this.duration_});if(rebound>0)view.animate({resolution:minResolution,
easing:ol.easing.easeOut,anchor:this.lastAnchor_,duration:500});else if(rebound<0)view.animate({resolution:maxResolution,easing:ol.easing.easeOut,anchor:this.lastAnchor_,duration:500});this.startTime_=now;return false}this.delta_+=delta;var timeLeft=Math.max(this.timeout_-(now-this.startTime_),0);clearTimeout(this.timeoutId_);this.timeoutId_=setTimeout(this.handleWheelZoom_.bind(this,map),timeLeft);return false};
ol.interaction.MouseWheelZoom.prototype.decrementInteractingHint_=function(){this.trackpadTimeoutId_=undefined;var view=this.getMap().getView();view.setHint(ol.ViewHint.INTERACTING,-1)};
ol.interaction.MouseWheelZoom.prototype.handleWheelZoom_=function(map){var view=map.getView();if(view.getAnimating())view.cancelAnimations();var maxDelta=ol.MOUSEWHEELZOOM_MAXDELTA;var delta=ol.math.clamp(this.delta_,-maxDelta,maxDelta);ol.interaction.Interaction.zoomByDelta(view,-delta,this.lastAnchor_,this.duration_);this.mode_=undefined;this.delta_=0;this.lastAnchor_=null;this.startTime_=undefined;this.timeoutId_=undefined};
ol.interaction.MouseWheelZoom.prototype.setMouseAnchor=function(useAnchor){this.useAnchor_=useAnchor;if(!useAnchor)this.lastAnchor_=null};ol.interaction.MouseWheelZoom.Mode_={TRACKPAD:"trackpad",WHEEL:"wheel"};goog.provide("ol.interaction.PinchRotate");goog.require("ol");goog.require("ol.ViewHint");goog.require("ol.functions");goog.require("ol.interaction.Interaction");goog.require("ol.interaction.Pointer");goog.require("ol.RotationConstraint");
ol.interaction.PinchRotate=function(opt_options){ol.interaction.Pointer.call(this,{handleDownEvent:ol.interaction.PinchRotate.handleDownEvent_,handleDragEvent:ol.interaction.PinchRotate.handleDragEvent_,handleUpEvent:ol.interaction.PinchRotate.handleUpEvent_});var options=opt_options||{};this.anchor_=null;this.lastAngle_=undefined;this.rotating_=false;this.rotationDelta_=0;this.threshold_=options.threshold!==undefined?options.threshold:.3;this.duration_=options.duration!==undefined?options.duration:
250};ol.inherits(ol.interaction.PinchRotate,ol.interaction.Pointer);
ol.interaction.PinchRotate.handleDragEvent_=function(mapBrowserEvent){var rotationDelta=0;var touch0=this.targetPointers[0];var touch1=this.targetPointers[1];var angle=Math.atan2(touch1.clientY-touch0.clientY,touch1.clientX-touch0.clientX);if(this.lastAngle_!==undefined){var delta=angle-this.lastAngle_;this.rotationDelta_+=delta;if(!this.rotating_&&Math.abs(this.rotationDelta_)>this.threshold_)this.rotating_=true;rotationDelta=delta}this.lastAngle_=angle;var map=mapBrowserEvent.map;var view=map.getView();
if(view.getConstraints().rotation===ol.RotationConstraint.disable)return;var viewportPosition=map.getViewport().getBoundingClientRect();var centroid=ol.interaction.Pointer.centroid(this.targetPointers);centroid[0]-=viewportPosition.left;centroid[1]-=viewportPosition.top;this.anchor_=map.getCoordinateFromPixel(centroid);if(this.rotating_){var rotation=view.getRotation();map.render();ol.interaction.Interaction.rotateWithoutConstraints(view,rotation+rotationDelta,this.anchor_)}};
ol.interaction.PinchRotate.handleUpEvent_=function(mapBrowserEvent){if(this.targetPointers.length<2){var map=mapBrowserEvent.map;var view=map.getView();view.setHint(ol.ViewHint.INTERACTING,-1);if(this.rotating_){var rotation=view.getRotation();ol.interaction.Interaction.rotate(view,rotation,this.anchor_,this.duration_)}return false}else return true};
ol.interaction.PinchRotate.handleDownEvent_=function(mapBrowserEvent){if(this.targetPointers.length>=2){var map=mapBrowserEvent.map;this.anchor_=null;this.lastAngle_=undefined;this.rotating_=false;this.rotationDelta_=0;if(!this.handlingDownUpSequence)map.getView().setHint(ol.ViewHint.INTERACTING,1);return true}else return false};ol.interaction.PinchRotate.prototype.shouldStopEvent=ol.functions.FALSE;goog.provide("ol.interaction.PinchZoom");goog.require("ol");goog.require("ol.ViewHint");goog.require("ol.functions");goog.require("ol.interaction.Interaction");goog.require("ol.interaction.Pointer");
ol.interaction.PinchZoom=function(opt_options){ol.interaction.Pointer.call(this,{handleDownEvent:ol.interaction.PinchZoom.handleDownEvent_,handleDragEvent:ol.interaction.PinchZoom.handleDragEvent_,handleUpEvent:ol.interaction.PinchZoom.handleUpEvent_});var options=opt_options?opt_options:{};this.constrainResolution_=options.constrainResolution||false;this.anchor_=null;this.duration_=options.duration!==undefined?options.duration:400;this.lastDistance_=undefined;this.lastScaleDelta_=1};
ol.inherits(ol.interaction.PinchZoom,ol.interaction.Pointer);
ol.interaction.PinchZoom.handleDragEvent_=function(mapBrowserEvent){var scaleDelta=1;var touch0=this.targetPointers[0];var touch1=this.targetPointers[1];var dx=touch0.clientX-touch1.clientX;var dy=touch0.clientY-touch1.clientY;var distance=Math.sqrt(dx*dx+dy*dy);if(this.lastDistance_!==undefined)scaleDelta=this.lastDistance_/distance;this.lastDistance_=distance;var map=mapBrowserEvent.map;var view=map.getView();var resolution=view.getResolution();var maxResolution=view.getMaxResolution();var minResolution=
view.getMinResolution();var newResolution=resolution*scaleDelta;if(newResolution>maxResolution){scaleDelta=maxResolution/resolution;newResolution=maxResolution}else if(newResolution<minResolution){scaleDelta=minResolution/resolution;newResolution=minResolution}if(scaleDelta!=1)this.lastScaleDelta_=scaleDelta;var viewportPosition=map.getViewport().getBoundingClientRect();var centroid=ol.interaction.Pointer.centroid(this.targetPointers);centroid[0]-=viewportPosition.left;centroid[1]-=viewportPosition.top;
this.anchor_=map.getCoordinateFromPixel(centroid);map.render();ol.interaction.Interaction.zoomWithoutConstraints(view,newResolution,this.anchor_)};
ol.interaction.PinchZoom.handleUpEvent_=function(mapBrowserEvent){if(this.targetPointers.length<2){var map=mapBrowserEvent.map;var view=map.getView();view.setHint(ol.ViewHint.INTERACTING,-1);var resolution=view.getResolution();if(this.constrainResolution_||resolution<view.getMinResolution()||resolution>view.getMaxResolution()){var direction=this.lastScaleDelta_-1;ol.interaction.Interaction.zoom(view,resolution,this.anchor_,this.duration_,direction)}return false}else return true};
ol.interaction.PinchZoom.handleDownEvent_=function(mapBrowserEvent){if(this.targetPointers.length>=2){var map=mapBrowserEvent.map;this.anchor_=null;this.lastDistance_=undefined;this.lastScaleDelta_=1;if(!this.handlingDownUpSequence)map.getView().setHint(ol.ViewHint.INTERACTING,1);return true}else return false};ol.interaction.PinchZoom.prototype.shouldStopEvent=ol.functions.FALSE;goog.provide("ol.interaction");goog.require("ol.Collection");goog.require("ol.Kinetic");goog.require("ol.interaction.DoubleClickZoom");goog.require("ol.interaction.DragPan");goog.require("ol.interaction.DragRotate");goog.require("ol.interaction.DragZoom");goog.require("ol.interaction.KeyboardPan");goog.require("ol.interaction.KeyboardZoom");goog.require("ol.interaction.MouseWheelZoom");goog.require("ol.interaction.PinchRotate");goog.require("ol.interaction.PinchZoom");
ol.interaction.defaults=function(opt_options){var options=opt_options?opt_options:{};var interactions=new ol.Collection;var kinetic=new ol.Kinetic(-.005,.05,100);var altShiftDragRotate=options.altShiftDragRotate!==undefined?options.altShiftDragRotate:true;if(altShiftDragRotate)interactions.push(new ol.interaction.DragRotate);var doubleClickZoom=options.doubleClickZoom!==undefined?options.doubleClickZoom:true;if(doubleClickZoom)interactions.push(new ol.interaction.DoubleClickZoom({delta:options.zoomDelta,
duration:options.zoomDuration}));var dragPan=options.dragPan!==undefined?options.dragPan:true;if(dragPan)interactions.push(new ol.interaction.DragPan({kinetic:kinetic}));var pinchRotate=options.pinchRotate!==undefined?options.pinchRotate:true;if(pinchRotate)interactions.push(new ol.interaction.PinchRotate);var pinchZoom=options.pinchZoom!==undefined?options.pinchZoom:true;if(pinchZoom)interactions.push(new ol.interaction.PinchZoom({constrainResolution:options.constrainResolution,duration:options.zoomDuration}));
var keyboard=options.keyboard!==undefined?options.keyboard:true;if(keyboard){interactions.push(new ol.interaction.KeyboardPan);interactions.push(new ol.interaction.KeyboardZoom({delta:options.zoomDelta,duration:options.zoomDuration}))}var mouseWheelZoom=options.mouseWheelZoom!==undefined?options.mouseWheelZoom:true;if(mouseWheelZoom)interactions.push(new ol.interaction.MouseWheelZoom({constrainResolution:options.constrainResolution,duration:options.zoomDuration}));var shiftDragZoom=options.shiftDragZoom!==
undefined?options.shiftDragZoom:true;if(shiftDragZoom)interactions.push(new ol.interaction.DragZoom({duration:options.zoomDuration}));return interactions};goog.provide("ol.ImageBase");goog.require("ol");goog.require("ol.events.EventTarget");goog.require("ol.events.EventType");ol.ImageBase=function(extent,resolution,pixelRatio,state){ol.events.EventTarget.call(this);this.extent=extent;this.pixelRatio_=pixelRatio;this.resolution=resolution;this.state=state};ol.inherits(ol.ImageBase,ol.events.EventTarget);ol.ImageBase.prototype.changed=function(){this.dispatchEvent(ol.events.EventType.CHANGE)};ol.ImageBase.prototype.getExtent=function(){return this.extent};
ol.ImageBase.prototype.getImage=function(){};ol.ImageBase.prototype.getPixelRatio=function(){return this.pixelRatio_};ol.ImageBase.prototype.getResolution=function(){return this.resolution};ol.ImageBase.prototype.getState=function(){return this.state};ol.ImageBase.prototype.load=function(){};goog.provide("ol.ImageState");ol.ImageState={IDLE:0,LOADING:1,LOADED:2,ERROR:3};goog.provide("ol.ImageCanvas");goog.require("ol");goog.require("ol.ImageBase");goog.require("ol.ImageState");ol.ImageCanvas=function(extent,resolution,pixelRatio,canvas,opt_loader){this.loader_=opt_loader!==undefined?opt_loader:null;var state=opt_loader!==undefined?ol.ImageState.IDLE:ol.ImageState.LOADED;ol.ImageBase.call(this,extent,resolution,pixelRatio,state);this.canvas_=canvas;this.error_=null};ol.inherits(ol.ImageCanvas,ol.ImageBase);ol.ImageCanvas.prototype.getError=function(){return this.error_};
ol.ImageCanvas.prototype.handleLoad_=function(err){if(err){this.error_=err;this.state=ol.ImageState.ERROR}else this.state=ol.ImageState.LOADED;this.changed()};ol.ImageCanvas.prototype.load=function(){if(this.state==ol.ImageState.IDLE){this.state=ol.ImageState.LOADING;this.changed();this.loader_(this.handleLoad_.bind(this))}};ol.ImageCanvas.prototype.getImage=function(){return this.canvas_};goog.provide("ol.LayerType");ol.LayerType={IMAGE:"IMAGE",TILE:"TILE",VECTOR_TILE:"VECTOR_TILE",VECTOR:"VECTOR"};goog.provide("ol.layer.VectorRenderType");ol.layer.VectorRenderType={IMAGE:"image",VECTOR:"vector"};goog.provide("ol.render.Event");goog.require("ol");goog.require("ol.events.Event");ol.render.Event=function(type,opt_vectorContext,opt_frameState,opt_context,opt_glContext){ol.events.Event.call(this,type);this.vectorContext=opt_vectorContext;this.frameState=opt_frameState;this.context=opt_context;this.glContext=opt_glContext};ol.inherits(ol.render.Event,ol.events.Event);goog.provide("ol.structs.LRUCache");goog.require("ol");goog.require("ol.asserts");goog.require("ol.events.EventTarget");goog.require("ol.events.EventType");ol.structs.LRUCache=function(opt_highWaterMark){ol.events.EventTarget.call(this);this.highWaterMark=opt_highWaterMark!==undefined?opt_highWaterMark:2048;this.count_=0;this.entries_={};this.oldest_=null;this.newest_=null};ol.inherits(ol.structs.LRUCache,ol.events.EventTarget);
ol.structs.LRUCache.prototype.canExpireCache=function(){return this.getCount()>this.highWaterMark};ol.structs.LRUCache.prototype.clear=function(){this.count_=0;this.entries_={};this.oldest_=null;this.newest_=null;this.dispatchEvent(ol.events.EventType.CLEAR)};ol.structs.LRUCache.prototype.containsKey=function(key){return this.entries_.hasOwnProperty(key)};
ol.structs.LRUCache.prototype.forEach=function(f,opt_this){var entry=this.oldest_;while(entry){f.call(opt_this,entry.value_,entry.key_,this);entry=entry.newer}};
ol.structs.LRUCache.prototype.get=function(key){var entry=this.entries_[key];ol.asserts.assert(entry!==undefined,15);if(entry===this.newest_)return entry.value_;else if(entry===this.oldest_){this.oldest_=this.oldest_.newer;this.oldest_.older=null}else{entry.newer.older=entry.older;entry.older.newer=entry.newer}entry.newer=null;entry.older=this.newest_;this.newest_.newer=entry;this.newest_=entry;return entry.value_};
ol.structs.LRUCache.prototype.remove=function(key){var entry=this.entries_[key];ol.asserts.assert(entry!==undefined,15);if(entry===this.newest_){this.newest_=entry.older;if(this.newest_)this.newest_.newer=null}else if(entry===this.oldest_){this.oldest_=entry.newer;if(this.oldest_)this.oldest_.older=null}else{entry.newer.older=entry.older;entry.older.newer=entry.newer}delete this.entries_[key];--this.count_;return entry.value_};ol.structs.LRUCache.prototype.getCount=function(){return this.count_};
ol.structs.LRUCache.prototype.getKeys=function(){var keys=new Array(this.count_);var i=0;var entry;for(entry=this.newest_;entry;entry=entry.older)keys[i++]=entry.key_;return keys};ol.structs.LRUCache.prototype.getValues=function(){var values=new Array(this.count_);var i=0;var entry;for(entry=this.newest_;entry;entry=entry.older)values[i++]=entry.value_;return values};ol.structs.LRUCache.prototype.peekLast=function(){return this.oldest_.value_};ol.structs.LRUCache.prototype.peekLastKey=function(){return this.oldest_.key_};
ol.structs.LRUCache.prototype.peekFirstKey=function(){return this.newest_.key_};ol.structs.LRUCache.prototype.pop=function(){var entry=this.oldest_;delete this.entries_[entry.key_];if(entry.newer)entry.newer.older=null;this.oldest_=entry.newer;if(!this.oldest_)this.newest_=null;--this.count_;return entry.value_};ol.structs.LRUCache.prototype.replace=function(key,value){this.get(key);this.entries_[key].value_=value};
ol.structs.LRUCache.prototype.set=function(key,value){ol.asserts.assert(!(key in this.entries_),16);var entry={key_:key,newer:null,older:this.newest_,value_:value};if(!this.newest_)this.oldest_=entry;else this.newest_.newer=entry;this.newest_=entry;this.entries_[key]=entry;++this.count_};ol.structs.LRUCache.prototype.prune=function(){while(this.canExpireCache())this.pop()};goog.provide("ol.render.canvas");goog.require("ol.css");goog.require("ol.dom");goog.require("ol.obj");goog.require("ol.structs.LRUCache");goog.require("ol.transform");ol.render.canvas.defaultFont="10px sans-serif";ol.render.canvas.defaultFillStyle=[0,0,0,1];ol.render.canvas.defaultLineCap="round";ol.render.canvas.defaultLineDash=[];ol.render.canvas.defaultLineDashOffset=0;ol.render.canvas.defaultLineJoin="round";ol.render.canvas.defaultMiterLimit=10;ol.render.canvas.defaultStrokeStyle=[0,0,0,1];
ol.render.canvas.defaultTextAlign="center";ol.render.canvas.defaultTextBaseline="middle";ol.render.canvas.defaultPadding=[0,0,0,0];ol.render.canvas.defaultLineWidth=1;ol.render.canvas.labelCache=new ol.structs.LRUCache;ol.render.canvas.checkedFonts_={};ol.render.canvas.measureContext_=null;ol.render.canvas.textHeights_={};
ol.render.canvas.checkFont=function(){var retries=60;var checked=ol.render.canvas.checkedFonts_;var labelCache=ol.render.canvas.labelCache;var font="32px monospace";var text="wmytzilWMYTZIL@#/&?$%10";var interval,referenceWidth;function isAvailable(fontFamily){var context=ol.render.canvas.getMeasureContext();context.font=font;referenceWidth=context.measureText(text).width;var available=true;if(fontFamily!="monospace"){context.font="32px "+fontFamily+",monospace";var width=context.measureText(text).width;
available=width!=referenceWidth}return available}function check(){var done=true;for(var font in checked)if(checked[font]<retries)if(isAvailable(font)){checked[font]=retries;ol.obj.clear(ol.render.canvas.textHeights_);ol.render.canvas.measureContext_=null;labelCache.clear()}else{++checked[font];done=false}if(done){window.clearInterval(interval);interval=undefined}}return function(fontSpec){var fontFamilies=ol.css.getFontFamilies(fontSpec);if(!fontFamilies)return;for(var i=0,ii=fontFamilies.length;i<
ii;++i){var fontFamily=fontFamilies[i];if(!(fontFamily in checked)){checked[fontFamily]=retries;if(!isAvailable(fontFamily)){checked[fontFamily]=0;if(interval===undefined)interval=window.setInterval(check,32)}}}}}();ol.render.canvas.getMeasureContext=function(){var context=ol.render.canvas.measureContext_;if(!context)context=ol.render.canvas.measureContext_=ol.dom.createCanvasContext2D(1,1);return context};
ol.render.canvas.measureTextHeight=function(){var span;var heights=ol.render.canvas.textHeights_;return function(font){var height=heights[font];if(height==undefined){if(!span){span=document.createElement("span");span.textContent="M";span.style.margin=span.style.padding="0 !important";span.style.position="absolute !important";span.style.left="-99999px !important"}span.style.font=font;document.body.appendChild(span);height=heights[font]=span.offsetHeight;document.body.removeChild(span)}return height}}();
ol.render.canvas.measureTextWidth=function(font,text){var measureContext=ol.render.canvas.getMeasureContext();if(font!=measureContext.font)measureContext.font=font;return measureContext.measureText(text).width};ol.render.canvas.rotateAtOffset=function(context,rotation,offsetX,offsetY){if(rotation!==0){context.translate(offsetX,offsetY);context.rotate(rotation);context.translate(-offsetX,-offsetY)}};ol.render.canvas.resetTransform_=ol.transform.create();
ol.render.canvas.drawImage=function(context,transform,opacity,image,originX,originY,w,h,x,y,scale){var alpha;if(opacity!=1){alpha=context.globalAlpha;context.globalAlpha=alpha*opacity}if(transform)context.setTransform.apply(context,transform);context.drawImage(image,originX,originY,w,h,x,y,w*scale,h*scale);if(alpha)context.globalAlpha=alpha;if(transform)context.setTransform.apply(context,ol.render.canvas.resetTransform_)};goog.provide("ol.color");goog.require("ol.asserts");goog.require("ol.math");ol.color.HEX_COLOR_RE_=/^#(?:[0-9a-f]{3,4}){1,2}$/i;ol.color.NAMED_COLOR_RE_=/^([a-z]*)$/i;ol.color.asArray=function(color){if(Array.isArray(color))return color;else return ol.color.fromString(color)};ol.color.asString=function(color){if(typeof color==="string")return color;else return ol.color.toString(color)};
ol.color.fromNamed=function(color){var el=document.createElement("div");el.style.color=color;document.body.appendChild(el);var rgb=getComputedStyle(el).color;document.body.removeChild(el);return rgb};
ol.color.fromString=function(){var MAX_CACHE_SIZE=1024;var cache={};var cacheSize=0;return function(s){var color;if(cache.hasOwnProperty(s))color=cache[s];else{if(cacheSize>=MAX_CACHE_SIZE){var i=0;var key;for(key in cache)if((i++&3)===0){delete cache[key];--cacheSize}}color=ol.color.fromStringInternal_(s);cache[s]=color;++cacheSize}return color}}();
ol.color.fromStringInternal_=function(s){var r,g,b,a,color,parts;if(ol.color.NAMED_COLOR_RE_.exec(s))s=ol.color.fromNamed(s);if(ol.color.HEX_COLOR_RE_.exec(s)){var n=s.length-1;var d;if(n<=4)d=1;else d=2;var hasAlpha=n===4||n===8;r=parseInt(s.substr(1+0*d,d),16);g=parseInt(s.substr(1+1*d,d),16);b=parseInt(s.substr(1+2*d,d),16);if(hasAlpha)a=parseInt(s.substr(1+3*d,d),16);else a=255;if(d==1){r=(r<<4)+r;g=(g<<4)+g;b=(b<<4)+b;if(hasAlpha)a=(a<<4)+a}color=[r,g,b,a/255]}else if(s.indexOf("rgba(")==0){parts=
s.slice(5,-1).split(",").map(Number);color=ol.color.normalize(parts)}else if(s.indexOf("rgb(")==0){parts=s.slice(4,-1).split(",").map(Number);parts.push(1);color=ol.color.normalize(parts)}else ol.asserts.assert(false,14);return color};ol.color.normalize=function(color,opt_color){var result=opt_color||[];result[0]=ol.math.clamp(color[0]+.5|0,0,255);result[1]=ol.math.clamp(color[1]+.5|0,0,255);result[2]=ol.math.clamp(color[2]+.5|0,0,255);result[3]=ol.math.clamp(color[3],0,1);return result};
ol.color.toString=function(color){var r=color[0];if(r!=(r|0))r=r+.5|0;var g=color[1];if(g!=(g|0))g=g+.5|0;var b=color[2];if(b!=(b|0))b=b+.5|0;var a=color[3]===undefined?1:color[3];return"rgba("+r+","+g+","+b+","+a+")"};goog.provide("ol.colorlike");goog.require("ol.color");ol.colorlike.asColorLike=function(color){if(ol.colorlike.isColorLike(color))return color;else return ol.color.asString(color)};ol.colorlike.isColorLike=function(color){return typeof color==="string"||color instanceof CanvasPattern||color instanceof CanvasGradient};goog.provide("ol.render.VectorContext");ol.render.VectorContext=function(){};ol.render.VectorContext.prototype.drawCustom=function(geometry,feature,renderer){};ol.render.VectorContext.prototype.drawGeometry=function(geometry){};ol.render.VectorContext.prototype.setStyle=function(style){};ol.render.VectorContext.prototype.drawCircle=function(circleGeometry,feature){};ol.render.VectorContext.prototype.drawFeature=function(feature,style){};
ol.render.VectorContext.prototype.drawGeometryCollection=function(geometryCollectionGeometry,feature){};ol.render.VectorContext.prototype.drawLineString=function(lineStringGeometry,feature){};ol.render.VectorContext.prototype.drawMultiLineString=function(multiLineStringGeometry,feature){};ol.render.VectorContext.prototype.drawMultiPoint=function(multiPointGeometry,feature){};ol.render.VectorContext.prototype.drawMultiPolygon=function(multiPolygonGeometry,feature){};
ol.render.VectorContext.prototype.drawPoint=function(pointGeometry,feature){};ol.render.VectorContext.prototype.drawPolygon=function(polygonGeometry,feature){};ol.render.VectorContext.prototype.drawText=function(geometry,feature){};ol.render.VectorContext.prototype.setFillStrokeStyle=function(fillStyle,strokeStyle){};ol.render.VectorContext.prototype.setImageStyle=function(imageStyle,opt_declutterGroup){};ol.render.VectorContext.prototype.setTextStyle=function(textStyle,opt_declutterGroup){};goog.provide("ol.render.canvas.Immediate");goog.require("ol");goog.require("ol.array");goog.require("ol.colorlike");goog.require("ol.extent");goog.require("ol.geom.GeometryType");goog.require("ol.geom.SimpleGeometry");goog.require("ol.geom.flat.transform");goog.require("ol.has");goog.require("ol.render.VectorContext");goog.require("ol.render.canvas");goog.require("ol.transform");
ol.render.canvas.Immediate=function(context,pixelRatio,extent,transform,viewRotation){ol.render.VectorContext.call(this);this.context_=context;this.pixelRatio_=pixelRatio;this.extent_=extent;this.transform_=transform;this.viewRotation_=viewRotation;this.contextFillState_=null;this.contextStrokeState_=null;this.contextTextState_=null;this.fillState_=null;this.strokeState_=null;this.image_=null;this.imageAnchorX_=0;this.imageAnchorY_=0;this.imageHeight_=0;this.imageOpacity_=0;this.imageOriginX_=0;this.imageOriginY_=
0;this.imageRotateWithView_=false;this.imageRotation_=0;this.imageScale_=0;this.imageSnapToPixel_=false;this.imageWidth_=0;this.text_="";this.textOffsetX_=0;this.textOffsetY_=0;this.textRotateWithView_=false;this.textRotation_=0;this.textScale_=0;this.textFillState_=null;this.textStrokeState_=null;this.textState_=null;this.pixelCoordinates_=[];this.tmpLocalTransform_=ol.transform.create()};ol.inherits(ol.render.canvas.Immediate,ol.render.VectorContext);
ol.render.canvas.Immediate.prototype.drawImages_=function(flatCoordinates,offset,end,stride){if(!this.image_)return;var pixelCoordinates=ol.geom.flat.transform.transform2D(flatCoordinates,offset,end,2,this.transform_,this.pixelCoordinates_);var context=this.context_;var localTransform=this.tmpLocalTransform_;var alpha=context.globalAlpha;if(this.imageOpacity_!=1)context.globalAlpha=alpha*this.imageOpacity_;var rotation=this.imageRotation_;if(this.imageRotateWithView_)rotation+=this.viewRotation_;
var i,ii;for(i=0,ii=pixelCoordinates.length;i<ii;i+=2){var x=pixelCoordinates[i]-this.imageAnchorX_;var y=pixelCoordinates[i+1]-this.imageAnchorY_;if(this.imageSnapToPixel_){x=Math.round(x);y=Math.round(y)}if(rotation!==0||this.imageScale_!=1){var centerX=x+this.imageAnchorX_;var centerY=y+this.imageAnchorY_;ol.transform.compose(localTransform,centerX,centerY,this.imageScale_,this.imageScale_,rotation,-centerX,-centerY);context.setTransform.apply(context,localTransform)}context.drawImage(this.image_,
this.imageOriginX_,this.imageOriginY_,this.imageWidth_,this.imageHeight_,x,y,this.imageWidth_,this.imageHeight_)}if(rotation!==0||this.imageScale_!=1)context.setTransform(1,0,0,1,0,0);if(this.imageOpacity_!=1)context.globalAlpha=alpha};
ol.render.canvas.Immediate.prototype.drawText_=function(flatCoordinates,offset,end,stride){if(!this.textState_||this.text_==="")return;if(this.textFillState_)this.setContextFillState_(this.textFillState_);if(this.textStrokeState_)this.setContextStrokeState_(this.textStrokeState_);this.setContextTextState_(this.textState_);var pixelCoordinates=ol.geom.flat.transform.transform2D(flatCoordinates,offset,end,stride,this.transform_,this.pixelCoordinates_);var context=this.context_;var rotation=this.textRotation_;
if(this.textRotateWithView_)rotation+=this.viewRotation_;for(;offset<end;offset+=stride){var x=pixelCoordinates[offset]+this.textOffsetX_;var y=pixelCoordinates[offset+1]+this.textOffsetY_;if(rotation!==0||this.textScale_!=1){var localTransform=ol.transform.compose(this.tmpLocalTransform_,x,y,this.textScale_,this.textScale_,rotation,-x,-y);context.setTransform.apply(context,localTransform)}if(this.textStrokeState_)context.strokeText(this.text_,x,y);if(this.textFillState_)context.fillText(this.text_,
x,y)}if(rotation!==0||this.textScale_!=1)context.setTransform(1,0,0,1,0,0)};
ol.render.canvas.Immediate.prototype.moveToLineTo_=function(flatCoordinates,offset,end,stride,close){var context=this.context_;var pixelCoordinates=ol.geom.flat.transform.transform2D(flatCoordinates,offset,end,stride,this.transform_,this.pixelCoordinates_);context.moveTo(pixelCoordinates[0],pixelCoordinates[1]);var length=pixelCoordinates.length;if(close)length-=2;for(var i=2;i<length;i+=2)context.lineTo(pixelCoordinates[i],pixelCoordinates[i+1]);if(close)context.closePath();return end};
ol.render.canvas.Immediate.prototype.drawRings_=function(flatCoordinates,offset,ends,stride){var i,ii;for(i=0,ii=ends.length;i<ii;++i)offset=this.moveToLineTo_(flatCoordinates,offset,ends[i],stride,true);return offset};
ol.render.canvas.Immediate.prototype.drawCircle=function(geometry){if(!ol.extent.intersects(this.extent_,geometry.getExtent()))return;if(this.fillState_||this.strokeState_){if(this.fillState_)this.setContextFillState_(this.fillState_);if(this.strokeState_)this.setContextStrokeState_(this.strokeState_);var pixelCoordinates=ol.geom.SimpleGeometry.transform2D(geometry,this.transform_,this.pixelCoordinates_);var dx=pixelCoordinates[2]-pixelCoordinates[0];var dy=pixelCoordinates[3]-pixelCoordinates[1];
var radius=Math.sqrt(dx*dx+dy*dy);var context=this.context_;context.beginPath();context.arc(pixelCoordinates[0],pixelCoordinates[1],radius,0,2*Math.PI);if(this.fillState_)context.fill();if(this.strokeState_)context.stroke()}if(this.text_!=="")this.drawText_(geometry.getCenter(),0,2,2)};ol.render.canvas.Immediate.prototype.setStyle=function(style){this.setFillStrokeStyle(style.getFill(),style.getStroke());this.setImageStyle(style.getImage());this.setTextStyle(style.getText())};
ol.render.canvas.Immediate.prototype.drawGeometry=function(geometry){var type=geometry.getType();switch(type){case ol.geom.GeometryType.POINT:this.drawPoint(geometry);break;case ol.geom.GeometryType.LINE_STRING:this.drawLineString(geometry);break;case ol.geom.GeometryType.POLYGON:this.drawPolygon(geometry);break;case ol.geom.GeometryType.MULTI_POINT:this.drawMultiPoint(geometry);break;case ol.geom.GeometryType.MULTI_LINE_STRING:this.drawMultiLineString(geometry);break;case ol.geom.GeometryType.MULTI_POLYGON:this.drawMultiPolygon(geometry);
break;case ol.geom.GeometryType.GEOMETRY_COLLECTION:this.drawGeometryCollection(geometry);break;case ol.geom.GeometryType.CIRCLE:this.drawCircle(geometry);break;default:}};ol.render.canvas.Immediate.prototype.drawFeature=function(feature,style){var geometry=style.getGeometryFunction()(feature);if(!geometry||!ol.extent.intersects(this.extent_,geometry.getExtent()))return;this.setStyle(style);this.drawGeometry(geometry)};
ol.render.canvas.Immediate.prototype.drawGeometryCollection=function(geometry){var geometries=geometry.getGeometriesArray();var i,ii;for(i=0,ii=geometries.length;i<ii;++i)this.drawGeometry(geometries[i])};
ol.render.canvas.Immediate.prototype.drawPoint=function(geometry){var flatCoordinates=geometry.getFlatCoordinates();var stride=geometry.getStride();if(this.image_)this.drawImages_(flatCoordinates,0,flatCoordinates.length,stride);if(this.text_!=="")this.drawText_(flatCoordinates,0,flatCoordinates.length,stride)};
ol.render.canvas.Immediate.prototype.drawMultiPoint=function(geometry){var flatCoordinates=geometry.getFlatCoordinates();var stride=geometry.getStride();if(this.image_)this.drawImages_(flatCoordinates,0,flatCoordinates.length,stride);if(this.text_!=="")this.drawText_(flatCoordinates,0,flatCoordinates.length,stride)};
ol.render.canvas.Immediate.prototype.drawLineString=function(geometry){if(!ol.extent.intersects(this.extent_,geometry.getExtent()))return;if(this.strokeState_){this.setContextStrokeState_(this.strokeState_);var context=this.context_;var flatCoordinates=geometry.getFlatCoordinates();context.beginPath();this.moveToLineTo_(flatCoordinates,0,flatCoordinates.length,geometry.getStride(),false);context.stroke()}if(this.text_!==""){var flatMidpoint=geometry.getFlatMidpoint();this.drawText_(flatMidpoint,0,
2,2)}};
ol.render.canvas.Immediate.prototype.drawMultiLineString=function(geometry){var geometryExtent=geometry.getExtent();if(!ol.extent.intersects(this.extent_,geometryExtent))return;if(this.strokeState_){this.setContextStrokeState_(this.strokeState_);var context=this.context_;var flatCoordinates=geometry.getFlatCoordinates();var offset=0;var ends=geometry.getEnds();var stride=geometry.getStride();context.beginPath();var i,ii;for(i=0,ii=ends.length;i<ii;++i)offset=this.moveToLineTo_(flatCoordinates,offset,
ends[i],stride,false);context.stroke()}if(this.text_!==""){var flatMidpoints=geometry.getFlatMidpoints();this.drawText_(flatMidpoints,0,flatMidpoints.length,2)}};
ol.render.canvas.Immediate.prototype.drawPolygon=function(geometry){if(!ol.extent.intersects(this.extent_,geometry.getExtent()))return;if(this.strokeState_||this.fillState_){if(this.fillState_)this.setContextFillState_(this.fillState_);if(this.strokeState_)this.setContextStrokeState_(this.strokeState_);var context=this.context_;context.beginPath();this.drawRings_(geometry.getOrientedFlatCoordinates(),0,geometry.getEnds(),geometry.getStride());if(this.fillState_)context.fill();if(this.strokeState_)context.stroke()}if(this.text_!==
""){var flatInteriorPoint=geometry.getFlatInteriorPoint();this.drawText_(flatInteriorPoint,0,2,2)}};
ol.render.canvas.Immediate.prototype.drawMultiPolygon=function(geometry){if(!ol.extent.intersects(this.extent_,geometry.getExtent()))return;if(this.strokeState_||this.fillState_){if(this.fillState_)this.setContextFillState_(this.fillState_);if(this.strokeState_)this.setContextStrokeState_(this.strokeState_);var context=this.context_;var flatCoordinates=geometry.getOrientedFlatCoordinates();var offset=0;var endss=geometry.getEndss();var stride=geometry.getStride();var i,ii;context.beginPath();for(i=
0,ii=endss.length;i<ii;++i){var ends=endss[i];offset=this.drawRings_(flatCoordinates,offset,ends,stride)}if(this.fillState_)context.fill();if(this.strokeState_)context.stroke()}if(this.text_!==""){var flatInteriorPoints=geometry.getFlatInteriorPoints();this.drawText_(flatInteriorPoints,0,flatInteriorPoints.length,2)}};
ol.render.canvas.Immediate.prototype.setContextFillState_=function(fillState){var context=this.context_;var contextFillState=this.contextFillState_;if(!contextFillState){context.fillStyle=fillState.fillStyle;this.contextFillState_={fillStyle:fillState.fillStyle}}else if(contextFillState.fillStyle!=fillState.fillStyle)contextFillState.fillStyle=context.fillStyle=fillState.fillStyle};
ol.render.canvas.Immediate.prototype.setContextStrokeState_=function(strokeState){var context=this.context_;var contextStrokeState=this.contextStrokeState_;if(!contextStrokeState){context.lineCap=strokeState.lineCap;if(ol.has.CANVAS_LINE_DASH){context.setLineDash(strokeState.lineDash);context.lineDashOffset=strokeState.lineDashOffset}context.lineJoin=strokeState.lineJoin;context.lineWidth=strokeState.lineWidth;context.miterLimit=strokeState.miterLimit;context.strokeStyle=strokeState.strokeStyle;this.contextStrokeState_=
{lineCap:strokeState.lineCap,lineDash:strokeState.lineDash,lineDashOffset:strokeState.lineDashOffset,lineJoin:strokeState.lineJoin,lineWidth:strokeState.lineWidth,miterLimit:strokeState.miterLimit,strokeStyle:strokeState.strokeStyle}}else{if(contextStrokeState.lineCap!=strokeState.lineCap)contextStrokeState.lineCap=context.lineCap=strokeState.lineCap;if(ol.has.CANVAS_LINE_DASH){if(!ol.array.equals(contextStrokeState.lineDash,strokeState.lineDash))context.setLineDash(contextStrokeState.lineDash=strokeState.lineDash);
if(contextStrokeState.lineDashOffset!=strokeState.lineDashOffset)contextStrokeState.lineDashOffset=context.lineDashOffset=strokeState.lineDashOffset}if(contextStrokeState.lineJoin!=strokeState.lineJoin)contextStrokeState.lineJoin=context.lineJoin=strokeState.lineJoin;if(contextStrokeState.lineWidth!=strokeState.lineWidth)contextStrokeState.lineWidth=context.lineWidth=strokeState.lineWidth;if(contextStrokeState.miterLimit!=strokeState.miterLimit)contextStrokeState.miterLimit=context.miterLimit=strokeState.miterLimit;
if(contextStrokeState.strokeStyle!=strokeState.strokeStyle)contextStrokeState.strokeStyle=context.strokeStyle=strokeState.strokeStyle}};
ol.render.canvas.Immediate.prototype.setContextTextState_=function(textState){var context=this.context_;var contextTextState=this.contextTextState_;var textAlign=textState.textAlign?textState.textAlign:ol.render.canvas.defaultTextAlign;if(!contextTextState){context.font=textState.font;context.textAlign=textAlign;context.textBaseline=textState.textBaseline;this.contextTextState_={font:textState.font,textAlign:textAlign,textBaseline:textState.textBaseline}}else{if(contextTextState.font!=textState.font)contextTextState.font=
context.font=textState.font;if(contextTextState.textAlign!=textAlign)contextTextState.textAlign=textAlign;if(contextTextState.textBaseline!=textState.textBaseline)contextTextState.textBaseline=context.textBaseline=textState.textBaseline}};
ol.render.canvas.Immediate.prototype.setFillStrokeStyle=function(fillStyle,strokeStyle){if(!fillStyle)this.fillState_=null;else{var fillStyleColor=fillStyle.getColor();this.fillState_={fillStyle:ol.colorlike.asColorLike(fillStyleColor?fillStyleColor:ol.render.canvas.defaultFillStyle)}}if(!strokeStyle)this.strokeState_=null;else{var strokeStyleColor=strokeStyle.getColor();var strokeStyleLineCap=strokeStyle.getLineCap();var strokeStyleLineDash=strokeStyle.getLineDash();var strokeStyleLineDashOffset=
strokeStyle.getLineDashOffset();var strokeStyleLineJoin=strokeStyle.getLineJoin();var strokeStyleWidth=strokeStyle.getWidth();var strokeStyleMiterLimit=strokeStyle.getMiterLimit();this.strokeState_={lineCap:strokeStyleLineCap!==undefined?strokeStyleLineCap:ol.render.canvas.defaultLineCap,lineDash:strokeStyleLineDash?strokeStyleLineDash:ol.render.canvas.defaultLineDash,lineDashOffset:strokeStyleLineDashOffset?strokeStyleLineDashOffset:ol.render.canvas.defaultLineDashOffset,lineJoin:strokeStyleLineJoin!==
undefined?strokeStyleLineJoin:ol.render.canvas.defaultLineJoin,lineWidth:this.pixelRatio_*(strokeStyleWidth!==undefined?strokeStyleWidth:ol.render.canvas.defaultLineWidth),miterLimit:strokeStyleMiterLimit!==undefined?strokeStyleMiterLimit:ol.render.canvas.defaultMiterLimit,strokeStyle:ol.colorlike.asColorLike(strokeStyleColor?strokeStyleColor:ol.render.canvas.defaultStrokeStyle)}}};
ol.render.canvas.Immediate.prototype.setImageStyle=function(imageStyle){if(!imageStyle)this.image_=null;else{var imageAnchor=imageStyle.getAnchor();var imageImage=imageStyle.getImage(1);var imageOrigin=imageStyle.getOrigin();var imageSize=imageStyle.getSize();this.imageAnchorX_=imageAnchor[0];this.imageAnchorY_=imageAnchor[1];this.imageHeight_=imageSize[1];this.image_=imageImage;this.imageOpacity_=imageStyle.getOpacity();this.imageOriginX_=imageOrigin[0];this.imageOriginY_=imageOrigin[1];this.imageRotateWithView_=
imageStyle.getRotateWithView();this.imageRotation_=imageStyle.getRotation();this.imageScale_=imageStyle.getScale()*this.pixelRatio_;this.imageSnapToPixel_=imageStyle.getSnapToPixel();this.imageWidth_=imageSize[0]}};
ol.render.canvas.Immediate.prototype.setTextStyle=function(textStyle){if(!textStyle)this.text_="";else{var textFillStyle=textStyle.getFill();if(!textFillStyle)this.textFillState_=null;else{var textFillStyleColor=textFillStyle.getColor();this.textFillState_={fillStyle:ol.colorlike.asColorLike(textFillStyleColor?textFillStyleColor:ol.render.canvas.defaultFillStyle)}}var textStrokeStyle=textStyle.getStroke();if(!textStrokeStyle)this.textStrokeState_=null;else{var textStrokeStyleColor=textStrokeStyle.getColor();
var textStrokeStyleLineCap=textStrokeStyle.getLineCap();var textStrokeStyleLineDash=textStrokeStyle.getLineDash();var textStrokeStyleLineDashOffset=textStrokeStyle.getLineDashOffset();var textStrokeStyleLineJoin=textStrokeStyle.getLineJoin();var textStrokeStyleWidth=textStrokeStyle.getWidth();var textStrokeStyleMiterLimit=textStrokeStyle.getMiterLimit();this.textStrokeState_={lineCap:textStrokeStyleLineCap!==undefined?textStrokeStyleLineCap:ol.render.canvas.defaultLineCap,lineDash:textStrokeStyleLineDash?
textStrokeStyleLineDash:ol.render.canvas.defaultLineDash,lineDashOffset:textStrokeStyleLineDashOffset?textStrokeStyleLineDashOffset:ol.render.canvas.defaultLineDashOffset,lineJoin:textStrokeStyleLineJoin!==undefined?textStrokeStyleLineJoin:ol.render.canvas.defaultLineJoin,lineWidth:textStrokeStyleWidth!==undefined?textStrokeStyleWidth:ol.render.canvas.defaultLineWidth,miterLimit:textStrokeStyleMiterLimit!==undefined?textStrokeStyleMiterLimit:ol.render.canvas.defaultMiterLimit,strokeStyle:ol.colorlike.asColorLike(textStrokeStyleColor?
textStrokeStyleColor:ol.render.canvas.defaultStrokeStyle)}}var textFont=textStyle.getFont();var textOffsetX=textStyle.getOffsetX();var textOffsetY=textStyle.getOffsetY();var textRotateWithView=textStyle.getRotateWithView();var textRotation=textStyle.getRotation();var textScale=textStyle.getScale();var textText=textStyle.getText();var textTextAlign=textStyle.getTextAlign();var textTextBaseline=textStyle.getTextBaseline();this.textState_={font:textFont!==undefined?textFont:ol.render.canvas.defaultFont,
textAlign:textTextAlign!==undefined?textTextAlign:ol.render.canvas.defaultTextAlign,textBaseline:textTextBaseline!==undefined?textTextBaseline:ol.render.canvas.defaultTextBaseline};this.text_=textText!==undefined?textText:"";this.textOffsetX_=textOffsetX!==undefined?this.pixelRatio_*textOffsetX:0;this.textOffsetY_=textOffsetY!==undefined?this.pixelRatio_*textOffsetY:0;this.textRotateWithView_=textRotateWithView!==undefined?textRotateWithView:false;this.textRotation_=textRotation!==undefined?textRotation:
0;this.textScale_=this.pixelRatio_*(textScale!==undefined?textScale:1)}};goog.provide("ol.renderer.Layer");goog.require("ol");goog.require("ol.ImageState");goog.require("ol.Observable");goog.require("ol.TileState");goog.require("ol.asserts");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.functions");goog.require("ol.source.State");ol.renderer.Layer=function(layer){ol.Observable.call(this);this.layer_=layer};ol.inherits(ol.renderer.Layer,ol.Observable);ol.renderer.Layer.prototype.forEachFeatureAtCoordinate=ol.nullFunction;
ol.renderer.Layer.prototype.hasFeatureAtCoordinate=ol.functions.FALSE;ol.renderer.Layer.prototype.createLoadedTileFinder=function(source,projection,tiles){return function(zoom,tileRange){function callback(tile){if(!tiles[zoom])tiles[zoom]={};tiles[zoom][tile.tileCoord.toString()]=tile}return source.forEachLoadedTile(projection,zoom,tileRange,callback)}};ol.renderer.Layer.prototype.getLayer=function(){return this.layer_};
ol.renderer.Layer.prototype.handleImageChange_=function(event){var image=event.target;if(image.getState()===ol.ImageState.LOADED)this.renderIfReadyAndVisible()};ol.renderer.Layer.prototype.loadImage=function(image){var imageState=image.getState();if(imageState!=ol.ImageState.LOADED&&imageState!=ol.ImageState.ERROR)ol.events.listen(image,ol.events.EventType.CHANGE,this.handleImageChange_,this);if(imageState==ol.ImageState.IDLE){image.load();imageState=image.getState()}return imageState==ol.ImageState.LOADED};
ol.renderer.Layer.prototype.renderIfReadyAndVisible=function(){var layer=this.getLayer();if(layer.getVisible()&&layer.getSourceState()==ol.source.State.READY)this.changed()};
ol.renderer.Layer.prototype.scheduleExpireCache=function(frameState,tileSource){if(tileSource.canExpireCache()){var postRenderFunction=function(tileSource,map,frameState){var tileSourceKey=ol.getUid(tileSource).toString();if(tileSourceKey in frameState.usedTiles)tileSource.expireCache(frameState.viewState.projection,frameState.usedTiles[tileSourceKey])}.bind(null,tileSource);frameState.postRenderFunctions.push(postRenderFunction)}};
ol.renderer.Layer.prototype.updateLogos=function(frameState,source){var logo=source.getLogo();if(logo!==undefined)if(typeof logo==="string")frameState.logos[logo]="";else if(logo){ol.asserts.assert(typeof logo.href=="string",44);ol.asserts.assert(typeof logo.src=="string",45);frameState.logos[logo.src]=logo.href}};
ol.renderer.Layer.prototype.updateUsedTiles=function(usedTiles,tileSource,z,tileRange){var tileSourceKey=ol.getUid(tileSource).toString();var zKey=z.toString();if(tileSourceKey in usedTiles)if(zKey in usedTiles[tileSourceKey])usedTiles[tileSourceKey][zKey].extend(tileRange);else usedTiles[tileSourceKey][zKey]=tileRange;else{usedTiles[tileSourceKey]={};usedTiles[tileSourceKey][zKey]=tileRange}};
ol.renderer.Layer.prototype.manageTilePyramid=function(frameState,tileSource,tileGrid,pixelRatio,projection,extent,currentZ,preload,opt_tileCallback,opt_this){var tileSourceKey=ol.getUid(tileSource).toString();if(!(tileSourceKey in frameState.wantedTiles))frameState.wantedTiles[tileSourceKey]={};var wantedTiles=frameState.wantedTiles[tileSourceKey];var tileQueue=frameState.tileQueue;var minZoom=tileGrid.getMinZoom();var tile,tileRange,tileResolution,x,y,z;for(z=minZoom;z<=currentZ;++z){tileRange=
tileGrid.getTileRangeForExtentAndZ(extent,z,tileRange);tileResolution=tileGrid.getResolution(z);for(x=tileRange.minX;x<=tileRange.maxX;++x)for(y=tileRange.minY;y<=tileRange.maxY;++y)if(currentZ-z<=preload){tile=tileSource.getTile(z,x,y,pixelRatio,projection);if(tile.getState()==ol.TileState.IDLE){wantedTiles[tile.getKey()]=true;if(!tileQueue.isKeyQueued(tile.getKey()))tileQueue.enqueue([tile,tileSourceKey,tileGrid.getTileCoordCenter(tile.tileCoord),tileResolution])}if(opt_tileCallback!==undefined)opt_tileCallback.call(opt_this,
tile)}else tileSource.useTile(z,x,y,projection)}};goog.provide("ol.renderer.canvas.Layer");goog.require("ol");goog.require("ol.extent");goog.require("ol.functions");goog.require("ol.render.Event");goog.require("ol.render.EventType");goog.require("ol.render.canvas");goog.require("ol.render.canvas.Immediate");goog.require("ol.renderer.Layer");goog.require("ol.transform");ol.renderer.canvas.Layer=function(layer){ol.renderer.Layer.call(this,layer);this.renderedResolution;this.transform_=ol.transform.create()};ol.inherits(ol.renderer.canvas.Layer,ol.renderer.Layer);
ol.renderer.canvas.Layer.prototype.clip=function(context,frameState,extent){var pixelRatio=frameState.pixelRatio;var width=frameState.size[0]*pixelRatio;var height=frameState.size[1]*pixelRatio;var rotation=frameState.viewState.rotation;var topLeft=ol.extent.getTopLeft(extent);var topRight=ol.extent.getTopRight(extent);var bottomRight=ol.extent.getBottomRight(extent);var bottomLeft=ol.extent.getBottomLeft(extent);ol.transform.apply(frameState.coordinateToPixelTransform,topLeft);ol.transform.apply(frameState.coordinateToPixelTransform,
topRight);ol.transform.apply(frameState.coordinateToPixelTransform,bottomRight);ol.transform.apply(frameState.coordinateToPixelTransform,bottomLeft);context.save();ol.render.canvas.rotateAtOffset(context,-rotation,width/2,height/2);context.beginPath();context.moveTo(topLeft[0]*pixelRatio,topLeft[1]*pixelRatio);context.lineTo(topRight[0]*pixelRatio,topRight[1]*pixelRatio);context.lineTo(bottomRight[0]*pixelRatio,bottomRight[1]*pixelRatio);context.lineTo(bottomLeft[0]*pixelRatio,bottomLeft[1]*pixelRatio);
context.clip();ol.render.canvas.rotateAtOffset(context,rotation,width/2,height/2)};
ol.renderer.canvas.Layer.prototype.dispatchComposeEvent_=function(type,context,frameState,opt_transform){var layer=this.getLayer();if(layer.hasListener(type)){var width=frameState.size[0]*frameState.pixelRatio;var height=frameState.size[1]*frameState.pixelRatio;var rotation=frameState.viewState.rotation;ol.render.canvas.rotateAtOffset(context,-rotation,width/2,height/2);var transform=opt_transform!==undefined?opt_transform:this.getTransform(frameState,0);var render=new ol.render.canvas.Immediate(context,
frameState.pixelRatio,frameState.extent,transform,frameState.viewState.rotation);var composeEvent=new ol.render.Event(type,render,frameState,context,null);layer.dispatchEvent(composeEvent);ol.render.canvas.rotateAtOffset(context,rotation,width/2,height/2)}};
ol.renderer.canvas.Layer.prototype.forEachLayerAtCoordinate=function(coordinate,frameState,callback,thisArg){var hasFeature=this.forEachFeatureAtCoordinate(coordinate,frameState,0,ol.functions.TRUE,this);if(hasFeature)return callback.call(thisArg,this.getLayer(),null);else return undefined};ol.renderer.canvas.Layer.prototype.postCompose=function(context,frameState,layerState,opt_transform){this.dispatchComposeEvent_(ol.render.EventType.POSTCOMPOSE,context,frameState,opt_transform)};
ol.renderer.canvas.Layer.prototype.preCompose=function(context,frameState,opt_transform){this.dispatchComposeEvent_(ol.render.EventType.PRECOMPOSE,context,frameState,opt_transform)};ol.renderer.canvas.Layer.prototype.dispatchRenderEvent=function(context,frameState,opt_transform){this.dispatchComposeEvent_(ol.render.EventType.RENDER,context,frameState,opt_transform)};
ol.renderer.canvas.Layer.prototype.getTransform=function(frameState,offsetX){var viewState=frameState.viewState;var pixelRatio=frameState.pixelRatio;var dx1=pixelRatio*frameState.size[0]/2;var dy1=pixelRatio*frameState.size[1]/2;var sx=pixelRatio/viewState.resolution;var sy=-sx;var angle=-viewState.rotation;var dx2=-viewState.center[0]+offsetX;var dy2=-viewState.center[1];return ol.transform.compose(this.transform_,dx1,dy1,sx,sy,angle,dx2,dy2)};
ol.renderer.canvas.Layer.prototype.composeFrame=function(frameState,layerState,context){};ol.renderer.canvas.Layer.prototype.prepareFrame=function(frameState,layerState){};goog.provide("ol.renderer.canvas.IntermediateCanvas");goog.require("ol");goog.require("ol.coordinate");goog.require("ol.dom");goog.require("ol.extent");goog.require("ol.renderer.canvas.Layer");goog.require("ol.transform");ol.renderer.canvas.IntermediateCanvas=function(layer){ol.renderer.canvas.Layer.call(this,layer);this.coordinateToCanvasPixelTransform=ol.transform.create();this.hitCanvasContext_=null};ol.inherits(ol.renderer.canvas.IntermediateCanvas,ol.renderer.canvas.Layer);
ol.renderer.canvas.IntermediateCanvas.prototype.composeFrame=function(frameState,layerState,context){this.preCompose(context,frameState);var image=this.getImage();if(image){var extent=layerState.extent;var clipped=extent!==undefined&&!ol.extent.containsExtent(extent,frameState.extent)&&ol.extent.intersects(extent,frameState.extent);if(clipped)this.clip(context,frameState,extent);var imageTransform=this.getImageTransform();var alpha=context.globalAlpha;context.globalAlpha=layerState.opacity;var dx=
imageTransform[4];var dy=imageTransform[5];var dw=image.width*imageTransform[0];var dh=image.height*imageTransform[3];context.drawImage(image,0,0,+image.width,+image.height,Math.round(dx),Math.round(dy),Math.round(dw),Math.round(dh));context.globalAlpha=alpha;if(clipped)context.restore()}this.postCompose(context,frameState,layerState)};ol.renderer.canvas.IntermediateCanvas.prototype.getImage=function(){};ol.renderer.canvas.IntermediateCanvas.prototype.getImageTransform=function(){};
ol.renderer.canvas.IntermediateCanvas.prototype.forEachFeatureAtCoordinate=function(coordinate,frameState,hitTolerance,callback,thisArg){var layer=this.getLayer();var source=layer.getSource();var resolution=frameState.viewState.resolution;var rotation=frameState.viewState.rotation;var skippedFeatureUids=frameState.skippedFeatureUids;return source.forEachFeatureAtCoordinate(coordinate,resolution,rotation,hitTolerance,skippedFeatureUids,function(feature){return callback.call(thisArg,feature,layer)})};
ol.renderer.canvas.IntermediateCanvas.prototype.forEachLayerAtCoordinate=function(coordinate,frameState,callback,thisArg){if(!this.getImage())return undefined;if(this.getLayer().getSource().forEachFeatureAtCoordinate!==ol.nullFunction)return ol.renderer.canvas.Layer.prototype.forEachLayerAtCoordinate.apply(this,arguments);else{var pixel=ol.transform.apply(this.coordinateToCanvasPixelTransform,coordinate.slice());ol.coordinate.scale(pixel,frameState.viewState.resolution/this.renderedResolution);if(!this.hitCanvasContext_)this.hitCanvasContext_=
ol.dom.createCanvasContext2D(1,1);this.hitCanvasContext_.clearRect(0,0,1,1);this.hitCanvasContext_.drawImage(this.getImage(),pixel[0],pixel[1],1,1,0,0,1,1);var imageData=this.hitCanvasContext_.getImageData(0,0,1,1).data;if(imageData[3]>0)return callback.call(thisArg,this.getLayer(),imageData);else return undefined}};goog.provide("ol.renderer.canvas.ImageLayer");goog.require("ol");goog.require("ol.ImageCanvas");goog.require("ol.LayerType");goog.require("ol.ViewHint");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.layer.VectorRenderType");goog.require("ol.obj");goog.require("ol.plugins");goog.require("ol.renderer.Type");goog.require("ol.renderer.canvas.IntermediateCanvas");goog.require("ol.transform");
ol.renderer.canvas.ImageLayer=function(imageLayer){ol.renderer.canvas.IntermediateCanvas.call(this,imageLayer);this.image_=null;this.imageTransform_=ol.transform.create();this.skippedFeatures_=[];this.vectorRenderer_=null};ol.inherits(ol.renderer.canvas.ImageLayer,ol.renderer.canvas.IntermediateCanvas);
ol.renderer.canvas.ImageLayer["handles"]=function(type,layer){return type===ol.renderer.Type.CANVAS&&(layer.getType()===ol.LayerType.IMAGE||layer.getType()===ol.LayerType.VECTOR&&layer.getRenderMode()===ol.layer.VectorRenderType.IMAGE)};
ol.renderer.canvas.ImageLayer["create"]=function(mapRenderer,layer){var renderer=new ol.renderer.canvas.ImageLayer(layer);if(layer.getType()===ol.LayerType.VECTOR){var candidates=ol.plugins.getLayerRendererPlugins();for(var i=0,ii=candidates.length;i<ii;++i){var candidate=candidates[i];if(candidate!==ol.renderer.canvas.ImageLayer&&candidate["handles"](ol.renderer.Type.CANVAS,layer))renderer.setVectorRenderer(candidate["create"](mapRenderer,layer))}}return renderer};
ol.renderer.canvas.ImageLayer.prototype.getImage=function(){return!this.image_?null:this.image_.getImage()};ol.renderer.canvas.ImageLayer.prototype.getImageTransform=function(){return this.imageTransform_};
ol.renderer.canvas.ImageLayer.prototype.prepareFrame=function(frameState,layerState){var pixelRatio=frameState.pixelRatio;var size=frameState.size;var viewState=frameState.viewState;var viewCenter=viewState.center;var viewResolution=viewState.resolution;var image;var imageLayer=this.getLayer();var imageSource=imageLayer.getSource();var hints=frameState.viewHints;var renderedExtent=frameState.extent;if(layerState.extent!==undefined)renderedExtent=ol.extent.getIntersection(renderedExtent,layerState.extent);
if(!hints[ol.ViewHint.ANIMATING]&&!hints[ol.ViewHint.INTERACTING]&&!ol.extent.isEmpty(renderedExtent)){var projection=viewState.projection;if(!ol.ENABLE_RASTER_REPROJECTION){var sourceProjection=imageSource.getProjection();if(sourceProjection)projection=sourceProjection}var vectorRenderer=this.vectorRenderer_;if(vectorRenderer){var context=vectorRenderer.context;var imageFrameState=ol.obj.assign({},frameState,{size:[ol.extent.getWidth(renderedExtent)/viewResolution,ol.extent.getHeight(renderedExtent)/
viewResolution],viewState:ol.obj.assign({},frameState.viewState,{rotation:0})});var skippedFeatures=Object.keys(imageFrameState.skippedFeatureUids).sort();if(vectorRenderer.prepareFrame(imageFrameState,layerState)&&(vectorRenderer.replayGroupChanged||!ol.array.equals(skippedFeatures,this.skippedFeatures_))){context.canvas.width=imageFrameState.size[0]*pixelRatio;context.canvas.height=imageFrameState.size[1]*pixelRatio;vectorRenderer.composeFrame(imageFrameState,layerState,context);this.image_=new ol.ImageCanvas(renderedExtent,
viewResolution,pixelRatio,context.canvas);this.skippedFeatures_=skippedFeatures}}else{image=imageSource.getImage(renderedExtent,viewResolution,pixelRatio,projection);if(image){var loaded=this.loadImage(image);if(loaded)this.image_=image}}}if(this.image_){image=this.image_;var imageExtent=image.getExtent();var imageResolution=image.getResolution();var imagePixelRatio=image.getPixelRatio();var scale=pixelRatio*imageResolution/(viewResolution*imagePixelRatio);var transform=ol.transform.compose(this.imageTransform_,
pixelRatio*size[0]/2,pixelRatio*size[1]/2,scale,scale,0,imagePixelRatio*(imageExtent[0]-viewCenter[0])/imageResolution,imagePixelRatio*(viewCenter[1]-imageExtent[3])/imageResolution);ol.transform.compose(this.coordinateToCanvasPixelTransform,pixelRatio*size[0]/2-transform[4],pixelRatio*size[1]/2-transform[5],pixelRatio/viewResolution,-pixelRatio/viewResolution,0,-viewCenter[0],-viewCenter[1]);this.updateLogos(frameState,imageSource);this.renderedResolution=imageResolution*pixelRatio/imagePixelRatio}return!!this.image_};
ol.renderer.canvas.ImageLayer.prototype.forEachFeatureAtCoordinate=function(coordinate,frameState,hitTolerance,callback,thisArg){if(this.vectorRenderer_)return this.vectorRenderer_.forEachFeatureAtCoordinate(coordinate,frameState,hitTolerance,callback,thisArg);else return ol.renderer.canvas.IntermediateCanvas.prototype.forEachFeatureAtCoordinate.call(this,coordinate,frameState,hitTolerance,callback,thisArg)};
ol.renderer.canvas.ImageLayer.prototype.setVectorRenderer=function(renderer){this.vectorRenderer_=renderer};goog.provide("ol.style.IconImageCache");goog.require("ol.color");ol.style.IconImageCache=function(){this.cache_={};this.cacheSize_=0;this.maxCacheSize_=32};ol.style.IconImageCache.getKey=function(src,crossOrigin,color){var colorString=color?ol.color.asString(color):"null";return crossOrigin+":"+src+":"+colorString};ol.style.IconImageCache.prototype.clear=function(){this.cache_={};this.cacheSize_=0};
ol.style.IconImageCache.prototype.expire=function(){if(this.cacheSize_>this.maxCacheSize_){var i=0;var key,iconImage;for(key in this.cache_){iconImage=this.cache_[key];if((i++&3)===0&&!iconImage.hasListener()){delete this.cache_[key];--this.cacheSize_}}}};ol.style.IconImageCache.prototype.get=function(src,crossOrigin,color){var key=ol.style.IconImageCache.getKey(src,crossOrigin,color);return key in this.cache_?this.cache_[key]:null};
ol.style.IconImageCache.prototype.set=function(src,crossOrigin,color,iconImage){var key=ol.style.IconImageCache.getKey(src,crossOrigin,color);this.cache_[key]=iconImage;++this.cacheSize_};ol.style.IconImageCache.prototype.setSize=function(maxCacheSize){this.maxCacheSize_=maxCacheSize;this.expire()};goog.provide("ol.style");goog.require("ol.style.IconImageCache");ol.style.iconImageCache=new ol.style.IconImageCache;goog.provide("ol.renderer.Map");goog.require("ol");goog.require("ol.Disposable");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.functions");goog.require("ol.layer.Layer");goog.require("ol.plugins");goog.require("ol.style");goog.require("ol.transform");ol.renderer.Map=function(container,map){ol.Disposable.call(this);this.map_=map;this.layerRenderers_={};this.layerRendererListeners_={}};ol.inherits(ol.renderer.Map,ol.Disposable);
ol.renderer.Map.prototype.calculateMatrices2D=function(frameState){var viewState=frameState.viewState;var coordinateToPixelTransform=frameState.coordinateToPixelTransform;var pixelToCoordinateTransform=frameState.pixelToCoordinateTransform;ol.transform.compose(coordinateToPixelTransform,frameState.size[0]/2,frameState.size[1]/2,1/viewState.resolution,-1/viewState.resolution,-viewState.rotation,-viewState.center[0],-viewState.center[1]);ol.transform.invert(ol.transform.setFromArray(pixelToCoordinateTransform,
coordinateToPixelTransform))};ol.renderer.Map.prototype.removeLayerRenderers=function(){for(var key in this.layerRenderers_)this.removeLayerRendererByKey_(key).dispose()};ol.renderer.Map.expireIconCache_=function(map,frameState){var cache=ol.style.iconImageCache;cache.expire()};
ol.renderer.Map.prototype.forEachFeatureAtCoordinate=function(coordinate,frameState,hitTolerance,callback,thisArg,layerFilter,thisArg2){var result;var viewState=frameState.viewState;var viewResolution=viewState.resolution;function forEachFeatureAtCoordinate(feature,layer){var key=ol.getUid(feature).toString();var managed=frameState.layerStates[ol.getUid(layer)].managed;if(!(key in frameState.skippedFeatureUids&&!managed))return callback.call(thisArg,feature,managed?layer:null)}var projection=viewState.projection;
var translatedCoordinate=coordinate;if(projection.canWrapX()){var projectionExtent=projection.getExtent();var worldWidth=ol.extent.getWidth(projectionExtent);var x=coordinate[0];if(x<projectionExtent[0]||x>projectionExtent[2]){var worldsAway=Math.ceil((projectionExtent[0]-x)/worldWidth);translatedCoordinate=[x+worldWidth*worldsAway,coordinate[1]]}}var layerStates=frameState.layerStatesArray;var numLayers=layerStates.length;var i;for(i=numLayers-1;i>=0;--i){var layerState=layerStates[i];var layer=
layerState.layer;if(ol.layer.Layer.visibleAtResolution(layerState,viewResolution)&&layerFilter.call(thisArg2,layer)){var layerRenderer=this.getLayerRenderer(layer);if(layer.getSource())result=layerRenderer.forEachFeatureAtCoordinate(layer.getSource().getWrapX()?translatedCoordinate:coordinate,frameState,hitTolerance,forEachFeatureAtCoordinate,thisArg);if(result)return result}}return undefined};ol.renderer.Map.prototype.forEachLayerAtPixel=function(pixel,frameState,callback,thisArg,layerFilter,thisArg2){};
ol.renderer.Map.prototype.hasFeatureAtCoordinate=function(coordinate,frameState,hitTolerance,layerFilter,thisArg){var hasFeature=this.forEachFeatureAtCoordinate(coordinate,frameState,hitTolerance,ol.functions.TRUE,this,layerFilter,thisArg);return hasFeature!==undefined};
ol.renderer.Map.prototype.getLayerRenderer=function(layer){var layerKey=ol.getUid(layer).toString();if(layerKey in this.layerRenderers_)return this.layerRenderers_[layerKey];else{var layerRendererPlugins=ol.plugins.getLayerRendererPlugins();var renderer;var type=this.getType();for(var i=0,ii=layerRendererPlugins.length;i<ii;++i){var plugin=layerRendererPlugins[i];if(plugin["handles"](type,layer)){renderer=plugin["create"](this,layer);break}}if(renderer){this.layerRenderers_[layerKey]=renderer;this.layerRendererListeners_[layerKey]=
ol.events.listen(renderer,ol.events.EventType.CHANGE,this.handleLayerRendererChange_,this)}else throw new Error("Unable to create renderer for layer: "+layer.getType());return renderer}};ol.renderer.Map.prototype.getLayerRendererByKey=function(layerKey){return this.layerRenderers_[layerKey]};ol.renderer.Map.prototype.getLayerRenderers=function(){return this.layerRenderers_};ol.renderer.Map.prototype.getMap=function(){return this.map_};ol.renderer.Map.prototype.getType=function(){};
ol.renderer.Map.prototype.handleLayerRendererChange_=function(){this.map_.render()};ol.renderer.Map.prototype.removeLayerRendererByKey_=function(layerKey){var layerRenderer=this.layerRenderers_[layerKey];delete this.layerRenderers_[layerKey];ol.events.unlistenByKey(this.layerRendererListeners_[layerKey]);delete this.layerRendererListeners_[layerKey];return layerRenderer};ol.renderer.Map.prototype.renderFrame=ol.nullFunction;
ol.renderer.Map.prototype.removeUnusedLayerRenderers_=function(map,frameState){var layerKey;for(layerKey in this.layerRenderers_)if(!frameState||!(layerKey in frameState.layerStates))this.removeLayerRendererByKey_(layerKey).dispose()};ol.renderer.Map.prototype.scheduleExpireIconCache=function(frameState){frameState.postRenderFunctions.push(ol.renderer.Map.expireIconCache_)};
ol.renderer.Map.prototype.scheduleRemoveUnusedLayerRenderers=function(frameState){var layerKey;for(layerKey in this.layerRenderers_)if(!(layerKey in frameState.layerStates)){frameState.postRenderFunctions.push(this.removeUnusedLayerRenderers_.bind(this));return}};ol.renderer.Map.sortByZIndex=function(state1,state2){return state1.zIndex-state2.zIndex};goog.provide("ol.renderer.canvas.Map");goog.require("ol.transform");goog.require("ol");goog.require("ol.array");goog.require("ol.css");goog.require("ol.dom");goog.require("ol.layer.Layer");goog.require("ol.render.Event");goog.require("ol.render.EventType");goog.require("ol.render.canvas");goog.require("ol.render.canvas.Immediate");goog.require("ol.renderer.Map");goog.require("ol.renderer.Type");goog.require("ol.source.State");
ol.renderer.canvas.Map=function(container,map){ol.renderer.Map.call(this,container,map);this.context_=ol.dom.createCanvasContext2D();this.canvas_=this.context_.canvas;this.canvas_.style.width="100%";this.canvas_.style.height="100%";this.canvas_.style.display="block";this.canvas_.className=ol.css.CLASS_UNSELECTABLE;container.insertBefore(this.canvas_,container.childNodes[0]||null);this.renderedVisible_=true;this.transform_=ol.transform.create()};ol.inherits(ol.renderer.canvas.Map,ol.renderer.Map);
ol.renderer.canvas.Map["handles"]=function(type){return type===ol.renderer.Type.CANVAS};ol.renderer.canvas.Map["create"]=function(container,map){return new ol.renderer.canvas.Map(container,map)};
ol.renderer.canvas.Map.prototype.dispatchComposeEvent_=function(type,frameState){var map=this.getMap();var context=this.context_;if(map.hasListener(type)){var extent=frameState.extent;var pixelRatio=frameState.pixelRatio;var viewState=frameState.viewState;var rotation=viewState.rotation;var transform=this.getTransform(frameState);var vectorContext=new ol.render.canvas.Immediate(context,pixelRatio,extent,transform,rotation);var composeEvent=new ol.render.Event(type,vectorContext,frameState,context,
null);map.dispatchEvent(composeEvent)}};ol.renderer.canvas.Map.prototype.getTransform=function(frameState){var viewState=frameState.viewState;var dx1=this.canvas_.width/2;var dy1=this.canvas_.height/2;var sx=frameState.pixelRatio/viewState.resolution;var sy=-sx;var angle=-viewState.rotation;var dx2=-viewState.center[0];var dy2=-viewState.center[1];return ol.transform.compose(this.transform_,dx1,dy1,sx,sy,angle,dx2,dy2)};ol.renderer.canvas.Map.prototype.getType=function(){return ol.renderer.Type.CANVAS};
ol.renderer.canvas.Map.prototype.renderFrame=function(frameState){if(!frameState){if(this.renderedVisible_){this.canvas_.style.display="none";this.renderedVisible_=false}return}var context=this.context_;var pixelRatio=frameState.pixelRatio;var width=Math.round(frameState.size[0]*pixelRatio);var height=Math.round(frameState.size[1]*pixelRatio);if(this.canvas_.width!=width||this.canvas_.height!=height){this.canvas_.width=width;this.canvas_.height=height}else context.clearRect(0,0,width,height);var rotation=
frameState.viewState.rotation;this.calculateMatrices2D(frameState);this.dispatchComposeEvent_(ol.render.EventType.PRECOMPOSE,frameState);var layerStatesArray=frameState.layerStatesArray;ol.array.stableSort(layerStatesArray,ol.renderer.Map.sortByZIndex);if(rotation){context.save();ol.render.canvas.rotateAtOffset(context,rotation,width/2,height/2)}var viewResolution=frameState.viewState.resolution;var i,ii,layer,layerRenderer,layerState;for(i=0,ii=layerStatesArray.length;i<ii;++i){layerState=layerStatesArray[i];
layer=layerState.layer;layerRenderer=this.getLayerRenderer(layer);if(!ol.layer.Layer.visibleAtResolution(layerState,viewResolution)||layerState.sourceState!=ol.source.State.READY)continue;if(layerRenderer.prepareFrame(frameState,layerState))layerRenderer.composeFrame(frameState,layerState,context)}if(rotation)context.restore();this.dispatchComposeEvent_(ol.render.EventType.POSTCOMPOSE,frameState);if(!this.renderedVisible_){this.canvas_.style.display="";this.renderedVisible_=true}this.scheduleRemoveUnusedLayerRenderers(frameState);
this.scheduleExpireIconCache(frameState)};
ol.renderer.canvas.Map.prototype.forEachLayerAtPixel=function(pixel,frameState,callback,thisArg,layerFilter,thisArg2){var result;var viewState=frameState.viewState;var viewResolution=viewState.resolution;var layerStates=frameState.layerStatesArray;var numLayers=layerStates.length;var coordinate=ol.transform.apply(frameState.pixelToCoordinateTransform,pixel.slice());var i;for(i=numLayers-1;i>=0;--i){var layerState=layerStates[i];var layer=layerState.layer;if(ol.layer.Layer.visibleAtResolution(layerState,
viewResolution)&&layerFilter.call(thisArg2,layer)){var layerRenderer=this.getLayerRenderer(layer);result=layerRenderer.forEachLayerAtCoordinate(coordinate,frameState,callback,thisArg);if(result)return result}}return undefined};goog.provide("ol.renderer.canvas.TileLayer");goog.require("ol");goog.require("ol.LayerType");goog.require("ol.TileRange");goog.require("ol.TileState");goog.require("ol.ViewHint");goog.require("ol.dom");goog.require("ol.extent");goog.require("ol.renderer.Type");goog.require("ol.renderer.canvas.IntermediateCanvas");goog.require("ol.transform");
ol.renderer.canvas.TileLayer=function(tileLayer){ol.renderer.canvas.IntermediateCanvas.call(this,tileLayer);this.context=this.context===null?null:ol.dom.createCanvasContext2D();this.oversampling_;this.renderedExtent_=null;this.renderedRevision;this.renderedTiles=[];this.tmpExtent=ol.extent.createEmpty();this.tmpTileRange_=new ol.TileRange(0,0,0,0);this.imageTransform_=ol.transform.create();this.zDirection=0};ol.inherits(ol.renderer.canvas.TileLayer,ol.renderer.canvas.IntermediateCanvas);
ol.renderer.canvas.TileLayer["handles"]=function(type,layer){return type===ol.renderer.Type.CANVAS&&layer.getType()===ol.LayerType.TILE};ol.renderer.canvas.TileLayer["create"]=function(mapRenderer,layer){return new ol.renderer.canvas.TileLayer(layer)};
ol.renderer.canvas.TileLayer.prototype.isDrawableTile_=function(tile){var tileState=tile.getState();var useInterimTilesOnError=this.getLayer().getUseInterimTilesOnError();return tileState==ol.TileState.LOADED||tileState==ol.TileState.EMPTY||tileState==ol.TileState.ERROR&&!useInterimTilesOnError};
ol.renderer.canvas.TileLayer.prototype.prepareFrame=function(frameState,layerState){var pixelRatio=frameState.pixelRatio;var size=frameState.size;var viewState=frameState.viewState;var projection=viewState.projection;var viewResolution=viewState.resolution;var viewCenter=viewState.center;var tileLayer=this.getLayer();var tileSource=tileLayer.getSource();var sourceRevision=tileSource.getRevision();var tileGrid=tileSource.getTileGridForProjection(projection);var z=tileGrid.getZForResolution(viewResolution,
this.zDirection);var tileResolution=tileGrid.getResolution(z);var oversampling=Math.round(viewResolution/tileResolution)||1;var extent=frameState.extent;if(layerState.extent!==undefined)extent=ol.extent.getIntersection(extent,layerState.extent);if(ol.extent.isEmpty(extent))return false;var tileRange=tileGrid.getTileRangeForExtentAndZ(extent,z);var imageExtent=tileGrid.getTileRangeExtent(z,tileRange);var tilePixelRatio=tileSource.getTilePixelRatio(pixelRatio);var tilesToDrawByZ={};tilesToDrawByZ[z]=
{};var findLoadedTiles=this.createLoadedTileFinder(tileSource,projection,tilesToDrawByZ);var tmpExtent=this.tmpExtent;var tmpTileRange=this.tmpTileRange_;var newTiles=false;var tile,x,y;for(x=tileRange.minX;x<=tileRange.maxX;++x)for(y=tileRange.minY;y<=tileRange.maxY;++y){tile=tileSource.getTile(z,x,y,pixelRatio,projection);if(tile.getState()==ol.TileState.ERROR)if(!tileLayer.getUseInterimTilesOnError())tile.setState(ol.TileState.LOADED);else if(tileLayer.getPreload()>0)newTiles=true;if(!this.isDrawableTile_(tile))tile=
tile.getInterimTile();if(this.isDrawableTile_(tile)){var uid=ol.getUid(this);if(tile.getState()==ol.TileState.LOADED){tilesToDrawByZ[z][tile.tileCoord.toString()]=tile;var inTransition=tile.inTransition(uid);if(!newTiles&&(inTransition||this.renderedTiles.indexOf(tile)===-1))newTiles=true}if(tile.getAlpha(uid,frameState.time)===1)continue}var childTileRange=tileGrid.getTileCoordChildTileRange(tile.tileCoord,tmpTileRange,tmpExtent);var covered=false;if(childTileRange)covered=findLoadedTiles(z+1,childTileRange);
if(!covered)tileGrid.forEachTileCoordParentTileRange(tile.tileCoord,findLoadedTiles,null,tmpTileRange,tmpExtent)}var renderedResolution=tileResolution*pixelRatio/tilePixelRatio*oversampling;var hints=frameState.viewHints;var animatingOrInteracting=hints[ol.ViewHint.ANIMATING]||hints[ol.ViewHint.INTERACTING];if(!(this.renderedResolution&&Date.now()-frameState.time>16&&animatingOrInteracting)&&(newTiles||!(this.renderedExtent_&&ol.extent.containsExtent(this.renderedExtent_,extent))||this.renderedRevision!=
sourceRevision||oversampling!=this.oversampling_||!animatingOrInteracting&&renderedResolution!=this.renderedResolution)){var context=this.context;if(context){var tilePixelSize=tileSource.getTilePixelSize(z,pixelRatio,projection);var width=Math.round(tileRange.getWidth()*tilePixelSize[0]/oversampling);var height=Math.round(tileRange.getHeight()*tilePixelSize[1]/oversampling);var canvas=context.canvas;if(canvas.width!=width||canvas.height!=height){this.oversampling_=oversampling;canvas.width=width;
canvas.height=height}else{if(this.renderedExtent_&&!ol.extent.equals(imageExtent,this.renderedExtent_))context.clearRect(0,0,width,height);oversampling=this.oversampling_}}this.renderedTiles.length=0;var zs=Object.keys(tilesToDrawByZ).map(Number);zs.sort(function(a,b){if(a===z)return 1;else if(b===z)return-1;else return a>b?1:a<b?-1:0});var currentResolution,currentScale,currentTilePixelSize,currentZ,i,ii;var tileExtent,tileGutter,tilesToDraw,w,h;for(i=0,ii=zs.length;i<ii;++i){currentZ=zs[i];currentTilePixelSize=
tileSource.getTilePixelSize(currentZ,pixelRatio,projection);currentResolution=tileGrid.getResolution(currentZ);currentScale=currentResolution/tileResolution;tileGutter=tilePixelRatio*tileSource.getGutter(projection);tilesToDraw=tilesToDrawByZ[currentZ];for(var tileCoordKey in tilesToDraw){tile=tilesToDraw[tileCoordKey];tileExtent=tileGrid.getTileCoordExtent(tile.getTileCoord(),tmpExtent);x=(tileExtent[0]-imageExtent[0])/tileResolution*tilePixelRatio/oversampling;y=(imageExtent[3]-tileExtent[3])/tileResolution*
tilePixelRatio/oversampling;w=currentTilePixelSize[0]*currentScale/oversampling;h=currentTilePixelSize[1]*currentScale/oversampling;this.drawTileImage(tile,frameState,layerState,x,y,w,h,tileGutter,z===currentZ);this.renderedTiles.push(tile)}}this.renderedRevision=sourceRevision;this.renderedResolution=tileResolution*pixelRatio/tilePixelRatio*oversampling;this.renderedExtent_=imageExtent}var scale=this.renderedResolution/viewResolution;var transform=ol.transform.compose(this.imageTransform_,pixelRatio*
size[0]/2,pixelRatio*size[1]/2,scale,scale,0,(this.renderedExtent_[0]-viewCenter[0])/this.renderedResolution*pixelRatio,(viewCenter[1]-this.renderedExtent_[3])/this.renderedResolution*pixelRatio);ol.transform.compose(this.coordinateToCanvasPixelTransform,pixelRatio*size[0]/2-transform[4],pixelRatio*size[1]/2-transform[5],pixelRatio/viewResolution,-pixelRatio/viewResolution,0,-viewCenter[0],-viewCenter[1]);this.updateUsedTiles(frameState.usedTiles,tileSource,z,tileRange);this.manageTilePyramid(frameState,
tileSource,tileGrid,pixelRatio,projection,extent,z,tileLayer.getPreload());this.scheduleExpireCache(frameState,tileSource);this.updateLogos(frameState,tileSource);return this.renderedTiles.length>0};
ol.renderer.canvas.TileLayer.prototype.drawTileImage=function(tile,frameState,layerState,x,y,w,h,gutter,transition){var image=tile.getImage(this.getLayer());if(!image)return;var uid=ol.getUid(this);var alpha=transition?tile.getAlpha(uid,frameState.time):1;if(alpha===1&&!this.getLayer().getSource().getOpaque(frameState.viewState.projection))this.context.clearRect(x,y,w,h);var alphaChanged=alpha!==this.context.globalAlpha;if(alphaChanged){this.context.save();this.context.globalAlpha=alpha}this.context.drawImage(image,
gutter,gutter,image.width-2*gutter,image.height-2*gutter,x,y,w,h);if(alphaChanged)this.context.restore();if(alpha!==1)frameState.animate=true;else if(transition)tile.endTransition(uid)};ol.renderer.canvas.TileLayer.prototype.getImage=function(){var context=this.context;return context?context.canvas:null};ol.renderer.canvas.TileLayer.prototype.getLayer;ol.renderer.canvas.TileLayer.prototype.getImageTransform=function(){return this.imageTransform_};goog.provide("ol.ext.rbush");ol.ext.rbush=function(){};
(function(){(function(exports){var commonjsGlobal=typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function createCommonjsModule(fn,module){return module={exports:{}},fn(module,module.exports),module.exports}var quickselect=createCommonjsModule(function(module,exports){(function(global,factory){module.exports=factory()})(commonjsGlobal,function(){function quickselect(arr,k,left,right,compare){quickselectStep(arr,k,left||0,right||arr.length-1,
compare||defaultCompare)}function quickselectStep(arr,k,left,right,compare){while(right>left){if(right-left>600){var n=right-left+1;var m=k-left+1;var z=Math.log(n);var s=.5*Math.exp(2*z/3);var sd=.5*Math.sqrt(z*s*(n-s)/n)*(m-n/2<0?-1:1);var newLeft=Math.max(left,Math.floor(k-m*s/n+sd));var newRight=Math.min(right,Math.floor(k+(n-m)*s/n+sd));quickselectStep(arr,k,newLeft,newRight,compare)}var t=arr[k];var i=left;var j=right;swap(arr,left,k);if(compare(arr[right],t)>0)swap(arr,left,right);while(i<
j){swap(arr,i,j);i++;j--;while(compare(arr[i],t)<0)i++;while(compare(arr[j],t)>0)j--}if(compare(arr[left],t)===0)swap(arr,left,j);else{j++;swap(arr,j,right)}if(j<=k)left=j+1;if(k<=j)right=j-1}}function swap(arr,i,j){var tmp=arr[i];arr[i]=arr[j];arr[j]=tmp}function defaultCompare(a,b){return a<b?-1:a>b?1:0}return quickselect})});var rbush_1=rbush;function rbush(maxEntries,format){if(!(this instanceof rbush))return new rbush(maxEntries,format);this._maxEntries=Math.max(4,maxEntries||9);this._minEntries=
Math.max(2,Math.ceil(this._maxEntries*.4));if(format)this._initFormat(format);this.clear()}rbush.prototype={all:function(){return this._all(this.data,[])},search:function(bbox){var node=this.data,result=[],toBBox=this.toBBox;if(!intersects(bbox,node))return result;var nodesToSearch=[],i,len,child,childBBox;while(node){for(i=0,len=node.children.length;i<len;i++){child=node.children[i];childBBox=node.leaf?toBBox(child):child;if(intersects(bbox,childBBox))if(node.leaf)result.push(child);else if(contains(bbox,
childBBox))this._all(child,result);else nodesToSearch.push(child)}node=nodesToSearch.pop()}return result},collides:function(bbox){var node=this.data,toBBox=this.toBBox;if(!intersects(bbox,node))return false;var nodesToSearch=[],i,len,child,childBBox;while(node){for(i=0,len=node.children.length;i<len;i++){child=node.children[i];childBBox=node.leaf?toBBox(child):child;if(intersects(bbox,childBBox)){if(node.leaf||contains(bbox,childBBox))return true;nodesToSearch.push(child)}}node=nodesToSearch.pop()}return false},
load:function(data){if(!(data&&data.length))return this;if(data.length<this._minEntries){for(var i=0,len=data.length;i<len;i++)this.insert(data[i]);return this}var node=this._build(data.slice(),0,data.length-1,0);if(!this.data.children.length)this.data=node;else if(this.data.height===node.height)this._splitRoot(this.data,node);else{if(this.data.height<node.height){var tmpNode=this.data;this.data=node;node=tmpNode}this._insert(node,this.data.height-node.height-1,true)}return this},insert:function(item){if(item)this._insert(item,
this.data.height-1);return this},clear:function(){this.data=createNode([]);return this},remove:function(item,equalsFn){if(!item)return this;var node=this.data,bbox=this.toBBox(item),path=[],indexes=[],i,parent,index,goingUp;while(node||path.length){if(!node){node=path.pop();parent=path[path.length-1];i=indexes.pop();goingUp=true}if(node.leaf){index=findItem(item,node.children,equalsFn);if(index!==-1){node.children.splice(index,1);path.push(node);this._condense(path);return this}}if(!goingUp&&!node.leaf&&
contains(node,bbox)){path.push(node);indexes.push(i);i=0;parent=node;node=node.children[0]}else if(parent){i++;node=parent.children[i];goingUp=false}else node=null}return this},toBBox:function(item){return item},compareMinX:compareNodeMinX,compareMinY:compareNodeMinY,toJSON:function(){return this.data},fromJSON:function(data){this.data=data;return this},_all:function(node,result){var nodesToSearch=[];while(node){if(node.leaf)result.push.apply(result,node.children);else nodesToSearch.push.apply(nodesToSearch,
node.children);node=nodesToSearch.pop()}return result},_build:function(items,left,right,height){var N=right-left+1,M=this._maxEntries,node;if(N<=M){node=createNode(items.slice(left,right+1));calcBBox(node,this.toBBox);return node}if(!height){height=Math.ceil(Math.log(N)/Math.log(M));M=Math.ceil(N/Math.pow(M,height-1))}node=createNode([]);node.leaf=false;node.height=height;var N2=Math.ceil(N/M),N1=N2*Math.ceil(Math.sqrt(M)),i,j,right2,right3;multiSelect(items,left,right,N1,this.compareMinX);for(i=
left;i<=right;i+=N1){right2=Math.min(i+N1-1,right);multiSelect(items,i,right2,N2,this.compareMinY);for(j=i;j<=right2;j+=N2){right3=Math.min(j+N2-1,right2);node.children.push(this._build(items,j,right3,height-1))}}calcBBox(node,this.toBBox);return node},_chooseSubtree:function(bbox,node,level,path){var i,len,child,targetNode,area,enlargement,minArea,minEnlargement;while(true){path.push(node);if(node.leaf||path.length-1===level)break;minArea=minEnlargement=Infinity;for(i=0,len=node.children.length;i<
len;i++){child=node.children[i];area=bboxArea(child);enlargement=enlargedArea(bbox,child)-area;if(enlargement<minEnlargement){minEnlargement=enlargement;minArea=area<minArea?area:minArea;targetNode=child}else if(enlargement===minEnlargement)if(area<minArea){minArea=area;targetNode=child}}node=targetNode||node.children[0]}return node},_insert:function(item,level,isNode){var toBBox=this.toBBox,bbox=isNode?item:toBBox(item),insertPath=[];var node=this._chooseSubtree(bbox,this.data,level,insertPath);
node.children.push(item);extend(node,bbox);while(level>=0)if(insertPath[level].children.length>this._maxEntries){this._split(insertPath,level);level--}else break;this._adjustParentBBoxes(bbox,insertPath,level)},_split:function(insertPath,level){var node=insertPath[level],M=node.children.length,m=this._minEntries;this._chooseSplitAxis(node,m,M);var splitIndex=this._chooseSplitIndex(node,m,M);var newNode=createNode(node.children.splice(splitIndex,node.children.length-splitIndex));newNode.height=node.height;
newNode.leaf=node.leaf;calcBBox(node,this.toBBox);calcBBox(newNode,this.toBBox);if(level)insertPath[level-1].children.push(newNode);else this._splitRoot(node,newNode)},_splitRoot:function(node,newNode){this.data=createNode([node,newNode]);this.data.height=node.height+1;this.data.leaf=false;calcBBox(this.data,this.toBBox)},_chooseSplitIndex:function(node,m,M){var i,bbox1,bbox2,overlap,area,minOverlap,minArea,index;minOverlap=minArea=Infinity;for(i=m;i<=M-m;i++){bbox1=distBBox(node,0,i,this.toBBox);
bbox2=distBBox(node,i,M,this.toBBox);overlap=intersectionArea(bbox1,bbox2);area=bboxArea(bbox1)+bboxArea(bbox2);if(overlap<minOverlap){minOverlap=overlap;index=i;minArea=area<minArea?area:minArea}else if(overlap===minOverlap)if(area<minArea){minArea=area;index=i}}return index},_chooseSplitAxis:function(node,m,M){var compareMinX=node.leaf?this.compareMinX:compareNodeMinX,compareMinY=node.leaf?this.compareMinY:compareNodeMinY,xMargin=this._allDistMargin(node,m,M,compareMinX),yMargin=this._allDistMargin(node,
m,M,compareMinY);if(xMargin<yMargin)node.children.sort(compareMinX)},_allDistMargin:function(node,m,M,compare){node.children.sort(compare);var toBBox=this.toBBox,leftBBox=distBBox(node,0,m,toBBox),rightBBox=distBBox(node,M-m,M,toBBox),margin=bboxMargin(leftBBox)+bboxMargin(rightBBox),i,child;for(i=m;i<M-m;i++){child=node.children[i];extend(leftBBox,node.leaf?toBBox(child):child);margin+=bboxMargin(leftBBox)}for(i=M-m-1;i>=m;i--){child=node.children[i];extend(rightBBox,node.leaf?toBBox(child):child);
margin+=bboxMargin(rightBBox)}return margin},_adjustParentBBoxes:function(bbox,path,level){for(var i=level;i>=0;i--)extend(path[i],bbox)},_condense:function(path){for(var i=path.length-1,siblings;i>=0;i--)if(path[i].children.length===0)if(i>0){siblings=path[i-1].children;siblings.splice(siblings.indexOf(path[i]),1)}else this.clear();else calcBBox(path[i],this.toBBox)},_initFormat:function(format){var compareArr=["return a"," - b",";"];this.compareMinX=new Function("a","b",compareArr.join(format[0]));
this.compareMinY=new Function("a","b",compareArr.join(format[1]));this.toBBox=new Function("a","return {minX: a"+format[0]+", minY: a"+format[1]+", maxX: a"+format[2]+", maxY: a"+format[3]+"};")}};function findItem(item,items,equalsFn){if(!equalsFn)return items.indexOf(item);for(var i=0;i<items.length;i++)if(equalsFn(item,items[i]))return i;return-1}function calcBBox(node,toBBox){distBBox(node,0,node.children.length,toBBox,node)}function distBBox(node,k,p,toBBox,destNode){if(!destNode)destNode=createNode(null);
destNode.minX=Infinity;destNode.minY=Infinity;destNode.maxX=-Infinity;destNode.maxY=-Infinity;for(var i=k,child;i<p;i++){child=node.children[i];extend(destNode,node.leaf?toBBox(child):child)}return destNode}function extend(a,b){a.minX=Math.min(a.minX,b.minX);a.minY=Math.min(a.minY,b.minY);a.maxX=Math.max(a.maxX,b.maxX);a.maxY=Math.max(a.maxY,b.maxY);return a}function compareNodeMinX(a,b){return a.minX-b.minX}function compareNodeMinY(a,b){return a.minY-b.minY}function bboxArea(a){return(a.maxX-a.minX)*
(a.maxY-a.minY)}function bboxMargin(a){return a.maxX-a.minX+(a.maxY-a.minY)}function enlargedArea(a,b){return(Math.max(b.maxX,a.maxX)-Math.min(b.minX,a.minX))*(Math.max(b.maxY,a.maxY)-Math.min(b.minY,a.minY))}function intersectionArea(a,b){var minX=Math.max(a.minX,b.minX),minY=Math.max(a.minY,b.minY),maxX=Math.min(a.maxX,b.maxX),maxY=Math.min(a.maxY,b.maxY);return Math.max(0,maxX-minX)*Math.max(0,maxY-minY)}function contains(a,b){return a.minX<=b.minX&&a.minY<=b.minY&&b.maxX<=a.maxX&&b.maxY<=a.maxY}
function intersects(a,b){return b.minX<=a.maxX&&b.minY<=a.maxY&&b.maxX>=a.minX&&b.maxY>=a.minY}function createNode(children){return{children:children,height:1,leaf:true,minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity}}function multiSelect(arr,left,right,n,compare){var stack=[left,right],mid;while(stack.length){right=stack.pop();left=stack.pop();if(right-left<=n)continue;mid=left+Math.ceil((right-left)/n/2)*n;quickselect(arr,mid,left,right,compare);stack.push(left,mid,mid,right)}}exports["default"]=
rbush_1})(this.rbush=this.rbush||{})}).call(ol.ext);ol.ext.rbush=ol.ext.rbush.default;goog.provide("ol.render.ReplayGroup");ol.render.ReplayGroup=function(){};ol.render.ReplayGroup.prototype.getReplay=function(zIndex,replayType){};ol.render.ReplayGroup.prototype.isEmpty=function(){};goog.provide("ol.render.ReplayType");ol.render.ReplayType={CIRCLE:"Circle",DEFAULT:"Default",IMAGE:"Image",LINE_STRING:"LineString",POLYGON:"Polygon",TEXT:"Text"};goog.provide("ol.geom.flat.length");ol.geom.flat.length.lineString=function(flatCoordinates,offset,end,stride){var x1=flatCoordinates[offset];var y1=flatCoordinates[offset+1];var length=0;var i;for(i=offset+stride;i<end;i+=stride){var x2=flatCoordinates[i];var y2=flatCoordinates[i+1];length+=Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));x1=x2;y1=y2}return length};
ol.geom.flat.length.linearRing=function(flatCoordinates,offset,end,stride){var perimeter=ol.geom.flat.length.lineString(flatCoordinates,offset,end,stride);var dx=flatCoordinates[end-stride]-flatCoordinates[offset];var dy=flatCoordinates[end-stride+1]-flatCoordinates[offset+1];perimeter+=Math.sqrt(dx*dx+dy*dy);return perimeter};goog.provide("ol.geom.flat.textpath");goog.require("ol.math");
ol.geom.flat.textpath.lineString=function(flatCoordinates,offset,end,stride,text,measure,startM,maxAngle){var result=[];var reverse=flatCoordinates[offset]>flatCoordinates[end-stride];var numChars=text.length;var x1=flatCoordinates[offset];var y1=flatCoordinates[offset+1];offset+=stride;var x2=flatCoordinates[offset];var y2=flatCoordinates[offset+1];var segmentM=0;var segmentLength=Math.sqrt(Math.pow(x2-x1,2)+Math.pow(y2-y1,2));var chunk="";var chunkLength=0;var data,index,previousAngle;for(var i=
0;i<numChars;++i){index=reverse?numChars-i-1:i;var char=text.charAt(index);chunk=reverse?char+chunk:chunk+char;var charLength=measure(chunk)-chunkLength;chunkLength+=charLength;var charM=startM+charLength/2;while(offset<end-stride&&segmentM+segmentLength<charM){x1=x2;y1=y2;offset+=stride;x2=flatCoordinates[offset];y2=flatCoordinates[offset+1];segmentM+=segmentLength;segmentLength=Math.sqrt(Math.pow(x2-x1,2)+Math.pow(y2-y1,2))}var segmentPos=charM-segmentM;var angle=Math.atan2(y2-y1,x2-x1);if(reverse)angle+=
angle>0?-Math.PI:Math.PI;if(previousAngle!==undefined){var delta=angle-previousAngle;delta+=delta>Math.PI?-2*Math.PI:delta<-Math.PI?2*Math.PI:0;if(Math.abs(delta)>maxAngle)return null}var interpolate=segmentPos/segmentLength;var x=ol.math.lerp(x1,x2,interpolate);var y=ol.math.lerp(y1,y2,interpolate);if(previousAngle==angle){if(reverse){data[0]=x;data[1]=y;data[2]=charLength/2}data[4]=chunk}else{chunk=char;chunkLength=charLength;data=[x,y,charLength/2,angle,chunk];if(reverse)result.unshift(data);else result.push(data);
previousAngle=angle}startM+=charLength}return result};goog.provide("ol.render.canvas.Instruction");ol.render.canvas.Instruction={BEGIN_GEOMETRY:0,BEGIN_PATH:1,CIRCLE:2,CLOSE_PATH:3,CUSTOM:4,DRAW_CHARS:5,DRAW_IMAGE:6,END_GEOMETRY:7,FILL:8,MOVE_TO_LINE_TO:9,SET_FILL_STYLE:10,SET_STROKE_STYLE:11,STROKE:12};goog.provide("ol.render.replay");goog.require("ol.render.ReplayType");ol.render.replay.ORDER=[ol.render.ReplayType.POLYGON,ol.render.ReplayType.CIRCLE,ol.render.ReplayType.LINE_STRING,ol.render.ReplayType.IMAGE,ol.render.ReplayType.TEXT,ol.render.ReplayType.DEFAULT];ol.render.replay.TEXT_ALIGN={};ol.render.replay.TEXT_ALIGN["left"]=0;ol.render.replay.TEXT_ALIGN["end"]=0;ol.render.replay.TEXT_ALIGN["center"]=.5;ol.render.replay.TEXT_ALIGN["right"]=1;ol.render.replay.TEXT_ALIGN["start"]=1;
ol.render.replay.TEXT_ALIGN["top"]=0;ol.render.replay.TEXT_ALIGN["middle"]=.5;ol.render.replay.TEXT_ALIGN["hanging"]=.2;ol.render.replay.TEXT_ALIGN["alphabetic"]=.8;ol.render.replay.TEXT_ALIGN["ideographic"]=.8;ol.render.replay.TEXT_ALIGN["bottom"]=1;goog.provide("ol.render.canvas.Replay");goog.require("ol");goog.require("ol.array");goog.require("ol.colorlike");goog.require("ol.extent");goog.require("ol.extent.Relationship");goog.require("ol.geom.GeometryType");goog.require("ol.geom.flat.inflate");goog.require("ol.geom.flat.length");goog.require("ol.geom.flat.textpath");goog.require("ol.geom.flat.transform");goog.require("ol.has");goog.require("ol.obj");goog.require("ol.render.VectorContext");goog.require("ol.render.canvas");goog.require("ol.render.canvas.Instruction");
goog.require("ol.render.replay");goog.require("ol.transform");
ol.render.canvas.Replay=function(tolerance,maxExtent,resolution,pixelRatio,overlaps,declutterTree){ol.render.VectorContext.call(this);this.declutterTree=declutterTree;this.tmpExtent_=ol.extent.createEmpty();this.tolerance=tolerance;this.maxExtent=maxExtent;this.overlaps=overlaps;this.pixelRatio=pixelRatio;this.maxLineWidth=0;this.resolution=resolution;this.fillOrigin_;this.beginGeometryInstruction1_=null;this.beginGeometryInstruction2_=null;this.bufferedMaxExtent_=null;this.instructions=[];this.coordinates=
[];this.coordinateCache_={};this.renderedTransform_=ol.transform.create();this.hitDetectionInstructions=[];this.pixelCoordinates_=null;this.state={};this.viewRotation_=0;this.tmpLocalTransform_=ol.transform.create();this.resetTransform_=ol.transform.create()};ol.inherits(ol.render.canvas.Replay,ol.render.VectorContext);
ol.render.canvas.Replay.prototype.replayTextBackground_=function(context,p1,p2,p3,p4,fillInstruction,strokeInstruction){context.beginPath();context.moveTo.apply(context,p1);context.lineTo.apply(context,p2);context.lineTo.apply(context,p3);context.lineTo.apply(context,p4);context.lineTo.apply(context,p1);if(fillInstruction){this.fillOrigin_=fillInstruction[2];this.fill_(context)}if(strokeInstruction){this.setStrokeStyle_(context,strokeInstruction);context.stroke()}};
ol.render.canvas.Replay.prototype.replayImage_=function(context,x,y,image,anchorX,anchorY,declutterGroup,height,opacity,originX,originY,rotation,scale,snapToPixel,width,padding,fillInstruction,strokeInstruction){var fillStroke=fillInstruction||strokeInstruction;var localTransform=this.tmpLocalTransform_;anchorX*=scale;anchorY*=scale;x-=anchorX;y-=anchorY;if(snapToPixel){x=Math.round(x);y=Math.round(y)}var w=width+originX>image.width?image.width-originX:width;var h=height+originY>image.height?image.height-
originY:height;var box=this.tmpExtent_;var boxW=padding[3]+w*scale+padding[1];var boxH=padding[0]+h*scale+padding[2];var boxX=x-padding[3];var boxY=y-padding[0];var p1;var p2;var p3;var p4;if(fillStroke||rotation!==0){p1=[boxX,boxY];p2=[boxX+boxW,boxY];p3=[boxX+boxW,boxY+boxH];p4=[boxX,boxY+boxH]}var transform=null;if(rotation!==0){var centerX=x+anchorX;var centerY=y+anchorY;transform=ol.transform.compose(localTransform,centerX,centerY,1,1,rotation,-centerX,-centerY);ol.extent.createOrUpdateEmpty(box);
ol.extent.extendCoordinate(box,ol.transform.apply(localTransform,p1));ol.extent.extendCoordinate(box,ol.transform.apply(localTransform,p2));ol.extent.extendCoordinate(box,ol.transform.apply(localTransform,p3));ol.extent.extendCoordinate(box,ol.transform.apply(localTransform,p4))}else ol.extent.createOrUpdate(boxX,boxY,boxX+boxW,boxY+boxH,box);var canvas=context.canvas;var intersects=box[0]<=canvas.width&&box[2]>=0&&box[1]<=canvas.height&&box[3]>=0;if(declutterGroup){if(!intersects&&declutterGroup[4]==
1)return;ol.extent.extend(declutterGroup,box);var declutterArgs=intersects?[context,transform?transform.slice(0):null,opacity,image,originX,originY,w,h,x,y,scale]:null;if(declutterArgs&&fillStroke)declutterArgs.push(fillInstruction,strokeInstruction,p1,p2,p3,p4);declutterGroup.push(declutterArgs)}else if(intersects){if(fillStroke)this.replayTextBackground_(context,p1,p2,p3,p4,fillInstruction,strokeInstruction);ol.render.canvas.drawImage(context,transform,opacity,image,originX,originY,w,h,x,y,scale)}};
ol.render.canvas.Replay.prototype.applyPixelRatio=function(dashArray){var pixelRatio=this.pixelRatio;return pixelRatio==1?dashArray:dashArray.map(function(dash){return dash*pixelRatio})};
ol.render.canvas.Replay.prototype.appendFlatCoordinates=function(flatCoordinates,offset,end,stride,closed,skipFirst){var myEnd=this.coordinates.length;var extent=this.getBufferedMaxExtent();if(skipFirst)offset+=stride;var lastCoord=[flatCoordinates[offset],flatCoordinates[offset+1]];var nextCoord=[NaN,NaN];var skipped=true;var i,lastRel,nextRel;for(i=offset+stride;i<end;i+=stride){nextCoord[0]=flatCoordinates[i];nextCoord[1]=flatCoordinates[i+1];nextRel=ol.extent.coordinateRelationship(extent,nextCoord);
if(nextRel!==lastRel){if(skipped){this.coordinates[myEnd++]=lastCoord[0];this.coordinates[myEnd++]=lastCoord[1]}this.coordinates[myEnd++]=nextCoord[0];this.coordinates[myEnd++]=nextCoord[1];skipped=false}else if(nextRel===ol.extent.Relationship.INTERSECTING){this.coordinates[myEnd++]=nextCoord[0];this.coordinates[myEnd++]=nextCoord[1];skipped=false}else skipped=true;lastCoord[0]=nextCoord[0];lastCoord[1]=nextCoord[1];lastRel=nextRel}if(closed&&skipped||i===offset+stride){this.coordinates[myEnd++]=
lastCoord[0];this.coordinates[myEnd++]=lastCoord[1]}return myEnd};ol.render.canvas.Replay.prototype.drawCustomCoordinates_=function(flatCoordinates,offset,ends,stride,replayEnds){for(var i=0,ii=ends.length;i<ii;++i){var end=ends[i];var replayEnd=this.appendFlatCoordinates(flatCoordinates,offset,end,stride,false,false);replayEnds.push(replayEnd);offset=end}return offset};
ol.render.canvas.Replay.prototype.drawCustom=function(geometry,feature,renderer){this.beginGeometry(geometry,feature);var type=geometry.getType();var stride=geometry.getStride();var replayBegin=this.coordinates.length;var flatCoordinates,replayEnd,replayEnds,replayEndss;var offset;if(type==ol.geom.GeometryType.MULTI_POLYGON){geometry=geometry;flatCoordinates=geometry.getOrientedFlatCoordinates();replayEndss=[];var endss=geometry.getEndss();offset=0;for(var i=0,ii=endss.length;i<ii;++i){var myEnds=
[];offset=this.drawCustomCoordinates_(flatCoordinates,offset,endss[i],stride,myEnds);replayEndss.push(myEnds)}this.instructions.push([ol.render.canvas.Instruction.CUSTOM,replayBegin,replayEndss,geometry,renderer,ol.geom.flat.inflate.coordinatesss])}else if(type==ol.geom.GeometryType.POLYGON||type==ol.geom.GeometryType.MULTI_LINE_STRING){replayEnds=[];flatCoordinates=type==ol.geom.GeometryType.POLYGON?geometry.getOrientedFlatCoordinates():geometry.getFlatCoordinates();offset=this.drawCustomCoordinates_(flatCoordinates,
0,geometry.getEnds(),stride,replayEnds);this.instructions.push([ol.render.canvas.Instruction.CUSTOM,replayBegin,replayEnds,geometry,renderer,ol.geom.flat.inflate.coordinatess])}else if(type==ol.geom.GeometryType.LINE_STRING||type==ol.geom.GeometryType.MULTI_POINT){flatCoordinates=geometry.getFlatCoordinates();replayEnd=this.appendFlatCoordinates(flatCoordinates,0,flatCoordinates.length,stride,false,false);this.instructions.push([ol.render.canvas.Instruction.CUSTOM,replayBegin,replayEnd,geometry,renderer,
ol.geom.flat.inflate.coordinates])}else if(type==ol.geom.GeometryType.POINT){flatCoordinates=geometry.getFlatCoordinates();this.coordinates.push(flatCoordinates[0],flatCoordinates[1]);replayEnd=this.coordinates.length;this.instructions.push([ol.render.canvas.Instruction.CUSTOM,replayBegin,replayEnd,geometry,renderer])}this.endGeometry(geometry,feature)};
ol.render.canvas.Replay.prototype.beginGeometry=function(geometry,feature){this.beginGeometryInstruction1_=[ol.render.canvas.Instruction.BEGIN_GEOMETRY,feature,0];this.instructions.push(this.beginGeometryInstruction1_);this.beginGeometryInstruction2_=[ol.render.canvas.Instruction.BEGIN_GEOMETRY,feature,0];this.hitDetectionInstructions.push(this.beginGeometryInstruction2_)};
ol.render.canvas.Replay.prototype.fill_=function(context){if(this.fillOrigin_){var origin=ol.transform.apply(this.renderedTransform_,this.fillOrigin_.slice());context.translate(origin[0],origin[1]);context.rotate(this.viewRotation_)}context.fill();if(this.fillOrigin_)context.setTransform.apply(context,ol.render.canvas.resetTransform_)};
ol.render.canvas.Replay.prototype.setStrokeStyle_=function(context,instruction){context.strokeStyle=instruction[1];context.lineWidth=instruction[2];context.lineCap=instruction[3];context.lineJoin=instruction[4];context.miterLimit=instruction[5];if(ol.has.CANVAS_LINE_DASH){context.lineDashOffset=instruction[7];context.setLineDash(instruction[6])}};
ol.render.canvas.Replay.prototype.renderDeclutter_=function(declutterGroup,feature){if(declutterGroup&&declutterGroup.length>5){var groupCount=declutterGroup[4];if(groupCount==1||groupCount==declutterGroup.length-5){var box={minX:declutterGroup[0],minY:declutterGroup[1],maxX:declutterGroup[2],maxY:declutterGroup[3],value:feature};if(!this.declutterTree.collides(box)){this.declutterTree.insert(box);var drawImage=ol.render.canvas.drawImage;for(var j=5,jj=declutterGroup.length;j<jj;++j){var declutterData=
declutterGroup[j];if(declutterData){if(declutterData.length>11)this.replayTextBackground_(declutterData[0],declutterData[13],declutterData[14],declutterData[15],declutterData[16],declutterData[11],declutterData[12]);drawImage.apply(undefined,declutterData)}}}declutterGroup.length=5;ol.extent.createOrUpdateEmpty(declutterGroup)}}};
ol.render.canvas.Replay.prototype.replay_=function(context,transform,skippedFeaturesHash,instructions,featureCallback,opt_hitExtent){var pixelCoordinates;if(this.pixelCoordinates_&&ol.array.equals(transform,this.renderedTransform_))pixelCoordinates=this.pixelCoordinates_;else{if(!this.pixelCoordinates_)this.pixelCoordinates_=[];pixelCoordinates=ol.geom.flat.transform.transform2D(this.coordinates,0,this.coordinates.length,2,transform,this.pixelCoordinates_);ol.transform.setFromArray(this.renderedTransform_,
transform)}var skipFeatures=!ol.obj.isEmpty(skippedFeaturesHash);var i=0;var ii=instructions.length;var d=0;var dd;var anchorX,anchorY,prevX,prevY,roundX,roundY,declutterGroup,image;var pendingFill=0;var pendingStroke=0;var lastFillInstruction=null;var lastStrokeInstruction=null;var coordinateCache=this.coordinateCache_;var viewRotation=this.viewRotation_;var state={context:context,pixelRatio:this.pixelRatio,resolution:this.resolution,rotation:viewRotation};var batchSize=this.instructions!=instructions||
this.overlaps?0:200;while(i<ii){var instruction=instructions[i];var type=instruction[0];var feature,x,y;switch(type){case ol.render.canvas.Instruction.BEGIN_GEOMETRY:feature=instruction[1];if(skipFeatures&&skippedFeaturesHash[ol.getUid(feature).toString()]||!feature.getGeometry())i=instruction[2];else if(opt_hitExtent!==undefined&&!ol.extent.intersects(opt_hitExtent,feature.getGeometry().getExtent()))i=instruction[2]+1;else++i;break;case ol.render.canvas.Instruction.BEGIN_PATH:if(pendingFill>batchSize){this.fill_(context);
pendingFill=0}if(pendingStroke>batchSize){context.stroke();pendingStroke=0}if(!pendingFill&&!pendingStroke){context.beginPath();prevX=prevY=NaN}++i;break;case ol.render.canvas.Instruction.CIRCLE:d=instruction[1];var x1=pixelCoordinates[d];var y1=pixelCoordinates[d+1];var x2=pixelCoordinates[d+2];var y2=pixelCoordinates[d+3];var dx=x2-x1;var dy=y2-y1;var r=Math.sqrt(dx*dx+dy*dy);context.moveTo(x1+r,y1);context.arc(x1,y1,r,0,2*Math.PI,true);++i;break;case ol.render.canvas.Instruction.CLOSE_PATH:context.closePath();
++i;break;case ol.render.canvas.Instruction.CUSTOM:d=instruction[1];dd=instruction[2];var geometry=instruction[3];var renderer=instruction[4];var fn=instruction.length==6?instruction[5]:undefined;state.geometry=geometry;state.feature=feature;if(!(i in coordinateCache))coordinateCache[i]=[];var coords=coordinateCache[i];if(fn)fn(pixelCoordinates,d,dd,2,coords);else{coords[0]=pixelCoordinates[d];coords[1]=pixelCoordinates[d+1];coords.length=2}renderer(coords,state);++i;break;case ol.render.canvas.Instruction.DRAW_IMAGE:d=
instruction[1];dd=instruction[2];image=instruction[3];anchorX=instruction[4];anchorY=instruction[5];declutterGroup=featureCallback?null:instruction[6];var height=instruction[7];var opacity=instruction[8];var originX=instruction[9];var originY=instruction[10];var rotateWithView=instruction[11];var rotation=instruction[12];var scale=instruction[13];var snapToPixel=instruction[14];var width=instruction[15];var padding,backgroundFill,backgroundStroke;if(instruction.length>16){padding=instruction[16];
backgroundFill=instruction[17];backgroundStroke=instruction[18]}else{padding=ol.render.canvas.defaultPadding;backgroundFill=backgroundStroke=false}if(rotateWithView)rotation+=viewRotation;for(;d<dd;d+=2)this.replayImage_(context,pixelCoordinates[d],pixelCoordinates[d+1],image,anchorX,anchorY,declutterGroup,height,opacity,originX,originY,rotation,scale,snapToPixel,width,padding,backgroundFill?lastFillInstruction:null,backgroundStroke?lastStrokeInstruction:null);this.renderDeclutter_(declutterGroup,
feature);++i;break;case ol.render.canvas.Instruction.DRAW_CHARS:var begin=instruction[1];var end=instruction[2];var baseline=instruction[3];declutterGroup=featureCallback?null:instruction[4];var overflow=instruction[5];var fillKey=instruction[6];var maxAngle=instruction[7];var measure=instruction[8];var offsetY=instruction[9];var strokeKey=instruction[10];var strokeWidth=instruction[11];var text=instruction[12];var textKey=instruction[13];var textScale=instruction[14];var pathLength=ol.geom.flat.length.lineString(pixelCoordinates,
begin,end,2);var textLength=measure(text);if(overflow||textLength<=pathLength){var textAlign=this.textStates[textKey].textAlign;var startM=(pathLength-textLength)*ol.render.replay.TEXT_ALIGN[textAlign];var parts=ol.geom.flat.textpath.lineString(pixelCoordinates,begin,end,2,text,measure,startM,maxAngle);if(parts){var c,cc,chars,label,part;if(strokeKey)for(c=0,cc=parts.length;c<cc;++c){part=parts[c];chars=part[4];label=this.getImage(chars,textKey,"",strokeKey);anchorX=part[2]+strokeWidth;anchorY=baseline*
label.height+(.5-baseline)*2*strokeWidth-offsetY;this.replayImage_(context,part[0],part[1],label,anchorX,anchorY,declutterGroup,label.height,1,0,0,part[3],textScale,false,label.width,ol.render.canvas.defaultPadding,null,null)}if(fillKey)for(c=0,cc=parts.length;c<cc;++c){part=parts[c];chars=part[4];label=this.getImage(chars,textKey,fillKey,"");anchorX=part[2];anchorY=baseline*label.height-offsetY;this.replayImage_(context,part[0],part[1],label,anchorX,anchorY,declutterGroup,label.height,1,0,0,part[3],
textScale,false,label.width,ol.render.canvas.defaultPadding,null,null)}}}this.renderDeclutter_(declutterGroup,feature);++i;break;case ol.render.canvas.Instruction.END_GEOMETRY:if(featureCallback!==undefined){feature=instruction[1];var result=featureCallback(feature);if(result)return result}++i;break;case ol.render.canvas.Instruction.FILL:if(batchSize)pendingFill++;else this.fill_(context);++i;break;case ol.render.canvas.Instruction.MOVE_TO_LINE_TO:d=instruction[1];dd=instruction[2];x=pixelCoordinates[d];
y=pixelCoordinates[d+1];roundX=x+.5|0;roundY=y+.5|0;if(roundX!==prevX||roundY!==prevY){context.moveTo(x,y);prevX=roundX;prevY=roundY}for(d+=2;d<dd;d+=2){x=pixelCoordinates[d];y=pixelCoordinates[d+1];roundX=x+.5|0;roundY=y+.5|0;if(d==dd-2||roundX!==prevX||roundY!==prevY){context.lineTo(x,y);prevX=roundX;prevY=roundY}}++i;break;case ol.render.canvas.Instruction.SET_FILL_STYLE:lastFillInstruction=instruction;this.fillOrigin_=instruction[2];if(pendingFill){this.fill_(context);pendingFill=0;if(pendingStroke){context.stroke();
pendingStroke=0}}context.fillStyle=instruction[1];++i;break;case ol.render.canvas.Instruction.SET_STROKE_STYLE:lastStrokeInstruction=instruction;if(pendingStroke){context.stroke();pendingStroke=0}this.setStrokeStyle_(context,instruction);++i;break;case ol.render.canvas.Instruction.STROKE:if(batchSize)pendingStroke++;else context.stroke();++i;break;default:++i;break}}if(pendingFill)this.fill_(context);if(pendingStroke)context.stroke();return undefined};
ol.render.canvas.Replay.prototype.replay=function(context,transform,viewRotation,skippedFeaturesHash){this.viewRotation_=viewRotation;this.replay_(context,transform,skippedFeaturesHash,this.instructions,undefined,undefined)};
ol.render.canvas.Replay.prototype.replayHitDetection=function(context,transform,viewRotation,skippedFeaturesHash,opt_featureCallback,opt_hitExtent){this.viewRotation_=viewRotation;return this.replay_(context,transform,skippedFeaturesHash,this.hitDetectionInstructions,opt_featureCallback,opt_hitExtent)};
ol.render.canvas.Replay.prototype.reverseHitDetectionInstructions=function(){var hitDetectionInstructions=this.hitDetectionInstructions;hitDetectionInstructions.reverse();var i;var n=hitDetectionInstructions.length;var instruction;var type;var begin=-1;for(i=0;i<n;++i){instruction=hitDetectionInstructions[i];type=instruction[0];if(type==ol.render.canvas.Instruction.END_GEOMETRY)begin=i;else if(type==ol.render.canvas.Instruction.BEGIN_GEOMETRY){instruction[2]=i;ol.array.reverseSubArray(this.hitDetectionInstructions,
begin,i);begin=-1}}};
ol.render.canvas.Replay.prototype.setFillStrokeStyle=function(fillStyle,strokeStyle){var state=this.state;if(fillStyle){var fillStyleColor=fillStyle.getColor();state.fillStyle=ol.colorlike.asColorLike(fillStyleColor?fillStyleColor:ol.render.canvas.defaultFillStyle)}else state.fillStyle=undefined;if(strokeStyle){var strokeStyleColor=strokeStyle.getColor();state.strokeStyle=ol.colorlike.asColorLike(strokeStyleColor?strokeStyleColor:ol.render.canvas.defaultStrokeStyle);var strokeStyleLineCap=strokeStyle.getLineCap();
state.lineCap=strokeStyleLineCap!==undefined?strokeStyleLineCap:ol.render.canvas.defaultLineCap;var strokeStyleLineDash=strokeStyle.getLineDash();state.lineDash=strokeStyleLineDash?strokeStyleLineDash.slice():ol.render.canvas.defaultLineDash;var strokeStyleLineDashOffset=strokeStyle.getLineDashOffset();state.lineDashOffset=strokeStyleLineDashOffset?strokeStyleLineDashOffset:ol.render.canvas.defaultLineDashOffset;var strokeStyleLineJoin=strokeStyle.getLineJoin();state.lineJoin=strokeStyleLineJoin!==
undefined?strokeStyleLineJoin:ol.render.canvas.defaultLineJoin;var strokeStyleWidth=strokeStyle.getWidth();state.lineWidth=strokeStyleWidth!==undefined?strokeStyleWidth:ol.render.canvas.defaultLineWidth;var strokeStyleMiterLimit=strokeStyle.getMiterLimit();state.miterLimit=strokeStyleMiterLimit!==undefined?strokeStyleMiterLimit:ol.render.canvas.defaultMiterLimit;if(state.lineWidth>this.maxLineWidth){this.maxLineWidth=state.lineWidth;this.bufferedMaxExtent_=null}}else{state.strokeStyle=undefined;state.lineCap=
undefined;state.lineDash=null;state.lineDashOffset=undefined;state.lineJoin=undefined;state.lineWidth=undefined;state.miterLimit=undefined}};ol.render.canvas.Replay.prototype.applyFill=function(state,geometry){var fillStyle=state.fillStyle;var fillInstruction=[ol.render.canvas.Instruction.SET_FILL_STYLE,fillStyle];if(typeof fillStyle!=="string"){var fillExtent=geometry.getExtent();fillInstruction.push([fillExtent[0],fillExtent[3]])}this.instructions.push(fillInstruction)};
ol.render.canvas.Replay.prototype.applyStroke=function(state){this.instructions.push([ol.render.canvas.Instruction.SET_STROKE_STYLE,state.strokeStyle,state.lineWidth*this.pixelRatio,state.lineCap,state.lineJoin,state.miterLimit,this.applyPixelRatio(state.lineDash),state.lineDashOffset*this.pixelRatio])};
ol.render.canvas.Replay.prototype.updateFillStyle=function(state,applyFill,geometry){var fillStyle=state.fillStyle;if(typeof fillStyle!=="string"||state.currentFillStyle!=fillStyle){applyFill.call(this,state,geometry);state.currentFillStyle=fillStyle}};
ol.render.canvas.Replay.prototype.updateStrokeStyle=function(state,applyStroke){var strokeStyle=state.strokeStyle;var lineCap=state.lineCap;var lineDash=state.lineDash;var lineDashOffset=state.lineDashOffset;var lineJoin=state.lineJoin;var lineWidth=state.lineWidth;var miterLimit=state.miterLimit;if(state.currentStrokeStyle!=strokeStyle||state.currentLineCap!=lineCap||lineDash!=state.currentLineDash&&!ol.array.equals(state.currentLineDash,lineDash)||state.currentLineDashOffset!=lineDashOffset||state.currentLineJoin!=
lineJoin||state.currentLineWidth!=lineWidth||state.currentMiterLimit!=miterLimit){applyStroke.call(this,state);state.currentStrokeStyle=strokeStyle;state.currentLineCap=lineCap;state.currentLineDash=lineDash;state.currentLineDashOffset=lineDashOffset;state.currentLineJoin=lineJoin;state.currentLineWidth=lineWidth;state.currentMiterLimit=miterLimit}};
ol.render.canvas.Replay.prototype.endGeometry=function(geometry,feature){this.beginGeometryInstruction1_[2]=this.instructions.length;this.beginGeometryInstruction1_=null;this.beginGeometryInstruction2_[2]=this.hitDetectionInstructions.length;this.beginGeometryInstruction2_=null;var endGeometryInstruction=[ol.render.canvas.Instruction.END_GEOMETRY,feature];this.instructions.push(endGeometryInstruction);this.hitDetectionInstructions.push(endGeometryInstruction)};
ol.render.canvas.Replay.prototype.finish=ol.nullFunction;ol.render.canvas.Replay.prototype.getBufferedMaxExtent=function(){if(!this.bufferedMaxExtent_){this.bufferedMaxExtent_=ol.extent.clone(this.maxExtent);if(this.maxLineWidth>0){var width=this.resolution*(this.maxLineWidth+1)/2;ol.extent.buffer(this.bufferedMaxExtent_,width,this.bufferedMaxExtent_)}}return this.bufferedMaxExtent_};goog.provide("ol.render.canvas.ImageReplay");goog.require("ol");goog.require("ol.render.canvas.Instruction");goog.require("ol.render.canvas.Replay");
ol.render.canvas.ImageReplay=function(tolerance,maxExtent,resolution,pixelRatio,overlaps,declutterTree){ol.render.canvas.Replay.call(this,tolerance,maxExtent,resolution,pixelRatio,overlaps,declutterTree);this.declutterGroup_=null;this.hitDetectionImage_=null;this.image_=null;this.anchorX_=undefined;this.anchorY_=undefined;this.height_=undefined;this.opacity_=undefined;this.originX_=undefined;this.originY_=undefined;this.rotateWithView_=undefined;this.rotation_=undefined;this.scale_=undefined;this.snapToPixel_=
undefined;this.width_=undefined};ol.inherits(ol.render.canvas.ImageReplay,ol.render.canvas.Replay);ol.render.canvas.ImageReplay.prototype.drawCoordinates_=function(flatCoordinates,offset,end,stride){return this.appendFlatCoordinates(flatCoordinates,offset,end,stride,false,false)};
ol.render.canvas.ImageReplay.prototype.drawPoint=function(pointGeometry,feature){if(!this.image_)return;this.beginGeometry(pointGeometry,feature);var flatCoordinates=pointGeometry.getFlatCoordinates();var stride=pointGeometry.getStride();var myBegin=this.coordinates.length;var myEnd=this.drawCoordinates_(flatCoordinates,0,flatCoordinates.length,stride);this.instructions.push([ol.render.canvas.Instruction.DRAW_IMAGE,myBegin,myEnd,this.image_,this.anchorX_,this.anchorY_,this.declutterGroup_,this.height_,
this.opacity_,this.originX_,this.originY_,this.rotateWithView_,this.rotation_,this.scale_*this.pixelRatio,this.snapToPixel_,this.width_]);this.hitDetectionInstructions.push([ol.render.canvas.Instruction.DRAW_IMAGE,myBegin,myEnd,this.hitDetectionImage_,this.anchorX_,this.anchorY_,this.declutterGroup_,this.height_,this.opacity_,this.originX_,this.originY_,this.rotateWithView_,this.rotation_,this.scale_,this.snapToPixel_,this.width_]);this.endGeometry(pointGeometry,feature)};
ol.render.canvas.ImageReplay.prototype.drawMultiPoint=function(multiPointGeometry,feature){if(!this.image_)return;this.beginGeometry(multiPointGeometry,feature);var flatCoordinates=multiPointGeometry.getFlatCoordinates();var stride=multiPointGeometry.getStride();var myBegin=this.coordinates.length;var myEnd=this.drawCoordinates_(flatCoordinates,0,flatCoordinates.length,stride);this.instructions.push([ol.render.canvas.Instruction.DRAW_IMAGE,myBegin,myEnd,this.image_,this.anchorX_,this.anchorY_,this.declutterGroup_,
this.height_,this.opacity_,this.originX_,this.originY_,this.rotateWithView_,this.rotation_,this.scale_*this.pixelRatio,this.snapToPixel_,this.width_]);this.hitDetectionInstructions.push([ol.render.canvas.Instruction.DRAW_IMAGE,myBegin,myEnd,this.hitDetectionImage_,this.anchorX_,this.anchorY_,this.declutterGroup_,this.height_,this.opacity_,this.originX_,this.originY_,this.rotateWithView_,this.rotation_,this.scale_,this.snapToPixel_,this.width_]);this.endGeometry(multiPointGeometry,feature)};
ol.render.canvas.ImageReplay.prototype.finish=function(){this.reverseHitDetectionInstructions();this.anchorX_=undefined;this.anchorY_=undefined;this.hitDetectionImage_=null;this.image_=null;this.height_=undefined;this.scale_=undefined;this.opacity_=undefined;this.originX_=undefined;this.originY_=undefined;this.rotateWithView_=undefined;this.rotation_=undefined;this.snapToPixel_=undefined;this.width_=undefined};
ol.render.canvas.ImageReplay.prototype.setImageStyle=function(imageStyle,declutterGroup){var anchor=imageStyle.getAnchor();var size=imageStyle.getSize();var hitDetectionImage=imageStyle.getHitDetectionImage(1);var image=imageStyle.getImage(1);var origin=imageStyle.getOrigin();this.anchorX_=anchor[0];this.anchorY_=anchor[1];this.declutterGroup_=declutterGroup;this.hitDetectionImage_=hitDetectionImage;this.image_=image;this.height_=size[1];this.opacity_=imageStyle.getOpacity();this.originX_=origin[0];
this.originY_=origin[1];this.rotateWithView_=imageStyle.getRotateWithView();this.rotation_=imageStyle.getRotation();this.scale_=imageStyle.getScale();this.snapToPixel_=imageStyle.getSnapToPixel();this.width_=size[0]};goog.provide("ol.render.canvas.LineStringReplay");goog.require("ol");goog.require("ol.render.canvas.Instruction");goog.require("ol.render.canvas.Replay");ol.render.canvas.LineStringReplay=function(tolerance,maxExtent,resolution,pixelRatio,overlaps,declutterTree){ol.render.canvas.Replay.call(this,tolerance,maxExtent,resolution,pixelRatio,overlaps,declutterTree)};ol.inherits(ol.render.canvas.LineStringReplay,ol.render.canvas.Replay);
ol.render.canvas.LineStringReplay.prototype.drawFlatCoordinates_=function(flatCoordinates,offset,end,stride){var myBegin=this.coordinates.length;var myEnd=this.appendFlatCoordinates(flatCoordinates,offset,end,stride,false,false);var moveToLineToInstruction=[ol.render.canvas.Instruction.MOVE_TO_LINE_TO,myBegin,myEnd];this.instructions.push(moveToLineToInstruction);this.hitDetectionInstructions.push(moveToLineToInstruction);return end};
ol.render.canvas.LineStringReplay.prototype.drawLineString=function(lineStringGeometry,feature){var state=this.state;var strokeStyle=state.strokeStyle;var lineWidth=state.lineWidth;if(strokeStyle===undefined||lineWidth===undefined)return;this.updateStrokeStyle(state,this.applyStroke);this.beginGeometry(lineStringGeometry,feature);this.hitDetectionInstructions.push([ol.render.canvas.Instruction.SET_STROKE_STYLE,state.strokeStyle,state.lineWidth,state.lineCap,state.lineJoin,state.miterLimit,state.lineDash,
state.lineDashOffset],[ol.render.canvas.Instruction.BEGIN_PATH]);var flatCoordinates=lineStringGeometry.getFlatCoordinates();var stride=lineStringGeometry.getStride();this.drawFlatCoordinates_(flatCoordinates,0,flatCoordinates.length,stride);this.hitDetectionInstructions.push([ol.render.canvas.Instruction.STROKE]);this.endGeometry(lineStringGeometry,feature)};
ol.render.canvas.LineStringReplay.prototype.drawMultiLineString=function(multiLineStringGeometry,feature){var state=this.state;var strokeStyle=state.strokeStyle;var lineWidth=state.lineWidth;if(strokeStyle===undefined||lineWidth===undefined)return;this.updateStrokeStyle(state,this.applyStroke);this.beginGeometry(multiLineStringGeometry,feature);this.hitDetectionInstructions.push([ol.render.canvas.Instruction.SET_STROKE_STYLE,state.strokeStyle,state.lineWidth,state.lineCap,state.lineJoin,state.miterLimit,
state.lineDash,state.lineDashOffset],[ol.render.canvas.Instruction.BEGIN_PATH]);var ends=multiLineStringGeometry.getEnds();var flatCoordinates=multiLineStringGeometry.getFlatCoordinates();var stride=multiLineStringGeometry.getStride();var offset=0;var i,ii;for(i=0,ii=ends.length;i<ii;++i)offset=this.drawFlatCoordinates_(flatCoordinates,offset,ends[i],stride);this.hitDetectionInstructions.push([ol.render.canvas.Instruction.STROKE]);this.endGeometry(multiLineStringGeometry,feature)};
ol.render.canvas.LineStringReplay.prototype.finish=function(){var state=this.state;if(state.lastStroke!=undefined&&state.lastStroke!=this.coordinates.length)this.instructions.push([ol.render.canvas.Instruction.STROKE]);this.reverseHitDetectionInstructions();this.state=null};
ol.render.canvas.LineStringReplay.prototype.applyStroke=function(state){if(state.lastStroke!=undefined&&state.lastStroke!=this.coordinates.length){this.instructions.push([ol.render.canvas.Instruction.STROKE]);state.lastStroke=this.coordinates.length}state.lastStroke=0;ol.render.canvas.Replay.prototype.applyStroke.call(this,state);this.instructions.push([ol.render.canvas.Instruction.BEGIN_PATH])};goog.provide("ol.render.canvas.PolygonReplay");goog.require("ol");goog.require("ol.color");goog.require("ol.geom.flat.simplify");goog.require("ol.render.canvas");goog.require("ol.render.canvas.Instruction");goog.require("ol.render.canvas.Replay");ol.render.canvas.PolygonReplay=function(tolerance,maxExtent,resolution,pixelRatio,overlaps,declutterTree){ol.render.canvas.Replay.call(this,tolerance,maxExtent,resolution,pixelRatio,overlaps,declutterTree)};ol.inherits(ol.render.canvas.PolygonReplay,ol.render.canvas.Replay);
ol.render.canvas.PolygonReplay.prototype.drawFlatCoordinatess_=function(flatCoordinates,offset,ends,stride){var state=this.state;var fill=state.fillStyle!==undefined;var stroke=state.strokeStyle!=undefined;var numEnds=ends.length;var beginPathInstruction=[ol.render.canvas.Instruction.BEGIN_PATH];this.instructions.push(beginPathInstruction);this.hitDetectionInstructions.push(beginPathInstruction);for(var i=0;i<numEnds;++i){var end=ends[i];var myBegin=this.coordinates.length;var myEnd=this.appendFlatCoordinates(flatCoordinates,
offset,end,stride,true,!stroke);var moveToLineToInstruction=[ol.render.canvas.Instruction.MOVE_TO_LINE_TO,myBegin,myEnd];this.instructions.push(moveToLineToInstruction);this.hitDetectionInstructions.push(moveToLineToInstruction);if(stroke){var closePathInstruction=[ol.render.canvas.Instruction.CLOSE_PATH];this.instructions.push(closePathInstruction);this.hitDetectionInstructions.push(closePathInstruction)}offset=end}var fillInstruction=[ol.render.canvas.Instruction.FILL];this.hitDetectionInstructions.push(fillInstruction);
if(fill)this.instructions.push(fillInstruction);if(stroke){var strokeInstruction=[ol.render.canvas.Instruction.STROKE];this.instructions.push(strokeInstruction);this.hitDetectionInstructions.push(strokeInstruction)}return offset};
ol.render.canvas.PolygonReplay.prototype.drawCircle=function(circleGeometry,feature){var state=this.state;var fillStyle=state.fillStyle;var strokeStyle=state.strokeStyle;if(fillStyle===undefined&&strokeStyle===undefined)return;this.setFillStrokeStyles_(circleGeometry);this.beginGeometry(circleGeometry,feature);this.hitDetectionInstructions.push([ol.render.canvas.Instruction.SET_FILL_STYLE,ol.color.asString(ol.render.canvas.defaultFillStyle)]);if(state.strokeStyle!==undefined)this.hitDetectionInstructions.push([ol.render.canvas.Instruction.SET_STROKE_STYLE,
state.strokeStyle,state.lineWidth,state.lineCap,state.lineJoin,state.miterLimit,state.lineDash,state.lineDashOffset]);var flatCoordinates=circleGeometry.getFlatCoordinates();var stride=circleGeometry.getStride();var myBegin=this.coordinates.length;this.appendFlatCoordinates(flatCoordinates,0,flatCoordinates.length,stride,false,false);var beginPathInstruction=[ol.render.canvas.Instruction.BEGIN_PATH];var circleInstruction=[ol.render.canvas.Instruction.CIRCLE,myBegin];this.instructions.push(beginPathInstruction,
circleInstruction);this.hitDetectionInstructions.push(beginPathInstruction,circleInstruction);var fillInstruction=[ol.render.canvas.Instruction.FILL];this.hitDetectionInstructions.push(fillInstruction);if(state.fillStyle!==undefined)this.instructions.push(fillInstruction);if(state.strokeStyle!==undefined){var strokeInstruction=[ol.render.canvas.Instruction.STROKE];this.instructions.push(strokeInstruction);this.hitDetectionInstructions.push(strokeInstruction)}this.endGeometry(circleGeometry,feature)};
ol.render.canvas.PolygonReplay.prototype.drawPolygon=function(polygonGeometry,feature){var state=this.state;this.setFillStrokeStyles_(polygonGeometry);this.beginGeometry(polygonGeometry,feature);this.hitDetectionInstructions.push([ol.render.canvas.Instruction.SET_FILL_STYLE,ol.color.asString(ol.render.canvas.defaultFillStyle)]);if(state.strokeStyle!==undefined)this.hitDetectionInstructions.push([ol.render.canvas.Instruction.SET_STROKE_STYLE,state.strokeStyle,state.lineWidth,state.lineCap,state.lineJoin,
state.miterLimit,state.lineDash,state.lineDashOffset]);var ends=polygonGeometry.getEnds();var flatCoordinates=polygonGeometry.getOrientedFlatCoordinates();var stride=polygonGeometry.getStride();this.drawFlatCoordinatess_(flatCoordinates,0,ends,stride);this.endGeometry(polygonGeometry,feature)};
ol.render.canvas.PolygonReplay.prototype.drawMultiPolygon=function(multiPolygonGeometry,feature){var state=this.state;var fillStyle=state.fillStyle;var strokeStyle=state.strokeStyle;if(fillStyle===undefined&&strokeStyle===undefined)return;this.setFillStrokeStyles_(multiPolygonGeometry);this.beginGeometry(multiPolygonGeometry,feature);this.hitDetectionInstructions.push([ol.render.canvas.Instruction.SET_FILL_STYLE,ol.color.asString(ol.render.canvas.defaultFillStyle)]);if(state.strokeStyle!==undefined)this.hitDetectionInstructions.push([ol.render.canvas.Instruction.SET_STROKE_STYLE,
state.strokeStyle,state.lineWidth,state.lineCap,state.lineJoin,state.miterLimit,state.lineDash,state.lineDashOffset]);var endss=multiPolygonGeometry.getEndss();var flatCoordinates=multiPolygonGeometry.getOrientedFlatCoordinates();var stride=multiPolygonGeometry.getStride();var offset=0;var i,ii;for(i=0,ii=endss.length;i<ii;++i)offset=this.drawFlatCoordinatess_(flatCoordinates,offset,endss[i],stride);this.endGeometry(multiPolygonGeometry,feature)};
ol.render.canvas.PolygonReplay.prototype.finish=function(){this.reverseHitDetectionInstructions();this.state=null;var tolerance=this.tolerance;if(tolerance!==0){var coordinates=this.coordinates;var i,ii;for(i=0,ii=coordinates.length;i<ii;++i)coordinates[i]=ol.geom.flat.simplify.snap(coordinates[i],tolerance)}};
ol.render.canvas.PolygonReplay.prototype.setFillStrokeStyles_=function(geometry){var state=this.state;var fillStyle=state.fillStyle;if(fillStyle!==undefined)this.updateFillStyle(state,this.applyFill,geometry);if(state.strokeStyle!==undefined)this.updateStrokeStyle(state,this.applyStroke)};goog.provide("ol.geom.flat.straightchunk");
ol.geom.flat.straightchunk.lineString=function(maxAngle,flatCoordinates,offset,end,stride){var chunkStart=offset;var chunkEnd=offset;var chunkM=0;var m=0;var start=offset;var acos,i,m12,m23,x1,y1,x12,y12,x23,y23;for(i=offset;i<end;i+=stride){var x2=flatCoordinates[i];var y2=flatCoordinates[i+1];if(x1!==undefined){x23=x2-x1;y23=y2-y1;m23=Math.sqrt(x23*x23+y23*y23);if(x12!==undefined){m+=m12;acos=Math.acos((x12*x23+y12*y23)/(m12*m23));if(acos>maxAngle){if(m>chunkM){chunkM=m;chunkStart=start;chunkEnd=
i}m=0;start=i-stride}}m12=m23;x12=x23;y12=y23}x1=x2;y1=y2}m+=m23;return m>chunkM?[start,i]:[chunkStart,chunkEnd]};goog.provide("ol.style.TextPlacement");ol.style.TextPlacement={POINT:"point",LINE:"line"};goog.provide("ol.render.canvas.TextReplay");goog.require("ol");goog.require("ol.colorlike");goog.require("ol.dom");goog.require("ol.extent");goog.require("ol.geom.flat.straightchunk");goog.require("ol.geom.GeometryType");goog.require("ol.has");goog.require("ol.render.canvas");goog.require("ol.render.canvas.Instruction");goog.require("ol.render.canvas.Replay");goog.require("ol.render.replay");goog.require("ol.style.TextPlacement");
ol.render.canvas.TextReplay=function(tolerance,maxExtent,resolution,pixelRatio,overlaps,declutterTree){ol.render.canvas.Replay.call(this,tolerance,maxExtent,resolution,pixelRatio,overlaps,declutterTree);this.declutterGroup_;this.labels_=null;this.text_="";this.textOffsetX_=0;this.textOffsetY_=0;this.textRotateWithView_=undefined;this.textRotation_=0;this.textFillState_=null;this.fillStates={};this.textStrokeState_=null;this.strokeStates={};this.textState_={};this.textStates={};this.textKey_="";this.fillKey_=
"";this.strokeKey_="";this.widths_={};var labelCache=ol.render.canvas.labelCache;labelCache.prune()};ol.inherits(ol.render.canvas.TextReplay,ol.render.canvas.Replay);ol.render.canvas.TextReplay.measureTextWidths=function(font,lines,widths){var numLines=lines.length;var width=0;var currentWidth,i;for(i=0;i<numLines;++i){currentWidth=ol.render.canvas.measureTextWidth(font,lines[i]);width=Math.max(width,currentWidth);widths.push(currentWidth)}return width};
ol.render.canvas.TextReplay.prototype.drawText=function(geometry,feature){var fillState=this.textFillState_;var strokeState=this.textStrokeState_;var textState=this.textState_;if(this.text_===""||!textState||!fillState&&!strokeState)return;var begin=this.coordinates.length;var geometryType=geometry.getType();var flatCoordinates=null;var end=2;var stride=2;var i,ii;if(textState.placement===ol.style.TextPlacement.LINE){if(!ol.extent.intersects(this.getBufferedMaxExtent(),geometry.getExtent()))return;
var ends;flatCoordinates=geometry.getFlatCoordinates();stride=geometry.getStride();if(geometryType==ol.geom.GeometryType.LINE_STRING)ends=[flatCoordinates.length];else if(geometryType==ol.geom.GeometryType.MULTI_LINE_STRING)ends=geometry.getEnds();else if(geometryType==ol.geom.GeometryType.POLYGON)ends=geometry.getEnds().slice(0,1);else if(geometryType==ol.geom.GeometryType.MULTI_POLYGON){var endss=geometry.getEndss();ends=[];for(i=0,ii=endss.length;i<ii;++i)ends.push(endss[i][0])}this.beginGeometry(geometry,
feature);var textAlign=textState.textAlign;var flatOffset=0;var flatEnd;for(var o=0,oo=ends.length;o<oo;++o){if(textAlign==undefined){var range=ol.geom.flat.straightchunk.lineString(textState.maxAngle,flatCoordinates,flatOffset,ends[o],stride);flatOffset=range[0];flatEnd=range[1]}else flatEnd=ends[o];for(i=flatOffset;i<flatEnd;i+=stride)this.coordinates.push(flatCoordinates[i],flatCoordinates[i+1]);end=this.coordinates.length;flatOffset=ends[o];this.drawChars_(begin,end,this.declutterGroup_);begin=
end}this.endGeometry(geometry,feature)}else{var label=this.getImage(this.text_,this.textKey_,this.fillKey_,this.strokeKey_);var width=label.width/this.pixelRatio;switch(geometryType){case ol.geom.GeometryType.POINT:case ol.geom.GeometryType.MULTI_POINT:flatCoordinates=geometry.getFlatCoordinates();end=flatCoordinates.length;break;case ol.geom.GeometryType.LINE_STRING:flatCoordinates=geometry.getFlatMidpoint();break;case ol.geom.GeometryType.CIRCLE:flatCoordinates=geometry.getCenter();break;case ol.geom.GeometryType.MULTI_LINE_STRING:flatCoordinates=
geometry.getFlatMidpoints();end=flatCoordinates.length;break;case ol.geom.GeometryType.POLYGON:flatCoordinates=geometry.getFlatInteriorPoint();if(!textState.overflow&&flatCoordinates[2]/this.resolution<width)return;stride=3;break;case ol.geom.GeometryType.MULTI_POLYGON:var interiorPoints=geometry.getFlatInteriorPoints();flatCoordinates=[];for(i=0,ii=interiorPoints.length;i<ii;i+=3)if(textState.overflow||interiorPoints[i+2]/this.resolution>=width)flatCoordinates.push(interiorPoints[i],interiorPoints[i+
1]);end=flatCoordinates.length;if(end==0)return;break;default:}end=this.appendFlatCoordinates(flatCoordinates,0,end,stride,false,false);this.beginGeometry(geometry,feature);if(textState.backgroundFill||textState.backgroundStroke){this.setFillStrokeStyle(textState.backgroundFill,textState.backgroundStroke);this.updateFillStyle(this.state,this.applyFill,geometry);this.updateStrokeStyle(this.state,this.applyStroke)}this.drawTextImage_(label,begin,end);this.endGeometry(geometry,feature)}};
ol.render.canvas.TextReplay.prototype.getImage=function(text,textKey,fillKey,strokeKey){var label;var key=strokeKey+textKey+text+fillKey+this.pixelRatio;var labelCache=ol.render.canvas.labelCache;if(!labelCache.containsKey(key)){var strokeState=strokeKey?this.strokeStates[strokeKey]||this.textStrokeState_:null;var fillState=fillKey?this.fillStates[fillKey]||this.textFillState_:null;var textState=this.textStates[textKey]||this.textState_;var pixelRatio=this.pixelRatio;var scale=textState.scale*pixelRatio;
var align=ol.render.replay.TEXT_ALIGN[textState.textAlign||ol.render.canvas.defaultTextAlign];var strokeWidth=strokeKey&&strokeState.lineWidth?strokeState.lineWidth:0;var lines=text.split("\n");var numLines=lines.length;var widths=[];var width=ol.render.canvas.TextReplay.measureTextWidths(textState.font,lines,widths);var lineHeight=ol.render.canvas.measureTextHeight(textState.font);var height=lineHeight*numLines;var renderWidth=width+strokeWidth;var context=ol.dom.createCanvasContext2D(Math.ceil(renderWidth*
scale),Math.ceil((height+strokeWidth)*scale));label=context.canvas;labelCache.set(key,label);if(scale!=1)context.scale(scale,scale);context.font=textState.font;if(strokeKey){context.strokeStyle=strokeState.strokeStyle;context.lineWidth=strokeWidth*(ol.has.SAFARI?scale:1);context.lineCap=strokeState.lineCap;context.lineJoin=strokeState.lineJoin;context.miterLimit=strokeState.miterLimit;if(ol.has.CANVAS_LINE_DASH&&strokeState.lineDash.length){context.setLineDash(strokeState.lineDash);context.lineDashOffset=
strokeState.lineDashOffset}}if(fillKey)context.fillStyle=fillState.fillStyle;context.textBaseline="middle";context.textAlign="center";var leftRight=.5-align;var x=align*label.width/scale+leftRight*strokeWidth;var i;if(strokeKey)for(i=0;i<numLines;++i)context.strokeText(lines[i],x+leftRight*widths[i],.5*(strokeWidth+lineHeight)+i*lineHeight);if(fillKey)for(i=0;i<numLines;++i)context.fillText(lines[i],x+leftRight*widths[i],.5*(strokeWidth+lineHeight)+i*lineHeight)}return labelCache.get(key)};
ol.render.canvas.TextReplay.prototype.drawTextImage_=function(label,begin,end){var textState=this.textState_;var strokeState=this.textStrokeState_;var pixelRatio=this.pixelRatio;var align=ol.render.replay.TEXT_ALIGN[textState.textAlign||ol.render.canvas.defaultTextAlign];var baseline=ol.render.replay.TEXT_ALIGN[textState.textBaseline];var strokeWidth=strokeState&&strokeState.lineWidth?strokeState.lineWidth:0;var anchorX=align*label.width/pixelRatio+2*(.5-align)*strokeWidth;var anchorY=baseline*label.height/
pixelRatio+2*(.5-baseline)*strokeWidth;this.instructions.push([ol.render.canvas.Instruction.DRAW_IMAGE,begin,end,label,(anchorX-this.textOffsetX_)*pixelRatio,(anchorY-this.textOffsetY_)*pixelRatio,this.declutterGroup_,label.height,1,0,0,this.textRotateWithView_,this.textRotation_,1,true,label.width,textState.padding==ol.render.canvas.defaultPadding?ol.render.canvas.defaultPadding:textState.padding.map(function(p){return p*pixelRatio}),!!textState.backgroundFill,!!textState.backgroundStroke]);this.hitDetectionInstructions.push([ol.render.canvas.Instruction.DRAW_IMAGE,
begin,end,label,(anchorX-this.textOffsetX_)*pixelRatio,(anchorY-this.textOffsetY_)*pixelRatio,this.declutterGroup_,label.height,1,0,0,this.textRotateWithView_,this.textRotation_,1/pixelRatio,true,label.width,textState.padding,!!textState.backgroundFill,!!textState.backgroundStroke])};
ol.render.canvas.TextReplay.prototype.drawChars_=function(begin,end,declutterGroup){var strokeState=this.textStrokeState_;var textState=this.textState_;var fillState=this.textFillState_;var strokeKey=this.strokeKey_;if(strokeState)if(!(strokeKey in this.strokeStates))this.strokeStates[strokeKey]={strokeStyle:strokeState.strokeStyle,lineCap:strokeState.lineCap,lineDashOffset:strokeState.lineDashOffset,lineWidth:strokeState.lineWidth,lineJoin:strokeState.lineJoin,miterLimit:strokeState.miterLimit,lineDash:strokeState.lineDash};
var textKey=this.textKey_;if(!(this.textKey_ in this.textStates))this.textStates[this.textKey_]={font:textState.font,textAlign:textState.textAlign||ol.render.canvas.defaultTextAlign,scale:textState.scale};var fillKey=this.fillKey_;if(fillState)if(!(fillKey in this.fillStates))this.fillStates[fillKey]={fillStyle:fillState.fillStyle};var pixelRatio=this.pixelRatio;var baseline=ol.render.replay.TEXT_ALIGN[textState.textBaseline];var offsetY=this.textOffsetY_*pixelRatio;var text=this.text_;var font=textState.font;
var textScale=textState.scale;var strokeWidth=strokeState?strokeState.lineWidth*textScale/2:0;var widths=this.widths_[font];if(!widths)this.widths_[font]=widths={};this.instructions.push([ol.render.canvas.Instruction.DRAW_CHARS,begin,end,baseline,declutterGroup,textState.overflow,fillKey,textState.maxAngle,function(text){var width=widths[text];if(!width)width=widths[text]=ol.render.canvas.measureTextWidth(font,text);return width*textScale*pixelRatio},offsetY,strokeKey,strokeWidth*pixelRatio,text,
textKey,1]);this.hitDetectionInstructions.push([ol.render.canvas.Instruction.DRAW_CHARS,begin,end,baseline,declutterGroup,textState.overflow,fillKey,textState.maxAngle,function(text){var width=widths[text];if(!width)width=widths[text]=ol.render.canvas.measureTextWidth(font,text);return width*textScale},offsetY,strokeKey,strokeWidth,text,textKey,1/pixelRatio])};
ol.render.canvas.TextReplay.prototype.setTextStyle=function(textStyle,declutterGroup){var textState,fillState,strokeState;if(!textStyle)this.text_="";else{this.declutterGroup_=declutterGroup;var textFillStyle=textStyle.getFill();if(!textFillStyle)fillState=this.textFillState_=null;else{fillState=this.textFillState_;if(!fillState)fillState=this.textFillState_={};fillState.fillStyle=ol.colorlike.asColorLike(textFillStyle.getColor()||ol.render.canvas.defaultFillStyle)}var textStrokeStyle=textStyle.getStroke();
if(!textStrokeStyle)strokeState=this.textStrokeState_=null;else{strokeState=this.textStrokeState_;if(!strokeState)strokeState=this.textStrokeState_={};var lineDash=textStrokeStyle.getLineDash();var lineDashOffset=textStrokeStyle.getLineDashOffset();var lineWidth=textStrokeStyle.getWidth();var miterLimit=textStrokeStyle.getMiterLimit();strokeState.lineCap=textStrokeStyle.getLineCap()||ol.render.canvas.defaultLineCap;strokeState.lineDash=lineDash?lineDash.slice():ol.render.canvas.defaultLineDash;strokeState.lineDashOffset=
lineDashOffset===undefined?ol.render.canvas.defaultLineDashOffset:lineDashOffset;strokeState.lineJoin=textStrokeStyle.getLineJoin()||ol.render.canvas.defaultLineJoin;strokeState.lineWidth=lineWidth===undefined?ol.render.canvas.defaultLineWidth:lineWidth;strokeState.miterLimit=miterLimit===undefined?ol.render.canvas.defaultMiterLimit:miterLimit;strokeState.strokeStyle=ol.colorlike.asColorLike(textStrokeStyle.getColor()||ol.render.canvas.defaultStrokeStyle)}textState=this.textState_;var font=textStyle.getFont()||
ol.render.canvas.defaultFont;ol.render.canvas.checkFont(font);var textScale=textStyle.getScale();textState.overflow=textStyle.getOverflow();textState.font=font;textState.maxAngle=textStyle.getMaxAngle();textState.placement=textStyle.getPlacement();textState.textAlign=textStyle.getTextAlign();textState.textBaseline=textStyle.getTextBaseline()||ol.render.canvas.defaultTextBaseline;textState.backgroundFill=textStyle.getBackgroundFill();textState.backgroundStroke=textStyle.getBackgroundStroke();textState.padding=
textStyle.getPadding()||ol.render.canvas.defaultPadding;textState.scale=textScale===undefined?1:textScale;var textOffsetX=textStyle.getOffsetX();var textOffsetY=textStyle.getOffsetY();var textRotateWithView=textStyle.getRotateWithView();var textRotation=textStyle.getRotation();this.text_=textStyle.getText()||"";this.textOffsetX_=textOffsetX===undefined?0:textOffsetX;this.textOffsetY_=textOffsetY===undefined?0:textOffsetY;this.textRotateWithView_=textRotateWithView===undefined?false:textRotateWithView;
this.textRotation_=textRotation===undefined?0:textRotation;this.strokeKey_=strokeState?(typeof strokeState.strokeStyle=="string"?strokeState.strokeStyle:ol.getUid(strokeState.strokeStyle))+strokeState.lineCap+strokeState.lineDashOffset+"|"+strokeState.lineWidth+strokeState.lineJoin+strokeState.miterLimit+"["+strokeState.lineDash.join()+"]":"";this.textKey_=textState.font+textState.scale+(textState.textAlign||"?");this.fillKey_=fillState?typeof fillState.fillStyle=="string"?fillState.fillStyle:"|"+
ol.getUid(fillState.fillStyle):""}};goog.provide("ol.render.canvas.ReplayGroup");goog.require("ol");goog.require("ol.array");goog.require("ol.dom");goog.require("ol.extent");goog.require("ol.geom.flat.transform");goog.require("ol.obj");goog.require("ol.render.ReplayGroup");goog.require("ol.render.ReplayType");goog.require("ol.render.canvas.Replay");goog.require("ol.render.canvas.ImageReplay");goog.require("ol.render.canvas.LineStringReplay");goog.require("ol.render.canvas.PolygonReplay");goog.require("ol.render.canvas.TextReplay");
goog.require("ol.render.replay");goog.require("ol.transform");
ol.render.canvas.ReplayGroup=function(tolerance,maxExtent,resolution,pixelRatio,overlaps,declutterTree,opt_renderBuffer){ol.render.ReplayGroup.call(this);this.declutterTree_=declutterTree;this.declutterGroup_=null;this.tolerance_=tolerance;this.maxExtent_=maxExtent;this.overlaps_=overlaps;this.pixelRatio_=pixelRatio;this.resolution_=resolution;this.renderBuffer_=opt_renderBuffer;this.replaysByZIndex_={};this.hitDetectionContext_=ol.dom.createCanvasContext2D(1,1);this.hitDetectionTransform_=ol.transform.create()};
ol.inherits(ol.render.canvas.ReplayGroup,ol.render.ReplayGroup);ol.render.canvas.ReplayGroup.circleArrayCache_={0:[[true]]};ol.render.canvas.ReplayGroup.fillCircleArrayRowToMiddle_=function(array,x,y){var i;var radius=Math.floor(array.length/2);if(x>=radius)for(i=radius;i<x;i++)array[i][y]=true;else if(x<radius)for(i=x+1;i<radius;i++)array[i][y]=true};
ol.render.canvas.ReplayGroup.getCircleArray_=function(radius){if(ol.render.canvas.ReplayGroup.circleArrayCache_[radius]!==undefined)return ol.render.canvas.ReplayGroup.circleArrayCache_[radius];var arraySize=radius*2+1;var arr=new Array(arraySize);for(var i=0;i<arraySize;i++)arr[i]=new Array(arraySize);var x=radius;var y=0;var error=0;while(x>=y){ol.render.canvas.ReplayGroup.fillCircleArrayRowToMiddle_(arr,radius+x,radius+y);ol.render.canvas.ReplayGroup.fillCircleArrayRowToMiddle_(arr,radius+y,radius+
x);ol.render.canvas.ReplayGroup.fillCircleArrayRowToMiddle_(arr,radius-y,radius+x);ol.render.canvas.ReplayGroup.fillCircleArrayRowToMiddle_(arr,radius-x,radius+y);ol.render.canvas.ReplayGroup.fillCircleArrayRowToMiddle_(arr,radius-x,radius-y);ol.render.canvas.ReplayGroup.fillCircleArrayRowToMiddle_(arr,radius-y,radius-x);ol.render.canvas.ReplayGroup.fillCircleArrayRowToMiddle_(arr,radius+y,radius-x);ol.render.canvas.ReplayGroup.fillCircleArrayRowToMiddle_(arr,radius+x,radius-y);y++;error+=1+2*y;if(2*
(error-x)+1>0){x-=1;error+=1-2*x}}ol.render.canvas.ReplayGroup.circleArrayCache_[radius]=arr;return arr};
ol.render.canvas.ReplayGroup.replayDeclutter=function(declutterReplays,context,rotation){var zs=Object.keys(declutterReplays).map(Number).sort(ol.array.numberSafeCompareFunction);var skippedFeatureUids={};for(var z=0,zz=zs.length;z<zz;++z){var replayData=declutterReplays[zs[z].toString()];for(var i=0,ii=replayData.length;i<ii;){var replay=replayData[i++];var transform=replayData[i++];replay.replay(context,transform,rotation,skippedFeatureUids)}}};
ol.render.canvas.ReplayGroup.prototype.addDeclutter=function(group){var declutter=null;if(this.declutterTree_)if(group){declutter=this.declutterGroup_;declutter[4]++}else{declutter=this.declutterGroup_=ol.extent.createEmpty();declutter.push(1)}return declutter};
ol.render.canvas.ReplayGroup.prototype.clip=function(context,transform){var flatClipCoords=this.getClipCoords(transform);context.beginPath();context.moveTo(flatClipCoords[0],flatClipCoords[1]);context.lineTo(flatClipCoords[2],flatClipCoords[3]);context.lineTo(flatClipCoords[4],flatClipCoords[5]);context.lineTo(flatClipCoords[6],flatClipCoords[7]);context.clip()};
ol.render.canvas.ReplayGroup.prototype.hasReplays=function(replays){for(var zIndex in this.replaysByZIndex_){var candidates=this.replaysByZIndex_[zIndex];for(var i=0,ii=replays.length;i<ii;++i)if(replays[i]in candidates)return true}return false};ol.render.canvas.ReplayGroup.prototype.finish=function(){var zKey;for(zKey in this.replaysByZIndex_){var replays=this.replaysByZIndex_[zKey];var replayKey;for(replayKey in replays)replays[replayKey].finish()}};
ol.render.canvas.ReplayGroup.prototype.forEachFeatureAtCoordinate=function(coordinate,resolution,rotation,hitTolerance,skippedFeaturesHash,callback,declutterReplays){hitTolerance=Math.round(hitTolerance);var contextSize=hitTolerance*2+1;var transform=ol.transform.compose(this.hitDetectionTransform_,hitTolerance+.5,hitTolerance+.5,1/resolution,-1/resolution,-rotation,-coordinate[0],-coordinate[1]);var context=this.hitDetectionContext_;if(context.canvas.width!==contextSize||context.canvas.height!==
contextSize){context.canvas.width=contextSize;context.canvas.height=contextSize}else context.clearRect(0,0,contextSize,contextSize);var hitExtent;if(this.renderBuffer_!==undefined){hitExtent=ol.extent.createEmpty();ol.extent.extendCoordinate(hitExtent,coordinate);ol.extent.buffer(hitExtent,resolution*(this.renderBuffer_+hitTolerance),hitExtent)}var mask=ol.render.canvas.ReplayGroup.getCircleArray_(hitTolerance);var declutteredFeatures;if(this.declutterTree_)declutteredFeatures=this.declutterTree_.all().map(function(entry){return entry.value});
var replayType;function featureCallback(feature){var imageData=context.getImageData(0,0,contextSize,contextSize).data;for(var i=0;i<contextSize;i++)for(var j=0;j<contextSize;j++)if(mask[i][j])if(imageData[(j*contextSize+i)*4+3]>0){var result;if(!(declutteredFeatures&&(replayType==ol.render.ReplayType.IMAGE||replayType==ol.render.ReplayType.TEXT))||declutteredFeatures.indexOf(feature)!==-1)result=callback(feature);if(result)return result;else{context.clearRect(0,0,contextSize,contextSize);return undefined}}}
var zs=Object.keys(this.replaysByZIndex_).map(Number);zs.sort(ol.array.numberSafeCompareFunction);var i,j,replays,replay,result;for(i=zs.length-1;i>=0;--i){var zIndexKey=zs[i].toString();replays=this.replaysByZIndex_[zIndexKey];for(j=ol.render.replay.ORDER.length-1;j>=0;--j){replayType=ol.render.replay.ORDER[j];replay=replays[replayType];if(replay!==undefined)if(declutterReplays&&(replayType==ol.render.ReplayType.IMAGE||replayType==ol.render.ReplayType.TEXT)){var declutter=declutterReplays[zIndexKey];
if(!declutter)declutterReplays[zIndexKey]=[replay,transform.slice(0)];else declutter.push(replay,transform.slice(0))}else{result=replay.replayHitDetection(context,transform,rotation,skippedFeaturesHash,featureCallback,hitExtent);if(result)return result}}}return undefined};
ol.render.canvas.ReplayGroup.prototype.getClipCoords=function(transform){var maxExtent=this.maxExtent_;var minX=maxExtent[0];var minY=maxExtent[1];var maxX=maxExtent[2];var maxY=maxExtent[3];var flatClipCoords=[minX,minY,minX,maxY,maxX,maxY,maxX,minY];ol.geom.flat.transform.transform2D(flatClipCoords,0,8,2,transform,flatClipCoords);return flatClipCoords};
ol.render.canvas.ReplayGroup.prototype.getReplay=function(zIndex,replayType){var zIndexKey=zIndex!==undefined?zIndex.toString():"0";var replays=this.replaysByZIndex_[zIndexKey];if(replays===undefined){replays={};this.replaysByZIndex_[zIndexKey]=replays}var replay=replays[replayType];if(replay===undefined){var Constructor=ol.render.canvas.ReplayGroup.BATCH_CONSTRUCTORS_[replayType];replay=new Constructor(this.tolerance_,this.maxExtent_,this.resolution_,this.pixelRatio_,this.overlaps_,this.declutterTree_);
replays[replayType]=replay}return replay};ol.render.canvas.ReplayGroup.prototype.getReplays=function(){return this.replaysByZIndex_};ol.render.canvas.ReplayGroup.prototype.isEmpty=function(){return ol.obj.isEmpty(this.replaysByZIndex_)};
ol.render.canvas.ReplayGroup.prototype.replay=function(context,transform,viewRotation,skippedFeaturesHash,opt_replayTypes,opt_declutterReplays){var zs=Object.keys(this.replaysByZIndex_).map(Number);zs.sort(ol.array.numberSafeCompareFunction);context.save();this.clip(context,transform);var replayTypes=opt_replayTypes?opt_replayTypes:ol.render.replay.ORDER;var i,ii,j,jj,replays,replay;for(i=0,ii=zs.length;i<ii;++i){var zIndexKey=zs[i].toString();replays=this.replaysByZIndex_[zIndexKey];for(j=0,jj=replayTypes.length;j<
jj;++j){var replayType=replayTypes[j];replay=replays[replayType];if(replay!==undefined)if(opt_declutterReplays&&(replayType==ol.render.ReplayType.IMAGE||replayType==ol.render.ReplayType.TEXT)){var declutter=opt_declutterReplays[zIndexKey];if(!declutter)opt_declutterReplays[zIndexKey]=[replay,transform.slice(0)];else declutter.push(replay,transform.slice(0))}else replay.replay(context,transform,viewRotation,skippedFeaturesHash)}}context.restore()};
ol.render.canvas.ReplayGroup.BATCH_CONSTRUCTORS_={"Circle":ol.render.canvas.PolygonReplay,"Default":ol.render.canvas.Replay,"Image":ol.render.canvas.ImageReplay,"LineString":ol.render.canvas.LineStringReplay,"Polygon":ol.render.canvas.PolygonReplay,"Text":ol.render.canvas.TextReplay};goog.provide("ol.renderer.vector");goog.require("ol");goog.require("ol.ImageState");goog.require("ol.geom.GeometryType");goog.require("ol.render.ReplayType");ol.renderer.vector.defaultOrder=function(feature1,feature2){return ol.getUid(feature1)-ol.getUid(feature2)};ol.renderer.vector.getSquaredTolerance=function(resolution,pixelRatio){var tolerance=ol.renderer.vector.getTolerance(resolution,pixelRatio);return tolerance*tolerance};
ol.renderer.vector.getTolerance=function(resolution,pixelRatio){return ol.SIMPLIFY_TOLERANCE*resolution/pixelRatio};
ol.renderer.vector.renderCircleGeometry_=function(replayGroup,geometry,style,feature){var fillStyle=style.getFill();var strokeStyle=style.getStroke();if(fillStyle||strokeStyle){var circleReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.CIRCLE);circleReplay.setFillStrokeStyle(fillStyle,strokeStyle);circleReplay.drawCircle(geometry,feature)}var textStyle=style.getText();if(textStyle){var textReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.TEXT);textReplay.setTextStyle(textStyle,
replayGroup.addDeclutter(false));textReplay.drawText(geometry,feature)}};
ol.renderer.vector.renderFeature=function(replayGroup,feature,style,squaredTolerance,listener,thisArg){var loading=false;var imageStyle,imageState;imageStyle=style.getImage();if(imageStyle){imageState=imageStyle.getImageState();if(imageState==ol.ImageState.LOADED||imageState==ol.ImageState.ERROR)imageStyle.unlistenImageChange(listener,thisArg);else{if(imageState==ol.ImageState.IDLE)imageStyle.load();imageState=imageStyle.getImageState();imageStyle.listenImageChange(listener,thisArg);loading=true}}ol.renderer.vector.renderFeature_(replayGroup,
feature,style,squaredTolerance);return loading};
ol.renderer.vector.renderFeature_=function(replayGroup,feature,style,squaredTolerance){var geometry=style.getGeometryFunction()(feature);if(!geometry)return;var simplifiedGeometry=geometry.getSimplifiedGeometry(squaredTolerance);var renderer=style.getRenderer();if(renderer)ol.renderer.vector.renderGeometry_(replayGroup,simplifiedGeometry,style,feature);else{var geometryRenderer=ol.renderer.vector.GEOMETRY_RENDERERS_[simplifiedGeometry.getType()];geometryRenderer(replayGroup,simplifiedGeometry,style,
feature)}};ol.renderer.vector.renderGeometry_=function(replayGroup,geometry,style,feature){if(geometry.getType()==ol.geom.GeometryType.GEOMETRY_COLLECTION){var geometries=geometry.getGeometries();for(var i=0,ii=geometries.length;i<ii;++i)ol.renderer.vector.renderGeometry_(replayGroup,geometries[i],style,feature);return}var replay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.DEFAULT);replay.drawCustom(geometry,feature,style.getRenderer())};
ol.renderer.vector.renderGeometryCollectionGeometry_=function(replayGroup,geometry,style,feature){var geometries=geometry.getGeometriesArray();var i,ii;for(i=0,ii=geometries.length;i<ii;++i){var geometryRenderer=ol.renderer.vector.GEOMETRY_RENDERERS_[geometries[i].getType()];geometryRenderer(replayGroup,geometries[i],style,feature)}};
ol.renderer.vector.renderLineStringGeometry_=function(replayGroup,geometry,style,feature){var strokeStyle=style.getStroke();if(strokeStyle){var lineStringReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.LINE_STRING);lineStringReplay.setFillStrokeStyle(null,strokeStyle);lineStringReplay.drawLineString(geometry,feature)}var textStyle=style.getText();if(textStyle){var textReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.TEXT);textReplay.setTextStyle(textStyle,replayGroup.addDeclutter(false));
textReplay.drawText(geometry,feature)}};
ol.renderer.vector.renderMultiLineStringGeometry_=function(replayGroup,geometry,style,feature){var strokeStyle=style.getStroke();if(strokeStyle){var lineStringReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.LINE_STRING);lineStringReplay.setFillStrokeStyle(null,strokeStyle);lineStringReplay.drawMultiLineString(geometry,feature)}var textStyle=style.getText();if(textStyle){var textReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.TEXT);textReplay.setTextStyle(textStyle,
replayGroup.addDeclutter(false));textReplay.drawText(geometry,feature)}};
ol.renderer.vector.renderMultiPolygonGeometry_=function(replayGroup,geometry,style,feature){var fillStyle=style.getFill();var strokeStyle=style.getStroke();if(strokeStyle||fillStyle){var polygonReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.POLYGON);polygonReplay.setFillStrokeStyle(fillStyle,strokeStyle);polygonReplay.drawMultiPolygon(geometry,feature)}var textStyle=style.getText();if(textStyle){var textReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.TEXT);
textReplay.setTextStyle(textStyle,replayGroup.addDeclutter(false));textReplay.drawText(geometry,feature)}};
ol.renderer.vector.renderPointGeometry_=function(replayGroup,geometry,style,feature){var imageStyle=style.getImage();if(imageStyle){if(imageStyle.getImageState()!=ol.ImageState.LOADED)return;var imageReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.IMAGE);imageReplay.setImageStyle(imageStyle,replayGroup.addDeclutter(false));imageReplay.drawPoint(geometry,feature)}var textStyle=style.getText();if(textStyle){var textReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.TEXT);
textReplay.setTextStyle(textStyle,replayGroup.addDeclutter(!!imageStyle));textReplay.drawText(geometry,feature)}};
ol.renderer.vector.renderMultiPointGeometry_=function(replayGroup,geometry,style,feature){var imageStyle=style.getImage();if(imageStyle){if(imageStyle.getImageState()!=ol.ImageState.LOADED)return;var imageReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.IMAGE);imageReplay.setImageStyle(imageStyle,replayGroup.addDeclutter(false));imageReplay.drawMultiPoint(geometry,feature)}var textStyle=style.getText();if(textStyle){var textReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.TEXT);
textReplay.setTextStyle(textStyle,replayGroup.addDeclutter(!!imageStyle));textReplay.drawText(geometry,feature)}};
ol.renderer.vector.renderPolygonGeometry_=function(replayGroup,geometry,style,feature){var fillStyle=style.getFill();var strokeStyle=style.getStroke();if(fillStyle||strokeStyle){var polygonReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.POLYGON);polygonReplay.setFillStrokeStyle(fillStyle,strokeStyle);polygonReplay.drawPolygon(geometry,feature)}var textStyle=style.getText();if(textStyle){var textReplay=replayGroup.getReplay(style.getZIndex(),ol.render.ReplayType.TEXT);textReplay.setTextStyle(textStyle,
replayGroup.addDeclutter(false));textReplay.drawText(geometry,feature)}};
ol.renderer.vector.GEOMETRY_RENDERERS_={"Point":ol.renderer.vector.renderPointGeometry_,"LineString":ol.renderer.vector.renderLineStringGeometry_,"Polygon":ol.renderer.vector.renderPolygonGeometry_,"MultiPoint":ol.renderer.vector.renderMultiPointGeometry_,"MultiLineString":ol.renderer.vector.renderMultiLineStringGeometry_,"MultiPolygon":ol.renderer.vector.renderMultiPolygonGeometry_,"GeometryCollection":ol.renderer.vector.renderGeometryCollectionGeometry_,"Circle":ol.renderer.vector.renderCircleGeometry_};goog.provide("ol.renderer.canvas.VectorLayer");goog.require("ol");goog.require("ol.LayerType");goog.require("ol.ViewHint");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.ext.rbush");goog.require("ol.extent");goog.require("ol.render.EventType");goog.require("ol.render.canvas");goog.require("ol.render.canvas.ReplayGroup");goog.require("ol.renderer.Type");goog.require("ol.renderer.canvas.Layer");goog.require("ol.renderer.vector");
ol.renderer.canvas.VectorLayer=function(vectorLayer){ol.renderer.canvas.Layer.call(this,vectorLayer);this.declutterTree_=vectorLayer.getDeclutter()?ol.ext.rbush(9):null;this.dirty_=false;this.renderedRevision_=-1;this.renderedResolution_=NaN;this.renderedExtent_=ol.extent.createEmpty();this.renderedRenderOrder_=null;this.replayGroup_=null;this.replayGroupChanged=true;this.context=ol.dom.createCanvasContext2D();ol.events.listen(ol.render.canvas.labelCache,ol.events.EventType.CLEAR,this.handleFontsChanged_,
this)};ol.inherits(ol.renderer.canvas.VectorLayer,ol.renderer.canvas.Layer);ol.renderer.canvas.VectorLayer["handles"]=function(type,layer){return type===ol.renderer.Type.CANVAS&&layer.getType()===ol.LayerType.VECTOR};ol.renderer.canvas.VectorLayer["create"]=function(mapRenderer,layer){return new ol.renderer.canvas.VectorLayer(layer)};
ol.renderer.canvas.VectorLayer.prototype.disposeInternal=function(){ol.events.unlisten(ol.render.canvas.labelCache,ol.events.EventType.CLEAR,this.handleFontsChanged_,this);ol.renderer.canvas.Layer.prototype.disposeInternal.call(this)};
ol.renderer.canvas.VectorLayer.prototype.composeFrame=function(frameState,layerState,context){var extent=frameState.extent;var pixelRatio=frameState.pixelRatio;var skippedFeatureUids=layerState.managed?frameState.skippedFeatureUids:{};var viewState=frameState.viewState;var projection=viewState.projection;var rotation=viewState.rotation;var projectionExtent=projection.getExtent();var vectorSource=this.getLayer().getSource();var transform=this.getTransform(frameState,0);this.preCompose(context,frameState,
transform);var clipExtent=layerState.extent;var clipped=clipExtent!==undefined;if(clipped)this.clip(context,frameState,clipExtent);var replayGroup=this.replayGroup_;if(replayGroup&&!replayGroup.isEmpty()){if(this.declutterTree_)this.declutterTree_.clear();var layer=this.getLayer();var drawOffsetX=0;var drawOffsetY=0;var replayContext;var transparentLayer=layerState.opacity!==1;var hasRenderListeners=layer.hasListener(ol.render.EventType.RENDER);if(transparentLayer||hasRenderListeners){var drawWidth=
context.canvas.width;var drawHeight=context.canvas.height;if(rotation){var drawSize=Math.round(Math.sqrt(drawWidth*drawWidth+drawHeight*drawHeight));drawOffsetX=(drawSize-drawWidth)/2;drawOffsetY=(drawSize-drawHeight)/2;drawWidth=drawHeight=drawSize}this.context.canvas.width=drawWidth;this.context.canvas.height=drawHeight;replayContext=this.context}else replayContext=context;var alpha=replayContext.globalAlpha;if(!transparentLayer)replayContext.globalAlpha=layerState.opacity;if(replayContext!=context)replayContext.translate(drawOffsetX,
drawOffsetY);var width=frameState.size[0]*pixelRatio;var height=frameState.size[1]*pixelRatio;ol.render.canvas.rotateAtOffset(replayContext,-rotation,width/2,height/2);replayGroup.replay(replayContext,transform,rotation,skippedFeatureUids);if(vectorSource.getWrapX()&&projection.canWrapX()&&!ol.extent.containsExtent(projectionExtent,extent)){var startX=extent[0];var worldWidth=ol.extent.getWidth(projectionExtent);var world=0;var offsetX;while(startX<projectionExtent[0]){--world;offsetX=worldWidth*
world;transform=this.getTransform(frameState,offsetX);replayGroup.replay(replayContext,transform,rotation,skippedFeatureUids);startX+=worldWidth}world=0;startX=extent[2];while(startX>projectionExtent[2]){++world;offsetX=worldWidth*world;transform=this.getTransform(frameState,offsetX);replayGroup.replay(replayContext,transform,rotation,skippedFeatureUids);startX-=worldWidth}transform=this.getTransform(frameState,0)}ol.render.canvas.rotateAtOffset(replayContext,rotation,width/2,height/2);if(replayContext!=
context){if(hasRenderListeners)this.dispatchRenderEvent(replayContext,frameState,transform);if(transparentLayer){var mainContextAlpha=context.globalAlpha;context.globalAlpha=layerState.opacity;context.drawImage(replayContext.canvas,-drawOffsetX,-drawOffsetY);context.globalAlpha=mainContextAlpha}else context.drawImage(replayContext.canvas,-drawOffsetX,-drawOffsetY);replayContext.translate(-drawOffsetX,-drawOffsetY)}if(!transparentLayer)replayContext.globalAlpha=alpha}if(clipped)context.restore();this.postCompose(context,
frameState,layerState,transform)};
ol.renderer.canvas.VectorLayer.prototype.forEachFeatureAtCoordinate=function(coordinate,frameState,hitTolerance,callback,thisArg){if(!this.replayGroup_)return undefined;else{var resolution=frameState.viewState.resolution;var rotation=frameState.viewState.rotation;var layer=this.getLayer();var features={};var result=this.replayGroup_.forEachFeatureAtCoordinate(coordinate,resolution,rotation,hitTolerance,{},function(feature){var key=ol.getUid(feature).toString();if(!(key in features)){features[key]=
true;return callback.call(thisArg,feature,layer)}},null);return result}};ol.renderer.canvas.VectorLayer.prototype.handleFontsChanged_=function(event){var layer=this.getLayer();if(layer.getVisible()&&this.replayGroup_)layer.changed()};ol.renderer.canvas.VectorLayer.prototype.handleStyleImageChange_=function(event){this.renderIfReadyAndVisible()};
ol.renderer.canvas.VectorLayer.prototype.prepareFrame=function(frameState,layerState){var vectorLayer=this.getLayer();var vectorSource=vectorLayer.getSource();this.updateLogos(frameState,vectorSource);var animating=frameState.viewHints[ol.ViewHint.ANIMATING];var interacting=frameState.viewHints[ol.ViewHint.INTERACTING];var updateWhileAnimating=vectorLayer.getUpdateWhileAnimating();var updateWhileInteracting=vectorLayer.getUpdateWhileInteracting();if(!this.dirty_&&(!updateWhileAnimating&&animating)||
!updateWhileInteracting&&interacting)return true;var frameStateExtent=frameState.extent;var viewState=frameState.viewState;var projection=viewState.projection;var resolution=viewState.resolution;var pixelRatio=frameState.pixelRatio;var vectorLayerRevision=vectorLayer.getRevision();var vectorLayerRenderBuffer=vectorLayer.getRenderBuffer();var vectorLayerRenderOrder=vectorLayer.getRenderOrder();if(vectorLayerRenderOrder===undefined)vectorLayerRenderOrder=ol.renderer.vector.defaultOrder;var extent=ol.extent.buffer(frameStateExtent,
vectorLayerRenderBuffer*resolution);var projectionExtent=viewState.projection.getExtent();if(vectorSource.getWrapX()&&viewState.projection.canWrapX()&&!ol.extent.containsExtent(projectionExtent,frameState.extent)){var worldWidth=ol.extent.getWidth(projectionExtent);var buffer=Math.max(ol.extent.getWidth(extent)/2,worldWidth);extent[0]=projectionExtent[0]-buffer;extent[2]=projectionExtent[2]+buffer}if(!this.dirty_&&this.renderedResolution_==resolution&&this.renderedRevision_==vectorLayerRevision&&
this.renderedRenderOrder_==vectorLayerRenderOrder&&ol.extent.containsExtent(this.renderedExtent_,extent)){this.replayGroupChanged=false;return true}this.replayGroup_=null;this.dirty_=false;var replayGroup=new ol.render.canvas.ReplayGroup(ol.renderer.vector.getTolerance(resolution,pixelRatio),extent,resolution,pixelRatio,vectorSource.getOverlaps(),this.declutterTree_,vectorLayer.getRenderBuffer());vectorSource.loadFeatures(extent,resolution,projection);var renderFeature=function(feature){var styles;
var styleFunction=feature.getStyleFunction();if(styleFunction)styles=styleFunction.call(feature,resolution);else{styleFunction=vectorLayer.getStyleFunction();if(styleFunction)styles=styleFunction(feature,resolution)}if(styles){var dirty=this.renderFeature(feature,resolution,pixelRatio,styles,replayGroup);this.dirty_=this.dirty_||dirty}}.bind(this);if(vectorLayerRenderOrder){var features=[];vectorSource.forEachFeatureInExtent(extent,function(feature){features.push(feature)},this);features.sort(vectorLayerRenderOrder);
for(var i=0,ii=features.length;i<ii;++i)renderFeature(features[i])}else vectorSource.forEachFeatureInExtent(extent,renderFeature,this);replayGroup.finish();this.renderedResolution_=resolution;this.renderedRevision_=vectorLayerRevision;this.renderedRenderOrder_=vectorLayerRenderOrder;this.renderedExtent_=extent;this.replayGroup_=replayGroup;this.replayGroupChanged=true;return true};
ol.renderer.canvas.VectorLayer.prototype.renderFeature=function(feature,resolution,pixelRatio,styles,replayGroup){if(!styles)return false;var loading=false;if(Array.isArray(styles))for(var i=0,ii=styles.length;i<ii;++i)loading=ol.renderer.vector.renderFeature(replayGroup,feature,styles[i],ol.renderer.vector.getSquaredTolerance(resolution,pixelRatio),this.handleStyleImageChange_,this)||loading;else loading=ol.renderer.vector.renderFeature(replayGroup,feature,styles,ol.renderer.vector.getSquaredTolerance(resolution,
pixelRatio),this.handleStyleImageChange_,this);return loading};goog.provide("ol.layer.VectorTileRenderType");ol.layer.VectorTileRenderType={IMAGE:"image",HYBRID:"hybrid",VECTOR:"vector"};goog.provide("ol.renderer.canvas.VectorTileLayer");goog.require("ol");goog.require("ol.LayerType");goog.require("ol.TileState");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.ext.rbush");goog.require("ol.extent");goog.require("ol.layer.VectorTileRenderType");goog.require("ol.proj");goog.require("ol.proj.Units");goog.require("ol.render.ReplayType");goog.require("ol.render.canvas");goog.require("ol.render.canvas.ReplayGroup");goog.require("ol.render.replay");
goog.require("ol.renderer.Type");goog.require("ol.renderer.canvas.TileLayer");goog.require("ol.renderer.vector");goog.require("ol.transform");
ol.renderer.canvas.VectorTileLayer=function(layer){this.context=null;ol.renderer.canvas.TileLayer.call(this,layer);this.declutterTree_=layer.getDeclutter()?ol.ext.rbush(9):null;this.dirty_=false;this.renderedLayerRevision_;this.tmpTransform_=ol.transform.create();this.zDirection=layer.getRenderMode()==ol.layer.VectorTileRenderType.VECTOR?1:0;ol.events.listen(ol.render.canvas.labelCache,ol.events.EventType.CLEAR,this.handleFontsChanged_,this)};ol.inherits(ol.renderer.canvas.VectorTileLayer,ol.renderer.canvas.TileLayer);
ol.renderer.canvas.VectorTileLayer["handles"]=function(type,layer){return type===ol.renderer.Type.CANVAS&&layer.getType()===ol.LayerType.VECTOR_TILE};ol.renderer.canvas.VectorTileLayer["create"]=function(mapRenderer,layer){return new ol.renderer.canvas.VectorTileLayer(layer)};
ol.renderer.canvas.VectorTileLayer.IMAGE_REPLAYS={"image":[ol.render.ReplayType.POLYGON,ol.render.ReplayType.CIRCLE,ol.render.ReplayType.LINE_STRING,ol.render.ReplayType.IMAGE,ol.render.ReplayType.TEXT],"hybrid":[ol.render.ReplayType.POLYGON,ol.render.ReplayType.LINE_STRING]};ol.renderer.canvas.VectorTileLayer.VECTOR_REPLAYS={"image":[ol.render.ReplayType.DEFAULT],"hybrid":[ol.render.ReplayType.IMAGE,ol.render.ReplayType.TEXT,ol.render.ReplayType.DEFAULT],"vector":ol.render.replay.ORDER};
ol.renderer.canvas.VectorTileLayer.prototype.disposeInternal=function(){ol.events.unlisten(ol.render.canvas.labelCache,ol.events.EventType.CLEAR,this.handleFontsChanged_,this);ol.renderer.canvas.TileLayer.prototype.disposeInternal.call(this)};
ol.renderer.canvas.VectorTileLayer.prototype.prepareFrame=function(frameState,layerState){var layer=this.getLayer();var layerRevision=layer.getRevision();if(this.renderedLayerRevision_!=layerRevision){this.renderedTiles.length=0;var renderMode=layer.getRenderMode();if(!this.context&&renderMode!=ol.layer.VectorTileRenderType.VECTOR)this.context=ol.dom.createCanvasContext2D();if(this.context&&renderMode==ol.layer.VectorTileRenderType.VECTOR)this.context=null}this.renderedLayerRevision_=layerRevision;
return ol.renderer.canvas.TileLayer.prototype.prepareFrame.apply(this,arguments)};
ol.renderer.canvas.VectorTileLayer.prototype.createReplayGroup_=function(tile,frameState){var layer=this.getLayer();var pixelRatio=frameState.pixelRatio;var projection=frameState.viewState.projection;var revision=layer.getRevision();var renderOrder=layer.getRenderOrder()||null;var replayState=tile.getReplayState(layer);if(!replayState.dirty&&replayState.renderedRevision==revision&&replayState.renderedRenderOrder==renderOrder)return;var source=layer.getSource();var sourceTileGrid=source.getTileGrid();
var tileGrid=source.getTileGridForProjection(projection);var resolution=tileGrid.getResolution(tile.tileCoord[0]);var tileExtent=tileGrid.getTileCoordExtent(tile.wrappedTileCoord);var zIndexKeys={};for(var t=0,tt=tile.tileKeys.length;t<tt;++t){var sourceTile=tile.getTile(tile.tileKeys[t]);if(sourceTile.getState()==ol.TileState.ERROR)continue;var sourceTileCoord=sourceTile.tileCoord;var sourceTileExtent=sourceTileGrid.getTileCoordExtent(sourceTileCoord);var sharedExtent=ol.extent.getIntersection(tileExtent,
sourceTileExtent);var bufferedExtent=ol.extent.equals(sourceTileExtent,sharedExtent)?null:ol.extent.buffer(sharedExtent,layer.getRenderBuffer()*resolution);var tileProjection=sourceTile.getProjection();var reproject=false;if(!ol.proj.equivalent(projection,tileProjection)){reproject=true;sourceTile.setProjection(projection)}replayState.dirty=false;var replayGroup=new ol.render.canvas.ReplayGroup(0,sharedExtent,resolution,pixelRatio,source.getOverlaps(),this.declutterTree_,layer.getRenderBuffer());
var squaredTolerance=ol.renderer.vector.getSquaredTolerance(resolution,pixelRatio);var renderFeature=function(feature){var styles;var styleFunction=feature.getStyleFunction();if(styleFunction)styles=styleFunction.call(feature,resolution);else{styleFunction=layer.getStyleFunction();if(styleFunction)styles=styleFunction(feature,resolution)}if(styles){var dirty=this.renderFeature(feature,squaredTolerance,styles,replayGroup);this.dirty_=this.dirty_||dirty;replayState.dirty=replayState.dirty||dirty}};
var features=sourceTile.getFeatures();if(renderOrder&&renderOrder!==replayState.renderedRenderOrder)features.sort(renderOrder);var feature;for(var i=0,ii=features.length;i<ii;++i){feature=features[i];if(reproject){if(tileProjection.getUnits()==ol.proj.Units.TILE_PIXELS){tileProjection.setWorldExtent(sourceTileExtent);tileProjection.setExtent(sourceTile.getExtent())}feature.getGeometry().transform(tileProjection,projection)}if(!bufferedExtent||ol.extent.intersects(bufferedExtent,feature.getGeometry().getExtent()))renderFeature.call(this,
feature)}replayGroup.finish();for(var r in replayGroup.getReplays())zIndexKeys[r]=true;sourceTile.setReplayGroup(layer,tile.tileCoord.toString(),replayGroup)}replayState.renderedRevision=revision;replayState.renderedRenderOrder=renderOrder};
ol.renderer.canvas.VectorTileLayer.prototype.drawTileImage=function(tile,frameState,layerState,x,y,w,h,gutter,transition){var vectorImageTile=tile;this.createReplayGroup_(vectorImageTile,frameState);if(this.context){this.renderTileImage_(vectorImageTile,frameState,layerState);ol.renderer.canvas.TileLayer.prototype.drawTileImage.apply(this,arguments)}};
ol.renderer.canvas.VectorTileLayer.prototype.forEachFeatureAtCoordinate=function(coordinate,frameState,hitTolerance,callback,thisArg){var resolution=frameState.viewState.resolution;var rotation=frameState.viewState.rotation;hitTolerance=hitTolerance==undefined?0:hitTolerance;var layer=this.getLayer();var features={};var renderedTiles=this.renderedTiles;var source=layer.getSource();var tileGrid=source.getTileGridForProjection(frameState.viewState.projection);var bufferedExtent,found;var i,ii,replayGroup;
var tile,tileCoord,tileExtent;for(i=0,ii=renderedTiles.length;i<ii;++i){tile=renderedTiles[i];tileCoord=tile.wrappedTileCoord;tileExtent=tileGrid.getTileCoordExtent(tileCoord,this.tmpExtent);bufferedExtent=ol.extent.buffer(tileExtent,hitTolerance*resolution,bufferedExtent);if(!ol.extent.containsCoordinate(bufferedExtent,coordinate))continue;for(var t=0,tt=tile.tileKeys.length;t<tt;++t){var sourceTile=tile.getTile(tile.tileKeys[t]);if(sourceTile.getState()==ol.TileState.ERROR)continue;replayGroup=
sourceTile.getReplayGroup(layer,tile.tileCoord.toString());found=found||replayGroup.forEachFeatureAtCoordinate(coordinate,resolution,rotation,hitTolerance,{},function(feature){var key=ol.getUid(feature).toString();if(!(key in features)){features[key]=true;return callback.call(thisArg,feature,layer)}},null)}}return found};
ol.renderer.canvas.VectorTileLayer.prototype.getReplayTransform_=function(tile,frameState){var layer=this.getLayer();var source=layer.getSource();var tileGrid=source.getTileGrid();var tileCoord=tile.tileCoord;var tileResolution=tileGrid.getResolution(tileCoord[0]);var viewState=frameState.viewState;var pixelRatio=frameState.pixelRatio;var renderResolution=viewState.resolution/pixelRatio;var tileExtent=tileGrid.getTileCoordExtent(tileCoord,this.tmpExtent);var center=viewState.center;var origin=ol.extent.getTopLeft(tileExtent);
var size=frameState.size;var offsetX=Math.round(pixelRatio*size[0]/2);var offsetY=Math.round(pixelRatio*size[1]/2);return ol.transform.compose(this.tmpTransform_,offsetX,offsetY,tileResolution/renderResolution,tileResolution/renderResolution,viewState.rotation,(origin[0]-center[0])/tileResolution,(center[1]-origin[1])/tileResolution)};ol.renderer.canvas.VectorTileLayer.prototype.handleFontsChanged_=function(event){var layer=this.getLayer();if(layer.getVisible()&&this.renderedLayerRevision_!==undefined)layer.changed()};
ol.renderer.canvas.VectorTileLayer.prototype.handleStyleImageChange_=function(event){this.renderIfReadyAndVisible()};
ol.renderer.canvas.VectorTileLayer.prototype.postCompose=function(context,frameState,layerState){var layer=this.getLayer();var declutterReplays=layer.getDeclutter()?{}:null;var source=layer.getSource();var renderMode=layer.getRenderMode();var replayTypes=ol.renderer.canvas.VectorTileLayer.VECTOR_REPLAYS[renderMode];var pixelRatio=frameState.pixelRatio;var rotation=frameState.viewState.rotation;var size=frameState.size;var offsetX,offsetY;if(rotation){offsetX=Math.round(pixelRatio*size[0]/2);offsetY=
Math.round(pixelRatio*size[1]/2);ol.render.canvas.rotateAtOffset(context,-rotation,offsetX,offsetY)}if(declutterReplays)this.declutterTree_.clear();var tiles=this.renderedTiles;var tileGrid=source.getTileGridForProjection(frameState.viewState.projection);var clips=[];var zs=[];for(var i=tiles.length-1;i>=0;--i){var tile=tiles[i];if(tile.getState()==ol.TileState.ABORT)continue;var tileCoord=tile.tileCoord;var worldOffset=tileGrid.getTileCoordExtent(tileCoord)[0]-tileGrid.getTileCoordExtent(tile.wrappedTileCoord)[0];
var transform=undefined;for(var t=0,tt=tile.tileKeys.length;t<tt;++t){var sourceTile=tile.getTile(tile.tileKeys[t]);if(sourceTile.getState()==ol.TileState.ERROR)continue;var replayGroup=sourceTile.getReplayGroup(layer,tileCoord.toString());if(renderMode!=ol.layer.VectorTileRenderType.VECTOR&&!replayGroup.hasReplays(replayTypes))continue;if(!transform)transform=this.getTransform(frameState,worldOffset);var currentZ=sourceTile.tileCoord[0];var currentClip=replayGroup.getClipCoords(transform);context.save();
context.globalAlpha=layerState.opacity;for(var j=0,jj=clips.length;j<jj;++j){var clip=clips[j];if(currentZ<zs[j]){context.beginPath();context.moveTo(currentClip[0],currentClip[1]);context.lineTo(currentClip[2],currentClip[3]);context.lineTo(currentClip[4],currentClip[5]);context.lineTo(currentClip[6],currentClip[7]);context.moveTo(clip[6],clip[7]);context.lineTo(clip[4],clip[5]);context.lineTo(clip[2],clip[3]);context.lineTo(clip[0],clip[1]);context.clip()}}replayGroup.replay(context,transform,rotation,
{},replayTypes,declutterReplays);context.restore();clips.push(currentClip);zs.push(currentZ)}}if(declutterReplays)ol.render.canvas.ReplayGroup.replayDeclutter(declutterReplays,context,rotation);if(rotation)ol.render.canvas.rotateAtOffset(context,rotation,offsetX,offsetY);ol.renderer.canvas.TileLayer.prototype.postCompose.apply(this,arguments)};
ol.renderer.canvas.VectorTileLayer.prototype.renderFeature=function(feature,squaredTolerance,styles,replayGroup){if(!styles)return false;var loading=false;if(Array.isArray(styles))for(var i=0,ii=styles.length;i<ii;++i)loading=ol.renderer.vector.renderFeature(replayGroup,feature,styles[i],squaredTolerance,this.handleStyleImageChange_,this)||loading;else loading=ol.renderer.vector.renderFeature(replayGroup,feature,styles,squaredTolerance,this.handleStyleImageChange_,this);return loading};
ol.renderer.canvas.VectorTileLayer.prototype.renderTileImage_=function(tile,frameState,layerState){var layer=this.getLayer();var replayState=tile.getReplayState(layer);var revision=layer.getRevision();var replays=ol.renderer.canvas.VectorTileLayer.IMAGE_REPLAYS[layer.getRenderMode()];if(replays&&replayState.renderedTileRevision!==revision){replayState.renderedTileRevision=revision;var tileCoord=tile.wrappedTileCoord;var z=tileCoord[0];var pixelRatio=frameState.pixelRatio;var source=layer.getSource();
var tileGrid=source.getTileGridForProjection(frameState.viewState.projection);var resolution=tileGrid.getResolution(z);var context=tile.getContext(layer);var size=source.getTilePixelSize(z,pixelRatio,frameState.viewState.projection);context.canvas.width=size[0];context.canvas.height=size[1];var tileExtent=tileGrid.getTileCoordExtent(tileCoord);for(var i=0,ii=tile.tileKeys.length;i<ii;++i){var sourceTile=tile.getTile(tile.tileKeys[i]);if(sourceTile.getState()==ol.TileState.ERROR)continue;var pixelScale=
pixelRatio/resolution;var transform=ol.transform.reset(this.tmpTransform_);ol.transform.scale(transform,pixelScale,-pixelScale);ol.transform.translate(transform,-tileExtent[0],-tileExtent[3]);var replayGroup=sourceTile.getReplayGroup(layer,tile.tileCoord.toString());replayGroup.replay(context,transform,0,{},replays)}}};goog.provide("ol.CanvasMap");goog.require("ol");goog.require("ol.PluggableMap");goog.require("ol.PluginType");goog.require("ol.control");goog.require("ol.interaction");goog.require("ol.obj");goog.require("ol.plugins");goog.require("ol.renderer.canvas.ImageLayer");goog.require("ol.renderer.canvas.Map");goog.require("ol.renderer.canvas.TileLayer");goog.require("ol.renderer.canvas.VectorLayer");goog.require("ol.renderer.canvas.VectorTileLayer");ol.plugins.register(ol.PluginType.MAP_RENDERER,ol.renderer.canvas.Map);
ol.plugins.registerMultiple(ol.PluginType.LAYER_RENDERER,[ol.renderer.canvas.ImageLayer,ol.renderer.canvas.TileLayer,ol.renderer.canvas.VectorLayer,ol.renderer.canvas.VectorTileLayer]);ol.CanvasMap=function(options){options=ol.obj.assign({},options);delete options.renderer;if(!options.controls)options.controls=ol.control.defaults();if(!options.interactions)options.interactions=ol.interaction.defaults();ol.PluggableMap.call(this,options)};ol.inherits(ol.CanvasMap,ol.PluggableMap);goog.provide("ol.control.FullScreen");goog.require("ol");goog.require("ol.control.Control");goog.require("ol.css");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.events.EventType");
ol.control.FullScreen=function(opt_options){var options=opt_options?opt_options:{};this.cssClassName_=options.className!==undefined?options.className:"ol-full-screen";var label=options.label!==undefined?options.label:"\u2922";this.labelNode_=typeof label==="string"?document.createTextNode(label):label;var labelActive=options.labelActive!==undefined?options.labelActive:"\u00d7";this.labelActiveNode_=typeof labelActive==="string"?document.createTextNode(labelActive):labelActive;var tipLabel=options.tipLabel?
options.tipLabel:"Toggle full-screen";var button=document.createElement("button");button.className=this.cssClassName_+"-"+ol.control.FullScreen.isFullScreen();button.setAttribute("type","button");button.title=tipLabel;button.appendChild(this.labelNode_);ol.events.listen(button,ol.events.EventType.CLICK,this.handleClick_,this);var cssClasses=this.cssClassName_+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+" "+(!ol.control.FullScreen.isFullScreenSupported()?ol.css.CLASS_UNSUPPORTED:"");var element=
document.createElement("div");element.className=cssClasses;element.appendChild(button);ol.control.Control.call(this,{element:element,target:options.target});this.keys_=options.keys!==undefined?options.keys:false;this.source_=options.source};ol.inherits(ol.control.FullScreen,ol.control.Control);ol.control.FullScreen.prototype.handleClick_=function(event){event.preventDefault();this.handleFullScreen_()};
ol.control.FullScreen.prototype.handleFullScreen_=function(){if(!ol.control.FullScreen.isFullScreenSupported())return;var map=this.getMap();if(!map)return;if(ol.control.FullScreen.isFullScreen())ol.control.FullScreen.exitFullScreen();else{var element;if(this.source_)element=typeof this.source_==="string"?document.getElementById(this.source_):this.source_;else element=map.getTargetElement();if(this.keys_)ol.control.FullScreen.requestFullScreenWithKeys(element);else ol.control.FullScreen.requestFullScreen(element)}};
ol.control.FullScreen.prototype.handleFullScreenChange_=function(){var button=this.element.firstElementChild;var map=this.getMap();if(ol.control.FullScreen.isFullScreen()){button.className=this.cssClassName_+"-true";ol.dom.replaceNode(this.labelActiveNode_,this.labelNode_)}else{button.className=this.cssClassName_+"-false";ol.dom.replaceNode(this.labelNode_,this.labelActiveNode_)}if(map)map.updateSize()};
ol.control.FullScreen.prototype.setMap=function(map){ol.control.Control.prototype.setMap.call(this,map);if(map)this.listenerKeys.push(ol.events.listen(document,ol.control.FullScreen.getChangeType_(),this.handleFullScreenChange_,this))};ol.control.FullScreen.isFullScreenSupported=function(){var body=document.body;return!!(body.webkitRequestFullscreen||body.mozRequestFullScreen&&document.mozFullScreenEnabled||body.msRequestFullscreen&&document.msFullscreenEnabled||body.requestFullscreen&&document.fullscreenEnabled)};
ol.control.FullScreen.isFullScreen=function(){return!!(document.webkitIsFullScreen||document.mozFullScreen||document.msFullscreenElement||document.fullscreenElement)};ol.control.FullScreen.requestFullScreen=function(element){if(element.requestFullscreen)element.requestFullscreen();else if(element.msRequestFullscreen)element.msRequestFullscreen();else if(element.mozRequestFullScreen)element.mozRequestFullScreen();else if(element.webkitRequestFullscreen)element.webkitRequestFullscreen()};
ol.control.FullScreen.requestFullScreenWithKeys=function(element){if(element.mozRequestFullScreenWithKeys)element.mozRequestFullScreenWithKeys();else if(element.webkitRequestFullscreen)element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);else ol.control.FullScreen.requestFullScreen(element)};
ol.control.FullScreen.exitFullScreen=function(){if(document.exitFullscreen)document.exitFullscreen();else if(document.msExitFullscreen)document.msExitFullscreen();else if(document.mozCancelFullScreen)document.mozCancelFullScreen();else if(document.webkitExitFullscreen)document.webkitExitFullscreen()};
ol.control.FullScreen.getChangeType_=function(){var changeType;return function(){if(!changeType){var body=document.body;if(body.webkitRequestFullscreen)changeType="webkitfullscreenchange";else if(body.mozRequestFullScreen)changeType="mozfullscreenchange";else if(body.msRequestFullscreen)changeType="MSFullscreenChange";else if(body.requestFullscreen)changeType="fullscreenchange"}return changeType}}();goog.provide("ol.control.MousePosition");goog.require("ol");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.Object");goog.require("ol.control.Control");goog.require("ol.proj");
ol.control.MousePosition=function(opt_options){var options=opt_options?opt_options:{};var element=document.createElement("DIV");element.className=options.className!==undefined?options.className:"ol-mouse-position";var render=options.render?options.render:ol.control.MousePosition.render;ol.control.Control.call(this,{element:element,render:render,target:options.target});ol.events.listen(this,ol.Object.getChangeEventType(ol.control.MousePosition.Property_.PROJECTION),this.handleProjectionChanged_,this);
if(options.coordinateFormat)this.setCoordinateFormat(options.coordinateFormat);if(options.projection)this.setProjection(options.projection);this.undefinedHTML_=options.undefinedHTML!==undefined?options.undefinedHTML:"";this.renderedHTML_=element.innerHTML;this.mapProjection_=null;this.transform_=null;this.lastMouseMovePixel_=null};ol.inherits(ol.control.MousePosition,ol.control.Control);
ol.control.MousePosition.render=function(mapEvent){var frameState=mapEvent.frameState;if(!frameState)this.mapProjection_=null;else if(this.mapProjection_!=frameState.viewState.projection){this.mapProjection_=frameState.viewState.projection;this.transform_=null}this.updateHTML_(this.lastMouseMovePixel_)};ol.control.MousePosition.prototype.handleProjectionChanged_=function(){this.transform_=null};ol.control.MousePosition.prototype.getCoordinateFormat=function(){return this.get(ol.control.MousePosition.Property_.COORDINATE_FORMAT)};
ol.control.MousePosition.prototype.getProjection=function(){return this.get(ol.control.MousePosition.Property_.PROJECTION)};ol.control.MousePosition.prototype.handleMouseMove=function(event){var map=this.getMap();this.lastMouseMovePixel_=map.getEventPixel(event);this.updateHTML_(this.lastMouseMovePixel_)};ol.control.MousePosition.prototype.handleMouseOut=function(event){this.updateHTML_(null);this.lastMouseMovePixel_=null};
ol.control.MousePosition.prototype.setMap=function(map){ol.control.Control.prototype.setMap.call(this,map);if(map){var viewport=map.getViewport();this.listenerKeys.push(ol.events.listen(viewport,ol.events.EventType.MOUSEMOVE,this.handleMouseMove,this),ol.events.listen(viewport,ol.events.EventType.MOUSEOUT,this.handleMouseOut,this))}};ol.control.MousePosition.prototype.setCoordinateFormat=function(format){this.set(ol.control.MousePosition.Property_.COORDINATE_FORMAT,format)};
ol.control.MousePosition.prototype.setProjection=function(projection){this.set(ol.control.MousePosition.Property_.PROJECTION,ol.proj.get(projection))};
ol.control.MousePosition.prototype.updateHTML_=function(pixel){var html=this.undefinedHTML_;if(pixel&&this.mapProjection_){if(!this.transform_){var projection=this.getProjection();if(projection)this.transform_=ol.proj.getTransformFromProjections(this.mapProjection_,projection);else this.transform_=ol.proj.identityTransform}var map=this.getMap();var coordinate=map.getCoordinateFromPixel(pixel);if(coordinate){this.transform_(coordinate,coordinate);var coordinateFormat=this.getCoordinateFormat();if(coordinateFormat)html=
coordinateFormat(coordinate);else html=coordinate.toString()}}if(!this.renderedHTML_||html!=this.renderedHTML_){this.element.innerHTML=html;this.renderedHTML_=html}};ol.control.MousePosition.Property_={PROJECTION:"projection",COORDINATE_FORMAT:"coordinateFormat"};goog.provide("ol.OverlayPositioning");ol.OverlayPositioning={BOTTOM_LEFT:"bottom-left",BOTTOM_CENTER:"bottom-center",BOTTOM_RIGHT:"bottom-right",CENTER_LEFT:"center-left",CENTER_CENTER:"center-center",CENTER_RIGHT:"center-right",TOP_LEFT:"top-left",TOP_CENTER:"top-center",TOP_RIGHT:"top-right"};goog.provide("ol.Overlay");goog.require("ol");goog.require("ol.MapEventType");goog.require("ol.Object");goog.require("ol.OverlayPositioning");goog.require("ol.css");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.extent");
ol.Overlay=function(options){ol.Object.call(this);this.options=options;this.id=options.id;this.insertFirst=options.insertFirst!==undefined?options.insertFirst:true;this.stopEvent=options.stopEvent!==undefined?options.stopEvent:true;this.element=document.createElement("DIV");this.element.className=options.className!==undefined?options.className:"ol-overlay-container "+ol.css.CLASS_SELECTABLE;this.element.style.position="absolute";this.autoPan=options.autoPan!==undefined?options.autoPan:false;this.autoPanAnimation=
options.autoPanAnimation||{};this.autoPanMargin=options.autoPanMargin!==undefined?options.autoPanMargin:20;this.rendered={bottom_:"",left_:"",right_:"",top_:"",visible:true};this.mapPostrenderListenerKey=null;ol.events.listen(this,ol.Object.getChangeEventType(ol.Overlay.Property.ELEMENT),this.handleElementChanged,this);ol.events.listen(this,ol.Object.getChangeEventType(ol.Overlay.Property.MAP),this.handleMapChanged,this);ol.events.listen(this,ol.Object.getChangeEventType(ol.Overlay.Property.OFFSET),
this.handleOffsetChanged,this);ol.events.listen(this,ol.Object.getChangeEventType(ol.Overlay.Property.POSITION),this.handlePositionChanged,this);ol.events.listen(this,ol.Object.getChangeEventType(ol.Overlay.Property.POSITIONING),this.handlePositioningChanged,this);if(options.element!==undefined)this.setElement(options.element);this.setOffset(options.offset!==undefined?options.offset:[0,0]);this.setPositioning(options.positioning!==undefined?options.positioning:ol.OverlayPositioning.TOP_LEFT);if(options.position!==
undefined)this.setPosition(options.position)};ol.inherits(ol.Overlay,ol.Object);ol.Overlay.prototype.getElement=function(){return this.get(ol.Overlay.Property.ELEMENT)};ol.Overlay.prototype.getId=function(){return this.id};ol.Overlay.prototype.getMap=function(){return this.get(ol.Overlay.Property.MAP)};ol.Overlay.prototype.getOffset=function(){return this.get(ol.Overlay.Property.OFFSET)};ol.Overlay.prototype.getPosition=function(){return this.get(ol.Overlay.Property.POSITION)};
ol.Overlay.prototype.getPositioning=function(){return this.get(ol.Overlay.Property.POSITIONING)};ol.Overlay.prototype.handleElementChanged=function(){ol.dom.removeChildren(this.element);var element=this.getElement();if(element)this.element.appendChild(element)};
ol.Overlay.prototype.handleMapChanged=function(){if(this.mapPostrenderListenerKey){ol.dom.removeNode(this.element);ol.events.unlistenByKey(this.mapPostrenderListenerKey);this.mapPostrenderListenerKey=null}var map=this.getMap();if(map){this.mapPostrenderListenerKey=ol.events.listen(map,ol.MapEventType.POSTRENDER,this.render,this);this.updatePixelPosition();var container=this.stopEvent?map.getOverlayContainerStopEvent():map.getOverlayContainer();if(this.insertFirst)container.insertBefore(this.element,
container.childNodes[0]||null);else container.appendChild(this.element)}};ol.Overlay.prototype.render=function(){this.updatePixelPosition()};ol.Overlay.prototype.handleOffsetChanged=function(){this.updatePixelPosition()};ol.Overlay.prototype.handlePositionChanged=function(){this.updatePixelPosition();if(this.get(ol.Overlay.Property.POSITION)&&this.autoPan)this.panIntoView()};ol.Overlay.prototype.handlePositioningChanged=function(){this.updatePixelPosition()};
ol.Overlay.prototype.setElement=function(element){this.set(ol.Overlay.Property.ELEMENT,element)};ol.Overlay.prototype.setMap=function(map){this.set(ol.Overlay.Property.MAP,map)};ol.Overlay.prototype.setOffset=function(offset){this.set(ol.Overlay.Property.OFFSET,offset)};ol.Overlay.prototype.setPosition=function(position){this.set(ol.Overlay.Property.POSITION,position)};
ol.Overlay.prototype.panIntoView=function(){var map=this.getMap();if(!map||!map.getTargetElement())return;var mapRect=this.getRect(map.getTargetElement(),map.getSize());var element=this.getElement();var overlayRect=this.getRect(element,[ol.dom.outerWidth(element),ol.dom.outerHeight(element)]);var margin=this.autoPanMargin;if(!ol.extent.containsExtent(mapRect,overlayRect)){var offsetLeft=overlayRect[0]-mapRect[0];var offsetRight=mapRect[2]-overlayRect[2];var offsetTop=overlayRect[1]-mapRect[1];var offsetBottom=
mapRect[3]-overlayRect[3];var delta=[0,0];if(offsetLeft<0)delta[0]=offsetLeft-margin;else if(offsetRight<0)delta[0]=Math.abs(offsetRight)+margin;if(offsetTop<0)delta[1]=offsetTop-margin;else if(offsetBottom<0)delta[1]=Math.abs(offsetBottom)+margin;if(delta[0]!==0||delta[1]!==0){var center=map.getView().getCenter();var centerPx=map.getPixelFromCoordinate(center);var newCenterPx=[centerPx[0]+delta[0],centerPx[1]+delta[1]];map.getView().animate({center:map.getCoordinateFromPixel(newCenterPx),duration:this.autoPanAnimation.duration,
easing:this.autoPanAnimation.easing})}}};ol.Overlay.prototype.getRect=function(element,size){var box=element.getBoundingClientRect();var offsetX=box.left+window.pageXOffset;var offsetY=box.top+window.pageYOffset;return[offsetX,offsetY,offsetX+size[0],offsetY+size[1]]};ol.Overlay.prototype.setPositioning=function(positioning){this.set(ol.Overlay.Property.POSITIONING,positioning)};
ol.Overlay.prototype.setVisible=function(visible){if(this.rendered.visible!==visible){this.element.style.display=visible?"":"none";this.rendered.visible=visible}};ol.Overlay.prototype.updatePixelPosition=function(){var map=this.getMap();var position=this.getPosition();if(!map||!map.isRendered()||!position){this.setVisible(false);return}var pixel=map.getPixelFromCoordinate(position);var mapSize=map.getSize();this.updateRenderedPosition(pixel,mapSize)};
ol.Overlay.prototype.updateRenderedPosition=function(pixel,mapSize){var style=this.element.style;var offset=this.getOffset();var positioning=this.getPositioning();this.setVisible(true);var offsetX=offset[0];var offsetY=offset[1];if(positioning==ol.OverlayPositioning.BOTTOM_RIGHT||positioning==ol.OverlayPositioning.CENTER_RIGHT||positioning==ol.OverlayPositioning.TOP_RIGHT){if(this.rendered.left_!=="")this.rendered.left_=style.left="";var right=Math.round(mapSize[0]-pixel[0]-offsetX)+"px";if(this.rendered.right_!=
right)this.rendered.right_=style.right=right}else{if(this.rendered.right_!=="")this.rendered.right_=style.right="";if(positioning==ol.OverlayPositioning.BOTTOM_CENTER||positioning==ol.OverlayPositioning.CENTER_CENTER||positioning==ol.OverlayPositioning.TOP_CENTER)offsetX-=this.element.offsetWidth/2;var left=Math.round(pixel[0]+offsetX)+"px";if(this.rendered.left_!=left)this.rendered.left_=style.left=left}if(positioning==ol.OverlayPositioning.BOTTOM_LEFT||positioning==ol.OverlayPositioning.BOTTOM_CENTER||
positioning==ol.OverlayPositioning.BOTTOM_RIGHT){if(this.rendered.top_!=="")this.rendered.top_=style.top="";var bottom=Math.round(mapSize[1]-pixel[1]-offsetY)+"px";if(this.rendered.bottom_!=bottom)this.rendered.bottom_=style.bottom=bottom}else{if(this.rendered.bottom_!=="")this.rendered.bottom_=style.bottom="";if(positioning==ol.OverlayPositioning.CENTER_LEFT||positioning==ol.OverlayPositioning.CENTER_CENTER||positioning==ol.OverlayPositioning.CENTER_RIGHT)offsetY-=this.element.offsetHeight/2;var top=
Math.round(pixel[1]+offsetY)+"px";if(this.rendered.top_!=top)this.rendered.top_=style.top=top}};ol.Overlay.prototype.getOptions=function(){return this.options};ol.Overlay.Property={ELEMENT:"element",MAP:"map",OFFSET:"offset",POSITION:"position",POSITIONING:"positioning"};goog.provide("ol.control.OverviewMap");goog.require("ol");goog.require("ol.Collection");goog.require("ol.PluggableMap");goog.require("ol.MapEventType");goog.require("ol.MapProperty");goog.require("ol.Object");goog.require("ol.ObjectEventType");goog.require("ol.Overlay");goog.require("ol.OverlayPositioning");goog.require("ol.ViewProperty");goog.require("ol.control.Control");goog.require("ol.coordinate");goog.require("ol.css");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.events.EventType");
goog.require("ol.extent");
ol.control.OverviewMap=function(opt_options){var options=opt_options?opt_options:{};this.collapsed_=options.collapsed!==undefined?options.collapsed:true;this.collapsible_=options.collapsible!==undefined?options.collapsible:true;if(!this.collapsible_)this.collapsed_=false;var className=options.className!==undefined?options.className:"ol-overviewmap";var tipLabel=options.tipLabel!==undefined?options.tipLabel:"Overview map";var collapseLabel=options.collapseLabel!==undefined?options.collapseLabel:"\u00ab";
if(typeof collapseLabel==="string"){this.collapseLabel_=document.createElement("span");this.collapseLabel_.textContent=collapseLabel}else this.collapseLabel_=collapseLabel;var label=options.label!==undefined?options.label:"\u00bb";if(typeof label==="string"){this.label_=document.createElement("span");this.label_.textContent=label}else this.label_=label;var activeLabel=this.collapsible_&&!this.collapsed_?this.collapseLabel_:this.label_;var button=document.createElement("button");button.setAttribute("type",
"button");button.title=tipLabel;button.appendChild(activeLabel);ol.events.listen(button,ol.events.EventType.CLICK,this.handleClick_,this);this.ovmapDiv_=document.createElement("DIV");this.ovmapDiv_.className="ol-overviewmap-map";this.ovmap_=new ol.PluggableMap({controls:new ol.Collection,interactions:new ol.Collection,view:options.view});var ovmap=this.ovmap_;if(options.layers)options.layers.forEach(function(layer){ovmap.addLayer(layer)},this);var box=document.createElement("DIV");box.className="ol-overviewmap-box";
box.style.boxSizing="border-box";this.boxOverlay_=new ol.Overlay({position:[0,0],positioning:ol.OverlayPositioning.BOTTOM_LEFT,element:box});this.ovmap_.addOverlay(this.boxOverlay_);var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+(this.collapsed_&&this.collapsible_?" ol-collapsed":"")+(this.collapsible_?"":" ol-uncollapsible");var element=document.createElement("div");element.className=cssClasses;element.appendChild(this.ovmapDiv_);element.appendChild(button);var render=
options.render?options.render:ol.control.OverviewMap.render;ol.control.Control.call(this,{element:element,render:render,target:options.target});var scope=this;var overlay=this.boxOverlay_;var overlayBox=this.boxOverlay_.getElement();var computeDesiredMousePosition=function(mousePosition){return{clientX:mousePosition.clientX-overlayBox.offsetWidth/2,clientY:mousePosition.clientY+overlayBox.offsetHeight/2}};var move=function(event){var coordinates=ovmap.getEventCoordinate(computeDesiredMousePosition(event));
overlay.setPosition(coordinates)};var endMoving=function(event){var coordinates=ovmap.getEventCoordinate(event);scope.getMap().getView().setCenter(coordinates);window.removeEventListener("mousemove",move);window.removeEventListener("mouseup",endMoving)};overlayBox.addEventListener("mousedown",function(){window.addEventListener("mousemove",move);window.addEventListener("mouseup",endMoving)})};ol.inherits(ol.control.OverviewMap,ol.control.Control);
ol.control.OverviewMap.prototype.setMap=function(map){var oldMap=this.getMap();if(map===oldMap)return;if(oldMap){var oldView=oldMap.getView();if(oldView)this.unbindView_(oldView);this.ovmap_.setTarget(null)}ol.control.Control.prototype.setMap.call(this,map);if(map){this.ovmap_.setTarget(this.ovmapDiv_);this.listenerKeys.push(ol.events.listen(map,ol.ObjectEventType.PROPERTYCHANGE,this.handleMapPropertyChange_,this));if(this.ovmap_.getLayers().getLength()===0)this.ovmap_.setLayerGroup(map.getLayerGroup());
var view=map.getView();if(view){this.bindView_(view);if(view.isDef()){this.ovmap_.updateSize();this.resetExtent_()}}}};ol.control.OverviewMap.prototype.handleMapPropertyChange_=function(event){if(event.key===ol.MapProperty.VIEW){var oldView=event.oldValue;if(oldView)this.unbindView_(oldView);var newView=this.getMap().getView();this.bindView_(newView)}};
ol.control.OverviewMap.prototype.bindView_=function(view){ol.events.listen(view,ol.Object.getChangeEventType(ol.ViewProperty.ROTATION),this.handleRotationChanged_,this)};ol.control.OverviewMap.prototype.unbindView_=function(view){ol.events.unlisten(view,ol.Object.getChangeEventType(ol.ViewProperty.ROTATION),this.handleRotationChanged_,this)};ol.control.OverviewMap.prototype.handleRotationChanged_=function(){this.ovmap_.getView().setRotation(this.getMap().getView().getRotation())};
ol.control.OverviewMap.render=function(mapEvent){this.validateExtent_();this.updateBox_()};
ol.control.OverviewMap.prototype.validateExtent_=function(){var map=this.getMap();var ovmap=this.ovmap_;if(!map.isRendered()||!ovmap.isRendered())return;var mapSize=map.getSize();var view=map.getView();var extent=view.calculateExtent(mapSize);var ovmapSize=ovmap.getSize();var ovview=ovmap.getView();var ovextent=ovview.calculateExtent(ovmapSize);var topLeftPixel=ovmap.getPixelFromCoordinate(ol.extent.getTopLeft(extent));var bottomRightPixel=ovmap.getPixelFromCoordinate(ol.extent.getBottomRight(extent));
var boxWidth=Math.abs(topLeftPixel[0]-bottomRightPixel[0]);var boxHeight=Math.abs(topLeftPixel[1]-bottomRightPixel[1]);var ovmapWidth=ovmapSize[0];var ovmapHeight=ovmapSize[1];if(boxWidth<ovmapWidth*ol.OVERVIEWMAP_MIN_RATIO||boxHeight<ovmapHeight*ol.OVERVIEWMAP_MIN_RATIO||boxWidth>ovmapWidth*ol.OVERVIEWMAP_MAX_RATIO||boxHeight>ovmapHeight*ol.OVERVIEWMAP_MAX_RATIO)this.resetExtent_();else if(!ol.extent.containsExtent(ovextent,extent))this.recenter_()};
ol.control.OverviewMap.prototype.resetExtent_=function(){if(ol.OVERVIEWMAP_MAX_RATIO===0||ol.OVERVIEWMAP_MIN_RATIO===0)return;var map=this.getMap();var ovmap=this.ovmap_;var mapSize=map.getSize();var view=map.getView();var extent=view.calculateExtent(mapSize);var ovview=ovmap.getView();var steps=Math.log(ol.OVERVIEWMAP_MAX_RATIO/ol.OVERVIEWMAP_MIN_RATIO)/Math.LN2;var ratio=1/(Math.pow(2,steps/2)*ol.OVERVIEWMAP_MIN_RATIO);ol.extent.scaleFromCenter(extent,ratio);ovview.fit(extent)};
ol.control.OverviewMap.prototype.recenter_=function(){var map=this.getMap();var ovmap=this.ovmap_;var view=map.getView();var ovview=ovmap.getView();ovview.setCenter(view.getCenter())};
ol.control.OverviewMap.prototype.updateBox_=function(){var map=this.getMap();var ovmap=this.ovmap_;if(!map.isRendered()||!ovmap.isRendered())return;var mapSize=map.getSize();var view=map.getView();var ovview=ovmap.getView();var rotation=view.getRotation();var overlay=this.boxOverlay_;var box=this.boxOverlay_.getElement();var extent=view.calculateExtent(mapSize);var ovresolution=ovview.getResolution();var bottomLeft=ol.extent.getBottomLeft(extent);var topRight=ol.extent.getTopRight(extent);var rotateBottomLeft=
this.calculateCoordinateRotate_(rotation,bottomLeft);overlay.setPosition(rotateBottomLeft);if(box){box.style.width=Math.abs((bottomLeft[0]-topRight[0])/ovresolution)+"px";box.style.height=Math.abs((topRight[1]-bottomLeft[1])/ovresolution)+"px"}};
ol.control.OverviewMap.prototype.calculateCoordinateRotate_=function(rotation,coordinate){var coordinateRotate;var map=this.getMap();var view=map.getView();var currentCenter=view.getCenter();if(currentCenter){coordinateRotate=[coordinate[0]-currentCenter[0],coordinate[1]-currentCenter[1]];ol.coordinate.rotate(coordinateRotate,rotation);ol.coordinate.add(coordinateRotate,currentCenter)}return coordinateRotate};ol.control.OverviewMap.prototype.handleClick_=function(event){event.preventDefault();this.handleToggle_()};
ol.control.OverviewMap.prototype.handleToggle_=function(){this.element.classList.toggle("ol-collapsed");if(this.collapsed_)ol.dom.replaceNode(this.collapseLabel_,this.label_);else ol.dom.replaceNode(this.label_,this.collapseLabel_);this.collapsed_=!this.collapsed_;var ovmap=this.ovmap_;if(!this.collapsed_&&!ovmap.isRendered()){ovmap.updateSize();this.resetExtent_();ol.events.listenOnce(ovmap,ol.MapEventType.POSTRENDER,function(event){this.updateBox_()},this)}};
ol.control.OverviewMap.prototype.getCollapsible=function(){return this.collapsible_};ol.control.OverviewMap.prototype.setCollapsible=function(collapsible){if(this.collapsible_===collapsible)return;this.collapsible_=collapsible;this.element.classList.toggle("ol-uncollapsible");if(!collapsible&&this.collapsed_)this.handleToggle_()};ol.control.OverviewMap.prototype.setCollapsed=function(collapsed){if(!this.collapsible_||this.collapsed_===collapsed)return;this.handleToggle_()};
ol.control.OverviewMap.prototype.getCollapsed=function(){return this.collapsed_};ol.control.OverviewMap.prototype.getOverviewMap=function(){return this.ovmap_};goog.provide("ol.control.ScaleLineUnits");ol.control.ScaleLineUnits={DEGREES:"degrees",IMPERIAL:"imperial",NAUTICAL:"nautical",METRIC:"metric",US:"us"};goog.provide("ol.control.ScaleLine");goog.require("ol");goog.require("ol.Object");goog.require("ol.asserts");goog.require("ol.control.Control");goog.require("ol.control.ScaleLineUnits");goog.require("ol.css");goog.require("ol.events");goog.require("ol.proj");goog.require("ol.proj.Units");
ol.control.ScaleLine=function(opt_options){var options=opt_options?opt_options:{};var className=options.className!==undefined?options.className:"ol-scale-line";this.innerElement_=document.createElement("DIV");this.innerElement_.className=className+"-inner";this.element_=document.createElement("DIV");this.element_.className=className+" "+ol.css.CLASS_UNSELECTABLE;this.element_.appendChild(this.innerElement_);this.viewState_=null;this.minWidth_=options.minWidth!==undefined?options.minWidth:64;this.renderedVisible_=
false;this.renderedWidth_=undefined;this.renderedHTML_="";var render=options.render?options.render:ol.control.ScaleLine.render;ol.control.Control.call(this,{element:this.element_,render:render,target:options.target});ol.events.listen(this,ol.Object.getChangeEventType(ol.control.ScaleLine.Property_.UNITS),this.handleUnitsChanged_,this);this.setUnits(options.units||ol.control.ScaleLineUnits.METRIC)};ol.inherits(ol.control.ScaleLine,ol.control.Control);ol.control.ScaleLine.LEADING_DIGITS=[1,2,5];
ol.control.ScaleLine.prototype.getUnits=function(){return this.get(ol.control.ScaleLine.Property_.UNITS)};ol.control.ScaleLine.render=function(mapEvent){var frameState=mapEvent.frameState;if(!frameState)this.viewState_=null;else this.viewState_=frameState.viewState;this.updateElement_()};ol.control.ScaleLine.prototype.handleUnitsChanged_=function(){this.updateElement_()};ol.control.ScaleLine.prototype.setUnits=function(units){this.set(ol.control.ScaleLine.Property_.UNITS,units)};
ol.control.ScaleLine.prototype.updateElement_=function(){var viewState=this.viewState_;if(!viewState){if(this.renderedVisible_){this.element_.style.display="none";this.renderedVisible_=false}return}var center=viewState.center;var projection=viewState.projection;var units=this.getUnits();var pointResolutionUnits=units==ol.control.ScaleLineUnits.DEGREES?ol.proj.Units.DEGREES:ol.proj.Units.METERS;var pointResolution=ol.proj.getPointResolution(projection,viewState.resolution,center,pointResolutionUnits);
if(units!=ol.control.ScaleLineUnits.DEGREES)pointResolution*=projection.getMetersPerUnit();var nominalCount=this.minWidth_*pointResolution;var suffix="";if(units==ol.control.ScaleLineUnits.DEGREES){var metersPerDegree=ol.proj.METERS_PER_UNIT[ol.proj.Units.DEGREES];if(projection.getUnits()==ol.proj.Units.DEGREES)nominalCount*=metersPerDegree;else pointResolution/=metersPerDegree;if(nominalCount<metersPerDegree/60){suffix="\u2033";pointResolution*=3600}else if(nominalCount<metersPerDegree){suffix="\u2032";
pointResolution*=60}else suffix="\u00b0"}else if(units==ol.control.ScaleLineUnits.IMPERIAL)if(nominalCount<.9144){suffix="in";pointResolution/=.0254}else if(nominalCount<1609.344){suffix="ft";pointResolution/=.3048}else{suffix="mi";pointResolution/=1609.344}else if(units==ol.control.ScaleLineUnits.NAUTICAL){pointResolution/=1852;suffix="nm"}else if(units==ol.control.ScaleLineUnits.METRIC)if(nominalCount<.001){suffix="\u03bcm";pointResolution*=1E6}else if(nominalCount<1){suffix="mm";pointResolution*=
1E3}else if(nominalCount<1E3)suffix="m";else{suffix="km";pointResolution/=1E3}else if(units==ol.control.ScaleLineUnits.US)if(nominalCount<.9144){suffix="in";pointResolution*=39.37}else if(nominalCount<1609.344){suffix="ft";pointResolution/=.30480061}else{suffix="mi";pointResolution/=1609.3472}else ol.asserts.assert(false,33);var i=3*Math.floor(Math.log(this.minWidth_*pointResolution)/Math.log(10));var count,width;while(true){count=ol.control.ScaleLine.LEADING_DIGITS[(i%3+3)%3]*Math.pow(10,Math.floor(i/
3));width=Math.round(count/pointResolution);if(isNaN(width)){this.element_.style.display="none";this.renderedVisible_=false;return}else if(width>=this.minWidth_)break;++i}var html=count+" "+suffix;if(this.renderedHTML_!=html){this.innerElement_.innerHTML=html;this.renderedHTML_=html}if(this.renderedWidth_!=width){this.innerElement_.style.width=width+"px";this.renderedWidth_=width}if(!this.renderedVisible_){this.element_.style.display="";this.renderedVisible_=true}};
ol.control.ScaleLine.Property_={UNITS:"units"};goog.provide("ol.control.ZoomSlider");goog.require("ol");goog.require("ol.ViewHint");goog.require("ol.control.Control");goog.require("ol.css");goog.require("ol.easing");goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.events.EventType");goog.require("ol.math");goog.require("ol.pointer.EventType");goog.require("ol.pointer.PointerEventHandler");
ol.control.ZoomSlider=function(opt_options){var options=opt_options?opt_options:{};this.currentResolution_=undefined;this.direction_=ol.control.ZoomSlider.Direction_.VERTICAL;this.dragging_;this.heightLimit_=0;this.widthLimit_=0;this.previousX_;this.previousY_;this.thumbSize_=null;this.sliderInitialized_=false;this.duration_=options.duration!==undefined?options.duration:200;var className=options.className!==undefined?options.className:"ol-zoomslider";var thumbElement=document.createElement("button");
thumbElement.setAttribute("type","button");thumbElement.className=className+"-thumb "+ol.css.CLASS_UNSELECTABLE;var containerElement=document.createElement("div");containerElement.className=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL;containerElement.appendChild(thumbElement);this.dragger_=new ol.pointer.PointerEventHandler(containerElement);ol.events.listen(this.dragger_,ol.pointer.EventType.POINTERDOWN,this.handleDraggerStart_,this);ol.events.listen(this.dragger_,ol.pointer.EventType.POINTERMOVE,
this.handleDraggerDrag_,this);ol.events.listen(this.dragger_,ol.pointer.EventType.POINTERUP,this.handleDraggerEnd_,this);ol.events.listen(containerElement,ol.events.EventType.CLICK,this.handleContainerClick_,this);ol.events.listen(thumbElement,ol.events.EventType.CLICK,ol.events.Event.stopPropagation);var render=options.render?options.render:ol.control.ZoomSlider.render;ol.control.Control.call(this,{element:containerElement,render:render})};ol.inherits(ol.control.ZoomSlider,ol.control.Control);
ol.control.ZoomSlider.prototype.disposeInternal=function(){this.dragger_.dispose();ol.control.Control.prototype.disposeInternal.call(this)};ol.control.ZoomSlider.Direction_={VERTICAL:0,HORIZONTAL:1};ol.control.ZoomSlider.prototype.setMap=function(map){ol.control.Control.prototype.setMap.call(this,map);if(map)map.render()};
ol.control.ZoomSlider.prototype.initSlider_=function(){var container=this.element;var containerSize={width:container.offsetWidth,height:container.offsetHeight};var thumb=container.firstElementChild;var computedStyle=getComputedStyle(thumb);var thumbWidth=thumb.offsetWidth+parseFloat(computedStyle["marginRight"])+parseFloat(computedStyle["marginLeft"]);var thumbHeight=thumb.offsetHeight+parseFloat(computedStyle["marginTop"])+parseFloat(computedStyle["marginBottom"]);this.thumbSize_=[thumbWidth,thumbHeight];
if(containerSize.width>containerSize.height){this.direction_=ol.control.ZoomSlider.Direction_.HORIZONTAL;this.widthLimit_=containerSize.width-thumbWidth}else{this.direction_=ol.control.ZoomSlider.Direction_.VERTICAL;this.heightLimit_=containerSize.height-thumbHeight}this.sliderInitialized_=true};
ol.control.ZoomSlider.render=function(mapEvent){if(!mapEvent.frameState)return;if(!this.sliderInitialized_)this.initSlider_();var res=mapEvent.frameState.viewState.resolution;if(res!==this.currentResolution_){this.currentResolution_=res;this.setThumbPosition_(res)}};
ol.control.ZoomSlider.prototype.handleContainerClick_=function(event){var view=this.getMap().getView();var relativePosition=this.getRelativePosition_(event.offsetX-this.thumbSize_[0]/2,event.offsetY-this.thumbSize_[1]/2);var resolution=this.getResolutionForPosition_(relativePosition);view.animate({resolution:view.constrainResolution(resolution),duration:this.duration_,easing:ol.easing.easeOut})};
ol.control.ZoomSlider.prototype.handleDraggerStart_=function(event){if(!this.dragging_&&event.originalEvent.target===this.element.firstElementChild){this.getMap().getView().setHint(ol.ViewHint.INTERACTING,1);this.previousX_=event.clientX;this.previousY_=event.clientY;this.dragging_=true}};
ol.control.ZoomSlider.prototype.handleDraggerDrag_=function(event){if(this.dragging_){var element=this.element.firstElementChild;var deltaX=event.clientX-this.previousX_+parseInt(element.style.left,10);var deltaY=event.clientY-this.previousY_+parseInt(element.style.top,10);var relativePosition=this.getRelativePosition_(deltaX,deltaY);this.currentResolution_=this.getResolutionForPosition_(relativePosition);this.getMap().getView().setResolution(this.currentResolution_);this.setThumbPosition_(this.currentResolution_);
this.previousX_=event.clientX;this.previousY_=event.clientY}};ol.control.ZoomSlider.prototype.handleDraggerEnd_=function(event){if(this.dragging_){var view=this.getMap().getView();view.setHint(ol.ViewHint.INTERACTING,-1);view.animate({resolution:view.constrainResolution(this.currentResolution_),duration:this.duration_,easing:ol.easing.easeOut});this.dragging_=false;this.previousX_=undefined;this.previousY_=undefined}};
ol.control.ZoomSlider.prototype.setThumbPosition_=function(res){var position=this.getPositionForResolution_(res);var thumb=this.element.firstElementChild;if(this.direction_==ol.control.ZoomSlider.Direction_.HORIZONTAL)thumb.style.left=this.widthLimit_*position+"px";else thumb.style.top=this.heightLimit_*position+"px"};
ol.control.ZoomSlider.prototype.getRelativePosition_=function(x,y){var amount;if(this.direction_===ol.control.ZoomSlider.Direction_.HORIZONTAL)amount=x/this.widthLimit_;else amount=y/this.heightLimit_;return ol.math.clamp(amount,0,1)};ol.control.ZoomSlider.prototype.getResolutionForPosition_=function(position){var fn=this.getMap().getView().getResolutionForValueFunction();return fn(1-position)};
ol.control.ZoomSlider.prototype.getPositionForResolution_=function(res){var fn=this.getMap().getView().getValueForResolutionFunction();return 1-fn(res)};goog.provide("ol.control.ZoomToExtent");goog.require("ol");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.control.Control");goog.require("ol.css");
ol.control.ZoomToExtent=function(opt_options){var options=opt_options?opt_options:{};this.extent=options.extent?options.extent:null;var className=options.className!==undefined?options.className:"ol-zoom-extent";var label=options.label!==undefined?options.label:"E";var tipLabel=options.tipLabel!==undefined?options.tipLabel:"Fit to extent";var button=document.createElement("button");button.setAttribute("type","button");button.title=tipLabel;button.appendChild(typeof label==="string"?document.createTextNode(label):
label);ol.events.listen(button,ol.events.EventType.CLICK,this.handleClick_,this);var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL;var element=document.createElement("div");element.className=cssClasses;element.appendChild(button);ol.control.Control.call(this,{element:element,target:options.target})};ol.inherits(ol.control.ZoomToExtent,ol.control.Control);ol.control.ZoomToExtent.prototype.handleClick_=function(event){event.preventDefault();this.handleZoomToExtent()};
ol.control.ZoomToExtent.prototype.handleZoomToExtent=function(){var map=this.getMap();var view=map.getView();var extent=!this.extent?view.getProjection().getExtent():this.extent;view.fit(extent)};goog.provide("ol.DeviceOrientation");goog.require("ol.events");goog.require("ol");goog.require("ol.Object");goog.require("ol.has");goog.require("ol.math");ol.DeviceOrientation=function(opt_options){ol.Object.call(this);var options=opt_options?opt_options:{};this.listenerKey_=null;ol.events.listen(this,ol.Object.getChangeEventType(ol.DeviceOrientation.Property_.TRACKING),this.handleTrackingChanged_,this);this.setTracking(options.tracking!==undefined?options.tracking:false)};
ol.inherits(ol.DeviceOrientation,ol.Object);ol.DeviceOrientation.prototype.disposeInternal=function(){this.setTracking(false);ol.Object.prototype.disposeInternal.call(this)};
ol.DeviceOrientation.prototype.orientationChange_=function(originalEvent){var event=originalEvent;if(event.alpha!==null){var alpha=ol.math.toRadians(event.alpha);this.set(ol.DeviceOrientation.Property_.ALPHA,alpha);if(typeof event.absolute==="boolean"&&event.absolute)this.set(ol.DeviceOrientation.Property_.HEADING,alpha);else if(typeof event.webkitCompassHeading==="number"&&event.webkitCompassAccuracy!=-1){var heading=ol.math.toRadians(event.webkitCompassHeading);this.set(ol.DeviceOrientation.Property_.HEADING,
heading)}}if(event.beta!==null)this.set(ol.DeviceOrientation.Property_.BETA,ol.math.toRadians(event.beta));if(event.gamma!==null)this.set(ol.DeviceOrientation.Property_.GAMMA,ol.math.toRadians(event.gamma));this.changed()};ol.DeviceOrientation.prototype.getAlpha=function(){return this.get(ol.DeviceOrientation.Property_.ALPHA)};ol.DeviceOrientation.prototype.getBeta=function(){return this.get(ol.DeviceOrientation.Property_.BETA)};ol.DeviceOrientation.prototype.getGamma=function(){return this.get(ol.DeviceOrientation.Property_.GAMMA)};
ol.DeviceOrientation.prototype.getHeading=function(){return this.get(ol.DeviceOrientation.Property_.HEADING)};ol.DeviceOrientation.prototype.getTracking=function(){return this.get(ol.DeviceOrientation.Property_.TRACKING)};
ol.DeviceOrientation.prototype.handleTrackingChanged_=function(){if(ol.has.DEVICE_ORIENTATION){var tracking=this.getTracking();if(tracking&&!this.listenerKey_)this.listenerKey_=ol.events.listen(window,"deviceorientation",this.orientationChange_,this);else if(!tracking&&this.listenerKey_!==null){ol.events.unlistenByKey(this.listenerKey_);this.listenerKey_=null}}};ol.DeviceOrientation.prototype.setTracking=function(tracking){this.set(ol.DeviceOrientation.Property_.TRACKING,tracking)};
ol.DeviceOrientation.Property_={ALPHA:"alpha",BETA:"beta",GAMMA:"gamma",HEADING:"heading",TRACKING:"tracking"};goog.provide("ol.style.Image");ol.style.Image=function(options){this.opacity_=options.opacity;this.rotateWithView_=options.rotateWithView;this.rotation_=options.rotation;this.scale_=options.scale;this.snapToPixel_=options.snapToPixel};ol.style.Image.prototype.getOpacity=function(){return this.opacity_};ol.style.Image.prototype.getRotateWithView=function(){return this.rotateWithView_};ol.style.Image.prototype.getRotation=function(){return this.rotation_};ol.style.Image.prototype.getScale=function(){return this.scale_};
ol.style.Image.prototype.getSnapToPixel=function(){return this.snapToPixel_};ol.style.Image.prototype.getAnchor=function(){};ol.style.Image.prototype.getImage=function(pixelRatio){};ol.style.Image.prototype.getHitDetectionImage=function(pixelRatio){};ol.style.Image.prototype.getImageState=function(){};ol.style.Image.prototype.getImageSize=function(){};ol.style.Image.prototype.getHitDetectionImageSize=function(){};ol.style.Image.prototype.getOrigin=function(){};ol.style.Image.prototype.getSize=function(){};
ol.style.Image.prototype.setOpacity=function(opacity){this.opacity_=opacity};ol.style.Image.prototype.setRotateWithView=function(rotateWithView){this.rotateWithView_=rotateWithView};ol.style.Image.prototype.setRotation=function(rotation){this.rotation_=rotation};ol.style.Image.prototype.setScale=function(scale){this.scale_=scale};ol.style.Image.prototype.setSnapToPixel=function(snapToPixel){this.snapToPixel_=snapToPixel};ol.style.Image.prototype.listenImageChange=function(listener,thisArg){};
ol.style.Image.prototype.load=function(){};ol.style.Image.prototype.unlistenImageChange=function(listener,thisArg){};goog.provide("ol.style.RegularShape");goog.require("ol");goog.require("ol.colorlike");goog.require("ol.dom");goog.require("ol.has");goog.require("ol.ImageState");goog.require("ol.render.canvas");goog.require("ol.style.Image");
ol.style.RegularShape=function(options){this.checksums_=null;this.canvas_=null;this.hitDetectionCanvas_=null;this.fill_=options.fill!==undefined?options.fill:null;this.origin_=[0,0];this.points_=options.points;this.radius_=options.radius!==undefined?options.radius:options.radius1;this.radius2_=options.radius2;this.angle_=options.angle!==undefined?options.angle:0;this.stroke_=options.stroke!==undefined?options.stroke:null;this.anchor_=null;this.size_=null;this.imageSize_=null;this.hitDetectionImageSize_=
null;this.atlasManager_=options.atlasManager;this.render_(this.atlasManager_);var snapToPixel=options.snapToPixel!==undefined?options.snapToPixel:true;var rotateWithView=options.rotateWithView!==undefined?options.rotateWithView:false;ol.style.Image.call(this,{opacity:1,rotateWithView:rotateWithView,rotation:options.rotation!==undefined?options.rotation:0,scale:1,snapToPixel:snapToPixel})};ol.inherits(ol.style.RegularShape,ol.style.Image);
ol.style.RegularShape.prototype.clone=function(){var style=new ol.style.RegularShape({fill:this.getFill()?this.getFill().clone():undefined,points:this.getPoints(),radius:this.getRadius(),radius2:this.getRadius2(),angle:this.getAngle(),snapToPixel:this.getSnapToPixel(),stroke:this.getStroke()?this.getStroke().clone():undefined,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),atlasManager:this.atlasManager_});style.setOpacity(this.getOpacity());style.setScale(this.getScale());return style};
ol.style.RegularShape.prototype.getAnchor=function(){return this.anchor_};ol.style.RegularShape.prototype.getAngle=function(){return this.angle_};ol.style.RegularShape.prototype.getFill=function(){return this.fill_};ol.style.RegularShape.prototype.getHitDetectionImage=function(pixelRatio){return this.hitDetectionCanvas_};ol.style.RegularShape.prototype.getImage=function(pixelRatio){return this.canvas_};ol.style.RegularShape.prototype.getImageSize=function(){return this.imageSize_};
ol.style.RegularShape.prototype.getHitDetectionImageSize=function(){return this.hitDetectionImageSize_};ol.style.RegularShape.prototype.getImageState=function(){return ol.ImageState.LOADED};ol.style.RegularShape.prototype.getOrigin=function(){return this.origin_};ol.style.RegularShape.prototype.getPoints=function(){return this.points_};ol.style.RegularShape.prototype.getRadius=function(){return this.radius_};ol.style.RegularShape.prototype.getRadius2=function(){return this.radius2_};
ol.style.RegularShape.prototype.getSize=function(){return this.size_};ol.style.RegularShape.prototype.getStroke=function(){return this.stroke_};ol.style.RegularShape.prototype.listenImageChange=function(listener,thisArg){};ol.style.RegularShape.prototype.load=function(){};ol.style.RegularShape.prototype.unlistenImageChange=function(listener,thisArg){};
ol.style.RegularShape.prototype.render_=function(atlasManager){var imageSize;var lineCap="";var lineJoin="";var miterLimit=0;var lineDash=null;var lineDashOffset=0;var strokeStyle;var strokeWidth=0;if(this.stroke_){strokeStyle=this.stroke_.getColor();if(strokeStyle===null)strokeStyle=ol.render.canvas.defaultStrokeStyle;strokeStyle=ol.colorlike.asColorLike(strokeStyle);strokeWidth=this.stroke_.getWidth();if(strokeWidth===undefined)strokeWidth=ol.render.canvas.defaultLineWidth;lineDash=this.stroke_.getLineDash();
lineDashOffset=this.stroke_.getLineDashOffset();if(!ol.has.CANVAS_LINE_DASH){lineDash=null;lineDashOffset=0}lineJoin=this.stroke_.getLineJoin();if(lineJoin===undefined)lineJoin=ol.render.canvas.defaultLineJoin;lineCap=this.stroke_.getLineCap();if(lineCap===undefined)lineCap=ol.render.canvas.defaultLineCap;miterLimit=this.stroke_.getMiterLimit();if(miterLimit===undefined)miterLimit=ol.render.canvas.defaultMiterLimit}var size=2*(this.radius_+strokeWidth)+1;var renderOptions={strokeStyle:strokeStyle,
strokeWidth:strokeWidth,size:size,lineCap:lineCap,lineDash:lineDash,lineDashOffset:lineDashOffset,lineJoin:lineJoin,miterLimit:miterLimit};if(atlasManager===undefined){var context=ol.dom.createCanvasContext2D(size,size);this.canvas_=context.canvas;size=this.canvas_.width;imageSize=size;this.draw_(renderOptions,context,0,0);this.createHitDetectionCanvas_(renderOptions)}else{size=Math.round(size);var hasCustomHitDetectionImage=!this.fill_;var renderHitDetectionCallback;if(hasCustomHitDetectionImage)renderHitDetectionCallback=
this.drawHitDetectionCanvas_.bind(this,renderOptions);var id=this.getChecksum();var info=atlasManager.add(id,size,size,this.draw_.bind(this,renderOptions),renderHitDetectionCallback);this.canvas_=info.image;this.origin_=[info.offsetX,info.offsetY];imageSize=info.image.width;if(hasCustomHitDetectionImage){this.hitDetectionCanvas_=info.hitImage;this.hitDetectionImageSize_=[info.hitImage.width,info.hitImage.height]}else{this.hitDetectionCanvas_=this.canvas_;this.hitDetectionImageSize_=[imageSize,imageSize]}}this.anchor_=
[size/2,size/2];this.size_=[size,size];this.imageSize_=[imageSize,imageSize]};
ol.style.RegularShape.prototype.draw_=function(renderOptions,context,x,y){var i,angle0,radiusC;context.setTransform(1,0,0,1,0,0);context.translate(x,y);context.beginPath();var points=this.points_;if(points===Infinity)context.arc(renderOptions.size/2,renderOptions.size/2,this.radius_,0,2*Math.PI,true);else{var radius2=this.radius2_!==undefined?this.radius2_:this.radius_;if(radius2!==this.radius_)points=2*points;for(i=0;i<=points;i++){angle0=i*2*Math.PI/points-Math.PI/2+this.angle_;radiusC=i%2===0?
this.radius_:radius2;context.lineTo(renderOptions.size/2+radiusC*Math.cos(angle0),renderOptions.size/2+radiusC*Math.sin(angle0))}}if(this.fill_){var color=this.fill_.getColor();if(color===null)color=ol.render.canvas.defaultFillStyle;context.fillStyle=ol.colorlike.asColorLike(color);context.fill()}if(this.stroke_){context.strokeStyle=renderOptions.strokeStyle;context.lineWidth=renderOptions.strokeWidth;if(renderOptions.lineDash){context.setLineDash(renderOptions.lineDash);context.lineDashOffset=renderOptions.lineDashOffset}context.lineCap=
renderOptions.lineCap;context.lineJoin=renderOptions.lineJoin;context.miterLimit=renderOptions.miterLimit;context.stroke()}context.closePath()};
ol.style.RegularShape.prototype.createHitDetectionCanvas_=function(renderOptions){this.hitDetectionImageSize_=[renderOptions.size,renderOptions.size];if(this.fill_){this.hitDetectionCanvas_=this.canvas_;return}var context=ol.dom.createCanvasContext2D(renderOptions.size,renderOptions.size);this.hitDetectionCanvas_=context.canvas;this.drawHitDetectionCanvas_(renderOptions,context,0,0)};
ol.style.RegularShape.prototype.drawHitDetectionCanvas_=function(renderOptions,context,x,y){context.setTransform(1,0,0,1,0,0);context.translate(x,y);context.beginPath();var points=this.points_;if(points===Infinity)context.arc(renderOptions.size/2,renderOptions.size/2,this.radius_,0,2*Math.PI,true);else{var radius2=this.radius2_!==undefined?this.radius2_:this.radius_;if(radius2!==this.radius_)points=2*points;var i,radiusC,angle0;for(i=0;i<=points;i++){angle0=i*2*Math.PI/points-Math.PI/2+this.angle_;
radiusC=i%2===0?this.radius_:radius2;context.lineTo(renderOptions.size/2+radiusC*Math.cos(angle0),renderOptions.size/2+radiusC*Math.sin(angle0))}}context.fillStyle=ol.render.canvas.defaultFillStyle;context.fill();if(this.stroke_){context.strokeStyle=renderOptions.strokeStyle;context.lineWidth=renderOptions.strokeWidth;if(renderOptions.lineDash){context.setLineDash(renderOptions.lineDash);context.lineDashOffset=renderOptions.lineDashOffset}context.stroke()}context.closePath()};
ol.style.RegularShape.prototype.getChecksum=function(){var strokeChecksum=this.stroke_?this.stroke_.getChecksum():"-";var fillChecksum=this.fill_?this.fill_.getChecksum():"-";var recalculate=!this.checksums_||(strokeChecksum!=this.checksums_[1]||fillChecksum!=this.checksums_[2]||this.radius_!=this.checksums_[3]||this.radius2_!=this.checksums_[4]||this.angle_!=this.checksums_[5]||this.points_!=this.checksums_[6]);if(recalculate){var checksum="r"+strokeChecksum+fillChecksum+(this.radius_!==undefined?
this.radius_.toString():"-")+(this.radius2_!==undefined?this.radius2_.toString():"-")+(this.angle_!==undefined?this.angle_.toString():"-")+(this.points_!==undefined?this.points_.toString():"-");this.checksums_=[checksum,strokeChecksum,fillChecksum,this.radius_,this.radius2_,this.angle_,this.points_]}return this.checksums_[0]};goog.provide("ol.style.Circle");goog.require("ol");goog.require("ol.style.RegularShape");ol.style.Circle=function(opt_options){var options=opt_options||{};ol.style.RegularShape.call(this,{points:Infinity,fill:options.fill,radius:options.radius,snapToPixel:options.snapToPixel,stroke:options.stroke,atlasManager:options.atlasManager})};ol.inherits(ol.style.Circle,ol.style.RegularShape);
ol.style.Circle.prototype.clone=function(){var style=new ol.style.Circle({fill:this.getFill()?this.getFill().clone():undefined,stroke:this.getStroke()?this.getStroke().clone():undefined,radius:this.getRadius(),snapToPixel:this.getSnapToPixel(),atlasManager:this.atlasManager_});style.setOpacity(this.getOpacity());style.setScale(this.getScale());return style};ol.style.Circle.prototype.setRadius=function(radius){this.radius_=radius;this.render_(this.atlasManager_)};goog.provide("ol.style.Fill");goog.require("ol");goog.require("ol.color");ol.style.Fill=function(opt_options){var options=opt_options||{};this.color_=options.color!==undefined?options.color:null;this.checksum_=undefined};ol.style.Fill.prototype.clone=function(){var color=this.getColor();return new ol.style.Fill({color:color&&color.slice?color.slice():color||undefined})};ol.style.Fill.prototype.getColor=function(){return this.color_};
ol.style.Fill.prototype.setColor=function(color){this.color_=color;this.checksum_=undefined};ol.style.Fill.prototype.getChecksum=function(){if(this.checksum_===undefined)if(this.color_ instanceof CanvasPattern||this.color_ instanceof CanvasGradient)this.checksum_=ol.getUid(this.color_).toString();else this.checksum_="f"+(this.color_?ol.color.asString(this.color_):"-");return this.checksum_};goog.provide("ol.style.Stroke");goog.require("ol");ol.style.Stroke=function(opt_options){var options=opt_options||{};this.color_=options.color!==undefined?options.color:null;this.lineCap_=options.lineCap;this.lineDash_=options.lineDash!==undefined?options.lineDash:null;this.lineDashOffset_=options.lineDashOffset;this.lineJoin_=options.lineJoin;this.miterLimit_=options.miterLimit;this.width_=options.width;this.checksum_=undefined};
ol.style.Stroke.prototype.clone=function(){var color=this.getColor();return new ol.style.Stroke({color:color&&color.slice?color.slice():color||undefined,lineCap:this.getLineCap(),lineDash:this.getLineDash()?this.getLineDash().slice():undefined,lineDashOffset:this.getLineDashOffset(),lineJoin:this.getLineJoin(),miterLimit:this.getMiterLimit(),width:this.getWidth()})};ol.style.Stroke.prototype.getColor=function(){return this.color_};ol.style.Stroke.prototype.getLineCap=function(){return this.lineCap_};
ol.style.Stroke.prototype.getLineDash=function(){return this.lineDash_};ol.style.Stroke.prototype.getLineDashOffset=function(){return this.lineDashOffset_};ol.style.Stroke.prototype.getLineJoin=function(){return this.lineJoin_};ol.style.Stroke.prototype.getMiterLimit=function(){return this.miterLimit_};ol.style.Stroke.prototype.getWidth=function(){return this.width_};ol.style.Stroke.prototype.setColor=function(color){this.color_=color;this.checksum_=undefined};
ol.style.Stroke.prototype.setLineCap=function(lineCap){this.lineCap_=lineCap;this.checksum_=undefined};ol.style.Stroke.prototype.setLineDash=function(lineDash){this.lineDash_=lineDash;this.checksum_=undefined};ol.style.Stroke.prototype.setLineDashOffset=function(lineDashOffset){this.lineDashOffset_=lineDashOffset;this.checksum_=undefined};ol.style.Stroke.prototype.setLineJoin=function(lineJoin){this.lineJoin_=lineJoin;this.checksum_=undefined};
ol.style.Stroke.prototype.setMiterLimit=function(miterLimit){this.miterLimit_=miterLimit;this.checksum_=undefined};ol.style.Stroke.prototype.setWidth=function(width){this.width_=width;this.checksum_=undefined};
ol.style.Stroke.prototype.getChecksum=function(){if(this.checksum_===undefined){this.checksum_="s";if(this.color_)if(typeof this.color_==="string")this.checksum_+=this.color_;else this.checksum_+=ol.getUid(this.color_).toString();else this.checksum_+="-";this.checksum_+=","+(this.lineCap_!==undefined?this.lineCap_.toString():"-")+","+(this.lineDash_?this.lineDash_.toString():"-")+","+(this.lineDashOffset_!==undefined?this.lineDashOffset_:"-")+","+(this.lineJoin_!==undefined?this.lineJoin_:"-")+","+
(this.miterLimit_!==undefined?this.miterLimit_.toString():"-")+","+(this.width_!==undefined?this.width_.toString():"-")}return this.checksum_};goog.provide("ol.style.Style");goog.require("ol.asserts");goog.require("ol.geom.GeometryType");goog.require("ol.style.Circle");goog.require("ol.style.Fill");goog.require("ol.style.Stroke");
ol.style.Style=function(opt_options){var options=opt_options||{};this.geometry_=null;this.geometryFunction_=ol.style.Style.defaultGeometryFunction;if(options.geometry!==undefined)this.setGeometry(options.geometry);this.fill_=options.fill!==undefined?options.fill:null;this.image_=options.image!==undefined?options.image:null;this.renderer_=options.renderer!==undefined?options.renderer:null;this.stroke_=options.stroke!==undefined?options.stroke:null;this.text_=options.text!==undefined?options.text:null;
this.zIndex_=options.zIndex};ol.style.Style.prototype.clone=function(){var geometry=this.getGeometry();if(geometry&&geometry.clone)geometry=geometry.clone();return new ol.style.Style({geometry:geometry,fill:this.getFill()?this.getFill().clone():undefined,image:this.getImage()?this.getImage().clone():undefined,stroke:this.getStroke()?this.getStroke().clone():undefined,text:this.getText()?this.getText().clone():undefined,zIndex:this.getZIndex()})};ol.style.Style.prototype.getRenderer=function(){return this.renderer_};
ol.style.Style.prototype.setRenderer=function(renderer){this.renderer_=renderer};ol.style.Style.prototype.getGeometry=function(){return this.geometry_};ol.style.Style.prototype.getGeometryFunction=function(){return this.geometryFunction_};ol.style.Style.prototype.getFill=function(){return this.fill_};ol.style.Style.prototype.setFill=function(fill){this.fill_=fill};ol.style.Style.prototype.getImage=function(){return this.image_};ol.style.Style.prototype.setImage=function(image){this.image_=image};
ol.style.Style.prototype.getStroke=function(){return this.stroke_};ol.style.Style.prototype.setStroke=function(stroke){this.stroke_=stroke};ol.style.Style.prototype.getText=function(){return this.text_};ol.style.Style.prototype.setText=function(text){this.text_=text};ol.style.Style.prototype.getZIndex=function(){return this.zIndex_};
ol.style.Style.prototype.setGeometry=function(geometry){if(typeof geometry==="function")this.geometryFunction_=geometry;else if(typeof geometry==="string")this.geometryFunction_=function(feature){return feature.get(geometry)};else if(!geometry)this.geometryFunction_=ol.style.Style.defaultGeometryFunction;else if(geometry!==undefined)this.geometryFunction_=function(){return geometry};this.geometry_=geometry};ol.style.Style.prototype.setZIndex=function(zIndex){this.zIndex_=zIndex};
ol.style.Style.createFunction=function(obj){var styleFunction;if(typeof obj==="function")styleFunction=obj;else{var styles;if(Array.isArray(obj))styles=obj;else{ol.asserts.assert(obj instanceof ol.style.Style,41);styles=[obj]}styleFunction=function(){return styles}}return styleFunction};ol.style.Style.default_=null;
ol.style.Style.defaultFunction=function(feature,resolution){if(!ol.style.Style.default_){var fill=new ol.style.Fill({color:"rgba(255,255,255,0.4)"});var stroke=new ol.style.Stroke({color:"#3399CC",width:1.25});ol.style.Style.default_=[new ol.style.Style({image:new ol.style.Circle({fill:fill,stroke:stroke,radius:5}),fill:fill,stroke:stroke})]}return ol.style.Style.default_};
ol.style.Style.createDefaultEditing=function(){var styles={};var white=[255,255,255,1];var blue=[0,153,255,1];var width=3;styles[ol.geom.GeometryType.POLYGON]=[new ol.style.Style({fill:new ol.style.Fill({color:[255,255,255,.5]})})];styles[ol.geom.GeometryType.MULTI_POLYGON]=styles[ol.geom.GeometryType.POLYGON];styles[ol.geom.GeometryType.LINE_STRING]=[new ol.style.Style({stroke:new ol.style.Stroke({color:white,width:width+2})}),new ol.style.Style({stroke:new ol.style.Stroke({color:blue,width:width})})];
styles[ol.geom.GeometryType.MULTI_LINE_STRING]=styles[ol.geom.GeometryType.LINE_STRING];styles[ol.geom.GeometryType.CIRCLE]=styles[ol.geom.GeometryType.POLYGON].concat(styles[ol.geom.GeometryType.LINE_STRING]);styles[ol.geom.GeometryType.POINT]=[new ol.style.Style({image:new ol.style.Circle({radius:width*2,fill:new ol.style.Fill({color:blue}),stroke:new ol.style.Stroke({color:white,width:width/2})}),zIndex:Infinity})];styles[ol.geom.GeometryType.MULTI_POINT]=styles[ol.geom.GeometryType.POINT];styles[ol.geom.GeometryType.GEOMETRY_COLLECTION]=
styles[ol.geom.GeometryType.POLYGON].concat(styles[ol.geom.GeometryType.LINE_STRING],styles[ol.geom.GeometryType.POINT]);return styles};ol.style.Style.defaultGeometryFunction=function(feature){return feature.getGeometry()};goog.provide("ol.Feature");goog.require("ol.asserts");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol");goog.require("ol.Object");goog.require("ol.geom.Geometry");goog.require("ol.style.Style");
ol.Feature=function(opt_geometryOrProperties){ol.Object.call(this);this.id_=undefined;this.geometryName_="geometry";this.style_=null;this.styleFunction_=undefined;this.geometryChangeKey_=null;ol.events.listen(this,ol.Object.getChangeEventType(this.geometryName_),this.handleGeometryChanged_,this);if(opt_geometryOrProperties!==undefined)if(opt_geometryOrProperties instanceof ol.geom.Geometry||!opt_geometryOrProperties){var geometry=opt_geometryOrProperties;this.setGeometry(geometry)}else{var properties=
opt_geometryOrProperties;this.setProperties(properties)}};ol.inherits(ol.Feature,ol.Object);ol.Feature.prototype.clone=function(){var clone=new ol.Feature(this.getProperties());clone.setGeometryName(this.getGeometryName());var geometry=this.getGeometry();if(geometry)clone.setGeometry(geometry.clone());var style=this.getStyle();if(style)clone.setStyle(style);return clone};ol.Feature.prototype.getGeometry=function(){return this.get(this.geometryName_)};ol.Feature.prototype.getId=function(){return this.id_};
ol.Feature.prototype.getGeometryName=function(){return this.geometryName_};ol.Feature.prototype.getStyle=function(){return this.style_};ol.Feature.prototype.getStyleFunction=function(){return this.styleFunction_};ol.Feature.prototype.handleGeometryChange_=function(){this.changed()};
ol.Feature.prototype.handleGeometryChanged_=function(){if(this.geometryChangeKey_){ol.events.unlistenByKey(this.geometryChangeKey_);this.geometryChangeKey_=null}var geometry=this.getGeometry();if(geometry)this.geometryChangeKey_=ol.events.listen(geometry,ol.events.EventType.CHANGE,this.handleGeometryChange_,this);this.changed()};ol.Feature.prototype.setGeometry=function(geometry){this.set(this.geometryName_,geometry)};
ol.Feature.prototype.setStyle=function(style){this.style_=style;this.styleFunction_=!style?undefined:ol.Feature.createStyleFunction(style);this.changed()};ol.Feature.prototype.setId=function(id){this.id_=id;this.changed()};
ol.Feature.prototype.setGeometryName=function(name){ol.events.unlisten(this,ol.Object.getChangeEventType(this.geometryName_),this.handleGeometryChanged_,this);this.geometryName_=name;ol.events.listen(this,ol.Object.getChangeEventType(this.geometryName_),this.handleGeometryChanged_,this);this.handleGeometryChanged_()};
ol.Feature.createStyleFunction=function(obj){var styleFunction;if(typeof obj==="function")if(obj.length==2)styleFunction=function(resolution){return obj(this,resolution)};else styleFunction=obj;else{var styles;if(Array.isArray(obj))styles=obj;else{ol.asserts.assert(obj instanceof ol.style.Style,41);styles=[obj]}styleFunction=function(){return styles}}return styleFunction};goog.provide("ol.format.FormatType");ol.format.FormatType={ARRAY_BUFFER:"arraybuffer",JSON:"json",TEXT:"text",XML:"xml"};goog.provide("ol.xml");goog.require("ol.array");ol.xml.DOCUMENT=document.implementation.createDocument("","",null);ol.xml.createElementNS=function(namespaceURI,qualifiedName){return ol.xml.DOCUMENT.createElementNS(namespaceURI,qualifiedName)};ol.xml.getAllTextContent=function(node,normalizeWhitespace){return ol.xml.getAllTextContent_(node,normalizeWhitespace,[]).join("")};
ol.xml.getAllTextContent_=function(node,normalizeWhitespace,accumulator){if(node.nodeType==Node.CDATA_SECTION_NODE||node.nodeType==Node.TEXT_NODE)if(normalizeWhitespace)accumulator.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g,""));else accumulator.push(node.nodeValue);else{var n;for(n=node.firstChild;n;n=n.nextSibling)ol.xml.getAllTextContent_(n,normalizeWhitespace,accumulator)}return accumulator};ol.xml.isDocument=function(value){return value instanceof Document};
ol.xml.isNode=function(value){return value instanceof Node};ol.xml.getAttributeNS=function(node,namespaceURI,name){return node.getAttributeNS(namespaceURI,name)||""};ol.xml.setAttributeNS=function(node,namespaceURI,name,value){node.setAttributeNS(namespaceURI,name,value)};ol.xml.parse=function(xml){return(new DOMParser).parseFromString(xml,"application/xml")};
ol.xml.makeArrayExtender=function(valueReader,opt_this){return function(node,objectStack){var value=valueReader.call(opt_this,node,objectStack);if(value!==undefined){var array=objectStack[objectStack.length-1];ol.array.extend(array,value)}}};ol.xml.makeArrayPusher=function(valueReader,opt_this){return function(node,objectStack){var value=valueReader.call(opt_this!==undefined?opt_this:this,node,objectStack);if(value!==undefined){var array=objectStack[objectStack.length-1];array.push(value)}}};
ol.xml.makeReplacer=function(valueReader,opt_this){return function(node,objectStack){var value=valueReader.call(opt_this!==undefined?opt_this:this,node,objectStack);if(value!==undefined)objectStack[objectStack.length-1]=value}};
ol.xml.makeObjectPropertyPusher=function(valueReader,opt_property,opt_this){return function(node,objectStack){var value=valueReader.call(opt_this!==undefined?opt_this:this,node,objectStack);if(value!==undefined){var object=objectStack[objectStack.length-1];var property=opt_property!==undefined?opt_property:node.localName;var array;if(property in object)array=object[property];else array=object[property]=[];array.push(value)}}};
ol.xml.makeObjectPropertySetter=function(valueReader,opt_property,opt_this){return function(node,objectStack){var value=valueReader.call(opt_this!==undefined?opt_this:this,node,objectStack);if(value!==undefined){var object=objectStack[objectStack.length-1];var property=opt_property!==undefined?opt_property:node.localName;object[property]=value}}};
ol.xml.makeChildAppender=function(nodeWriter,opt_this){return function(node,value,objectStack){nodeWriter.call(opt_this!==undefined?opt_this:this,node,value,objectStack);var parent=objectStack[objectStack.length-1];var parentNode=parent.node;parentNode.appendChild(node)}};
ol.xml.makeArraySerializer=function(nodeWriter,opt_this){var serializersNS,nodeFactory;return function(node,value,objectStack){if(serializersNS===undefined){serializersNS={};var serializers={};serializers[node.localName]=nodeWriter;serializersNS[node.namespaceURI]=serializers;nodeFactory=ol.xml.makeSimpleNodeFactory(node.localName)}ol.xml.serialize(serializersNS,nodeFactory,value,objectStack)}};
ol.xml.makeSimpleNodeFactory=function(opt_nodeName,opt_namespaceURI){var fixedNodeName=opt_nodeName;return function(value,objectStack,opt_nodeName){var context=objectStack[objectStack.length-1];var node=context.node;var nodeName=fixedNodeName;if(nodeName===undefined)nodeName=opt_nodeName;var namespaceURI=opt_namespaceURI;if(opt_namespaceURI===undefined)namespaceURI=node.namespaceURI;return ol.xml.createElementNS(namespaceURI,nodeName)}};ol.xml.OBJECT_PROPERTY_NODE_FACTORY=ol.xml.makeSimpleNodeFactory();
ol.xml.makeSequence=function(object,orderedKeys){var length=orderedKeys.length;var sequence=new Array(length);for(var i=0;i<length;++i)sequence[i]=object[orderedKeys[i]];return sequence};ol.xml.makeStructureNS=function(namespaceURIs,structure,opt_structureNS){var structureNS=opt_structureNS!==undefined?opt_structureNS:{};var i,ii;for(i=0,ii=namespaceURIs.length;i<ii;++i)structureNS[namespaceURIs[i]]=structure;return structureNS};
ol.xml.parseNode=function(parsersNS,node,objectStack,opt_this){var n;for(n=node.firstElementChild;n;n=n.nextElementSibling){var parsers=parsersNS[n.namespaceURI];if(parsers!==undefined){var parser=parsers[n.localName];if(parser!==undefined)parser.call(opt_this,n,objectStack)}}};ol.xml.pushParseAndPop=function(object,parsersNS,node,objectStack,opt_this){objectStack.push(object);ol.xml.parseNode(parsersNS,node,objectStack,opt_this);return objectStack.pop()};
ol.xml.serialize=function(serializersNS,nodeFactory,values,objectStack,opt_keys,opt_this){var length=(opt_keys!==undefined?opt_keys:values).length;var value,node;for(var i=0;i<length;++i){value=values[i];if(value!==undefined){node=nodeFactory.call(opt_this,value,objectStack,opt_keys!==undefined?opt_keys[i]:undefined);if(node!==undefined)serializersNS[node.namespaceURI][node.localName].call(opt_this,node,value,objectStack)}}};
ol.xml.pushSerializeAndPop=function(object,serializersNS,nodeFactory,values,objectStack,opt_keys,opt_this){objectStack.push(object);ol.xml.serialize(serializersNS,nodeFactory,values,objectStack,opt_keys,opt_this);return objectStack.pop()};goog.provide("ol.featureloader");goog.require("ol");goog.require("ol.format.FormatType");goog.require("ol.xml");
ol.featureloader.loadFeaturesXhr=function(url,format,success,failure){return function(extent,resolution,projection){var xhr=new XMLHttpRequest;xhr.open("GET",typeof url==="function"?url(extent,resolution,projection):url,true);if(format.getType()==ol.format.FormatType.ARRAY_BUFFER)xhr.responseType="arraybuffer";xhr.onload=function(event){if(!xhr.status||xhr.status>=200&&xhr.status<300){var type=format.getType();var source;if(type==ol.format.FormatType.JSON||type==ol.format.FormatType.TEXT)source=xhr.responseText;
else if(type==ol.format.FormatType.XML){source=xhr.responseXML;if(!source)source=ol.xml.parse(xhr.responseText)}else if(type==ol.format.FormatType.ARRAY_BUFFER)source=xhr.response;if(source)success.call(this,format.readFeatures(source,{featureProjection:projection}),format.readProjection(source),format.getLastExtent());else failure.call(this)}else failure.call(this)}.bind(this);xhr.onerror=function(){failure.call(this)}.bind(this);xhr.send()}};
ol.featureloader.xhr=function(url,format){return ol.featureloader.loadFeaturesXhr(url,format,function(features,dataProjection){this.addFeatures(features)},ol.nullFunction)};goog.provide("ol.format.Feature");goog.require("ol.geom.Geometry");goog.require("ol.obj");goog.require("ol.proj");ol.format.Feature=function(){this.defaultDataProjection=null;this.defaultFeatureProjection=null};ol.format.Feature.prototype.getReadOptions=function(source,opt_options){var options;if(opt_options)options={dataProjection:opt_options.dataProjection?opt_options.dataProjection:this.readProjection(source),featureProjection:opt_options.featureProjection};return this.adaptOptions(options)};
ol.format.Feature.prototype.adaptOptions=function(options){return ol.obj.assign({dataProjection:this.defaultDataProjection,featureProjection:this.defaultFeatureProjection},options)};ol.format.Feature.prototype.getLastExtent=function(){return null};ol.format.Feature.prototype.getType=function(){};ol.format.Feature.prototype.readFeature=function(source,opt_options){};ol.format.Feature.prototype.readFeatures=function(source,opt_options){};ol.format.Feature.prototype.readGeometry=function(source,opt_options){};
ol.format.Feature.prototype.readProjection=function(source){};ol.format.Feature.prototype.writeFeature=function(feature,opt_options){};ol.format.Feature.prototype.writeFeatures=function(features,opt_options){};ol.format.Feature.prototype.writeGeometry=function(geometry,opt_options){};
ol.format.Feature.transformWithOptions=function(geometry,write,opt_options){var featureProjection=opt_options?ol.proj.get(opt_options.featureProjection):null;var dataProjection=opt_options?ol.proj.get(opt_options.dataProjection):null;var transformed;if(featureProjection&&dataProjection&&!ol.proj.equivalent(featureProjection,dataProjection))if(geometry instanceof ol.geom.Geometry)transformed=(write?geometry.clone():geometry).transform(write?featureProjection:dataProjection,write?dataProjection:featureProjection);
else transformed=ol.proj.transformExtent(geometry,dataProjection,featureProjection);else transformed=geometry;if(write&&opt_options&&opt_options.decimals!==undefined){var power=Math.pow(10,opt_options.decimals);var transform=function(coordinates){for(var i=0,ii=coordinates.length;i<ii;++i)coordinates[i]=Math.round(coordinates[i]*power)/power;return coordinates};if(transformed===geometry)transformed=transformed.clone();transformed.applyTransform(transform)}return transformed};goog.provide("ol.format.JSONFeature");goog.require("ol");goog.require("ol.format.Feature");goog.require("ol.format.FormatType");ol.format.JSONFeature=function(){ol.format.Feature.call(this)};ol.inherits(ol.format.JSONFeature,ol.format.Feature);ol.format.JSONFeature.prototype.getObject_=function(source){if(typeof source==="string"){var object=JSON.parse(source);return object?object:null}else if(source!==null)return source;else return null};ol.format.JSONFeature.prototype.getType=function(){return ol.format.FormatType.JSON};
ol.format.JSONFeature.prototype.readFeature=function(source,opt_options){return this.readFeatureFromObject(this.getObject_(source),this.getReadOptions(source,opt_options))};ol.format.JSONFeature.prototype.readFeatures=function(source,opt_options){return this.readFeaturesFromObject(this.getObject_(source),this.getReadOptions(source,opt_options))};ol.format.JSONFeature.prototype.readFeatureFromObject=function(object,opt_options){};
ol.format.JSONFeature.prototype.readFeaturesFromObject=function(object,opt_options){};ol.format.JSONFeature.prototype.readGeometry=function(source,opt_options){return this.readGeometryFromObject(this.getObject_(source),this.getReadOptions(source,opt_options))};ol.format.JSONFeature.prototype.readGeometryFromObject=function(object,opt_options){};ol.format.JSONFeature.prototype.readProjection=function(source){return this.readProjectionFromObject(this.getObject_(source))};
ol.format.JSONFeature.prototype.readProjectionFromObject=function(object){};ol.format.JSONFeature.prototype.writeFeature=function(feature,opt_options){return JSON.stringify(this.writeFeatureObject(feature,opt_options))};ol.format.JSONFeature.prototype.writeFeatureObject=function(feature,opt_options){};ol.format.JSONFeature.prototype.writeFeatures=function(features,opt_options){return JSON.stringify(this.writeFeaturesObject(features,opt_options))};
ol.format.JSONFeature.prototype.writeFeaturesObject=function(features,opt_options){};ol.format.JSONFeature.prototype.writeGeometry=function(geometry,opt_options){return JSON.stringify(this.writeGeometryObject(geometry,opt_options))};ol.format.JSONFeature.prototype.writeGeometryObject=function(geometry,opt_options){};goog.provide("ol.geom.flat.interpolate");goog.require("ol.array");goog.require("ol.math");
ol.geom.flat.interpolate.lineString=function(flatCoordinates,offset,end,stride,fraction,opt_dest){var pointX=NaN;var pointY=NaN;var n=(end-offset)/stride;if(n===1){pointX=flatCoordinates[offset];pointY=flatCoordinates[offset+1]}else if(n==2){pointX=(1-fraction)*flatCoordinates[offset]+fraction*flatCoordinates[offset+stride];pointY=(1-fraction)*flatCoordinates[offset+1]+fraction*flatCoordinates[offset+stride+1]}else if(n!==0){var x1=flatCoordinates[offset];var y1=flatCoordinates[offset+1];var length=
0;var cumulativeLengths=[0];var i;for(i=offset+stride;i<end;i+=stride){var x2=flatCoordinates[i];var y2=flatCoordinates[i+1];length+=Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));cumulativeLengths.push(length);x1=x2;y1=y2}var target=fraction*length;var index=ol.array.binarySearch(cumulativeLengths,target);if(index<0){var t=(target-cumulativeLengths[-index-2])/(cumulativeLengths[-index-1]-cumulativeLengths[-index-2]);var o=offset+(-index-2)*stride;pointX=ol.math.lerp(flatCoordinates[o],flatCoordinates[o+
stride],t);pointY=ol.math.lerp(flatCoordinates[o+1],flatCoordinates[o+stride+1],t)}else{pointX=flatCoordinates[offset+index*stride];pointY=flatCoordinates[offset+index*stride+1]}}if(opt_dest){opt_dest[0]=pointX;opt_dest[1]=pointY;return opt_dest}else return[pointX,pointY]};
ol.geom.flat.interpolate.lineStringCoordinateAtM=function(flatCoordinates,offset,end,stride,m,extrapolate){if(end==offset)return null;var coordinate;if(m<flatCoordinates[offset+stride-1])if(extrapolate){coordinate=flatCoordinates.slice(offset,offset+stride);coordinate[stride-1]=m;return coordinate}else return null;else if(flatCoordinates[end-1]<m)if(extrapolate){coordinate=flatCoordinates.slice(end-stride,end);coordinate[stride-1]=m;return coordinate}else return null;if(m==flatCoordinates[offset+
stride-1])return flatCoordinates.slice(offset,offset+stride);var lo=offset/stride;var hi=end/stride;while(lo<hi){var mid=lo+hi>>1;if(m<flatCoordinates[(mid+1)*stride-1])hi=mid;else lo=mid+1}var m0=flatCoordinates[lo*stride-1];if(m==m0)return flatCoordinates.slice((lo-1)*stride,(lo-1)*stride+stride);var m1=flatCoordinates[(lo+1)*stride-1];var t=(m-m0)/(m1-m0);coordinate=[];var i;for(i=0;i<stride-1;++i)coordinate.push(ol.math.lerp(flatCoordinates[(lo-1)*stride+i],flatCoordinates[lo*stride+i],t));coordinate.push(m);
return coordinate};
ol.geom.flat.interpolate.lineStringsCoordinateAtM=function(flatCoordinates,offset,ends,stride,m,extrapolate,interpolate){if(interpolate)return ol.geom.flat.interpolate.lineStringCoordinateAtM(flatCoordinates,offset,ends[ends.length-1],stride,m,extrapolate);var coordinate;if(m<flatCoordinates[stride-1])if(extrapolate){coordinate=flatCoordinates.slice(0,stride);coordinate[stride-1]=m;return coordinate}else return null;if(flatCoordinates[flatCoordinates.length-1]<m)if(extrapolate){coordinate=flatCoordinates.slice(flatCoordinates.length-
stride);coordinate[stride-1]=m;return coordinate}else return null;var i,ii;for(i=0,ii=ends.length;i<ii;++i){var end=ends[i];if(offset==end)continue;if(m<flatCoordinates[offset+stride-1])return null;else if(m<=flatCoordinates[end-1])return ol.geom.flat.interpolate.lineStringCoordinateAtM(flatCoordinates,offset,end,stride,m,false);offset=end}return null};goog.provide("ol.geom.LineString");goog.require("ol");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.GeometryType");goog.require("ol.geom.SimpleGeometry");goog.require("ol.geom.flat.closest");goog.require("ol.geom.flat.deflate");goog.require("ol.geom.flat.inflate");goog.require("ol.geom.flat.interpolate");goog.require("ol.geom.flat.intersectsextent");goog.require("ol.geom.flat.length");goog.require("ol.geom.flat.segments");goog.require("ol.geom.flat.simplify");
ol.geom.LineString=function(coordinates,opt_layout){ol.geom.SimpleGeometry.call(this);this.flatMidpoint_=null;this.flatMidpointRevision_=-1;this.maxDelta_=-1;this.maxDeltaRevision_=-1;this.setCoordinates(coordinates,opt_layout)};ol.inherits(ol.geom.LineString,ol.geom.SimpleGeometry);ol.geom.LineString.prototype.appendCoordinate=function(coordinate){if(!this.flatCoordinates)this.flatCoordinates=coordinate.slice();else ol.array.extend(this.flatCoordinates,coordinate);this.changed()};
ol.geom.LineString.prototype.clone=function(){var lineString=new ol.geom.LineString(null);lineString.setFlatCoordinates(this.layout,this.flatCoordinates.slice());return lineString};
ol.geom.LineString.prototype.closestPointXY=function(x,y,closestPoint,minSquaredDistance){if(minSquaredDistance<ol.extent.closestSquaredDistanceXY(this.getExtent(),x,y))return minSquaredDistance;if(this.maxDeltaRevision_!=this.getRevision()){this.maxDelta_=Math.sqrt(ol.geom.flat.closest.getMaxSquaredDelta(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,0));this.maxDeltaRevision_=this.getRevision()}return ol.geom.flat.closest.getClosestPoint(this.flatCoordinates,0,this.flatCoordinates.length,
this.stride,this.maxDelta_,false,x,y,closestPoint,minSquaredDistance)};ol.geom.LineString.prototype.forEachSegment=function(callback,opt_this){return ol.geom.flat.segments.forEach(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,callback,opt_this)};
ol.geom.LineString.prototype.getCoordinateAtM=function(m,opt_extrapolate){if(this.layout!=ol.geom.GeometryLayout.XYM&&this.layout!=ol.geom.GeometryLayout.XYZM)return null;var extrapolate=opt_extrapolate!==undefined?opt_extrapolate:false;return ol.geom.flat.interpolate.lineStringCoordinateAtM(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,m,extrapolate)};
ol.geom.LineString.prototype.getCoordinates=function(){return ol.geom.flat.inflate.coordinates(this.flatCoordinates,0,this.flatCoordinates.length,this.stride)};ol.geom.LineString.prototype.getCoordinateAt=function(fraction,opt_dest){return ol.geom.flat.interpolate.lineString(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,fraction,opt_dest)};ol.geom.LineString.prototype.getLength=function(){return ol.geom.flat.length.lineString(this.flatCoordinates,0,this.flatCoordinates.length,this.stride)};
ol.geom.LineString.prototype.getFlatMidpoint=function(){if(this.flatMidpointRevision_!=this.getRevision()){this.flatMidpoint_=this.getCoordinateAt(.5,this.flatMidpoint_);this.flatMidpointRevision_=this.getRevision()}return this.flatMidpoint_};
ol.geom.LineString.prototype.getSimplifiedGeometryInternal=function(squaredTolerance){var simplifiedFlatCoordinates=[];simplifiedFlatCoordinates.length=ol.geom.flat.simplify.douglasPeucker(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,squaredTolerance,simplifiedFlatCoordinates,0);var simplifiedLineString=new ol.geom.LineString(null);simplifiedLineString.setFlatCoordinates(ol.geom.GeometryLayout.XY,simplifiedFlatCoordinates);return simplifiedLineString};
ol.geom.LineString.prototype.getType=function(){return ol.geom.GeometryType.LINE_STRING};ol.geom.LineString.prototype.intersectsExtent=function(extent){return ol.geom.flat.intersectsextent.lineString(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,extent)};
ol.geom.LineString.prototype.setCoordinates=function(coordinates,opt_layout){if(!coordinates)this.setFlatCoordinates(ol.geom.GeometryLayout.XY,null);else{this.setLayout(opt_layout,coordinates,1);if(!this.flatCoordinates)this.flatCoordinates=[];this.flatCoordinates.length=ol.geom.flat.deflate.coordinates(this.flatCoordinates,0,coordinates,this.stride);this.changed()}};
ol.geom.LineString.prototype.setFlatCoordinates=function(layout,flatCoordinates){this.setFlatCoordinatesInternal(layout,flatCoordinates);this.changed()};goog.provide("ol.geom.MultiLineString");goog.require("ol");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.GeometryType");goog.require("ol.geom.LineString");goog.require("ol.geom.SimpleGeometry");goog.require("ol.geom.flat.closest");goog.require("ol.geom.flat.deflate");goog.require("ol.geom.flat.inflate");goog.require("ol.geom.flat.interpolate");goog.require("ol.geom.flat.intersectsextent");goog.require("ol.geom.flat.simplify");
ol.geom.MultiLineString=function(coordinates,opt_layout){ol.geom.SimpleGeometry.call(this);this.ends_=[];this.maxDelta_=-1;this.maxDeltaRevision_=-1;this.setCoordinates(coordinates,opt_layout)};ol.inherits(ol.geom.MultiLineString,ol.geom.SimpleGeometry);
ol.geom.MultiLineString.prototype.appendLineString=function(lineString){if(!this.flatCoordinates)this.flatCoordinates=lineString.getFlatCoordinates().slice();else ol.array.extend(this.flatCoordinates,lineString.getFlatCoordinates().slice());this.ends_.push(this.flatCoordinates.length);this.changed()};
ol.geom.MultiLineString.prototype.clone=function(){var multiLineString=new ol.geom.MultiLineString(null);multiLineString.setFlatCoordinates(this.layout,this.flatCoordinates.slice(),this.ends_.slice());return multiLineString};
ol.geom.MultiLineString.prototype.closestPointXY=function(x,y,closestPoint,minSquaredDistance){if(minSquaredDistance<ol.extent.closestSquaredDistanceXY(this.getExtent(),x,y))return minSquaredDistance;if(this.maxDeltaRevision_!=this.getRevision()){this.maxDelta_=Math.sqrt(ol.geom.flat.closest.getsMaxSquaredDelta(this.flatCoordinates,0,this.ends_,this.stride,0));this.maxDeltaRevision_=this.getRevision()}return ol.geom.flat.closest.getsClosestPoint(this.flatCoordinates,0,this.ends_,this.stride,this.maxDelta_,
false,x,y,closestPoint,minSquaredDistance)};
ol.geom.MultiLineString.prototype.getCoordinateAtM=function(m,opt_extrapolate,opt_interpolate){if(this.layout!=ol.geom.GeometryLayout.XYM&&this.layout!=ol.geom.GeometryLayout.XYZM||this.flatCoordinates.length===0)return null;var extrapolate=opt_extrapolate!==undefined?opt_extrapolate:false;var interpolate=opt_interpolate!==undefined?opt_interpolate:false;return ol.geom.flat.interpolate.lineStringsCoordinateAtM(this.flatCoordinates,0,this.ends_,this.stride,m,extrapolate,interpolate)};
ol.geom.MultiLineString.prototype.getCoordinates=function(){return ol.geom.flat.inflate.coordinatess(this.flatCoordinates,0,this.ends_,this.stride)};ol.geom.MultiLineString.prototype.getEnds=function(){return this.ends_};ol.geom.MultiLineString.prototype.getLineString=function(index){if(index<0||this.ends_.length<=index)return null;var lineString=new ol.geom.LineString(null);lineString.setFlatCoordinates(this.layout,this.flatCoordinates.slice(index===0?0:this.ends_[index-1],this.ends_[index]));return lineString};
ol.geom.MultiLineString.prototype.getLineStrings=function(){var flatCoordinates=this.flatCoordinates;var ends=this.ends_;var layout=this.layout;var lineStrings=[];var offset=0;var i,ii;for(i=0,ii=ends.length;i<ii;++i){var end=ends[i];var lineString=new ol.geom.LineString(null);lineString.setFlatCoordinates(layout,flatCoordinates.slice(offset,end));lineStrings.push(lineString);offset=end}return lineStrings};
ol.geom.MultiLineString.prototype.getFlatMidpoints=function(){var midpoints=[];var flatCoordinates=this.flatCoordinates;var offset=0;var ends=this.ends_;var stride=this.stride;var i,ii;for(i=0,ii=ends.length;i<ii;++i){var end=ends[i];var midpoint=ol.geom.flat.interpolate.lineString(flatCoordinates,offset,end,stride,.5);ol.array.extend(midpoints,midpoint);offset=end}return midpoints};
ol.geom.MultiLineString.prototype.getSimplifiedGeometryInternal=function(squaredTolerance){var simplifiedFlatCoordinates=[];var simplifiedEnds=[];simplifiedFlatCoordinates.length=ol.geom.flat.simplify.douglasPeuckers(this.flatCoordinates,0,this.ends_,this.stride,squaredTolerance,simplifiedFlatCoordinates,0,simplifiedEnds);var simplifiedMultiLineString=new ol.geom.MultiLineString(null);simplifiedMultiLineString.setFlatCoordinates(ol.geom.GeometryLayout.XY,simplifiedFlatCoordinates,simplifiedEnds);
return simplifiedMultiLineString};ol.geom.MultiLineString.prototype.getType=function(){return ol.geom.GeometryType.MULTI_LINE_STRING};ol.geom.MultiLineString.prototype.intersectsExtent=function(extent){return ol.geom.flat.intersectsextent.lineStrings(this.flatCoordinates,0,this.ends_,this.stride,extent)};
ol.geom.MultiLineString.prototype.setCoordinates=function(coordinates,opt_layout){if(!coordinates)this.setFlatCoordinates(ol.geom.GeometryLayout.XY,null,this.ends_);else{this.setLayout(opt_layout,coordinates,2);if(!this.flatCoordinates)this.flatCoordinates=[];var ends=ol.geom.flat.deflate.coordinatess(this.flatCoordinates,0,coordinates,this.stride,this.ends_);this.flatCoordinates.length=ends.length===0?0:ends[ends.length-1];this.changed()}};
ol.geom.MultiLineString.prototype.setFlatCoordinates=function(layout,flatCoordinates,ends){this.setFlatCoordinatesInternal(layout,flatCoordinates);this.ends_=ends;this.changed()};
ol.geom.MultiLineString.prototype.setLineStrings=function(lineStrings){var layout=this.getLayout();var flatCoordinates=[];var ends=[];var i,ii;for(i=0,ii=lineStrings.length;i<ii;++i){var lineString=lineStrings[i];if(i===0)layout=lineString.getLayout();ol.array.extend(flatCoordinates,lineString.getFlatCoordinates());ends.push(flatCoordinates.length)}this.setFlatCoordinates(layout,flatCoordinates,ends)};goog.provide("ol.geom.MultiPoint");goog.require("ol");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.GeometryType");goog.require("ol.geom.Point");goog.require("ol.geom.SimpleGeometry");goog.require("ol.geom.flat.deflate");goog.require("ol.geom.flat.inflate");goog.require("ol.math");ol.geom.MultiPoint=function(coordinates,opt_layout){ol.geom.SimpleGeometry.call(this);this.setCoordinates(coordinates,opt_layout)};
ol.inherits(ol.geom.MultiPoint,ol.geom.SimpleGeometry);ol.geom.MultiPoint.prototype.appendPoint=function(point){if(!this.flatCoordinates)this.flatCoordinates=point.getFlatCoordinates().slice();else ol.array.extend(this.flatCoordinates,point.getFlatCoordinates());this.changed()};ol.geom.MultiPoint.prototype.clone=function(){var multiPoint=new ol.geom.MultiPoint(null);multiPoint.setFlatCoordinates(this.layout,this.flatCoordinates.slice());return multiPoint};
ol.geom.MultiPoint.prototype.closestPointXY=function(x,y,closestPoint,minSquaredDistance){if(minSquaredDistance<ol.extent.closestSquaredDistanceXY(this.getExtent(),x,y))return minSquaredDistance;var flatCoordinates=this.flatCoordinates;var stride=this.stride;var i,ii,j;for(i=0,ii=flatCoordinates.length;i<ii;i+=stride){var squaredDistance=ol.math.squaredDistance(x,y,flatCoordinates[i],flatCoordinates[i+1]);if(squaredDistance<minSquaredDistance){minSquaredDistance=squaredDistance;for(j=0;j<stride;++j)closestPoint[j]=
flatCoordinates[i+j];closestPoint.length=stride}}return minSquaredDistance};ol.geom.MultiPoint.prototype.getCoordinates=function(){return ol.geom.flat.inflate.coordinates(this.flatCoordinates,0,this.flatCoordinates.length,this.stride)};
ol.geom.MultiPoint.prototype.getPoint=function(index){var n=!this.flatCoordinates?0:this.flatCoordinates.length/this.stride;if(index<0||n<=index)return null;var point=new ol.geom.Point(null);point.setFlatCoordinates(this.layout,this.flatCoordinates.slice(index*this.stride,(index+1)*this.stride));return point};
ol.geom.MultiPoint.prototype.getPoints=function(){var flatCoordinates=this.flatCoordinates;var layout=this.layout;var stride=this.stride;var points=[];var i,ii;for(i=0,ii=flatCoordinates.length;i<ii;i+=stride){var point=new ol.geom.Point(null);point.setFlatCoordinates(layout,flatCoordinates.slice(i,i+stride));points.push(point)}return points};ol.geom.MultiPoint.prototype.getType=function(){return ol.geom.GeometryType.MULTI_POINT};
ol.geom.MultiPoint.prototype.intersectsExtent=function(extent){var flatCoordinates=this.flatCoordinates;var stride=this.stride;var i,ii,x,y;for(i=0,ii=flatCoordinates.length;i<ii;i+=stride){x=flatCoordinates[i];y=flatCoordinates[i+1];if(ol.extent.containsXY(extent,x,y))return true}return false};
ol.geom.MultiPoint.prototype.setCoordinates=function(coordinates,opt_layout){if(!coordinates)this.setFlatCoordinates(ol.geom.GeometryLayout.XY,null);else{this.setLayout(opt_layout,coordinates,1);if(!this.flatCoordinates)this.flatCoordinates=[];this.flatCoordinates.length=ol.geom.flat.deflate.coordinates(this.flatCoordinates,0,coordinates,this.stride);this.changed()}};
ol.geom.MultiPoint.prototype.setFlatCoordinates=function(layout,flatCoordinates){this.setFlatCoordinatesInternal(layout,flatCoordinates);this.changed()};goog.provide("ol.geom.flat.center");goog.require("ol.extent");ol.geom.flat.center.linearRingss=function(flatCoordinates,offset,endss,stride){var flatCenters=[];var i,ii;var extent=ol.extent.createEmpty();for(i=0,ii=endss.length;i<ii;++i){var ends=endss[i];extent=ol.extent.createOrUpdateFromFlatCoordinates(flatCoordinates,offset,ends[0],stride);flatCenters.push((extent[0]+extent[2])/2,(extent[1]+extent[3])/2);offset=ends[ends.length-1]}return flatCenters};goog.provide("ol.geom.MultiPolygon");goog.require("ol");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.GeometryType");goog.require("ol.geom.MultiPoint");goog.require("ol.geom.Polygon");goog.require("ol.geom.SimpleGeometry");goog.require("ol.geom.flat.area");goog.require("ol.geom.flat.center");goog.require("ol.geom.flat.closest");goog.require("ol.geom.flat.contains");goog.require("ol.geom.flat.deflate");goog.require("ol.geom.flat.inflate");
goog.require("ol.geom.flat.interiorpoint");goog.require("ol.geom.flat.intersectsextent");goog.require("ol.geom.flat.orient");goog.require("ol.geom.flat.simplify");ol.geom.MultiPolygon=function(coordinates,opt_layout){ol.geom.SimpleGeometry.call(this);this.endss_=[];this.flatInteriorPointsRevision_=-1;this.flatInteriorPoints_=null;this.maxDelta_=-1;this.maxDeltaRevision_=-1;this.orientedRevision_=-1;this.orientedFlatCoordinates_=null;this.setCoordinates(coordinates,opt_layout)};
ol.inherits(ol.geom.MultiPolygon,ol.geom.SimpleGeometry);ol.geom.MultiPolygon.prototype.appendPolygon=function(polygon){var ends;if(!this.flatCoordinates){this.flatCoordinates=polygon.getFlatCoordinates().slice();ends=polygon.getEnds().slice();this.endss_.push()}else{var offset=this.flatCoordinates.length;ol.array.extend(this.flatCoordinates,polygon.getFlatCoordinates());ends=polygon.getEnds().slice();var i,ii;for(i=0,ii=ends.length;i<ii;++i)ends[i]+=offset}this.endss_.push(ends);this.changed()};
ol.geom.MultiPolygon.prototype.clone=function(){var multiPolygon=new ol.geom.MultiPolygon(null);var len=this.endss_.length;var newEndss=new Array(len);for(var i=0;i<len;++i)newEndss[i]=this.endss_[i].slice();multiPolygon.setFlatCoordinates(this.layout,this.flatCoordinates.slice(),newEndss);return multiPolygon};
ol.geom.MultiPolygon.prototype.closestPointXY=function(x,y,closestPoint,minSquaredDistance){if(minSquaredDistance<ol.extent.closestSquaredDistanceXY(this.getExtent(),x,y))return minSquaredDistance;if(this.maxDeltaRevision_!=this.getRevision()){this.maxDelta_=Math.sqrt(ol.geom.flat.closest.getssMaxSquaredDelta(this.flatCoordinates,0,this.endss_,this.stride,0));this.maxDeltaRevision_=this.getRevision()}return ol.geom.flat.closest.getssClosestPoint(this.getOrientedFlatCoordinates(),0,this.endss_,this.stride,
this.maxDelta_,true,x,y,closestPoint,minSquaredDistance)};ol.geom.MultiPolygon.prototype.containsXY=function(x,y){return ol.geom.flat.contains.linearRingssContainsXY(this.getOrientedFlatCoordinates(),0,this.endss_,this.stride,x,y)};ol.geom.MultiPolygon.prototype.getArea=function(){return ol.geom.flat.area.linearRingss(this.getOrientedFlatCoordinates(),0,this.endss_,this.stride)};
ol.geom.MultiPolygon.prototype.getCoordinates=function(opt_right){var flatCoordinates;if(opt_right!==undefined){flatCoordinates=this.getOrientedFlatCoordinates().slice();ol.geom.flat.orient.orientLinearRingss(flatCoordinates,0,this.endss_,this.stride,opt_right)}else flatCoordinates=this.flatCoordinates;return ol.geom.flat.inflate.coordinatesss(flatCoordinates,0,this.endss_,this.stride)};ol.geom.MultiPolygon.prototype.getEndss=function(){return this.endss_};
ol.geom.MultiPolygon.prototype.getFlatInteriorPoints=function(){if(this.flatInteriorPointsRevision_!=this.getRevision()){var flatCenters=ol.geom.flat.center.linearRingss(this.flatCoordinates,0,this.endss_,this.stride);this.flatInteriorPoints_=ol.geom.flat.interiorpoint.linearRingss(this.getOrientedFlatCoordinates(),0,this.endss_,this.stride,flatCenters);this.flatInteriorPointsRevision_=this.getRevision()}return this.flatInteriorPoints_};
ol.geom.MultiPolygon.prototype.getInteriorPoints=function(){var interiorPoints=new ol.geom.MultiPoint(null);interiorPoints.setFlatCoordinates(ol.geom.GeometryLayout.XYM,this.getFlatInteriorPoints().slice());return interiorPoints};
ol.geom.MultiPolygon.prototype.getOrientedFlatCoordinates=function(){if(this.orientedRevision_!=this.getRevision()){var flatCoordinates=this.flatCoordinates;if(ol.geom.flat.orient.linearRingssAreOriented(flatCoordinates,0,this.endss_,this.stride))this.orientedFlatCoordinates_=flatCoordinates;else{this.orientedFlatCoordinates_=flatCoordinates.slice();this.orientedFlatCoordinates_.length=ol.geom.flat.orient.orientLinearRingss(this.orientedFlatCoordinates_,0,this.endss_,this.stride)}this.orientedRevision_=
this.getRevision()}return this.orientedFlatCoordinates_};
ol.geom.MultiPolygon.prototype.getSimplifiedGeometryInternal=function(squaredTolerance){var simplifiedFlatCoordinates=[];var simplifiedEndss=[];simplifiedFlatCoordinates.length=ol.geom.flat.simplify.quantizess(this.flatCoordinates,0,this.endss_,this.stride,Math.sqrt(squaredTolerance),simplifiedFlatCoordinates,0,simplifiedEndss);var simplifiedMultiPolygon=new ol.geom.MultiPolygon(null);simplifiedMultiPolygon.setFlatCoordinates(ol.geom.GeometryLayout.XY,simplifiedFlatCoordinates,simplifiedEndss);return simplifiedMultiPolygon};
ol.geom.MultiPolygon.prototype.getPolygon=function(index){if(index<0||this.endss_.length<=index)return null;var offset;if(index===0)offset=0;else{var prevEnds=this.endss_[index-1];offset=prevEnds[prevEnds.length-1]}var ends=this.endss_[index].slice();var end=ends[ends.length-1];if(offset!==0){var i,ii;for(i=0,ii=ends.length;i<ii;++i)ends[i]-=offset}var polygon=new ol.geom.Polygon(null);polygon.setFlatCoordinates(this.layout,this.flatCoordinates.slice(offset,end),ends);return polygon};
ol.geom.MultiPolygon.prototype.getPolygons=function(){var layout=this.layout;var flatCoordinates=this.flatCoordinates;var endss=this.endss_;var polygons=[];var offset=0;var i,ii,j,jj;for(i=0,ii=endss.length;i<ii;++i){var ends=endss[i].slice();var end=ends[ends.length-1];if(offset!==0)for(j=0,jj=ends.length;j<jj;++j)ends[j]-=offset;var polygon=new ol.geom.Polygon(null);polygon.setFlatCoordinates(layout,flatCoordinates.slice(offset,end),ends);polygons.push(polygon);offset=end}return polygons};
ol.geom.MultiPolygon.prototype.getType=function(){return ol.geom.GeometryType.MULTI_POLYGON};ol.geom.MultiPolygon.prototype.intersectsExtent=function(extent){return ol.geom.flat.intersectsextent.linearRingss(this.getOrientedFlatCoordinates(),0,this.endss_,this.stride,extent)};
ol.geom.MultiPolygon.prototype.setCoordinates=function(coordinates,opt_layout){if(!coordinates)this.setFlatCoordinates(ol.geom.GeometryLayout.XY,null,this.endss_);else{this.setLayout(opt_layout,coordinates,3);if(!this.flatCoordinates)this.flatCoordinates=[];var endss=ol.geom.flat.deflate.coordinatesss(this.flatCoordinates,0,coordinates,this.stride,this.endss_);if(endss.length===0)this.flatCoordinates.length=0;else{var lastEnds=endss[endss.length-1];this.flatCoordinates.length=lastEnds.length===0?
0:lastEnds[lastEnds.length-1]}this.changed()}};ol.geom.MultiPolygon.prototype.setFlatCoordinates=function(layout,flatCoordinates,endss){this.setFlatCoordinatesInternal(layout,flatCoordinates);this.endss_=endss;this.changed()};
ol.geom.MultiPolygon.prototype.setPolygons=function(polygons){var layout=this.getLayout();var flatCoordinates=[];var endss=[];var i,ii,ends;for(i=0,ii=polygons.length;i<ii;++i){var polygon=polygons[i];if(i===0)layout=polygon.getLayout();var offset=flatCoordinates.length;ends=polygon.getEnds();var j,jj;for(j=0,jj=ends.length;j<jj;++j)ends[j]+=offset;ol.array.extend(flatCoordinates,polygon.getFlatCoordinates());endss.push(ends)}this.setFlatCoordinates(layout,flatCoordinates,endss)};goog.provide("ol.format.EsriJSON");goog.require("ol");goog.require("ol.Feature");goog.require("ol.asserts");goog.require("ol.extent");goog.require("ol.format.Feature");goog.require("ol.format.JSONFeature");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.GeometryType");goog.require("ol.geom.LineString");goog.require("ol.geom.LinearRing");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.MultiPoint");goog.require("ol.geom.MultiPolygon");goog.require("ol.geom.Point");goog.require("ol.geom.Polygon");
goog.require("ol.geom.flat.deflate");goog.require("ol.geom.flat.orient");goog.require("ol.obj");goog.require("ol.proj");ol.format.EsriJSON=function(opt_options){var options=opt_options?opt_options:{};ol.format.JSONFeature.call(this);this.geometryName_=options.geometryName};ol.inherits(ol.format.EsriJSON,ol.format.JSONFeature);
ol.format.EsriJSON.readGeometry_=function(object,opt_options){if(!object)return null;var type;if(typeof object.x==="number"&&typeof object.y==="number")type=ol.geom.GeometryType.POINT;else if(object.points)type=ol.geom.GeometryType.MULTI_POINT;else if(object.paths)if(object.paths.length===1)type=ol.geom.GeometryType.LINE_STRING;else type=ol.geom.GeometryType.MULTI_LINE_STRING;else if(object.rings){var layout=ol.format.EsriJSON.getGeometryLayout_(object);var rings=ol.format.EsriJSON.convertRings_(object.rings,
layout);object=ol.obj.assign({},object);if(rings.length===1){type=ol.geom.GeometryType.POLYGON;object.rings=rings[0]}else{type=ol.geom.GeometryType.MULTI_POLYGON;object.rings=rings}}var geometryReader=ol.format.EsriJSON.GEOMETRY_READERS_[type];return ol.format.Feature.transformWithOptions(geometryReader(object),false,opt_options)};
ol.format.EsriJSON.convertRings_=function(rings,layout){var flatRing=[];var outerRings=[];var holes=[];var i,ii;for(i=0,ii=rings.length;i<ii;++i){flatRing.length=0;ol.geom.flat.deflate.coordinates(flatRing,0,rings[i],layout.length);var clockwise=ol.geom.flat.orient.linearRingIsClockwise(flatRing,0,flatRing.length,layout.length);if(clockwise)outerRings.push([rings[i]]);else holes.push(rings[i])}while(holes.length){var hole=holes.shift();var matched=false;for(i=outerRings.length-1;i>=0;i--){var outerRing=
outerRings[i][0];var containsHole=ol.extent.containsExtent((new ol.geom.LinearRing(outerRing)).getExtent(),(new ol.geom.LinearRing(hole)).getExtent());if(containsHole){outerRings[i].push(hole);matched=true;break}}if(!matched)outerRings.push([hole.reverse()])}return outerRings};
ol.format.EsriJSON.readPointGeometry_=function(object){var point;if(object.m!==undefined&&object.z!==undefined)point=new ol.geom.Point([object.x,object.y,object.z,object.m],ol.geom.GeometryLayout.XYZM);else if(object.z!==undefined)point=new ol.geom.Point([object.x,object.y,object.z],ol.geom.GeometryLayout.XYZ);else if(object.m!==undefined)point=new ol.geom.Point([object.x,object.y,object.m],ol.geom.GeometryLayout.XYM);else point=new ol.geom.Point([object.x,object.y]);return point};
ol.format.EsriJSON.readLineStringGeometry_=function(object){var layout=ol.format.EsriJSON.getGeometryLayout_(object);return new ol.geom.LineString(object.paths[0],layout)};ol.format.EsriJSON.readMultiLineStringGeometry_=function(object){var layout=ol.format.EsriJSON.getGeometryLayout_(object);return new ol.geom.MultiLineString(object.paths,layout)};
ol.format.EsriJSON.getGeometryLayout_=function(object){var layout=ol.geom.GeometryLayout.XY;if(object.hasZ===true&&object.hasM===true)layout=ol.geom.GeometryLayout.XYZM;else if(object.hasZ===true)layout=ol.geom.GeometryLayout.XYZ;else if(object.hasM===true)layout=ol.geom.GeometryLayout.XYM;return layout};ol.format.EsriJSON.readMultiPointGeometry_=function(object){var layout=ol.format.EsriJSON.getGeometryLayout_(object);return new ol.geom.MultiPoint(object.points,layout)};
ol.format.EsriJSON.readMultiPolygonGeometry_=function(object){var layout=ol.format.EsriJSON.getGeometryLayout_(object);return new ol.geom.MultiPolygon(object.rings,layout)};ol.format.EsriJSON.readPolygonGeometry_=function(object){var layout=ol.format.EsriJSON.getGeometryLayout_(object);return new ol.geom.Polygon(object.rings,layout)};
ol.format.EsriJSON.writePointGeometry_=function(geometry,opt_options){var coordinates=geometry.getCoordinates();var esriJSON;var layout=geometry.getLayout();if(layout===ol.geom.GeometryLayout.XYZ)esriJSON={x:coordinates[0],y:coordinates[1],z:coordinates[2]};else if(layout===ol.geom.GeometryLayout.XYM)esriJSON={x:coordinates[0],y:coordinates[1],m:coordinates[2]};else if(layout===ol.geom.GeometryLayout.XYZM)esriJSON={x:coordinates[0],y:coordinates[1],z:coordinates[2],m:coordinates[3]};else if(layout===
ol.geom.GeometryLayout.XY)esriJSON={x:coordinates[0],y:coordinates[1]};else ol.asserts.assert(false,34);return esriJSON};ol.format.EsriJSON.getHasZM_=function(geometry){var layout=geometry.getLayout();return{hasZ:layout===ol.geom.GeometryLayout.XYZ||layout===ol.geom.GeometryLayout.XYZM,hasM:layout===ol.geom.GeometryLayout.XYM||layout===ol.geom.GeometryLayout.XYZM}};
ol.format.EsriJSON.writeLineStringGeometry_=function(geometry,opt_options){var hasZM=ol.format.EsriJSON.getHasZM_(geometry);return{hasZ:hasZM.hasZ,hasM:hasZM.hasM,paths:[geometry.getCoordinates()]}};ol.format.EsriJSON.writePolygonGeometry_=function(geometry,opt_options){var hasZM=ol.format.EsriJSON.getHasZM_(geometry);return{hasZ:hasZM.hasZ,hasM:hasZM.hasM,rings:geometry.getCoordinates(false)}};
ol.format.EsriJSON.writeMultiLineStringGeometry_=function(geometry,opt_options){var hasZM=ol.format.EsriJSON.getHasZM_(geometry);return{hasZ:hasZM.hasZ,hasM:hasZM.hasM,paths:geometry.getCoordinates()}};ol.format.EsriJSON.writeMultiPointGeometry_=function(geometry,opt_options){var hasZM=ol.format.EsriJSON.getHasZM_(geometry);return{hasZ:hasZM.hasZ,hasM:hasZM.hasM,points:geometry.getCoordinates()}};
ol.format.EsriJSON.writeMultiPolygonGeometry_=function(geometry,opt_options){var hasZM=ol.format.EsriJSON.getHasZM_(geometry);var coordinates=geometry.getCoordinates(false);var output=[];for(var i=0;i<coordinates.length;i++)for(var x=coordinates[i].length-1;x>=0;x--)output.push(coordinates[i][x]);return{hasZ:hasZM.hasZ,hasM:hasZM.hasM,rings:output}};ol.format.EsriJSON.GEOMETRY_READERS_={};ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.POINT]=ol.format.EsriJSON.readPointGeometry_;
ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.LINE_STRING]=ol.format.EsriJSON.readLineStringGeometry_;ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.POLYGON]=ol.format.EsriJSON.readPolygonGeometry_;ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_POINT]=ol.format.EsriJSON.readMultiPointGeometry_;ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_LINE_STRING]=ol.format.EsriJSON.readMultiLineStringGeometry_;
ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_POLYGON]=ol.format.EsriJSON.readMultiPolygonGeometry_;ol.format.EsriJSON.GEOMETRY_WRITERS_={};ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.POINT]=ol.format.EsriJSON.writePointGeometry_;ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.LINE_STRING]=ol.format.EsriJSON.writeLineStringGeometry_;ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.POLYGON]=ol.format.EsriJSON.writePolygonGeometry_;
ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_POINT]=ol.format.EsriJSON.writeMultiPointGeometry_;ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_LINE_STRING]=ol.format.EsriJSON.writeMultiLineStringGeometry_;ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_POLYGON]=ol.format.EsriJSON.writeMultiPolygonGeometry_;ol.format.EsriJSON.prototype.readFeature;ol.format.EsriJSON.prototype.readFeatures;
ol.format.EsriJSON.prototype.readFeatureFromObject=function(object,opt_options){var esriJSONFeature=object;var geometry=ol.format.EsriJSON.readGeometry_(esriJSONFeature.geometry,opt_options);var feature=new ol.Feature;if(this.geometryName_)feature.setGeometryName(this.geometryName_);feature.setGeometry(geometry);if(opt_options&&opt_options.idField&&esriJSONFeature.attributes[opt_options.idField])feature.setId(esriJSONFeature.attributes[opt_options.idField]);if(esriJSONFeature.attributes)feature.setProperties(esriJSONFeature.attributes);
return feature};
ol.format.EsriJSON.prototype.readFeaturesFromObject=function(object,opt_options){var esriJSONObject=object;var options=opt_options?opt_options:{};if(esriJSONObject.features){var esriJSONFeatureCollection=object;var features=[];var esriJSONFeatures=esriJSONFeatureCollection.features;var i,ii;options.idField=object.objectIdFieldName;for(i=0,ii=esriJSONFeatures.length;i<ii;++i)features.push(this.readFeatureFromObject(esriJSONFeatures[i],options));return features}else return[this.readFeatureFromObject(object,options)]};
ol.format.EsriJSON.prototype.readGeometry;ol.format.EsriJSON.prototype.readGeometryFromObject=function(object,opt_options){return ol.format.EsriJSON.readGeometry_(object,opt_options)};ol.format.EsriJSON.prototype.readProjection;ol.format.EsriJSON.prototype.readProjectionFromObject=function(object){var esriJSONObject=object;if(esriJSONObject.spatialReference&&esriJSONObject.spatialReference.wkid){var crs=esriJSONObject.spatialReference.wkid;return ol.proj.get("EPSG:"+crs)}else return null};
ol.format.EsriJSON.writeGeometry_=function(geometry,opt_options){var geometryWriter=ol.format.EsriJSON.GEOMETRY_WRITERS_[geometry.getType()];return geometryWriter(ol.format.Feature.transformWithOptions(geometry,true,opt_options),opt_options)};ol.format.EsriJSON.prototype.writeGeometry;ol.format.EsriJSON.prototype.writeGeometryObject=function(geometry,opt_options){return ol.format.EsriJSON.writeGeometry_(geometry,this.adaptOptions(opt_options))};ol.format.EsriJSON.prototype.writeFeature;
ol.format.EsriJSON.prototype.writeFeatureObject=function(feature,opt_options){opt_options=this.adaptOptions(opt_options);var object={};var geometry=feature.getGeometry();if(geometry){object["geometry"]=ol.format.EsriJSON.writeGeometry_(geometry,opt_options);if(opt_options&&opt_options.featureProjection)object["geometry"]["spatialReference"]={wkid:ol.proj.get(opt_options.featureProjection).getCode().split(":").pop()}}var properties=feature.getProperties();delete properties[feature.getGeometryName()];
if(!ol.obj.isEmpty(properties))object["attributes"]=properties;else object["attributes"]={};return object};ol.format.EsriJSON.prototype.writeFeatures;ol.format.EsriJSON.prototype.writeFeaturesObject=function(features,opt_options){opt_options=this.adaptOptions(opt_options);var objects=[];var i,ii;for(i=0,ii=features.length;i<ii;++i)objects.push(this.writeFeatureObject(features[i],opt_options));return{"features":objects}};goog.provide("ol.format.filter.Filter");ol.format.filter.Filter=function(tagName){this.tagName_=tagName};ol.format.filter.Filter.prototype.getTagName=function(){return this.tagName_};goog.provide("ol.format.filter.LogicalNary");goog.require("ol");goog.require("ol.asserts");goog.require("ol.format.filter.Filter");ol.format.filter.LogicalNary=function(tagName,conditions){ol.format.filter.Filter.call(this,tagName);this.conditions=Array.prototype.slice.call(arguments,1);ol.asserts.assert(this.conditions.length>=2,57)};ol.inherits(ol.format.filter.LogicalNary,ol.format.filter.Filter);goog.provide("ol.format.filter.And");goog.require("ol");goog.require("ol.format.filter.LogicalNary");ol.format.filter.And=function(conditions){var params=["And"].concat(Array.prototype.slice.call(arguments));ol.format.filter.LogicalNary.apply(this,params)};ol.inherits(ol.format.filter.And,ol.format.filter.LogicalNary);goog.provide("ol.format.filter.Bbox");goog.require("ol");goog.require("ol.format.filter.Filter");ol.format.filter.Bbox=function(geometryName,extent,opt_srsName){ol.format.filter.Filter.call(this,"BBOX");this.geometryName=geometryName;this.extent=extent;this.srsName=opt_srsName};ol.inherits(ol.format.filter.Bbox,ol.format.filter.Filter);goog.provide("ol.format.filter.Spatial");goog.require("ol");goog.require("ol.format.filter.Filter");ol.format.filter.Spatial=function(tagName,geometryName,geometry,opt_srsName){ol.format.filter.Filter.call(this,tagName);this.geometryName=geometryName||"the_geom";this.geometry=geometry;this.srsName=opt_srsName};ol.inherits(ol.format.filter.Spatial,ol.format.filter.Filter);goog.provide("ol.format.filter.Contains");goog.require("ol");goog.require("ol.format.filter.Spatial");ol.format.filter.Contains=function(geometryName,geometry,opt_srsName){ol.format.filter.Spatial.call(this,"Contains",geometryName,geometry,opt_srsName)};ol.inherits(ol.format.filter.Contains,ol.format.filter.Spatial);goog.provide("ol.format.filter.Comparison");goog.require("ol");goog.require("ol.format.filter.Filter");ol.format.filter.Comparison=function(tagName,propertyName){ol.format.filter.Filter.call(this,tagName);this.propertyName=propertyName};ol.inherits(ol.format.filter.Comparison,ol.format.filter.Filter);goog.provide("ol.format.filter.During");goog.require("ol");goog.require("ol.format.filter.Comparison");ol.format.filter.During=function(propertyName,begin,end){ol.format.filter.Comparison.call(this,"During",propertyName);this.begin=begin;this.end=end};ol.inherits(ol.format.filter.During,ol.format.filter.Comparison);goog.provide("ol.format.filter.ComparisonBinary");goog.require("ol");goog.require("ol.format.filter.Comparison");ol.format.filter.ComparisonBinary=function(tagName,propertyName,expression,opt_matchCase){ol.format.filter.Comparison.call(this,tagName,propertyName);this.expression=expression;this.matchCase=opt_matchCase};ol.inherits(ol.format.filter.ComparisonBinary,ol.format.filter.Comparison);goog.provide("ol.format.filter.EqualTo");goog.require("ol");goog.require("ol.format.filter.ComparisonBinary");ol.format.filter.EqualTo=function(propertyName,expression,opt_matchCase){ol.format.filter.ComparisonBinary.call(this,"PropertyIsEqualTo",propertyName,expression,opt_matchCase)};ol.inherits(ol.format.filter.EqualTo,ol.format.filter.ComparisonBinary);goog.provide("ol.format.filter.GreaterThan");goog.require("ol");goog.require("ol.format.filter.ComparisonBinary");ol.format.filter.GreaterThan=function(propertyName,expression){ol.format.filter.ComparisonBinary.call(this,"PropertyIsGreaterThan",propertyName,expression)};ol.inherits(ol.format.filter.GreaterThan,ol.format.filter.ComparisonBinary);goog.provide("ol.format.filter.GreaterThanOrEqualTo");goog.require("ol");goog.require("ol.format.filter.ComparisonBinary");ol.format.filter.GreaterThanOrEqualTo=function(propertyName,expression){ol.format.filter.ComparisonBinary.call(this,"PropertyIsGreaterThanOrEqualTo",propertyName,expression)};ol.inherits(ol.format.filter.GreaterThanOrEqualTo,ol.format.filter.ComparisonBinary);goog.provide("ol.format.filter.Intersects");goog.require("ol");goog.require("ol.format.filter.Spatial");ol.format.filter.Intersects=function(geometryName,geometry,opt_srsName){ol.format.filter.Spatial.call(this,"Intersects",geometryName,geometry,opt_srsName)};ol.inherits(ol.format.filter.Intersects,ol.format.filter.Spatial);goog.provide("ol.format.filter.IsBetween");goog.require("ol");goog.require("ol.format.filter.Comparison");ol.format.filter.IsBetween=function(propertyName,lowerBoundary,upperBoundary){ol.format.filter.Comparison.call(this,"PropertyIsBetween",propertyName);this.lowerBoundary=lowerBoundary;this.upperBoundary=upperBoundary};ol.inherits(ol.format.filter.IsBetween,ol.format.filter.Comparison);goog.provide("ol.format.filter.IsLike");goog.require("ol");goog.require("ol.format.filter.Comparison");ol.format.filter.IsLike=function(propertyName,pattern,opt_wildCard,opt_singleChar,opt_escapeChar,opt_matchCase){ol.format.filter.Comparison.call(this,"PropertyIsLike",propertyName);this.pattern=pattern;this.wildCard=opt_wildCard!==undefined?opt_wildCard:"*";this.singleChar=opt_singleChar!==undefined?opt_singleChar:".";this.escapeChar=opt_escapeChar!==undefined?opt_escapeChar:"!";this.matchCase=opt_matchCase};
ol.inherits(ol.format.filter.IsLike,ol.format.filter.Comparison);goog.provide("ol.format.filter.IsNull");goog.require("ol");goog.require("ol.format.filter.Comparison");ol.format.filter.IsNull=function(propertyName){ol.format.filter.Comparison.call(this,"PropertyIsNull",propertyName)};ol.inherits(ol.format.filter.IsNull,ol.format.filter.Comparison);goog.provide("ol.format.filter.LessThan");goog.require("ol");goog.require("ol.format.filter.ComparisonBinary");ol.format.filter.LessThan=function(propertyName,expression){ol.format.filter.ComparisonBinary.call(this,"PropertyIsLessThan",propertyName,expression)};ol.inherits(ol.format.filter.LessThan,ol.format.filter.ComparisonBinary);goog.provide("ol.format.filter.LessThanOrEqualTo");goog.require("ol");goog.require("ol.format.filter.ComparisonBinary");ol.format.filter.LessThanOrEqualTo=function(propertyName,expression){ol.format.filter.ComparisonBinary.call(this,"PropertyIsLessThanOrEqualTo",propertyName,expression)};ol.inherits(ol.format.filter.LessThanOrEqualTo,ol.format.filter.ComparisonBinary);goog.provide("ol.format.filter.Not");goog.require("ol");goog.require("ol.format.filter.Filter");ol.format.filter.Not=function(condition){ol.format.filter.Filter.call(this,"Not");this.condition=condition};ol.inherits(ol.format.filter.Not,ol.format.filter.Filter);goog.provide("ol.format.filter.NotEqualTo");goog.require("ol");goog.require("ol.format.filter.ComparisonBinary");ol.format.filter.NotEqualTo=function(propertyName,expression,opt_matchCase){ol.format.filter.ComparisonBinary.call(this,"PropertyIsNotEqualTo",propertyName,expression,opt_matchCase)};ol.inherits(ol.format.filter.NotEqualTo,ol.format.filter.ComparisonBinary);goog.provide("ol.format.filter.Or");goog.require("ol");goog.require("ol.format.filter.LogicalNary");ol.format.filter.Or=function(conditions){var params=["Or"].concat(Array.prototype.slice.call(arguments));ol.format.filter.LogicalNary.apply(this,params)};ol.inherits(ol.format.filter.Or,ol.format.filter.LogicalNary);goog.provide("ol.format.filter.Within");goog.require("ol");goog.require("ol.format.filter.Spatial");ol.format.filter.Within=function(geometryName,geometry,opt_srsName){ol.format.filter.Spatial.call(this,"Within",geometryName,geometry,opt_srsName)};ol.inherits(ol.format.filter.Within,ol.format.filter.Spatial);goog.provide("ol.format.filter");goog.require("ol.format.filter.And");goog.require("ol.format.filter.Bbox");goog.require("ol.format.filter.Contains");goog.require("ol.format.filter.During");goog.require("ol.format.filter.EqualTo");goog.require("ol.format.filter.GreaterThan");goog.require("ol.format.filter.GreaterThanOrEqualTo");goog.require("ol.format.filter.Intersects");goog.require("ol.format.filter.IsBetween");goog.require("ol.format.filter.IsLike");goog.require("ol.format.filter.IsNull");goog.require("ol.format.filter.LessThan");
goog.require("ol.format.filter.LessThanOrEqualTo");goog.require("ol.format.filter.Not");goog.require("ol.format.filter.NotEqualTo");goog.require("ol.format.filter.Or");goog.require("ol.format.filter.Within");ol.format.filter.and=function(conditions){var params=[null].concat(Array.prototype.slice.call(arguments));return new (Function.prototype.bind.apply(ol.format.filter.And,params))};
ol.format.filter.or=function(conditions){var params=[null].concat(Array.prototype.slice.call(arguments));return new (Function.prototype.bind.apply(ol.format.filter.Or,params))};ol.format.filter.not=function(condition){return new ol.format.filter.Not(condition)};ol.format.filter.bbox=function(geometryName,extent,opt_srsName){return new ol.format.filter.Bbox(geometryName,extent,opt_srsName)};
ol.format.filter.contains=function(geometryName,geometry,opt_srsName){return new ol.format.filter.Contains(geometryName,geometry,opt_srsName)};ol.format.filter.intersects=function(geometryName,geometry,opt_srsName){return new ol.format.filter.Intersects(geometryName,geometry,opt_srsName)};ol.format.filter.within=function(geometryName,geometry,opt_srsName){return new ol.format.filter.Within(geometryName,geometry,opt_srsName)};
ol.format.filter.equalTo=function(propertyName,expression,opt_matchCase){return new ol.format.filter.EqualTo(propertyName,expression,opt_matchCase)};ol.format.filter.notEqualTo=function(propertyName,expression,opt_matchCase){return new ol.format.filter.NotEqualTo(propertyName,expression,opt_matchCase)};ol.format.filter.lessThan=function(propertyName,expression){return new ol.format.filter.LessThan(propertyName,expression)};
ol.format.filter.lessThanOrEqualTo=function(propertyName,expression){return new ol.format.filter.LessThanOrEqualTo(propertyName,expression)};ol.format.filter.greaterThan=function(propertyName,expression){return new ol.format.filter.GreaterThan(propertyName,expression)};ol.format.filter.greaterThanOrEqualTo=function(propertyName,expression){return new ol.format.filter.GreaterThanOrEqualTo(propertyName,expression)};ol.format.filter.isNull=function(propertyName){return new ol.format.filter.IsNull(propertyName)};
ol.format.filter.between=function(propertyName,lowerBoundary,upperBoundary){return new ol.format.filter.IsBetween(propertyName,lowerBoundary,upperBoundary)};ol.format.filter.like=function(propertyName,pattern,opt_wildCard,opt_singleChar,opt_escapeChar,opt_matchCase){return new ol.format.filter.IsLike(propertyName,pattern,opt_wildCard,opt_singleChar,opt_escapeChar,opt_matchCase)};ol.format.filter.during=function(propertyName,begin,end){return new ol.format.filter.During(propertyName,begin,end)};goog.provide("ol.geom.GeometryCollection");goog.require("ol");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.geom.Geometry");goog.require("ol.geom.GeometryType");goog.require("ol.obj");ol.geom.GeometryCollection=function(opt_geometries){ol.geom.Geometry.call(this);this.geometries_=opt_geometries?opt_geometries:null;this.listenGeometriesChange_()};ol.inherits(ol.geom.GeometryCollection,ol.geom.Geometry);
ol.geom.GeometryCollection.cloneGeometries_=function(geometries){var clonedGeometries=[];var i,ii;for(i=0,ii=geometries.length;i<ii;++i)clonedGeometries.push(geometries[i].clone());return clonedGeometries};ol.geom.GeometryCollection.prototype.unlistenGeometriesChange_=function(){var i,ii;if(!this.geometries_)return;for(i=0,ii=this.geometries_.length;i<ii;++i)ol.events.unlisten(this.geometries_[i],ol.events.EventType.CHANGE,this.changed,this)};
ol.geom.GeometryCollection.prototype.listenGeometriesChange_=function(){var i,ii;if(!this.geometries_)return;for(i=0,ii=this.geometries_.length;i<ii;++i)ol.events.listen(this.geometries_[i],ol.events.EventType.CHANGE,this.changed,this)};ol.geom.GeometryCollection.prototype.clone=function(){var geometryCollection=new ol.geom.GeometryCollection(null);geometryCollection.setGeometries(this.geometries_);return geometryCollection};
ol.geom.GeometryCollection.prototype.closestPointXY=function(x,y,closestPoint,minSquaredDistance){if(minSquaredDistance<ol.extent.closestSquaredDistanceXY(this.getExtent(),x,y))return minSquaredDistance;var geometries=this.geometries_;var i,ii;for(i=0,ii=geometries.length;i<ii;++i)minSquaredDistance=geometries[i].closestPointXY(x,y,closestPoint,minSquaredDistance);return minSquaredDistance};
ol.geom.GeometryCollection.prototype.containsXY=function(x,y){var geometries=this.geometries_;var i,ii;for(i=0,ii=geometries.length;i<ii;++i)if(geometries[i].containsXY(x,y))return true;return false};ol.geom.GeometryCollection.prototype.computeExtent=function(extent){ol.extent.createOrUpdateEmpty(extent);var geometries=this.geometries_;for(var i=0,ii=geometries.length;i<ii;++i)ol.extent.extend(extent,geometries[i].getExtent());return extent};ol.geom.GeometryCollection.prototype.getGeometries=function(){return ol.geom.GeometryCollection.cloneGeometries_(this.geometries_)};
ol.geom.GeometryCollection.prototype.getGeometriesArray=function(){return this.geometries_};
ol.geom.GeometryCollection.prototype.getSimplifiedGeometry=function(squaredTolerance){if(this.simplifiedGeometryRevision!=this.getRevision()){ol.obj.clear(this.simplifiedGeometryCache);this.simplifiedGeometryMaxMinSquaredTolerance=0;this.simplifiedGeometryRevision=this.getRevision()}if(squaredTolerance<0||this.simplifiedGeometryMaxMinSquaredTolerance!==0&&squaredTolerance<this.simplifiedGeometryMaxMinSquaredTolerance)return this;var key=squaredTolerance.toString();if(this.simplifiedGeometryCache.hasOwnProperty(key))return this.simplifiedGeometryCache[key];
else{var simplifiedGeometries=[];var geometries=this.geometries_;var simplified=false;var i,ii;for(i=0,ii=geometries.length;i<ii;++i){var geometry=geometries[i];var simplifiedGeometry=geometry.getSimplifiedGeometry(squaredTolerance);simplifiedGeometries.push(simplifiedGeometry);if(simplifiedGeometry!==geometry)simplified=true}if(simplified){var simplifiedGeometryCollection=new ol.geom.GeometryCollection(null);simplifiedGeometryCollection.setGeometriesArray(simplifiedGeometries);this.simplifiedGeometryCache[key]=
simplifiedGeometryCollection;return simplifiedGeometryCollection}else{this.simplifiedGeometryMaxMinSquaredTolerance=squaredTolerance;return this}}};ol.geom.GeometryCollection.prototype.getType=function(){return ol.geom.GeometryType.GEOMETRY_COLLECTION};ol.geom.GeometryCollection.prototype.intersectsExtent=function(extent){var geometries=this.geometries_;var i,ii;for(i=0,ii=geometries.length;i<ii;++i)if(geometries[i].intersectsExtent(extent))return true;return false};
ol.geom.GeometryCollection.prototype.isEmpty=function(){return this.geometries_.length===0};ol.geom.GeometryCollection.prototype.rotate=function(angle,anchor){var geometries=this.geometries_;for(var i=0,ii=geometries.length;i<ii;++i)geometries[i].rotate(angle,anchor);this.changed()};
ol.geom.GeometryCollection.prototype.scale=function(sx,opt_sy,opt_anchor){var anchor=opt_anchor;if(!anchor)anchor=ol.extent.getCenter(this.getExtent());var geometries=this.geometries_;for(var i=0,ii=geometries.length;i<ii;++i)geometries[i].scale(sx,opt_sy,anchor);this.changed()};ol.geom.GeometryCollection.prototype.setGeometries=function(geometries){this.setGeometriesArray(ol.geom.GeometryCollection.cloneGeometries_(geometries))};
ol.geom.GeometryCollection.prototype.setGeometriesArray=function(geometries){this.unlistenGeometriesChange_();this.geometries_=geometries;this.listenGeometriesChange_();this.changed()};ol.geom.GeometryCollection.prototype.applyTransform=function(transformFn){var geometries=this.geometries_;var i,ii;for(i=0,ii=geometries.length;i<ii;++i)geometries[i].applyTransform(transformFn);this.changed()};
ol.geom.GeometryCollection.prototype.translate=function(deltaX,deltaY){var geometries=this.geometries_;var i,ii;for(i=0,ii=geometries.length;i<ii;++i)geometries[i].translate(deltaX,deltaY);this.changed()};ol.geom.GeometryCollection.prototype.disposeInternal=function(){this.unlistenGeometriesChange_();ol.geom.Geometry.prototype.disposeInternal.call(this)};goog.provide("ol.format.GeoJSON");goog.require("ol");goog.require("ol.asserts");goog.require("ol.Feature");goog.require("ol.format.Feature");goog.require("ol.format.JSONFeature");goog.require("ol.geom.GeometryCollection");goog.require("ol.geom.LineString");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.MultiPoint");goog.require("ol.geom.MultiPolygon");goog.require("ol.geom.Point");goog.require("ol.geom.Polygon");goog.require("ol.obj");goog.require("ol.proj");
ol.format.GeoJSON=function(opt_options){var options=opt_options?opt_options:{};ol.format.JSONFeature.call(this);this.defaultDataProjection=ol.proj.get(options.defaultDataProjection?options.defaultDataProjection:"EPSG:4326");if(options.featureProjection)this.defaultFeatureProjection=ol.proj.get(options.featureProjection);this.geometryName_=options.geometryName;this.extractGeometryName_=options.extractGeometryName};ol.inherits(ol.format.GeoJSON,ol.format.JSONFeature);
ol.format.GeoJSON.readGeometry_=function(object,opt_options){if(!object)return null;var geometryReader=ol.format.GeoJSON.GEOMETRY_READERS_[object.type];return ol.format.Feature.transformWithOptions(geometryReader(object),false,opt_options)};ol.format.GeoJSON.readGeometryCollectionGeometry_=function(object,opt_options){var geometries=object.geometries.map(function(geometry){return ol.format.GeoJSON.readGeometry_(geometry,opt_options)});return new ol.geom.GeometryCollection(geometries)};
ol.format.GeoJSON.readPointGeometry_=function(object){return new ol.geom.Point(object.coordinates)};ol.format.GeoJSON.readLineStringGeometry_=function(object){return new ol.geom.LineString(object.coordinates)};ol.format.GeoJSON.readMultiLineStringGeometry_=function(object){return new ol.geom.MultiLineString(object.coordinates)};ol.format.GeoJSON.readMultiPointGeometry_=function(object){return new ol.geom.MultiPoint(object.coordinates)};ol.format.GeoJSON.readMultiPolygonGeometry_=function(object){return new ol.geom.MultiPolygon(object.coordinates)};
ol.format.GeoJSON.readPolygonGeometry_=function(object){return new ol.geom.Polygon(object.coordinates)};ol.format.GeoJSON.writeGeometry_=function(geometry,opt_options){var geometryWriter=ol.format.GeoJSON.GEOMETRY_WRITERS_[geometry.getType()];return geometryWriter(ol.format.Feature.transformWithOptions(geometry,true,opt_options),opt_options)};ol.format.GeoJSON.writeEmptyGeometryCollectionGeometry_=function(geometry){return{type:"GeometryCollection",geometries:[]}};
ol.format.GeoJSON.writeGeometryCollectionGeometry_=function(geometry,opt_options){var geometries=geometry.getGeometriesArray().map(function(geometry){var options=ol.obj.assign({},opt_options);delete options.featureProjection;return ol.format.GeoJSON.writeGeometry_(geometry,options)});return{type:"GeometryCollection",geometries:geometries}};ol.format.GeoJSON.writeLineStringGeometry_=function(geometry,opt_options){return{type:"LineString",coordinates:geometry.getCoordinates()}};
ol.format.GeoJSON.writeMultiLineStringGeometry_=function(geometry,opt_options){return{type:"MultiLineString",coordinates:geometry.getCoordinates()}};ol.format.GeoJSON.writeMultiPointGeometry_=function(geometry,opt_options){return{type:"MultiPoint",coordinates:geometry.getCoordinates()}};ol.format.GeoJSON.writeMultiPolygonGeometry_=function(geometry,opt_options){var right;if(opt_options)right=opt_options.rightHanded;return{type:"MultiPolygon",coordinates:geometry.getCoordinates(right)}};
ol.format.GeoJSON.writePointGeometry_=function(geometry,opt_options){return{type:"Point",coordinates:geometry.getCoordinates()}};ol.format.GeoJSON.writePolygonGeometry_=function(geometry,opt_options){var right;if(opt_options)right=opt_options.rightHanded;return{type:"Polygon",coordinates:geometry.getCoordinates(right)}};
ol.format.GeoJSON.GEOMETRY_READERS_={"Point":ol.format.GeoJSON.readPointGeometry_,"LineString":ol.format.GeoJSON.readLineStringGeometry_,"Polygon":ol.format.GeoJSON.readPolygonGeometry_,"MultiPoint":ol.format.GeoJSON.readMultiPointGeometry_,"MultiLineString":ol.format.GeoJSON.readMultiLineStringGeometry_,"MultiPolygon":ol.format.GeoJSON.readMultiPolygonGeometry_,"GeometryCollection":ol.format.GeoJSON.readGeometryCollectionGeometry_};
ol.format.GeoJSON.GEOMETRY_WRITERS_={"Point":ol.format.GeoJSON.writePointGeometry_,"LineString":ol.format.GeoJSON.writeLineStringGeometry_,"Polygon":ol.format.GeoJSON.writePolygonGeometry_,"MultiPoint":ol.format.GeoJSON.writeMultiPointGeometry_,"MultiLineString":ol.format.GeoJSON.writeMultiLineStringGeometry_,"MultiPolygon":ol.format.GeoJSON.writeMultiPolygonGeometry_,"GeometryCollection":ol.format.GeoJSON.writeGeometryCollectionGeometry_,"Circle":ol.format.GeoJSON.writeEmptyGeometryCollectionGeometry_};
ol.format.GeoJSON.prototype.readFeature;ol.format.GeoJSON.prototype.readFeatures;
ol.format.GeoJSON.prototype.readFeatureFromObject=function(object,opt_options){var geoJSONFeature=null;if(object.type==="Feature")geoJSONFeature=object;else geoJSONFeature={type:"Feature",geometry:object};var geometry=ol.format.GeoJSON.readGeometry_(geoJSONFeature.geometry,opt_options);var feature=new ol.Feature;if(this.geometryName_)feature.setGeometryName(this.geometryName_);else if(this.extractGeometryName_&&geoJSONFeature.geometry_name!==undefined)feature.setGeometryName(geoJSONFeature.geometry_name);
feature.setGeometry(geometry);if(geoJSONFeature.id!==undefined)feature.setId(geoJSONFeature.id);if(geoJSONFeature.properties)feature.setProperties(geoJSONFeature.properties);return feature};
ol.format.GeoJSON.prototype.readFeaturesFromObject=function(object,opt_options){var geoJSONObject=object;var features=null;if(geoJSONObject.type==="FeatureCollection"){var geoJSONFeatureCollection=object;features=[];var geoJSONFeatures=geoJSONFeatureCollection.features;var i,ii;for(i=0,ii=geoJSONFeatures.length;i<ii;++i)features.push(this.readFeatureFromObject(geoJSONFeatures[i],opt_options))}else features=[this.readFeatureFromObject(object,opt_options)];return features};ol.format.GeoJSON.prototype.readGeometry;
ol.format.GeoJSON.prototype.readGeometryFromObject=function(object,opt_options){return ol.format.GeoJSON.readGeometry_(object,opt_options)};ol.format.GeoJSON.prototype.readProjection;ol.format.GeoJSON.prototype.readProjectionFromObject=function(object){var geoJSONObject=object;var crs=geoJSONObject.crs;var projection;if(crs)if(crs.type=="name")projection=ol.proj.get(crs.properties.name);else ol.asserts.assert(false,36);else projection=this.defaultDataProjection;return projection};ol.format.GeoJSON.prototype.writeFeature;
ol.format.GeoJSON.prototype.writeFeatureObject=function(feature,opt_options){opt_options=this.adaptOptions(opt_options);var object={"type":"Feature"};var id=feature.getId();if(id!==undefined)object.id=id;var geometry=feature.getGeometry();if(geometry)object.geometry=ol.format.GeoJSON.writeGeometry_(geometry,opt_options);else object.geometry=null;var properties=feature.getProperties();delete properties[feature.getGeometryName()];if(!ol.obj.isEmpty(properties))object.properties=properties;else object.properties=
null;return object};ol.format.GeoJSON.prototype.writeFeatures;ol.format.GeoJSON.prototype.writeFeaturesObject=function(features,opt_options){opt_options=this.adaptOptions(opt_options);var objects=[];var i,ii;for(i=0,ii=features.length;i<ii;++i)objects.push(this.writeFeatureObject(features[i],opt_options));return{type:"FeatureCollection",features:objects}};ol.format.GeoJSON.prototype.writeGeometry;
ol.format.GeoJSON.prototype.writeGeometryObject=function(geometry,opt_options){return ol.format.GeoJSON.writeGeometry_(geometry,this.adaptOptions(opt_options))};goog.provide("ol.format.XMLFeature");goog.require("ol");goog.require("ol.array");goog.require("ol.format.Feature");goog.require("ol.format.FormatType");goog.require("ol.xml");ol.format.XMLFeature=function(){this.xmlSerializer_=new XMLSerializer;ol.format.Feature.call(this)};ol.inherits(ol.format.XMLFeature,ol.format.Feature);ol.format.XMLFeature.prototype.getType=function(){return ol.format.FormatType.XML};
ol.format.XMLFeature.prototype.readFeature=function(source,opt_options){if(ol.xml.isDocument(source))return this.readFeatureFromDocument(source,opt_options);else if(ol.xml.isNode(source))return this.readFeatureFromNode(source,opt_options);else if(typeof source==="string"){var doc=ol.xml.parse(source);return this.readFeatureFromDocument(doc,opt_options)}else return null};
ol.format.XMLFeature.prototype.readFeatureFromDocument=function(doc,opt_options){var features=this.readFeaturesFromDocument(doc,opt_options);if(features.length>0)return features[0];else return null};ol.format.XMLFeature.prototype.readFeatureFromNode=function(node,opt_options){return null};
ol.format.XMLFeature.prototype.readFeatures=function(source,opt_options){if(ol.xml.isDocument(source))return this.readFeaturesFromDocument(source,opt_options);else if(ol.xml.isNode(source))return this.readFeaturesFromNode(source,opt_options);else if(typeof source==="string"){var doc=ol.xml.parse(source);return this.readFeaturesFromDocument(doc,opt_options)}else return[]};
ol.format.XMLFeature.prototype.readFeaturesFromDocument=function(doc,opt_options){var features=[];var n;for(n=doc.firstChild;n;n=n.nextSibling)if(n.nodeType==Node.ELEMENT_NODE)ol.array.extend(features,this.readFeaturesFromNode(n,opt_options));return features};ol.format.XMLFeature.prototype.readFeaturesFromNode=function(node,opt_options){};
ol.format.XMLFeature.prototype.readGeometry=function(source,opt_options){if(ol.xml.isDocument(source))return this.readGeometryFromDocument(source,opt_options);else if(ol.xml.isNode(source))return this.readGeometryFromNode(source,opt_options);else if(typeof source==="string"){var doc=ol.xml.parse(source);return this.readGeometryFromDocument(doc,opt_options)}else return null};ol.format.XMLFeature.prototype.readGeometryFromDocument=function(doc,opt_options){return null};
ol.format.XMLFeature.prototype.readGeometryFromNode=function(node,opt_options){return null};ol.format.XMLFeature.prototype.readProjection=function(source){if(ol.xml.isDocument(source))return this.readProjectionFromDocument(source);else if(ol.xml.isNode(source))return this.readProjectionFromNode(source);else if(typeof source==="string"){var doc=ol.xml.parse(source);return this.readProjectionFromDocument(doc)}else return null};ol.format.XMLFeature.prototype.readProjectionFromDocument=function(doc){return this.defaultDataProjection};
ol.format.XMLFeature.prototype.readProjectionFromNode=function(node){return this.defaultDataProjection};ol.format.XMLFeature.prototype.writeFeature=function(feature,opt_options){var node=this.writeFeatureNode(feature,opt_options);return this.xmlSerializer_.serializeToString(node)};ol.format.XMLFeature.prototype.writeFeatureNode=function(feature,opt_options){return null};
ol.format.XMLFeature.prototype.writeFeatures=function(features,opt_options){var node=this.writeFeaturesNode(features,opt_options);return this.xmlSerializer_.serializeToString(node)};ol.format.XMLFeature.prototype.writeFeaturesNode=function(features,opt_options){return null};ol.format.XMLFeature.prototype.writeGeometry=function(geometry,opt_options){var node=this.writeGeometryNode(geometry,opt_options);return this.xmlSerializer_.serializeToString(node)};
ol.format.XMLFeature.prototype.writeGeometryNode=function(geometry,opt_options){return null};goog.provide("ol.format.GMLBase");goog.require("ol");goog.require("ol.array");goog.require("ol.Feature");goog.require("ol.format.Feature");goog.require("ol.format.XMLFeature");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.LineString");goog.require("ol.geom.LinearRing");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.MultiPoint");goog.require("ol.geom.MultiPolygon");goog.require("ol.geom.Point");goog.require("ol.geom.Polygon");goog.require("ol.obj");goog.require("ol.proj");
goog.require("ol.xml");ol.format.GMLBase=function(opt_options){var options=opt_options?opt_options:{};this.featureType=options.featureType;this.featureNS=options.featureNS;this.srsName=options.srsName;this.schemaLocation="";this.FEATURE_COLLECTION_PARSERS={};this.FEATURE_COLLECTION_PARSERS[ol.format.GMLBase.GMLNS]={"featureMember":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readFeaturesInternal),"featureMembers":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readFeaturesInternal)};ol.format.XMLFeature.call(this)};
ol.inherits(ol.format.GMLBase,ol.format.XMLFeature);ol.format.GMLBase.GMLNS="http://www.opengis.net/gml";ol.format.GMLBase.ONLY_WHITESPACE_RE_=/^[\s\xa0]*$/;
ol.format.GMLBase.prototype.readFeaturesInternal=function(node,objectStack){var localName=node.localName;var features=null;if(localName=="FeatureCollection")if(node.namespaceURI==="http://www.opengis.net/wfs")features=ol.xml.pushParseAndPop([],this.FEATURE_COLLECTION_PARSERS,node,objectStack,this);else features=ol.xml.pushParseAndPop(null,this.FEATURE_COLLECTION_PARSERS,node,objectStack,this);else if(localName=="featureMembers"||localName=="featureMember"){var context=objectStack[0];var featureType=
context["featureType"];var featureNS=context["featureNS"];var i,ii,prefix="p",defaultPrefix="p0";if(!featureType&&node.childNodes){featureType=[],featureNS={};for(i=0,ii=node.childNodes.length;i<ii;++i){var child=node.childNodes[i];if(child.nodeType===1){var ft=child.nodeName.split(":").pop();if(featureType.indexOf(ft)===-1){var key="";var count=0;var uri=child.namespaceURI;for(var candidate in featureNS){if(featureNS[candidate]===uri){key=candidate;break}++count}if(!key){key=prefix+count;featureNS[key]=
uri}featureType.push(key+":"+ft)}}}if(localName!="featureMember"){context["featureType"]=featureType;context["featureNS"]=featureNS}}if(typeof featureNS==="string"){var ns=featureNS;featureNS={};featureNS[defaultPrefix]=ns}var parsersNS={};var featureTypes=Array.isArray(featureType)?featureType:[featureType];for(var p in featureNS){var parsers={};for(i=0,ii=featureTypes.length;i<ii;++i){var featurePrefix=featureTypes[i].indexOf(":")===-1?defaultPrefix:featureTypes[i].split(":")[0];if(featurePrefix===
p)parsers[featureTypes[i].split(":").pop()]=localName=="featureMembers"?ol.xml.makeArrayPusher(this.readFeatureElement,this):ol.xml.makeReplacer(this.readFeatureElement,this)}parsersNS[featureNS[p]]=parsers}if(localName=="featureMember")features=ol.xml.pushParseAndPop(undefined,parsersNS,node,objectStack);else features=ol.xml.pushParseAndPop([],parsersNS,node,objectStack)}if(features===null)features=[];return features};
ol.format.GMLBase.prototype.readGeometryElement=function(node,objectStack){var context=objectStack[0];context["srsName"]=node.firstElementChild.getAttribute("srsName");context["srsDimension"]=node.firstElementChild.getAttribute("srsDimension");var geometry=ol.xml.pushParseAndPop(null,this.GEOMETRY_PARSERS_,node,objectStack,this);if(geometry)return ol.format.Feature.transformWithOptions(geometry,false,context);else return undefined};
ol.format.GMLBase.prototype.readFeatureElement=function(node,objectStack){var n;var fid=node.getAttribute("fid")||ol.xml.getAttributeNS(node,ol.format.GMLBase.GMLNS,"id");var values={},geometryName;for(n=node.firstElementChild;n;n=n.nextElementSibling){var localName=n.localName;if(n.childNodes.length===0||n.childNodes.length===1&&(n.firstChild.nodeType===3||n.firstChild.nodeType===4)){var value=ol.xml.getAllTextContent(n,false);if(ol.format.GMLBase.ONLY_WHITESPACE_RE_.test(value))value=undefined;
values[localName]=value}else{if(localName!=="boundedBy")geometryName=localName;values[localName]=this.readGeometryElement(n,objectStack)}}var feature=new ol.Feature(values);if(geometryName)feature.setGeometryName(geometryName);if(fid)feature.setId(fid);return feature};
ol.format.GMLBase.prototype.readPoint=function(node,objectStack){var flatCoordinates=this.readFlatCoordinatesFromNode_(node,objectStack);if(flatCoordinates){var point=new ol.geom.Point(null);point.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates);return point}};ol.format.GMLBase.prototype.readMultiPoint=function(node,objectStack){var coordinates=ol.xml.pushParseAndPop([],this.MULTIPOINT_PARSERS_,node,objectStack,this);if(coordinates)return new ol.geom.MultiPoint(coordinates);else return undefined};
ol.format.GMLBase.prototype.readMultiLineString=function(node,objectStack){var lineStrings=ol.xml.pushParseAndPop([],this.MULTILINESTRING_PARSERS_,node,objectStack,this);if(lineStrings){var multiLineString=new ol.geom.MultiLineString(null);multiLineString.setLineStrings(lineStrings);return multiLineString}else return undefined};
ol.format.GMLBase.prototype.readMultiPolygon=function(node,objectStack){var polygons=ol.xml.pushParseAndPop([],this.MULTIPOLYGON_PARSERS_,node,objectStack,this);if(polygons){var multiPolygon=new ol.geom.MultiPolygon(null);multiPolygon.setPolygons(polygons);return multiPolygon}else return undefined};ol.format.GMLBase.prototype.pointMemberParser_=function(node,objectStack){ol.xml.parseNode(this.POINTMEMBER_PARSERS_,node,objectStack,this)};
ol.format.GMLBase.prototype.lineStringMemberParser_=function(node,objectStack){ol.xml.parseNode(this.LINESTRINGMEMBER_PARSERS_,node,objectStack,this)};ol.format.GMLBase.prototype.polygonMemberParser_=function(node,objectStack){ol.xml.parseNode(this.POLYGONMEMBER_PARSERS_,node,objectStack,this)};
ol.format.GMLBase.prototype.readLineString=function(node,objectStack){var flatCoordinates=this.readFlatCoordinatesFromNode_(node,objectStack);if(flatCoordinates){var lineString=new ol.geom.LineString(null);lineString.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates);return lineString}else return undefined};
ol.format.GMLBase.prototype.readFlatLinearRing_=function(node,objectStack){var ring=ol.xml.pushParseAndPop(null,this.GEOMETRY_FLAT_COORDINATES_PARSERS_,node,objectStack,this);if(ring)return ring;else return undefined};ol.format.GMLBase.prototype.readLinearRing=function(node,objectStack){var flatCoordinates=this.readFlatCoordinatesFromNode_(node,objectStack);if(flatCoordinates){var ring=new ol.geom.LinearRing(null);ring.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates);return ring}else return undefined};
ol.format.GMLBase.prototype.readPolygon=function(node,objectStack){var flatLinearRings=ol.xml.pushParseAndPop([null],this.FLAT_LINEAR_RINGS_PARSERS_,node,objectStack,this);if(flatLinearRings&&flatLinearRings[0]){var polygon=new ol.geom.Polygon(null);var flatCoordinates=flatLinearRings[0];var ends=[flatCoordinates.length];var i,ii;for(i=1,ii=flatLinearRings.length;i<ii;++i){ol.array.extend(flatCoordinates,flatLinearRings[i]);ends.push(flatCoordinates.length)}polygon.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,
flatCoordinates,ends);return polygon}else return undefined};ol.format.GMLBase.prototype.readFlatCoordinatesFromNode_=function(node,objectStack){return ol.xml.pushParseAndPop(null,this.GEOMETRY_FLAT_COORDINATES_PARSERS_,node,objectStack,this)};ol.format.GMLBase.prototype.MULTIPOINT_PARSERS_={"http://www.opengis.net/gml":{"pointMember":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.pointMemberParser_),"pointMembers":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.pointMemberParser_)}};
ol.format.GMLBase.prototype.MULTILINESTRING_PARSERS_={"http://www.opengis.net/gml":{"lineStringMember":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.lineStringMemberParser_),"lineStringMembers":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.lineStringMemberParser_)}};ol.format.GMLBase.prototype.MULTIPOLYGON_PARSERS_={"http://www.opengis.net/gml":{"polygonMember":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.polygonMemberParser_),"polygonMembers":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.polygonMemberParser_)}};
ol.format.GMLBase.prototype.POINTMEMBER_PARSERS_={"http://www.opengis.net/gml":{"Point":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readFlatCoordinatesFromNode_)}};ol.format.GMLBase.prototype.LINESTRINGMEMBER_PARSERS_={"http://www.opengis.net/gml":{"LineString":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readLineString)}};ol.format.GMLBase.prototype.POLYGONMEMBER_PARSERS_={"http://www.opengis.net/gml":{"Polygon":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readPolygon)}};
ol.format.GMLBase.prototype.RING_PARSERS={"http://www.opengis.net/gml":{"LinearRing":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readFlatLinearRing_)}};ol.format.GMLBase.prototype.readGeometryFromNode=function(node,opt_options){var geometry=this.readGeometryElement(node,[this.getReadOptions(node,opt_options?opt_options:{})]);return geometry?geometry:null};ol.format.GMLBase.prototype.readFeatures;
ol.format.GMLBase.prototype.readFeaturesFromNode=function(node,opt_options){var options={featureType:this.featureType,featureNS:this.featureNS};if(opt_options)ol.obj.assign(options,this.getReadOptions(node,opt_options));var features=this.readFeaturesInternal(node,[options]);return features||[]};ol.format.GMLBase.prototype.readProjectionFromNode=function(node){return ol.proj.get(this.srsName?this.srsName:node.firstElementChild.getAttribute("srsName"))};goog.provide("ol.format.XSD");goog.require("ol.xml");goog.require("ol.string");ol.format.XSD.NAMESPACE_URI="http://www.w3.org/2001/XMLSchema";ol.format.XSD.readBoolean=function(node){var s=ol.xml.getAllTextContent(node,false);return ol.format.XSD.readBooleanString(s)};ol.format.XSD.readBooleanString=function(string){var m=/^\s*(true|1)|(false|0)\s*$/.exec(string);if(m)return m[1]!==undefined||false;else return undefined};
ol.format.XSD.readDateTime=function(node){var s=ol.xml.getAllTextContent(node,false);var dateTime=Date.parse(s);return isNaN(dateTime)?undefined:dateTime/1E3};ol.format.XSD.readDecimal=function(node){var s=ol.xml.getAllTextContent(node,false);return ol.format.XSD.readDecimalString(s)};ol.format.XSD.readDecimalString=function(string){var m=/^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*$/i.exec(string);if(m)return parseFloat(m[1]);else return undefined};
ol.format.XSD.readNonNegativeInteger=function(node){var s=ol.xml.getAllTextContent(node,false);return ol.format.XSD.readNonNegativeIntegerString(s)};ol.format.XSD.readNonNegativeIntegerString=function(string){var m=/^\s*(\d+)\s*$/.exec(string);if(m)return parseInt(m[1],10);else return undefined};ol.format.XSD.readString=function(node){return ol.xml.getAllTextContent(node,false).trim()};ol.format.XSD.writeBooleanTextNode=function(node,bool){ol.format.XSD.writeStringTextNode(node,bool?"1":"0")};
ol.format.XSD.writeCDATASection=function(node,string){node.appendChild(ol.xml.DOCUMENT.createCDATASection(string))};ol.format.XSD.writeDateTimeTextNode=function(node,dateTime){var date=new Date(dateTime*1E3);var string=date.getUTCFullYear()+"-"+ol.string.padNumber(date.getUTCMonth()+1,2)+"-"+ol.string.padNumber(date.getUTCDate(),2)+"T"+ol.string.padNumber(date.getUTCHours(),2)+":"+ol.string.padNumber(date.getUTCMinutes(),2)+":"+ol.string.padNumber(date.getUTCSeconds(),2)+"Z";node.appendChild(ol.xml.DOCUMENT.createTextNode(string))};
ol.format.XSD.writeDecimalTextNode=function(node,decimal){var string=decimal.toPrecision();node.appendChild(ol.xml.DOCUMENT.createTextNode(string))};ol.format.XSD.writeNonNegativeIntegerTextNode=function(node,nonNegativeInteger){var string=nonNegativeInteger.toString();node.appendChild(ol.xml.DOCUMENT.createTextNode(string))};ol.format.XSD.writeStringTextNode=function(node,string){node.appendChild(ol.xml.DOCUMENT.createTextNode(string))};goog.provide("ol.format.GML3");goog.require("ol");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.format.Feature");goog.require("ol.format.GMLBase");goog.require("ol.format.XSD");goog.require("ol.geom.Geometry");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.LineString");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.MultiPolygon");goog.require("ol.geom.Polygon");goog.require("ol.obj");goog.require("ol.proj");goog.require("ol.xml");
ol.format.GML3=function(opt_options){var options=opt_options?opt_options:{};ol.format.GMLBase.call(this,options);this.surface_=options.surface!==undefined?options.surface:false;this.curve_=options.curve!==undefined?options.curve:false;this.multiCurve_=options.multiCurve!==undefined?options.multiCurve:true;this.multiSurface_=options.multiSurface!==undefined?options.multiSurface:true;this.schemaLocation=options.schemaLocation?options.schemaLocation:ol.format.GML3.schemaLocation_;this.hasZ=options.hasZ!==
undefined?options.hasZ:false};ol.inherits(ol.format.GML3,ol.format.GMLBase);ol.format.GML3.schemaLocation_=ol.format.GMLBase.GMLNS+" http://schemas.opengis.net/gml/3.1.1/profiles/gmlsfProfile/"+"1.0.0/gmlsf.xsd";ol.format.GML3.prototype.readMultiCurve_=function(node,objectStack){var lineStrings=ol.xml.pushParseAndPop([],this.MULTICURVE_PARSERS_,node,objectStack,this);if(lineStrings){var multiLineString=new ol.geom.MultiLineString(null);multiLineString.setLineStrings(lineStrings);return multiLineString}else return undefined};
ol.format.GML3.prototype.readMultiSurface_=function(node,objectStack){var polygons=ol.xml.pushParseAndPop([],this.MULTISURFACE_PARSERS_,node,objectStack,this);if(polygons){var multiPolygon=new ol.geom.MultiPolygon(null);multiPolygon.setPolygons(polygons);return multiPolygon}else return undefined};ol.format.GML3.prototype.curveMemberParser_=function(node,objectStack){ol.xml.parseNode(this.CURVEMEMBER_PARSERS_,node,objectStack,this)};
ol.format.GML3.prototype.surfaceMemberParser_=function(node,objectStack){ol.xml.parseNode(this.SURFACEMEMBER_PARSERS_,node,objectStack,this)};ol.format.GML3.prototype.readPatch_=function(node,objectStack){return ol.xml.pushParseAndPop([null],this.PATCHES_PARSERS_,node,objectStack,this)};ol.format.GML3.prototype.readSegment_=function(node,objectStack){return ol.xml.pushParseAndPop([null],this.SEGMENTS_PARSERS_,node,objectStack,this)};
ol.format.GML3.prototype.readPolygonPatch_=function(node,objectStack){return ol.xml.pushParseAndPop([null],this.FLAT_LINEAR_RINGS_PARSERS_,node,objectStack,this)};ol.format.GML3.prototype.readLineStringSegment_=function(node,objectStack){return ol.xml.pushParseAndPop([null],this.GEOMETRY_FLAT_COORDINATES_PARSERS_,node,objectStack,this)};
ol.format.GML3.prototype.interiorParser_=function(node,objectStack){var flatLinearRing=ol.xml.pushParseAndPop(undefined,this.RING_PARSERS,node,objectStack,this);if(flatLinearRing){var flatLinearRings=objectStack[objectStack.length-1];flatLinearRings.push(flatLinearRing)}};
ol.format.GML3.prototype.exteriorParser_=function(node,objectStack){var flatLinearRing=ol.xml.pushParseAndPop(undefined,this.RING_PARSERS,node,objectStack,this);if(flatLinearRing){var flatLinearRings=objectStack[objectStack.length-1];flatLinearRings[0]=flatLinearRing}};
ol.format.GML3.prototype.readSurface_=function(node,objectStack){var flatLinearRings=ol.xml.pushParseAndPop([null],this.SURFACE_PARSERS_,node,objectStack,this);if(flatLinearRings&&flatLinearRings[0]){var polygon=new ol.geom.Polygon(null);var flatCoordinates=flatLinearRings[0];var ends=[flatCoordinates.length];var i,ii;for(i=1,ii=flatLinearRings.length;i<ii;++i){ol.array.extend(flatCoordinates,flatLinearRings[i]);ends.push(flatCoordinates.length)}polygon.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,
flatCoordinates,ends);return polygon}else return undefined};ol.format.GML3.prototype.readCurve_=function(node,objectStack){var flatCoordinates=ol.xml.pushParseAndPop([null],this.CURVE_PARSERS_,node,objectStack,this);if(flatCoordinates){var lineString=new ol.geom.LineString(null);lineString.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates);return lineString}else return undefined};
ol.format.GML3.prototype.readEnvelope_=function(node,objectStack){var flatCoordinates=ol.xml.pushParseAndPop([null],this.ENVELOPE_PARSERS_,node,objectStack,this);return ol.extent.createOrUpdate(flatCoordinates[1][0],flatCoordinates[1][1],flatCoordinates[2][0],flatCoordinates[2][1])};
ol.format.GML3.prototype.readFlatPos_=function(node,objectStack){var s=ol.xml.getAllTextContent(node,false);var re=/^\s*([+\-]?\d*\.?\d+(?:[eE][+\-]?\d+)?)\s*/;var flatCoordinates=[];var m;while(m=re.exec(s)){flatCoordinates.push(parseFloat(m[1]));s=s.substr(m[0].length)}if(s!=="")return undefined;var context=objectStack[0];var containerSrs=context["srsName"];var axisOrientation="enu";if(containerSrs){var proj=ol.proj.get(containerSrs);axisOrientation=proj.getAxisOrientation()}if(axisOrientation===
"neu"){var i,ii;for(i=0,ii=flatCoordinates.length;i<ii;i+=3){var y=flatCoordinates[i];var x=flatCoordinates[i+1];flatCoordinates[i]=x;flatCoordinates[i+1]=y}}var len=flatCoordinates.length;if(len==2)flatCoordinates.push(0);if(len===0)return undefined;return flatCoordinates};
ol.format.GML3.prototype.readFlatPosList_=function(node,objectStack){var s=ol.xml.getAllTextContent(node,false).replace(/^\s*|\s*$/g,"");var context=objectStack[0];var containerSrs=context["srsName"];var contextDimension=context["srsDimension"];var axisOrientation="enu";if(containerSrs){var proj=ol.proj.get(containerSrs);axisOrientation=proj.getAxisOrientation()}var coords=s.split(/\s+/);var dim=2;if(node.getAttribute("srsDimension"))dim=ol.format.XSD.readNonNegativeIntegerString(node.getAttribute("srsDimension"));
else if(node.getAttribute("dimension"))dim=ol.format.XSD.readNonNegativeIntegerString(node.getAttribute("dimension"));else if(node.parentNode.getAttribute("srsDimension"))dim=ol.format.XSD.readNonNegativeIntegerString(node.parentNode.getAttribute("srsDimension"));else if(contextDimension)dim=ol.format.XSD.readNonNegativeIntegerString(contextDimension);var x,y,z;var flatCoordinates=[];for(var i=0,ii=coords.length;i<ii;i+=dim){x=parseFloat(coords[i]);y=parseFloat(coords[i+1]);z=dim===3?parseFloat(coords[i+
2]):0;if(axisOrientation.substr(0,2)==="en")flatCoordinates.push(x,y,z);else flatCoordinates.push(y,x,z)}return flatCoordinates};ol.format.GML3.prototype.GEOMETRY_FLAT_COORDINATES_PARSERS_={"http://www.opengis.net/gml":{"pos":ol.xml.makeReplacer(ol.format.GML3.prototype.readFlatPos_),"posList":ol.xml.makeReplacer(ol.format.GML3.prototype.readFlatPosList_)}};ol.format.GML3.prototype.FLAT_LINEAR_RINGS_PARSERS_={"http://www.opengis.net/gml":{"interior":ol.format.GML3.prototype.interiorParser_,"exterior":ol.format.GML3.prototype.exteriorParser_}};
ol.format.GML3.prototype.GEOMETRY_PARSERS_={"http://www.opengis.net/gml":{"Point":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readPoint),"MultiPoint":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readMultiPoint),"LineString":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readLineString),"MultiLineString":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readMultiLineString),"LinearRing":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readLinearRing),"Polygon":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readPolygon),
"MultiPolygon":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readMultiPolygon),"Surface":ol.xml.makeReplacer(ol.format.GML3.prototype.readSurface_),"MultiSurface":ol.xml.makeReplacer(ol.format.GML3.prototype.readMultiSurface_),"Curve":ol.xml.makeReplacer(ol.format.GML3.prototype.readCurve_),"MultiCurve":ol.xml.makeReplacer(ol.format.GML3.prototype.readMultiCurve_),"Envelope":ol.xml.makeReplacer(ol.format.GML3.prototype.readEnvelope_)}};
ol.format.GML3.prototype.MULTICURVE_PARSERS_={"http://www.opengis.net/gml":{"curveMember":ol.xml.makeArrayPusher(ol.format.GML3.prototype.curveMemberParser_),"curveMembers":ol.xml.makeArrayPusher(ol.format.GML3.prototype.curveMemberParser_)}};ol.format.GML3.prototype.MULTISURFACE_PARSERS_={"http://www.opengis.net/gml":{"surfaceMember":ol.xml.makeArrayPusher(ol.format.GML3.prototype.surfaceMemberParser_),"surfaceMembers":ol.xml.makeArrayPusher(ol.format.GML3.prototype.surfaceMemberParser_)}};
ol.format.GML3.prototype.CURVEMEMBER_PARSERS_={"http://www.opengis.net/gml":{"LineString":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readLineString),"Curve":ol.xml.makeArrayPusher(ol.format.GML3.prototype.readCurve_)}};ol.format.GML3.prototype.SURFACEMEMBER_PARSERS_={"http://www.opengis.net/gml":{"Polygon":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readPolygon),"Surface":ol.xml.makeArrayPusher(ol.format.GML3.prototype.readSurface_)}};ol.format.GML3.prototype.SURFACE_PARSERS_={"http://www.opengis.net/gml":{"patches":ol.xml.makeReplacer(ol.format.GML3.prototype.readPatch_)}};
ol.format.GML3.prototype.CURVE_PARSERS_={"http://www.opengis.net/gml":{"segments":ol.xml.makeReplacer(ol.format.GML3.prototype.readSegment_)}};ol.format.GML3.prototype.ENVELOPE_PARSERS_={"http://www.opengis.net/gml":{"lowerCorner":ol.xml.makeArrayPusher(ol.format.GML3.prototype.readFlatPosList_),"upperCorner":ol.xml.makeArrayPusher(ol.format.GML3.prototype.readFlatPosList_)}};ol.format.GML3.prototype.PATCHES_PARSERS_={"http://www.opengis.net/gml":{"PolygonPatch":ol.xml.makeReplacer(ol.format.GML3.prototype.readPolygonPatch_)}};
ol.format.GML3.prototype.SEGMENTS_PARSERS_={"http://www.opengis.net/gml":{"LineStringSegment":ol.xml.makeReplacer(ol.format.GML3.prototype.readLineStringSegment_)}};
ol.format.GML3.prototype.writePos_=function(node,value,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsDimension=hasZ?3:2;node.setAttribute("srsDimension",srsDimension);var srsName=context["srsName"];var axisOrientation="enu";if(srsName)axisOrientation=ol.proj.get(srsName).getAxisOrientation();var point=value.getCoordinates();var coords;if(axisOrientation.substr(0,2)==="en")coords=point[0]+" "+point[1];else coords=point[1]+" "+point[0];if(hasZ){var z=point[2]||
0;coords+=" "+z}ol.format.XSD.writeStringTextNode(node,coords)};ol.format.GML3.prototype.getCoords_=function(point,opt_srsName,opt_hasZ){var axisOrientation="enu";if(opt_srsName)axisOrientation=ol.proj.get(opt_srsName).getAxisOrientation();var coords=axisOrientation.substr(0,2)==="en"?point[0]+" "+point[1]:point[1]+" "+point[0];if(opt_hasZ){var z=point[2]||0;coords+=" "+z}return coords};
ol.format.GML3.prototype.writePosList_=function(node,value,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsDimension=hasZ?3:2;node.setAttribute("srsDimension",srsDimension);var srsName=context["srsName"];var points=value.getCoordinates();var len=points.length;var parts=new Array(len);var point;for(var i=0;i<len;++i){point=points[i];parts[i]=this.getCoords_(point,srsName,hasZ)}ol.format.XSD.writeStringTextNode(node,parts.join(" "))};
ol.format.GML3.prototype.writePoint_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var pos=ol.xml.createElementNS(node.namespaceURI,"pos");node.appendChild(pos);this.writePos_(pos,geometry,objectStack)};ol.format.GML3.ENVELOPE_SERIALIZERS_={"http://www.opengis.net/gml":{"lowerCorner":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"upperCorner":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)}};
ol.format.GML3.prototype.writeEnvelope=function(node,extent,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var keys=["lowerCorner","upperCorner"];var values=[extent[0]+" "+extent[1],extent[2]+" "+extent[3]];ol.xml.pushSerializeAndPop({node:node},ol.format.GML3.ENVELOPE_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,keys,this)};
ol.format.GML3.prototype.writeLinearRing_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var posList=ol.xml.createElementNS(node.namespaceURI,"posList");node.appendChild(posList);this.writePosList_(posList,geometry,objectStack)};
ol.format.GML3.prototype.RING_NODE_FACTORY_=function(value,objectStack,opt_nodeName){var context=objectStack[objectStack.length-1];var parentNode=context.node;var exteriorWritten=context["exteriorWritten"];if(exteriorWritten===undefined)context["exteriorWritten"]=true;return ol.xml.createElementNS(parentNode.namespaceURI,exteriorWritten!==undefined?"interior":"exterior")};
ol.format.GML3.prototype.writeSurfaceOrPolygon_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];if(node.nodeName!=="PolygonPatch"&&srsName)node.setAttribute("srsName",srsName);if(node.nodeName==="Polygon"||node.nodeName==="PolygonPatch"){var rings=geometry.getLinearRings();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName},ol.format.GML3.RING_SERIALIZERS_,this.RING_NODE_FACTORY_,rings,objectStack,
undefined,this)}else if(node.nodeName==="Surface"){var patches=ol.xml.createElementNS(node.namespaceURI,"patches");node.appendChild(patches);this.writeSurfacePatches_(patches,geometry,objectStack)}};
ol.format.GML3.prototype.writeCurveOrLineString_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(node.nodeName!=="LineStringSegment"&&srsName)node.setAttribute("srsName",srsName);if(node.nodeName==="LineString"||node.nodeName==="LineStringSegment"){var posList=ol.xml.createElementNS(node.namespaceURI,"posList");node.appendChild(posList);this.writePosList_(posList,geometry,objectStack)}else if(node.nodeName==="Curve"){var segments=
ol.xml.createElementNS(node.namespaceURI,"segments");node.appendChild(segments);this.writeCurveSegments_(segments,geometry,objectStack)}};
ol.format.GML3.prototype.writeMultiSurfaceOrPolygon_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];var surface=context["surface"];if(srsName)node.setAttribute("srsName",srsName);var polygons=geometry.getPolygons();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName,surface:surface},ol.format.GML3.SURFACEORPOLYGONMEMBER_SERIALIZERS_,this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_,polygons,objectStack,undefined,
this)};ol.format.GML3.prototype.writeMultiPoint_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];var hasZ=context["hasZ"];if(srsName)node.setAttribute("srsName",srsName);var points=geometry.getPoints();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName},ol.format.GML3.POINTMEMBER_SERIALIZERS_,ol.xml.makeSimpleNodeFactory("pointMember"),points,objectStack,undefined,this)};
ol.format.GML3.prototype.writeMultiCurveOrLineString_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];var curve=context["curve"];if(srsName)node.setAttribute("srsName",srsName);var lines=geometry.getLineStrings();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName,curve:curve},ol.format.GML3.LINESTRINGORCURVEMEMBER_SERIALIZERS_,this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_,lines,objectStack,undefined,this)};
ol.format.GML3.prototype.writeRing_=function(node,ring,objectStack){var linearRing=ol.xml.createElementNS(node.namespaceURI,"LinearRing");node.appendChild(linearRing);this.writeLinearRing_(linearRing,ring,objectStack)};ol.format.GML3.prototype.writeSurfaceOrPolygonMember_=function(node,polygon,objectStack){var child=this.GEOMETRY_NODE_FACTORY_(polygon,objectStack);if(child){node.appendChild(child);this.writeSurfaceOrPolygon_(child,polygon,objectStack)}};
ol.format.GML3.prototype.writePointMember_=function(node,point,objectStack){var child=ol.xml.createElementNS(node.namespaceURI,"Point");node.appendChild(child);this.writePoint_(child,point,objectStack)};ol.format.GML3.prototype.writeLineStringOrCurveMember_=function(node,line,objectStack){var child=this.GEOMETRY_NODE_FACTORY_(line,objectStack);if(child){node.appendChild(child);this.writeCurveOrLineString_(child,line,objectStack)}};
ol.format.GML3.prototype.writeSurfacePatches_=function(node,polygon,objectStack){var child=ol.xml.createElementNS(node.namespaceURI,"PolygonPatch");node.appendChild(child);this.writeSurfaceOrPolygon_(child,polygon,objectStack)};ol.format.GML3.prototype.writeCurveSegments_=function(node,line,objectStack){var child=ol.xml.createElementNS(node.namespaceURI,"LineStringSegment");node.appendChild(child);this.writeCurveOrLineString_(child,line,objectStack)};
ol.format.GML3.prototype.writeGeometryElement=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var item=ol.obj.assign({},context);item.node=node;var value;if(Array.isArray(geometry))if(context.dataProjection)value=ol.proj.transformExtent(geometry,context.featureProjection,context.dataProjection);else value=geometry;else value=ol.format.Feature.transformWithOptions(geometry,true,context);ol.xml.pushSerializeAndPop(item,ol.format.GML3.GEOMETRY_SERIALIZERS_,this.GEOMETRY_NODE_FACTORY_,
[value],objectStack,undefined,this)};
ol.format.GML3.prototype.writeFeatureElement=function(node,feature,objectStack){var fid=feature.getId();if(fid)node.setAttribute("fid",fid);var context=objectStack[objectStack.length-1];var featureNS=context["featureNS"];var geometryName=feature.getGeometryName();if(!context.serializers){context.serializers={};context.serializers[featureNS]={}}var properties=feature.getProperties();var keys=[],values=[];for(var key in properties){var value=properties[key];if(value!==null){keys.push(key);values.push(value);
if(key==geometryName||value instanceof ol.geom.Geometry){if(!(key in context.serializers[featureNS]))context.serializers[featureNS][key]=ol.xml.makeChildAppender(this.writeGeometryElement,this)}else if(!(key in context.serializers[featureNS]))context.serializers[featureNS][key]=ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)}}var item=ol.obj.assign({},context);item.node=node;ol.xml.pushSerializeAndPop(item,context.serializers,ol.xml.makeSimpleNodeFactory(undefined,featureNS),values,objectStack,
keys)};
ol.format.GML3.prototype.writeFeatureMembers_=function(node,features,objectStack){var context=objectStack[objectStack.length-1];var featureType=context["featureType"];var featureNS=context["featureNS"];var serializers={};serializers[featureNS]={};serializers[featureNS][featureType]=ol.xml.makeChildAppender(this.writeFeatureElement,this);var item=ol.obj.assign({},context);item.node=node;ol.xml.pushSerializeAndPop(item,serializers,ol.xml.makeSimpleNodeFactory(featureType,featureNS),features,objectStack)};
ol.format.GML3.SURFACEORPOLYGONMEMBER_SERIALIZERS_={"http://www.opengis.net/gml":{"surfaceMember":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeSurfaceOrPolygonMember_),"polygonMember":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeSurfaceOrPolygonMember_)}};ol.format.GML3.POINTMEMBER_SERIALIZERS_={"http://www.opengis.net/gml":{"pointMember":ol.xml.makeChildAppender(ol.format.GML3.prototype.writePointMember_)}};
ol.format.GML3.LINESTRINGORCURVEMEMBER_SERIALIZERS_={"http://www.opengis.net/gml":{"lineStringMember":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeLineStringOrCurveMember_),"curveMember":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeLineStringOrCurveMember_)}};ol.format.GML3.RING_SERIALIZERS_={"http://www.opengis.net/gml":{"exterior":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeRing_),"interior":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeRing_)}};
ol.format.GML3.GEOMETRY_SERIALIZERS_={"http://www.opengis.net/gml":{"Curve":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeCurveOrLineString_),"MultiCurve":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeMultiCurveOrLineString_),"Point":ol.xml.makeChildAppender(ol.format.GML3.prototype.writePoint_),"MultiPoint":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeMultiPoint_),"LineString":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeCurveOrLineString_),"MultiLineString":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeMultiCurveOrLineString_),
"LinearRing":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeLinearRing_),"Polygon":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeSurfaceOrPolygon_),"MultiPolygon":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeMultiSurfaceOrPolygon_),"Surface":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeSurfaceOrPolygon_),"MultiSurface":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeMultiSurfaceOrPolygon_),"Envelope":ol.xml.makeChildAppender(ol.format.GML3.prototype.writeEnvelope)}};
ol.format.GML3.MULTIGEOMETRY_TO_MEMBER_NODENAME_={"MultiLineString":"lineStringMember","MultiCurve":"curveMember","MultiPolygon":"polygonMember","MultiSurface":"surfaceMember"};ol.format.GML3.prototype.MULTIGEOMETRY_MEMBER_NODE_FACTORY_=function(value,objectStack,opt_nodeName){var parentNode=objectStack[objectStack.length-1].node;return ol.xml.createElementNS("http://www.opengis.net/gml",ol.format.GML3.MULTIGEOMETRY_TO_MEMBER_NODENAME_[parentNode.nodeName])};
ol.format.GML3.prototype.GEOMETRY_NODE_FACTORY_=function(value,objectStack,opt_nodeName){var context=objectStack[objectStack.length-1];var multiSurface=context["multiSurface"];var surface=context["surface"];var curve=context["curve"];var multiCurve=context["multiCurve"];var nodeName;if(!Array.isArray(value)){nodeName=value.getType();if(nodeName==="MultiPolygon"&&multiSurface===true)nodeName="MultiSurface";else if(nodeName==="Polygon"&&surface===true)nodeName="Surface";else if(nodeName==="LineString"&&
curve===true)nodeName="Curve";else if(nodeName==="MultiLineString"&&multiCurve===true)nodeName="MultiCurve"}else nodeName="Envelope";return ol.xml.createElementNS("http://www.opengis.net/gml",nodeName)};
ol.format.GML3.prototype.writeGeometryNode=function(geometry,opt_options){opt_options=this.adaptOptions(opt_options);var geom=ol.xml.createElementNS("http://www.opengis.net/gml","geom");var context={node:geom,hasZ:this.hasZ,srsName:this.srsName,curve:this.curve_,surface:this.surface_,multiSurface:this.multiSurface_,multiCurve:this.multiCurve_};if(opt_options)ol.obj.assign(context,opt_options);this.writeGeometryElement(geom,geometry,[context]);return geom};ol.format.GML3.prototype.writeFeatures;
ol.format.GML3.prototype.writeFeaturesNode=function(features,opt_options){opt_options=this.adaptOptions(opt_options);var node=ol.xml.createElementNS("http://www.opengis.net/gml","featureMembers");ol.xml.setAttributeNS(node,"http://www.w3.org/2001/XMLSchema-instance","xsi:schemaLocation",this.schemaLocation);var context={srsName:this.srsName,hasZ:this.hasZ,curve:this.curve_,surface:this.surface_,multiSurface:this.multiSurface_,multiCurve:this.multiCurve_,featureNS:this.featureNS,featureType:this.featureType};
if(opt_options)ol.obj.assign(context,opt_options);this.writeFeatureMembers_(node,features,[context]);return node};goog.provide("ol.format.GML");goog.require("ol.format.GML3");ol.format.GML=ol.format.GML3;ol.format.GML.prototype.writeFeatures;ol.format.GML.prototype.writeFeaturesNode;goog.provide("ol.format.GML2");goog.require("ol");goog.require("ol.extent");goog.require("ol.format.Feature");goog.require("ol.format.GMLBase");goog.require("ol.format.XSD");goog.require("ol.geom.Geometry");goog.require("ol.obj");goog.require("ol.proj");goog.require("ol.xml");
ol.format.GML2=function(opt_options){var options=opt_options?opt_options:{};ol.format.GMLBase.call(this,options);this.FEATURE_COLLECTION_PARSERS[ol.format.GMLBase.GMLNS]["featureMember"]=ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readFeaturesInternal);this.schemaLocation=options.schemaLocation?options.schemaLocation:ol.format.GML2.schemaLocation_};ol.inherits(ol.format.GML2,ol.format.GMLBase);ol.format.GML2.schemaLocation_=ol.format.GMLBase.GMLNS+" http://schemas.opengis.net/gml/2.1.2/feature.xsd";
ol.format.GML2.prototype.readFlatCoordinates_=function(node,objectStack){var s=ol.xml.getAllTextContent(node,false).replace(/^\s*|\s*$/g,"");var context=objectStack[0];var containerSrs=context["srsName"];var axisOrientation="enu";if(containerSrs){var proj=ol.proj.get(containerSrs);if(proj)axisOrientation=proj.getAxisOrientation()}var coordsGroups=s.trim().split(/\s+/);var x,y,z;var flatCoordinates=[];for(var i=0,ii=coordsGroups.length;i<ii;i++){var coords=coordsGroups[i].split(/,+/);x=parseFloat(coords[0]);
y=parseFloat(coords[1]);z=coords.length===3?parseFloat(coords[2]):0;if(axisOrientation.substr(0,2)==="en")flatCoordinates.push(x,y,z);else flatCoordinates.push(y,x,z)}return flatCoordinates};ol.format.GML2.prototype.readBox_=function(node,objectStack){var flatCoordinates=ol.xml.pushParseAndPop([null],this.BOX_PARSERS_,node,objectStack,this);return ol.extent.createOrUpdate(flatCoordinates[1][0],flatCoordinates[1][1],flatCoordinates[1][3],flatCoordinates[1][4])};
ol.format.GML2.prototype.innerBoundaryIsParser_=function(node,objectStack){var flatLinearRing=ol.xml.pushParseAndPop(undefined,this.RING_PARSERS,node,objectStack,this);if(flatLinearRing){var flatLinearRings=objectStack[objectStack.length-1];flatLinearRings.push(flatLinearRing)}};
ol.format.GML2.prototype.outerBoundaryIsParser_=function(node,objectStack){var flatLinearRing=ol.xml.pushParseAndPop(undefined,this.RING_PARSERS,node,objectStack,this);if(flatLinearRing){var flatLinearRings=objectStack[objectStack.length-1];flatLinearRings[0]=flatLinearRing}};ol.format.GML2.prototype.GEOMETRY_FLAT_COORDINATES_PARSERS_={"http://www.opengis.net/gml":{"coordinates":ol.xml.makeReplacer(ol.format.GML2.prototype.readFlatCoordinates_)}};
ol.format.GML2.prototype.FLAT_LINEAR_RINGS_PARSERS_={"http://www.opengis.net/gml":{"innerBoundaryIs":ol.format.GML2.prototype.innerBoundaryIsParser_,"outerBoundaryIs":ol.format.GML2.prototype.outerBoundaryIsParser_}};ol.format.GML2.prototype.BOX_PARSERS_={"http://www.opengis.net/gml":{"coordinates":ol.xml.makeArrayPusher(ol.format.GML2.prototype.readFlatCoordinates_)}};
ol.format.GML2.prototype.GEOMETRY_PARSERS_={"http://www.opengis.net/gml":{"Point":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readPoint),"MultiPoint":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readMultiPoint),"LineString":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readLineString),"MultiLineString":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readMultiLineString),"LinearRing":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readLinearRing),"Polygon":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readPolygon),
"MultiPolygon":ol.xml.makeReplacer(ol.format.GMLBase.prototype.readMultiPolygon),"Box":ol.xml.makeReplacer(ol.format.GML2.prototype.readBox_)}};
ol.format.GML2.prototype.GEOMETRY_NODE_FACTORY_=function(value,objectStack,opt_nodeName){var context=objectStack[objectStack.length-1];var multiSurface=context["multiSurface"];var surface=context["surface"];var multiCurve=context["multiCurve"];var nodeName;if(!Array.isArray(value)){nodeName=value.getType();if(nodeName==="MultiPolygon"&&multiSurface===true)nodeName="MultiSurface";else if(nodeName==="Polygon"&&surface===true)nodeName="Surface";else if(nodeName==="MultiLineString"&&multiCurve===true)nodeName=
"MultiCurve"}else nodeName="Envelope";return ol.xml.createElementNS("http://www.opengis.net/gml",nodeName)};
ol.format.GML2.prototype.writeFeatureElement=function(node,feature,objectStack){var fid=feature.getId();if(fid)node.setAttribute("fid",fid);var context=objectStack[objectStack.length-1];var featureNS=context["featureNS"];var geometryName=feature.getGeometryName();if(!context.serializers){context.serializers={};context.serializers[featureNS]={}}var properties=feature.getProperties();var keys=[],values=[];for(var key in properties){var value=properties[key];if(value!==null){keys.push(key);values.push(value);
if(key==geometryName||value instanceof ol.geom.Geometry){if(!(key in context.serializers[featureNS]))context.serializers[featureNS][key]=ol.xml.makeChildAppender(this.writeGeometryElement,this)}else if(!(key in context.serializers[featureNS]))context.serializers[featureNS][key]=ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)}}var item=ol.obj.assign({},context);item.node=node;ol.xml.pushSerializeAndPop(item,context.serializers,ol.xml.makeSimpleNodeFactory(undefined,featureNS),values,objectStack,
keys)};
ol.format.GML2.prototype.writeGeometryElement=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var item=ol.obj.assign({},context);item.node=node;var value;if(Array.isArray(geometry))if(context.dataProjection)value=ol.proj.transformExtent(geometry,context.featureProjection,context.dataProjection);else value=geometry;else value=ol.format.Feature.transformWithOptions(geometry,true,context);ol.xml.pushSerializeAndPop(item,ol.format.GML2.GEOMETRY_SERIALIZERS_,this.GEOMETRY_NODE_FACTORY_,[value],
objectStack,undefined,this)};
ol.format.GML2.prototype.writeCurveOrLineString_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(node.nodeName!=="LineStringSegment"&&srsName)node.setAttribute("srsName",srsName);if(node.nodeName==="LineString"||node.nodeName==="LineStringSegment"){var coordinates=this.createCoordinatesNode_(node.namespaceURI);node.appendChild(coordinates);this.writeCoordinates_(coordinates,geometry,objectStack)}else if(node.nodeName==="Curve"){var segments=
ol.xml.createElementNS(node.namespaceURI,"segments");node.appendChild(segments);this.writeCurveSegments_(segments,geometry,objectStack)}};ol.format.GML2.prototype.createCoordinatesNode_=function(namespaceURI){var coordinates=ol.xml.createElementNS(namespaceURI,"coordinates");coordinates.setAttribute("decimal",".");coordinates.setAttribute("cs",",");coordinates.setAttribute("ts"," ");return coordinates};
ol.format.GML2.prototype.writeCoordinates_=function(node,value,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];var points=value.getCoordinates();var len=points.length;var parts=new Array(len);var point;for(var i=0;i<len;++i){point=points[i];parts[i]=this.getCoords_(point,srsName,hasZ)}ol.format.XSD.writeStringTextNode(node,parts.join(" "))};
ol.format.GML2.prototype.writeCurveSegments_=function(node,line,objectStack){var child=ol.xml.createElementNS(node.namespaceURI,"LineStringSegment");node.appendChild(child);this.writeCurveOrLineString_(child,line,objectStack)};
ol.format.GML2.prototype.writeSurfaceOrPolygon_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];if(node.nodeName!=="PolygonPatch"&&srsName)node.setAttribute("srsName",srsName);if(node.nodeName==="Polygon"||node.nodeName==="PolygonPatch"){var rings=geometry.getLinearRings();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName},ol.format.GML2.RING_SERIALIZERS_,this.RING_NODE_FACTORY_,rings,objectStack,
undefined,this)}else if(node.nodeName==="Surface"){var patches=ol.xml.createElementNS(node.namespaceURI,"patches");node.appendChild(patches);this.writeSurfacePatches_(patches,geometry,objectStack)}};
ol.format.GML2.prototype.RING_NODE_FACTORY_=function(value,objectStack,opt_nodeName){var context=objectStack[objectStack.length-1];var parentNode=context.node;var exteriorWritten=context["exteriorWritten"];if(exteriorWritten===undefined)context["exteriorWritten"]=true;return ol.xml.createElementNS(parentNode.namespaceURI,exteriorWritten!==undefined?"innerBoundaryIs":"outerBoundaryIs")};
ol.format.GML2.prototype.writeSurfacePatches_=function(node,polygon,objectStack){var child=ol.xml.createElementNS(node.namespaceURI,"PolygonPatch");node.appendChild(child);this.writeSurfaceOrPolygon_(child,polygon,objectStack)};ol.format.GML2.prototype.writeRing_=function(node,ring,objectStack){var linearRing=ol.xml.createElementNS(node.namespaceURI,"LinearRing");node.appendChild(linearRing);this.writeLinearRing_(linearRing,ring,objectStack)};
ol.format.GML2.prototype.getCoords_=function(point,opt_srsName,opt_hasZ){var axisOrientation="enu";if(opt_srsName)axisOrientation=ol.proj.get(opt_srsName).getAxisOrientation();var coords=axisOrientation.substr(0,2)==="en"?point[0]+","+point[1]:point[1]+","+point[0];if(opt_hasZ){var z=point[2]||0;coords+=","+z}return coords};
ol.format.GML2.prototype.writeMultiCurveOrLineString_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];var curve=context["curve"];if(srsName)node.setAttribute("srsName",srsName);var lines=geometry.getLineStrings();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName,curve:curve},ol.format.GML2.LINESTRINGORCURVEMEMBER_SERIALIZERS_,this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_,lines,objectStack,undefined,this)};
ol.format.GML2.prototype.writePoint_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var coordinates=this.createCoordinatesNode_(node.namespaceURI);node.appendChild(coordinates);var point=geometry.getCoordinates();var coord=this.getCoords_(point,srsName,hasZ);ol.format.XSD.writeStringTextNode(coordinates,coord)};
ol.format.GML2.prototype.writeMultiPoint_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var points=geometry.getPoints();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName},ol.format.GML2.POINTMEMBER_SERIALIZERS_,ol.xml.makeSimpleNodeFactory("pointMember"),points,objectStack,undefined,this)};
ol.format.GML2.prototype.writePointMember_=function(node,point,objectStack){var child=ol.xml.createElementNS(node.namespaceURI,"Point");node.appendChild(child);this.writePoint_(child,point,objectStack)};ol.format.GML2.prototype.writeLineStringOrCurveMember_=function(node,line,objectStack){var child=this.GEOMETRY_NODE_FACTORY_(line,objectStack);if(child){node.appendChild(child);this.writeCurveOrLineString_(child,line,objectStack)}};
ol.format.GML2.prototype.writeLinearRing_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var coordinates=this.createCoordinatesNode_(node.namespaceURI);node.appendChild(coordinates);this.writeCoordinates_(coordinates,geometry,objectStack)};
ol.format.GML2.prototype.writeMultiSurfaceOrPolygon_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];var surface=context["surface"];if(srsName)node.setAttribute("srsName",srsName);var polygons=geometry.getPolygons();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName,surface:surface},ol.format.GML2.SURFACEORPOLYGONMEMBER_SERIALIZERS_,this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_,polygons,objectStack,undefined,
this)};ol.format.GML2.prototype.writeSurfaceOrPolygonMember_=function(node,polygon,objectStack){var child=this.GEOMETRY_NODE_FACTORY_(polygon,objectStack);if(child){node.appendChild(child);this.writeSurfaceOrPolygon_(child,polygon,objectStack)}};
ol.format.GML2.prototype.writeEnvelope=function(node,extent,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var keys=["lowerCorner","upperCorner"];var values=[extent[0]+" "+extent[1],extent[2]+" "+extent[3]];ol.xml.pushSerializeAndPop({node:node},ol.format.GML2.ENVELOPE_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,keys,this)};
ol.format.GML2.GEOMETRY_SERIALIZERS_={"http://www.opengis.net/gml":{"Curve":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeCurveOrLineString_),"MultiCurve":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeMultiCurveOrLineString_),"Point":ol.xml.makeChildAppender(ol.format.GML2.prototype.writePoint_),"MultiPoint":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeMultiPoint_),"LineString":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeCurveOrLineString_),"MultiLineString":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeMultiCurveOrLineString_),
"LinearRing":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeLinearRing_),"Polygon":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeSurfaceOrPolygon_),"MultiPolygon":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeMultiSurfaceOrPolygon_),"Surface":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeSurfaceOrPolygon_),"MultiSurface":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeMultiSurfaceOrPolygon_),"Envelope":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeEnvelope)}};
ol.format.GML2.RING_SERIALIZERS_={"http://www.opengis.net/gml":{"outerBoundaryIs":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeRing_),"innerBoundaryIs":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeRing_)}};ol.format.GML2.POINTMEMBER_SERIALIZERS_={"http://www.opengis.net/gml":{"pointMember":ol.xml.makeChildAppender(ol.format.GML2.prototype.writePointMember_)}};
ol.format.GML2.LINESTRINGORCURVEMEMBER_SERIALIZERS_={"http://www.opengis.net/gml":{"lineStringMember":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeLineStringOrCurveMember_),"curveMember":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeLineStringOrCurveMember_)}};ol.format.GML2.prototype.MULTIGEOMETRY_MEMBER_NODE_FACTORY_=function(value,objectStack,opt_nodeName){var parentNode=objectStack[objectStack.length-1].node;return ol.xml.createElementNS("http://www.opengis.net/gml",ol.format.GML2.MULTIGEOMETRY_TO_MEMBER_NODENAME_[parentNode.nodeName])};
ol.format.GML2.MULTIGEOMETRY_TO_MEMBER_NODENAME_={"MultiLineString":"lineStringMember","MultiCurve":"curveMember","MultiPolygon":"polygonMember","MultiSurface":"surfaceMember"};ol.format.GML2.SURFACEORPOLYGONMEMBER_SERIALIZERS_={"http://www.opengis.net/gml":{"surfaceMember":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeSurfaceOrPolygonMember_),"polygonMember":ol.xml.makeChildAppender(ol.format.GML2.prototype.writeSurfaceOrPolygonMember_)}};
ol.format.GML2.ENVELOPE_SERIALIZERS_={"http://www.opengis.net/gml":{"lowerCorner":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"upperCorner":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)}};goog.provide("ol.format.GPX");goog.require("ol");goog.require("ol.Feature");goog.require("ol.array");goog.require("ol.format.Feature");goog.require("ol.format.XMLFeature");goog.require("ol.format.XSD");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.LineString");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.Point");goog.require("ol.proj");goog.require("ol.xml");
ol.format.GPX=function(opt_options){var options=opt_options?opt_options:{};ol.format.XMLFeature.call(this);this.defaultDataProjection=ol.proj.get("EPSG:4326");this.readExtensions_=options.readExtensions};ol.inherits(ol.format.GPX,ol.format.XMLFeature);ol.format.GPX.NAMESPACE_URIS_=[null,"http://www.topografix.com/GPX/1/0","http://www.topografix.com/GPX/1/1"];ol.format.GPX.SCHEMA_LOCATION_="http://www.topografix.com/GPX/1/1 "+"http://www.topografix.com/GPX/1/1/gpx.xsd";
ol.format.GPX.appendCoordinate_=function(flatCoordinates,layoutOptions,node,values){flatCoordinates.push(parseFloat(node.getAttribute("lon")),parseFloat(node.getAttribute("lat")));if("ele"in values){flatCoordinates.push(values["ele"]);delete values["ele"];layoutOptions.hasZ=true}else flatCoordinates.push(0);if("time"in values){flatCoordinates.push(values["time"]);delete values["time"];layoutOptions.hasM=true}else flatCoordinates.push(0);return flatCoordinates};
ol.format.GPX.applyLayoutOptions_=function(layoutOptions,flatCoordinates,ends){var layout=ol.geom.GeometryLayout.XY;var stride=2;if(layoutOptions.hasZ&&layoutOptions.hasM){layout=ol.geom.GeometryLayout.XYZM;stride=4}else if(layoutOptions.hasZ){layout=ol.geom.GeometryLayout.XYZ;stride=3}else if(layoutOptions.hasM){layout=ol.geom.GeometryLayout.XYM;stride=3}if(stride!==4){var i,ii;for(i=0,ii=flatCoordinates.length/4;i<ii;i++){flatCoordinates[i*stride]=flatCoordinates[i*4];flatCoordinates[i*stride+1]=
flatCoordinates[i*4+1];if(layoutOptions.hasZ)flatCoordinates[i*stride+2]=flatCoordinates[i*4+2];if(layoutOptions.hasM)flatCoordinates[i*stride+2]=flatCoordinates[i*4+3]}flatCoordinates.length=flatCoordinates.length/4*stride;if(ends)for(i=0,ii=ends.length;i<ii;i++)ends[i]=ends[i]/4*stride}return layout};
ol.format.GPX.parseLink_=function(node,objectStack){var values=objectStack[objectStack.length-1];var href=node.getAttribute("href");if(href!==null)values["link"]=href;ol.xml.parseNode(ol.format.GPX.LINK_PARSERS_,node,objectStack)};ol.format.GPX.parseExtensions_=function(node,objectStack){var values=objectStack[objectStack.length-1];values["extensionsNode_"]=node};
ol.format.GPX.parseRtePt_=function(node,objectStack){var values=ol.xml.pushParseAndPop({},ol.format.GPX.RTEPT_PARSERS_,node,objectStack);if(values){var rteValues=objectStack[objectStack.length-1];var flatCoordinates=rteValues["flatCoordinates"];var layoutOptions=rteValues["layoutOptions"];ol.format.GPX.appendCoordinate_(flatCoordinates,layoutOptions,node,values)}};
ol.format.GPX.parseTrkPt_=function(node,objectStack){var values=ol.xml.pushParseAndPop({},ol.format.GPX.TRKPT_PARSERS_,node,objectStack);if(values){var trkValues=objectStack[objectStack.length-1];var flatCoordinates=trkValues["flatCoordinates"];var layoutOptions=trkValues["layoutOptions"];ol.format.GPX.appendCoordinate_(flatCoordinates,layoutOptions,node,values)}};
ol.format.GPX.parseTrkSeg_=function(node,objectStack){var values=objectStack[objectStack.length-1];ol.xml.parseNode(ol.format.GPX.TRKSEG_PARSERS_,node,objectStack);var flatCoordinates=values["flatCoordinates"];var ends=values["ends"];ends.push(flatCoordinates.length)};
ol.format.GPX.readRte_=function(node,objectStack){var options=objectStack[0];var values=ol.xml.pushParseAndPop({"flatCoordinates":[],"layoutOptions":{}},ol.format.GPX.RTE_PARSERS_,node,objectStack);if(!values)return undefined;var flatCoordinates=values["flatCoordinates"];delete values["flatCoordinates"];var layoutOptions=values["layoutOptions"];delete values["layoutOptions"];var layout=ol.format.GPX.applyLayoutOptions_(layoutOptions,flatCoordinates);var geometry=new ol.geom.LineString(null);geometry.setFlatCoordinates(layout,
flatCoordinates);ol.format.Feature.transformWithOptions(geometry,false,options);var feature=new ol.Feature(geometry);feature.setProperties(values);return feature};
ol.format.GPX.readTrk_=function(node,objectStack){var options=objectStack[0];var values=ol.xml.pushParseAndPop({"flatCoordinates":[],"ends":[],"layoutOptions":{}},ol.format.GPX.TRK_PARSERS_,node,objectStack);if(!values)return undefined;var flatCoordinates=values["flatCoordinates"];delete values["flatCoordinates"];var ends=values["ends"];delete values["ends"];var layoutOptions=values["layoutOptions"];delete values["layoutOptions"];var layout=ol.format.GPX.applyLayoutOptions_(layoutOptions,flatCoordinates,
ends);var geometry=new ol.geom.MultiLineString(null);geometry.setFlatCoordinates(layout,flatCoordinates,ends);ol.format.Feature.transformWithOptions(geometry,false,options);var feature=new ol.Feature(geometry);feature.setProperties(values);return feature};
ol.format.GPX.readWpt_=function(node,objectStack){var options=objectStack[0];var values=ol.xml.pushParseAndPop({},ol.format.GPX.WPT_PARSERS_,node,objectStack);if(!values)return undefined;var layoutOptions={};var coordinates=ol.format.GPX.appendCoordinate_([],layoutOptions,node,values);var layout=ol.format.GPX.applyLayoutOptions_(layoutOptions,coordinates);var geometry=new ol.geom.Point(coordinates,layout);ol.format.Feature.transformWithOptions(geometry,false,options);var feature=new ol.Feature(geometry);
feature.setProperties(values);return feature};ol.format.GPX.FEATURE_READER_={"rte":ol.format.GPX.readRte_,"trk":ol.format.GPX.readTrk_,"wpt":ol.format.GPX.readWpt_};ol.format.GPX.GPX_PARSERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"rte":ol.xml.makeArrayPusher(ol.format.GPX.readRte_),"trk":ol.xml.makeArrayPusher(ol.format.GPX.readTrk_),"wpt":ol.xml.makeArrayPusher(ol.format.GPX.readWpt_)});
ol.format.GPX.LINK_PARSERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"text":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString,"linkText"),"type":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString,"linkType")});
ol.format.GPX.RTE_PARSERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"name":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"cmt":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"desc":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"src":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"link":ol.format.GPX.parseLink_,"number":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"extensions":ol.format.GPX.parseExtensions_,"type":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
"rtept":ol.format.GPX.parseRtePt_});ol.format.GPX.RTEPT_PARSERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"ele":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"time":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDateTime)});
ol.format.GPX.TRK_PARSERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"name":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"cmt":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"desc":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"src":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"link":ol.format.GPX.parseLink_,"number":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"type":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
"extensions":ol.format.GPX.parseExtensions_,"trkseg":ol.format.GPX.parseTrkSeg_});ol.format.GPX.TRKSEG_PARSERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"trkpt":ol.format.GPX.parseTrkPt_});ol.format.GPX.TRKPT_PARSERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"ele":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"time":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDateTime)});
ol.format.GPX.WPT_PARSERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"ele":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"time":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDateTime),"magvar":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"geoidheight":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"name":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"cmt":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"desc":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
"src":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"link":ol.format.GPX.parseLink_,"sym":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"type":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"fix":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"sat":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"hdop":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"vdop":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"pdop":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
"ageofdgpsdata":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"dgpsid":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"extensions":ol.format.GPX.parseExtensions_});
ol.format.GPX.prototype.handleReadExtensions_=function(features){if(!features)features=[];for(var i=0,ii=features.length;i<ii;++i){var feature=features[i];if(this.readExtensions_){var extensionsNode=feature.get("extensionsNode_")||null;this.readExtensions_(feature,extensionsNode)}feature.set("extensionsNode_",undefined)}};ol.format.GPX.prototype.readFeature;
ol.format.GPX.prototype.readFeatureFromNode=function(node,opt_options){if(!ol.array.includes(ol.format.GPX.NAMESPACE_URIS_,node.namespaceURI))return null;var featureReader=ol.format.GPX.FEATURE_READER_[node.localName];if(!featureReader)return null;var feature=featureReader(node,[this.getReadOptions(node,opt_options)]);if(!feature)return null;this.handleReadExtensions_([feature]);return feature};ol.format.GPX.prototype.readFeatures;
ol.format.GPX.prototype.readFeaturesFromNode=function(node,opt_options){if(!ol.array.includes(ol.format.GPX.NAMESPACE_URIS_,node.namespaceURI))return[];if(node.localName=="gpx"){var features=ol.xml.pushParseAndPop([],ol.format.GPX.GPX_PARSERS_,node,[this.getReadOptions(node,opt_options)]);if(features){this.handleReadExtensions_(features);return features}else return[]}return[]};ol.format.GPX.prototype.readProjection;
ol.format.GPX.writeLink_=function(node,value,objectStack){node.setAttribute("href",value);var context=objectStack[objectStack.length-1];var properties=context["properties"];var link=[properties["linkText"],properties["linkType"]];ol.xml.pushSerializeAndPop({node:node},ol.format.GPX.LINK_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,link,objectStack,ol.format.GPX.LINK_SEQUENCE_)};
ol.format.GPX.writeWptType_=function(node,coordinate,objectStack){var context=objectStack[objectStack.length-1];var parentNode=context.node;var namespaceURI=parentNode.namespaceURI;var properties=context["properties"];ol.xml.setAttributeNS(node,null,"lat",coordinate[1]);ol.xml.setAttributeNS(node,null,"lon",coordinate[0]);var geometryLayout=context["geometryLayout"];switch(geometryLayout){case ol.geom.GeometryLayout.XYZM:if(coordinate[3]!==0)properties["time"]=coordinate[3];case ol.geom.GeometryLayout.XYZ:if(coordinate[2]!==
0)properties["ele"]=coordinate[2];break;case ol.geom.GeometryLayout.XYM:if(coordinate[2]!==0)properties["time"]=coordinate[2];break;default:}var orderedKeys=node.nodeName=="rtept"?ol.format.GPX.RTEPT_TYPE_SEQUENCE_[namespaceURI]:ol.format.GPX.WPT_TYPE_SEQUENCE_[namespaceURI];var values=ol.xml.makeSequence(properties,orderedKeys);ol.xml.pushSerializeAndPop({node:node,"properties":properties},ol.format.GPX.WPT_TYPE_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,orderedKeys)};
ol.format.GPX.writeRte_=function(node,feature,objectStack){var options=objectStack[0];var properties=feature.getProperties();var context={node:node,"properties":properties};var geometry=feature.getGeometry();if(geometry){geometry=ol.format.Feature.transformWithOptions(geometry,true,options);context["geometryLayout"]=geometry.getLayout();properties["rtept"]=geometry.getCoordinates()}var parentNode=objectStack[objectStack.length-1].node;var orderedKeys=ol.format.GPX.RTE_SEQUENCE_[parentNode.namespaceURI];
var values=ol.xml.makeSequence(properties,orderedKeys);ol.xml.pushSerializeAndPop(context,ol.format.GPX.RTE_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,orderedKeys)};
ol.format.GPX.writeTrk_=function(node,feature,objectStack){var options=objectStack[0];var properties=feature.getProperties();var context={node:node,"properties":properties};var geometry=feature.getGeometry();if(geometry){geometry=ol.format.Feature.transformWithOptions(geometry,true,options);properties["trkseg"]=geometry.getLineStrings()}var parentNode=objectStack[objectStack.length-1].node;var orderedKeys=ol.format.GPX.TRK_SEQUENCE_[parentNode.namespaceURI];var values=ol.xml.makeSequence(properties,
orderedKeys);ol.xml.pushSerializeAndPop(context,ol.format.GPX.TRK_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,orderedKeys)};ol.format.GPX.writeTrkSeg_=function(node,lineString,objectStack){var context={node:node,"geometryLayout":lineString.getLayout(),"properties":{}};ol.xml.pushSerializeAndPop(context,ol.format.GPX.TRKSEG_SERIALIZERS_,ol.format.GPX.TRKSEG_NODE_FACTORY_,lineString.getCoordinates(),objectStack)};
ol.format.GPX.writeWpt_=function(node,feature,objectStack){var options=objectStack[0];var context=objectStack[objectStack.length-1];context["properties"]=feature.getProperties();var geometry=feature.getGeometry();if(geometry){geometry=ol.format.Feature.transformWithOptions(geometry,true,options);context["geometryLayout"]=geometry.getLayout();ol.format.GPX.writeWptType_(node,geometry.getCoordinates(),objectStack)}};ol.format.GPX.LINK_SEQUENCE_=["text","type"];
ol.format.GPX.LINK_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"text":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"type":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)});ol.format.GPX.RTE_SEQUENCE_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,["name","cmt","desc","src","link","number","type","rtept"]);
ol.format.GPX.RTE_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"name":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"cmt":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"desc":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"src":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"link":ol.xml.makeChildAppender(ol.format.GPX.writeLink_),"number":ol.xml.makeChildAppender(ol.format.XSD.writeNonNegativeIntegerTextNode),"type":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
"rtept":ol.xml.makeArraySerializer(ol.xml.makeChildAppender(ol.format.GPX.writeWptType_))});ol.format.GPX.RTEPT_TYPE_SEQUENCE_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,["ele","time"]);ol.format.GPX.TRK_SEQUENCE_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,["name","cmt","desc","src","link","number","type","trkseg"]);
ol.format.GPX.TRK_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"name":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"cmt":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"desc":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"src":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"link":ol.xml.makeChildAppender(ol.format.GPX.writeLink_),"number":ol.xml.makeChildAppender(ol.format.XSD.writeNonNegativeIntegerTextNode),"type":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
"trkseg":ol.xml.makeArraySerializer(ol.xml.makeChildAppender(ol.format.GPX.writeTrkSeg_))});ol.format.GPX.TRKSEG_NODE_FACTORY_=ol.xml.makeSimpleNodeFactory("trkpt");ol.format.GPX.TRKSEG_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"trkpt":ol.xml.makeChildAppender(ol.format.GPX.writeWptType_)});
ol.format.GPX.WPT_TYPE_SEQUENCE_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,["ele","time","magvar","geoidheight","name","cmt","desc","src","link","sym","type","fix","sat","hdop","vdop","pdop","ageofdgpsdata","dgpsid"]);
ol.format.GPX.WPT_TYPE_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"ele":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),"time":ol.xml.makeChildAppender(ol.format.XSD.writeDateTimeTextNode),"magvar":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),"geoidheight":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),"name":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"cmt":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
"desc":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"src":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"link":ol.xml.makeChildAppender(ol.format.GPX.writeLink_),"sym":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"type":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"fix":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"sat":ol.xml.makeChildAppender(ol.format.XSD.writeNonNegativeIntegerTextNode),"hdop":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),
"vdop":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),"pdop":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),"ageofdgpsdata":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),"dgpsid":ol.xml.makeChildAppender(ol.format.XSD.writeNonNegativeIntegerTextNode)});ol.format.GPX.GEOMETRY_TYPE_TO_NODENAME_={"Point":"wpt","LineString":"rte","MultiLineString":"trk"};
ol.format.GPX.GPX_NODE_FACTORY_=function(value,objectStack,opt_nodeName){var geometry=value.getGeometry();if(geometry){var nodeName=ol.format.GPX.GEOMETRY_TYPE_TO_NODENAME_[geometry.getType()];if(nodeName){var parentNode=objectStack[objectStack.length-1].node;return ol.xml.createElementNS(parentNode.namespaceURI,nodeName)}}};
ol.format.GPX.GPX_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.GPX.NAMESPACE_URIS_,{"rte":ol.xml.makeChildAppender(ol.format.GPX.writeRte_),"trk":ol.xml.makeChildAppender(ol.format.GPX.writeTrk_),"wpt":ol.xml.makeChildAppender(ol.format.GPX.writeWpt_)});ol.format.GPX.prototype.writeFeatures;
ol.format.GPX.prototype.writeFeaturesNode=function(features,opt_options){opt_options=this.adaptOptions(opt_options);var gpx=ol.xml.createElementNS("http://www.topografix.com/GPX/1/1","gpx");var xmlnsUri="http://www.w3.org/2000/xmlns/";var xmlSchemaInstanceUri="http://www.w3.org/2001/XMLSchema-instance";ol.xml.setAttributeNS(gpx,xmlnsUri,"xmlns:xsi",xmlSchemaInstanceUri);ol.xml.setAttributeNS(gpx,xmlSchemaInstanceUri,"xsi:schemaLocation",ol.format.GPX.SCHEMA_LOCATION_);gpx.setAttribute("version","1.1");
gpx.setAttribute("creator","OpenLayers");ol.xml.pushSerializeAndPop({node:gpx},ol.format.GPX.GPX_SERIALIZERS_,ol.format.GPX.GPX_NODE_FACTORY_,features,[opt_options]);return gpx};goog.provide("ol.format.IGCZ");ol.format.IGCZ={BAROMETRIC:"barometric",GPS:"gps",NONE:"none"};goog.provide("ol.format.TextFeature");goog.require("ol");goog.require("ol.format.Feature");goog.require("ol.format.FormatType");ol.format.TextFeature=function(){ol.format.Feature.call(this)};ol.inherits(ol.format.TextFeature,ol.format.Feature);ol.format.TextFeature.prototype.getText_=function(source){if(typeof source==="string")return source;else return""};ol.format.TextFeature.prototype.getType=function(){return ol.format.FormatType.TEXT};
ol.format.TextFeature.prototype.readFeature=function(source,opt_options){return this.readFeatureFromText(this.getText_(source),this.adaptOptions(opt_options))};ol.format.TextFeature.prototype.readFeatureFromText=function(text,opt_options){};ol.format.TextFeature.prototype.readFeatures=function(source,opt_options){return this.readFeaturesFromText(this.getText_(source),this.adaptOptions(opt_options))};ol.format.TextFeature.prototype.readFeaturesFromText=function(text,opt_options){};
ol.format.TextFeature.prototype.readGeometry=function(source,opt_options){return this.readGeometryFromText(this.getText_(source),this.adaptOptions(opt_options))};ol.format.TextFeature.prototype.readGeometryFromText=function(text,opt_options){};ol.format.TextFeature.prototype.readProjection=function(source){return this.readProjectionFromText(this.getText_(source))};ol.format.TextFeature.prototype.readProjectionFromText=function(text){return this.defaultDataProjection};
ol.format.TextFeature.prototype.writeFeature=function(feature,opt_options){return this.writeFeatureText(feature,this.adaptOptions(opt_options))};ol.format.TextFeature.prototype.writeFeatureText=function(feature,opt_options){};ol.format.TextFeature.prototype.writeFeatures=function(features,opt_options){return this.writeFeaturesText(features,this.adaptOptions(opt_options))};ol.format.TextFeature.prototype.writeFeaturesText=function(features,opt_options){};
ol.format.TextFeature.prototype.writeGeometry=function(geometry,opt_options){return this.writeGeometryText(geometry,this.adaptOptions(opt_options))};ol.format.TextFeature.prototype.writeGeometryText=function(geometry,opt_options){};goog.provide("ol.format.IGC");goog.require("ol");goog.require("ol.Feature");goog.require("ol.format.Feature");goog.require("ol.format.IGCZ");goog.require("ol.format.TextFeature");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.LineString");goog.require("ol.proj");ol.format.IGC=function(opt_options){var options=opt_options?opt_options:{};ol.format.TextFeature.call(this);this.defaultDataProjection=ol.proj.get("EPSG:4326");this.altitudeMode_=options.altitudeMode?options.altitudeMode:ol.format.IGCZ.NONE};
ol.inherits(ol.format.IGC,ol.format.TextFeature);ol.format.IGC.B_RECORD_RE_=/^B(\d{2})(\d{2})(\d{2})(\d{2})(\d{5})([NS])(\d{3})(\d{5})([EW])([AV])(\d{5})(\d{5})/;ol.format.IGC.H_RECORD_RE_=/^H.([A-Z]{3}).*?:(.*)/;ol.format.IGC.HFDTE_RECORD_RE_=/^HFDTE(\d{2})(\d{2})(\d{2})/;ol.format.IGC.NEWLINE_RE_=/\r\n|\r|\n/;ol.format.IGC.prototype.readFeature;
ol.format.IGC.prototype.readFeatureFromText=function(text,opt_options){var altitudeMode=this.altitudeMode_;var lines=text.split(ol.format.IGC.NEWLINE_RE_);var properties={};var flatCoordinates=[];var year=2E3;var month=0;var day=1;var lastDateTime=-1;var i,ii;for(i=0,ii=lines.length;i<ii;++i){var line=lines[i];var m;if(line.charAt(0)=="B"){m=ol.format.IGC.B_RECORD_RE_.exec(line);if(m){var hour=parseInt(m[1],10);var minute=parseInt(m[2],10);var second=parseInt(m[3],10);var y=parseInt(m[4],10)+parseInt(m[5],
10)/6E4;if(m[6]=="S")y=-y;var x=parseInt(m[7],10)+parseInt(m[8],10)/6E4;if(m[9]=="W")x=-x;flatCoordinates.push(x,y);if(altitudeMode!=ol.format.IGCZ.NONE){var z;if(altitudeMode==ol.format.IGCZ.GPS)z=parseInt(m[11],10);else if(altitudeMode==ol.format.IGCZ.BAROMETRIC)z=parseInt(m[12],10);else z=0;flatCoordinates.push(z)}var dateTime=Date.UTC(year,month,day,hour,minute,second);if(dateTime<lastDateTime)dateTime=Date.UTC(year,month,day+1,hour,minute,second);flatCoordinates.push(dateTime/1E3);lastDateTime=
dateTime}}else if(line.charAt(0)=="H"){m=ol.format.IGC.HFDTE_RECORD_RE_.exec(line);if(m){day=parseInt(m[1],10);month=parseInt(m[2],10)-1;year=2E3+parseInt(m[3],10)}else{m=ol.format.IGC.H_RECORD_RE_.exec(line);if(m)properties[m[1]]=m[2].trim()}}}if(flatCoordinates.length===0)return null;var lineString=new ol.geom.LineString(null);var layout=altitudeMode==ol.format.IGCZ.NONE?ol.geom.GeometryLayout.XYM:ol.geom.GeometryLayout.XYZM;lineString.setFlatCoordinates(layout,flatCoordinates);var feature=new ol.Feature(ol.format.Feature.transformWithOptions(lineString,
false,opt_options));feature.setProperties(properties);return feature};ol.format.IGC.prototype.readFeatures;ol.format.IGC.prototype.readFeaturesFromText=function(text,opt_options){var feature=this.readFeatureFromText(text,opt_options);if(feature)return[feature];else return[]};ol.format.IGC.prototype.readProjection;ol.format.IGC.prototype.writeFeatureText=function(feature,opt_options){};ol.format.IGC.prototype.writeFeaturesText=function(features,opt_options){};
ol.format.IGC.prototype.writeGeometryText=function(geometry,opt_options){};ol.format.IGC.prototype.readGeometryFromText=function(text,opt_options){};goog.provide("ol.style.IconAnchorUnits");ol.style.IconAnchorUnits={FRACTION:"fraction",PIXELS:"pixels"};goog.provide("ol.style.IconImage");goog.require("ol");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.events.EventTarget");goog.require("ol.events.EventType");goog.require("ol.ImageState");goog.require("ol.style");
ol.style.IconImage=function(image,src,size,crossOrigin,imageState,color){ol.events.EventTarget.call(this);this.hitDetectionImage_=null;this.image_=!image?new Image:image;if(crossOrigin!==null)this.image_.crossOrigin=crossOrigin;this.canvas_=color?document.createElement("CANVAS"):null;this.color_=color;this.imageListenerKeys_=null;this.imageState_=imageState;this.size_=size;this.src_=src;this.tainting_=false;if(this.imageState_==ol.ImageState.LOADED)this.determineTainting_()};
ol.inherits(ol.style.IconImage,ol.events.EventTarget);ol.style.IconImage.get=function(image,src,size,crossOrigin,imageState,color){var iconImageCache=ol.style.iconImageCache;var iconImage=iconImageCache.get(src,crossOrigin,color);if(!iconImage){iconImage=new ol.style.IconImage(image,src,size,crossOrigin,imageState,color);iconImageCache.set(src,crossOrigin,color,iconImage)}return iconImage};
ol.style.IconImage.prototype.determineTainting_=function(){var context=ol.dom.createCanvasContext2D(1,1);try{context.drawImage(this.image_,0,0);context.getImageData(0,0,1,1)}catch(e){this.tainting_=true}};ol.style.IconImage.prototype.dispatchChangeEvent_=function(){this.dispatchEvent(ol.events.EventType.CHANGE)};ol.style.IconImage.prototype.handleImageError_=function(){this.imageState_=ol.ImageState.ERROR;this.unlistenImage_();this.dispatchChangeEvent_()};
ol.style.IconImage.prototype.handleImageLoad_=function(){this.imageState_=ol.ImageState.LOADED;if(this.size_){this.image_.width=this.size_[0];this.image_.height=this.size_[1]}this.size_=[this.image_.width,this.image_.height];this.unlistenImage_();this.determineTainting_();this.replaceColor_();this.dispatchChangeEvent_()};ol.style.IconImage.prototype.getImage=function(pixelRatio){return this.canvas_?this.canvas_:this.image_};ol.style.IconImage.prototype.getImageState=function(){return this.imageState_};
ol.style.IconImage.prototype.getHitDetectionImage=function(pixelRatio){if(!this.hitDetectionImage_)if(this.tainting_){var width=this.size_[0];var height=this.size_[1];var context=ol.dom.createCanvasContext2D(width,height);context.fillRect(0,0,width,height);this.hitDetectionImage_=context.canvas}else this.hitDetectionImage_=this.image_;return this.hitDetectionImage_};ol.style.IconImage.prototype.getSize=function(){return this.size_};ol.style.IconImage.prototype.getSrc=function(){return this.src_};
ol.style.IconImage.prototype.load=function(){if(this.imageState_==ol.ImageState.IDLE){this.imageState_=ol.ImageState.LOADING;this.imageListenerKeys_=[ol.events.listenOnce(this.image_,ol.events.EventType.ERROR,this.handleImageError_,this),ol.events.listenOnce(this.image_,ol.events.EventType.LOAD,this.handleImageLoad_,this)];try{this.image_.src=this.src_}catch(e){this.handleImageError_()}}};
ol.style.IconImage.prototype.replaceColor_=function(){if(this.tainting_||this.color_===null)return;this.canvas_.width=this.image_.width;this.canvas_.height=this.image_.height;var ctx=this.canvas_.getContext("2d");ctx.drawImage(this.image_,0,0);var imgData=ctx.getImageData(0,0,this.image_.width,this.image_.height);var data=imgData.data;var r=this.color_[0]/255;var g=this.color_[1]/255;var b=this.color_[2]/255;for(var i=0,ii=data.length;i<ii;i+=4){data[i]*=r;data[i+1]*=g;data[i+2]*=b}ctx.putImageData(imgData,
0,0)};ol.style.IconImage.prototype.unlistenImage_=function(){this.imageListenerKeys_.forEach(ol.events.unlistenByKey);this.imageListenerKeys_=null};goog.provide("ol.style.IconOrigin");ol.style.IconOrigin={BOTTOM_LEFT:"bottom-left",BOTTOM_RIGHT:"bottom-right",TOP_LEFT:"top-left",TOP_RIGHT:"top-right"};goog.provide("ol.style.Icon");goog.require("ol");goog.require("ol.ImageState");goog.require("ol.asserts");goog.require("ol.color");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.style.IconAnchorUnits");goog.require("ol.style.IconImage");goog.require("ol.style.IconOrigin");goog.require("ol.style.Image");
ol.style.Icon=function(opt_options){var options=opt_options||{};this.anchor_=options.anchor!==undefined?options.anchor:[.5,.5];this.normalizedAnchor_=null;this.anchorOrigin_=options.anchorOrigin!==undefined?options.anchorOrigin:ol.style.IconOrigin.TOP_LEFT;this.anchorXUnits_=options.anchorXUnits!==undefined?options.anchorXUnits:ol.style.IconAnchorUnits.FRACTION;this.anchorYUnits_=options.anchorYUnits!==undefined?options.anchorYUnits:ol.style.IconAnchorUnits.FRACTION;this.crossOrigin_=options.crossOrigin!==
undefined?options.crossOrigin:null;var image=options.img!==undefined?options.img:null;var imgSize=options.imgSize!==undefined?options.imgSize:null;var src=options.src;ol.asserts.assert(!(src!==undefined&&image),4);ol.asserts.assert(!image||image&&imgSize,5);if((src===undefined||src.length===0)&&image)src=image.src||ol.getUid(image).toString();ol.asserts.assert(src!==undefined&&src.length>0,6);var imageState=options.src!==undefined?ol.ImageState.IDLE:ol.ImageState.LOADED;this.color_=options.color!==
undefined?ol.color.asArray(options.color):null;this.iconImage_=ol.style.IconImage.get(image,src,imgSize,this.crossOrigin_,imageState,this.color_);this.offset_=options.offset!==undefined?options.offset:[0,0];this.offsetOrigin_=options.offsetOrigin!==undefined?options.offsetOrigin:ol.style.IconOrigin.TOP_LEFT;this.origin_=null;this.size_=options.size!==undefined?options.size:null;var opacity=options.opacity!==undefined?options.opacity:1;var rotateWithView=options.rotateWithView!==undefined?options.rotateWithView:
false;var rotation=options.rotation!==undefined?options.rotation:0;var scale=options.scale!==undefined?options.scale:1;var snapToPixel=options.snapToPixel!==undefined?options.snapToPixel:true;ol.style.Image.call(this,{opacity:opacity,rotation:rotation,scale:scale,snapToPixel:snapToPixel,rotateWithView:rotateWithView})};ol.inherits(ol.style.Icon,ol.style.Image);
ol.style.Icon.prototype.clone=function(){return new ol.style.Icon({anchor:this.anchor_.slice(),anchorOrigin:this.anchorOrigin_,anchorXUnits:this.anchorXUnits_,anchorYUnits:this.anchorYUnits_,crossOrigin:this.crossOrigin_,color:this.color_&&this.color_.slice?this.color_.slice():this.color_||undefined,src:this.getSrc(),offset:this.offset_.slice(),offsetOrigin:this.offsetOrigin_,size:this.size_!==null?this.size_.slice():undefined,opacity:this.getOpacity(),scale:this.getScale(),snapToPixel:this.getSnapToPixel(),
rotation:this.getRotation(),rotateWithView:this.getRotateWithView()})};
ol.style.Icon.prototype.getAnchor=function(){if(this.normalizedAnchor_)return this.normalizedAnchor_;var anchor=this.anchor_;var size=this.getSize();if(this.anchorXUnits_==ol.style.IconAnchorUnits.FRACTION||this.anchorYUnits_==ol.style.IconAnchorUnits.FRACTION){if(!size)return null;anchor=this.anchor_.slice();if(this.anchorXUnits_==ol.style.IconAnchorUnits.FRACTION)anchor[0]*=size[0];if(this.anchorYUnits_==ol.style.IconAnchorUnits.FRACTION)anchor[1]*=size[1]}if(this.anchorOrigin_!=ol.style.IconOrigin.TOP_LEFT){if(!size)return null;
if(anchor===this.anchor_)anchor=this.anchor_.slice();if(this.anchorOrigin_==ol.style.IconOrigin.TOP_RIGHT||this.anchorOrigin_==ol.style.IconOrigin.BOTTOM_RIGHT)anchor[0]=-anchor[0]+size[0];if(this.anchorOrigin_==ol.style.IconOrigin.BOTTOM_LEFT||this.anchorOrigin_==ol.style.IconOrigin.BOTTOM_RIGHT)anchor[1]=-anchor[1]+size[1]}this.normalizedAnchor_=anchor;return this.normalizedAnchor_};ol.style.Icon.prototype.getColor=function(){return this.color_};ol.style.Icon.prototype.getImage=function(pixelRatio){return this.iconImage_.getImage(pixelRatio)};
ol.style.Icon.prototype.getImageSize=function(){return this.iconImage_.getSize()};ol.style.Icon.prototype.getHitDetectionImageSize=function(){return this.getImageSize()};ol.style.Icon.prototype.getImageState=function(){return this.iconImage_.getImageState()};ol.style.Icon.prototype.getHitDetectionImage=function(pixelRatio){return this.iconImage_.getHitDetectionImage(pixelRatio)};
ol.style.Icon.prototype.getOrigin=function(){if(this.origin_)return this.origin_;var offset=this.offset_;if(this.offsetOrigin_!=ol.style.IconOrigin.TOP_LEFT){var size=this.getSize();var iconImageSize=this.iconImage_.getSize();if(!size||!iconImageSize)return null;offset=offset.slice();if(this.offsetOrigin_==ol.style.IconOrigin.TOP_RIGHT||this.offsetOrigin_==ol.style.IconOrigin.BOTTOM_RIGHT)offset[0]=iconImageSize[0]-size[0]-offset[0];if(this.offsetOrigin_==ol.style.IconOrigin.BOTTOM_LEFT||this.offsetOrigin_==
ol.style.IconOrigin.BOTTOM_RIGHT)offset[1]=iconImageSize[1]-size[1]-offset[1]}this.origin_=offset;return this.origin_};ol.style.Icon.prototype.getSrc=function(){return this.iconImage_.getSrc()};ol.style.Icon.prototype.getSize=function(){return!this.size_?this.iconImage_.getSize():this.size_};ol.style.Icon.prototype.listenImageChange=function(listener,thisArg){return ol.events.listen(this.iconImage_,ol.events.EventType.CHANGE,listener,thisArg)};ol.style.Icon.prototype.load=function(){this.iconImage_.load()};
ol.style.Icon.prototype.unlistenImageChange=function(listener,thisArg){ol.events.unlisten(this.iconImage_,ol.events.EventType.CHANGE,listener,thisArg)};goog.provide("ol.style.Text");goog.require("ol.style.Fill");goog.require("ol.style.TextPlacement");
ol.style.Text=function(opt_options){var options=opt_options||{};this.font_=options.font;this.rotation_=options.rotation;this.rotateWithView_=options.rotateWithView;this.scale_=options.scale;this.text_=options.text;this.textAlign_=options.textAlign;this.textBaseline_=options.textBaseline;this.fill_=options.fill!==undefined?options.fill:new ol.style.Fill({color:ol.style.Text.DEFAULT_FILL_COLOR_});this.maxAngle_=options.maxAngle!==undefined?options.maxAngle:Math.PI/4;this.placement_=options.placement!==
undefined?options.placement:ol.style.TextPlacement.POINT;var overflow=options.overflow===undefined?options.exceedLength:options.overflow;this.overflow_=overflow!==undefined?overflow:false;this.stroke_=options.stroke!==undefined?options.stroke:null;this.offsetX_=options.offsetX!==undefined?options.offsetX:0;this.offsetY_=options.offsetY!==undefined?options.offsetY:0;this.backgroundFill_=options.backgroundFill?options.backgroundFill:null;this.backgroundStroke_=options.backgroundStroke?options.backgroundStroke:
null;this.padding_=options.padding===undefined?null:options.padding};ol.style.Text.DEFAULT_FILL_COLOR_="#333";
ol.style.Text.prototype.clone=function(){return new ol.style.Text({font:this.getFont(),placement:this.getPlacement(),maxAngle:this.getMaxAngle(),overflow:this.getOverflow(),rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),scale:this.getScale(),text:this.getText(),textAlign:this.getTextAlign(),textBaseline:this.getTextBaseline(),fill:this.getFill()?this.getFill().clone():undefined,stroke:this.getStroke()?this.getStroke().clone():undefined,offsetX:this.getOffsetX(),offsetY:this.getOffsetY()})};
ol.style.Text.prototype.getOverflow=function(){return this.overflow_};ol.style.Text.prototype.getFont=function(){return this.font_};ol.style.Text.prototype.getMaxAngle=function(){return this.maxAngle_};ol.style.Text.prototype.getPlacement=function(){return this.placement_};ol.style.Text.prototype.getOffsetX=function(){return this.offsetX_};ol.style.Text.prototype.getOffsetY=function(){return this.offsetY_};ol.style.Text.prototype.getFill=function(){return this.fill_};
ol.style.Text.prototype.getRotateWithView=function(){return this.rotateWithView_};ol.style.Text.prototype.getRotation=function(){return this.rotation_};ol.style.Text.prototype.getScale=function(){return this.scale_};ol.style.Text.prototype.getStroke=function(){return this.stroke_};ol.style.Text.prototype.getText=function(){return this.text_};ol.style.Text.prototype.getTextAlign=function(){return this.textAlign_};ol.style.Text.prototype.getTextBaseline=function(){return this.textBaseline_};
ol.style.Text.prototype.getBackgroundFill=function(){return this.backgroundFill_};ol.style.Text.prototype.getBackgroundStroke=function(){return this.backgroundStroke_};ol.style.Text.prototype.getPadding=function(){return this.padding_};ol.style.Text.prototype.setOverflow=function(overflow){this.overflow_=overflow};ol.style.Text.prototype.setFont=function(font){this.font_=font};ol.style.Text.prototype.setMaxAngle=function(maxAngle){this.maxAngle_=maxAngle};
ol.style.Text.prototype.setOffsetX=function(offsetX){this.offsetX_=offsetX};ol.style.Text.prototype.setOffsetY=function(offsetY){this.offsetY_=offsetY};ol.style.Text.prototype.setPlacement=function(placement){this.placement_=placement};ol.style.Text.prototype.setFill=function(fill){this.fill_=fill};ol.style.Text.prototype.setRotation=function(rotation){this.rotation_=rotation};ol.style.Text.prototype.setScale=function(scale){this.scale_=scale};
ol.style.Text.prototype.setStroke=function(stroke){this.stroke_=stroke};ol.style.Text.prototype.setText=function(text){this.text_=text};ol.style.Text.prototype.setTextAlign=function(textAlign){this.textAlign_=textAlign};ol.style.Text.prototype.setTextBaseline=function(textBaseline){this.textBaseline_=textBaseline};ol.style.Text.prototype.setBackgroundFill=function(fill){this.backgroundFill_=fill};ol.style.Text.prototype.setBackgroundStroke=function(stroke){this.backgroundStroke_=stroke};
ol.style.Text.prototype.setPadding=function(padding){this.padding_=padding};goog.provide("ol.format.KML");goog.require("ol");goog.require("ol.Feature");goog.require("ol.array");goog.require("ol.asserts");goog.require("ol.color");goog.require("ol.format.Feature");goog.require("ol.format.XMLFeature");goog.require("ol.format.XSD");goog.require("ol.geom.GeometryCollection");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.GeometryType");goog.require("ol.geom.LineString");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.MultiPoint");goog.require("ol.geom.MultiPolygon");
goog.require("ol.geom.Point");goog.require("ol.geom.Polygon");goog.require("ol.math");goog.require("ol.proj");goog.require("ol.style.Fill");goog.require("ol.style.Icon");goog.require("ol.style.IconAnchorUnits");goog.require("ol.style.IconOrigin");goog.require("ol.style.Stroke");goog.require("ol.style.Style");goog.require("ol.style.Text");goog.require("ol.xml");
ol.format.KML=function(opt_options){var options=opt_options?opt_options:{};ol.format.XMLFeature.call(this);if(!ol.format.KML.DEFAULT_STYLE_ARRAY_)ol.format.KML.createStyleDefaults_();this.defaultDataProjection=ol.proj.get("EPSG:4326");this.defaultStyle_=options.defaultStyle?options.defaultStyle:ol.format.KML.DEFAULT_STYLE_ARRAY_;this.extractStyles_=options.extractStyles!==undefined?options.extractStyles:true;this.writeStyles_=options.writeStyles!==undefined?options.writeStyles:true;this.sharedStyles_=
{};this.showPointNames_=options.showPointNames!==undefined?options.showPointNames:true};ol.inherits(ol.format.KML,ol.format.XMLFeature);ol.format.KML.GX_NAMESPACE_URIS_=["http://www.google.com/kml/ext/2.2"];ol.format.KML.NAMESPACE_URIS_=[null,"http://earth.google.com/kml/2.0","http://earth.google.com/kml/2.1","http://earth.google.com/kml/2.2","http://www.opengis.net/kml/2.2"];ol.format.KML.SCHEMA_LOCATION_="http://www.opengis.net/kml/2.2 "+"https://developers.google.com/kml/schema/kml22gx.xsd";
ol.format.KML.createStyleDefaults_=function(){ol.format.KML.DEFAULT_COLOR_=[255,255,255,1];ol.format.KML.DEFAULT_FILL_STYLE_=new ol.style.Fill({color:ol.format.KML.DEFAULT_COLOR_});ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_=[20,2];ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS_=ol.style.IconAnchorUnits.PIXELS;ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS_=ol.style.IconAnchorUnits.PIXELS;ol.format.KML.DEFAULT_IMAGE_STYLE_SIZE_=[64,64];ol.format.KML.DEFAULT_IMAGE_STYLE_SRC_="https://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png";
ol.format.KML.DEFAULT_IMAGE_SCALE_MULTIPLIER_=.5;ol.format.KML.DEFAULT_IMAGE_STYLE_=new ol.style.Icon({anchor:ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_,anchorOrigin:ol.style.IconOrigin.BOTTOM_LEFT,anchorXUnits:ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS_,anchorYUnits:ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS_,crossOrigin:"anonymous",rotation:0,scale:ol.format.KML.DEFAULT_IMAGE_SCALE_MULTIPLIER_,size:ol.format.KML.DEFAULT_IMAGE_STYLE_SIZE_,src:ol.format.KML.DEFAULT_IMAGE_STYLE_SRC_});ol.format.KML.DEFAULT_NO_IMAGE_STYLE_=
"NO_IMAGE";ol.format.KML.DEFAULT_STROKE_STYLE_=new ol.style.Stroke({color:ol.format.KML.DEFAULT_COLOR_,width:1});ol.format.KML.DEFAULT_TEXT_STROKE_STYLE_=new ol.style.Stroke({color:[51,51,51,1],width:2});ol.format.KML.DEFAULT_TEXT_STYLE_=new ol.style.Text({font:"bold 16px Helvetica",fill:ol.format.KML.DEFAULT_FILL_STYLE_,stroke:ol.format.KML.DEFAULT_TEXT_STROKE_STYLE_,scale:.8});ol.format.KML.DEFAULT_STYLE_=new ol.style.Style({fill:ol.format.KML.DEFAULT_FILL_STYLE_,image:ol.format.KML.DEFAULT_IMAGE_STYLE_,
text:ol.format.KML.DEFAULT_TEXT_STYLE_,stroke:ol.format.KML.DEFAULT_STROKE_STYLE_,zIndex:0});ol.format.KML.DEFAULT_STYLE_ARRAY_=[ol.format.KML.DEFAULT_STYLE_];return ol.format.KML.DEFAULT_STYLE_ARRAY_};ol.format.KML.ICON_ANCHOR_UNITS_MAP_={"fraction":ol.style.IconAnchorUnits.FRACTION,"pixels":ol.style.IconAnchorUnits.PIXELS,"insetPixels":ol.style.IconAnchorUnits.PIXELS};
ol.format.KML.createNameStyleFunction_=function(foundStyle,name){var textStyle=null;var textOffset=[0,0];var textAlign="start";if(foundStyle.getImage()){var imageSize=foundStyle.getImage().getImageSize();if(imageSize===null)imageSize=ol.format.KML.DEFAULT_IMAGE_STYLE_SIZE_;if(imageSize.length==2){var imageScale=foundStyle.getImage().getScale();textOffset[0]=imageScale*imageSize[0]/2;textOffset[1]=-imageScale*imageSize[1]/2;textAlign="left"}}if(foundStyle.getText()!==null){var foundText=foundStyle.getText();
textStyle=foundText.clone();textStyle.setFont(foundText.getFont()||ol.format.KML.DEFAULT_TEXT_STYLE_.getFont());textStyle.setScale(foundText.getScale()||ol.format.KML.DEFAULT_TEXT_STYLE_.getScale());textStyle.setFill(foundText.getFill()||ol.format.KML.DEFAULT_TEXT_STYLE_.getFill());textStyle.setStroke(foundText.getStroke()||ol.format.KML.DEFAULT_TEXT_STROKE_STYLE_)}else textStyle=ol.format.KML.DEFAULT_TEXT_STYLE_.clone();textStyle.setText(name);textStyle.setOffsetX(textOffset[0]);textStyle.setOffsetY(textOffset[1]);
textStyle.setTextAlign(textAlign);var nameStyle=new ol.style.Style({text:textStyle});return nameStyle};
ol.format.KML.createFeatureStyleFunction_=function(style,styleUrl,defaultStyle,sharedStyles,showPointNames){return function(resolution){var drawName=showPointNames;var nameStyle;var name="";if(drawName)if(this.getGeometry())drawName=this.getGeometry().getType()===ol.geom.GeometryType.POINT;if(drawName){name=this.get("name");drawName=drawName&&name}if(style){if(drawName){nameStyle=ol.format.KML.createNameStyleFunction_(style[0],name);return style.concat(nameStyle)}return style}if(styleUrl){var foundStyle=
ol.format.KML.findStyle_(styleUrl,defaultStyle,sharedStyles);if(drawName){nameStyle=ol.format.KML.createNameStyleFunction_(foundStyle[0],name);return foundStyle.concat(nameStyle)}return foundStyle}if(drawName){nameStyle=ol.format.KML.createNameStyleFunction_(defaultStyle[0],name);return defaultStyle.concat(nameStyle)}return defaultStyle}};
ol.format.KML.findStyle_=function(styleValue,defaultStyle,sharedStyles){if(Array.isArray(styleValue))return styleValue;else if(typeof styleValue==="string"){if(!(styleValue in sharedStyles)&&"#"+styleValue in sharedStyles)styleValue="#"+styleValue;return ol.format.KML.findStyle_(sharedStyles[styleValue],defaultStyle,sharedStyles)}else return defaultStyle};
ol.format.KML.readColor_=function(node){var s=ol.xml.getAllTextContent(node,false);var m=/^\s*#?\s*([0-9A-Fa-f]{8})\s*$/.exec(s);if(m){var hexColor=m[1];return[parseInt(hexColor.substr(6,2),16),parseInt(hexColor.substr(4,2),16),parseInt(hexColor.substr(2,2),16),parseInt(hexColor.substr(0,2),16)/255]}else return undefined};
ol.format.KML.readFlatCoordinates_=function(node){var s=ol.xml.getAllTextContent(node,false);var flatCoordinates=[];var re=/^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*,\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)(?:\s*,\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?))?\s*/i;var m;while(m=re.exec(s)){var x=parseFloat(m[1]);var y=parseFloat(m[2]);var z=m[3]?parseFloat(m[3]):0;flatCoordinates.push(x,y,z);s=s.substr(m[0].length)}if(s!=="")return undefined;return flatCoordinates};
ol.format.KML.readURI_=function(node){var s=ol.xml.getAllTextContent(node,false).trim();var baseURI=node.baseURI;if(!baseURI||baseURI=="about:blank")baseURI=window.location.href;if(baseURI){var url=new URL(s,baseURI);return url.href}else return s};
ol.format.KML.readVec2_=function(node){var xunits=node.getAttribute("xunits");var yunits=node.getAttribute("yunits");var origin;if(xunits!=="insetPixels")if(yunits!=="insetPixels")origin=ol.style.IconOrigin.BOTTOM_LEFT;else origin=ol.style.IconOrigin.TOP_LEFT;else if(yunits!=="insetPixels")origin=ol.style.IconOrigin.BOTTOM_RIGHT;else origin=ol.style.IconOrigin.TOP_RIGHT;return{x:parseFloat(node.getAttribute("x")),xunits:ol.format.KML.ICON_ANCHOR_UNITS_MAP_[xunits],y:parseFloat(node.getAttribute("y")),
yunits:ol.format.KML.ICON_ANCHOR_UNITS_MAP_[yunits],origin:origin}};ol.format.KML.readScale_=function(node){return ol.format.XSD.readDecimal(node)};ol.format.KML.readStyleMapValue_=function(node,objectStack){return ol.xml.pushParseAndPop(undefined,ol.format.KML.STYLE_MAP_PARSERS_,node,objectStack)};
ol.format.KML.IconStyleParser_=function(node,objectStack){var object=ol.xml.pushParseAndPop({},ol.format.KML.ICON_STYLE_PARSERS_,node,objectStack);if(!object)return;var styleObject=objectStack[objectStack.length-1];var IconObject="Icon"in object?object["Icon"]:{};var drawIcon=!("Icon"in object)||Object.keys(IconObject).length>0;var src;var href=IconObject["href"];if(href)src=href;else if(drawIcon)src=ol.format.KML.DEFAULT_IMAGE_STYLE_SRC_;var anchor,anchorXUnits,anchorYUnits;var anchorOrigin=ol.style.IconOrigin.BOTTOM_LEFT;
var hotSpot=object["hotSpot"];if(hotSpot){anchor=[hotSpot.x,hotSpot.y];anchorXUnits=hotSpot.xunits;anchorYUnits=hotSpot.yunits;anchorOrigin=hotSpot.origin}else if(src===ol.format.KML.DEFAULT_IMAGE_STYLE_SRC_){anchor=ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_;anchorXUnits=ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS_;anchorYUnits=ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS_}else if(/^http:\/\/maps\.(?:google|gstatic)\.com\//.test(src)){anchor=[.5,0];anchorXUnits=ol.style.IconAnchorUnits.FRACTION;
anchorYUnits=ol.style.IconAnchorUnits.FRACTION}var offset;var x=IconObject["x"];var y=IconObject["y"];if(x!==undefined&&y!==undefined)offset=[x,y];var size;var w=IconObject["w"];var h=IconObject["h"];if(w!==undefined&&h!==undefined)size=[w,h];var rotation;var heading=object["heading"];if(heading!==undefined)rotation=ol.math.toRadians(heading);var scale=object["scale"];if(drawIcon){if(src==ol.format.KML.DEFAULT_IMAGE_STYLE_SRC_){size=ol.format.KML.DEFAULT_IMAGE_STYLE_SIZE_;if(scale===undefined)scale=
ol.format.KML.DEFAULT_IMAGE_SCALE_MULTIPLIER_}var imageStyle=new ol.style.Icon({anchor:anchor,anchorOrigin:anchorOrigin,anchorXUnits:anchorXUnits,anchorYUnits:anchorYUnits,crossOrigin:"anonymous",offset:offset,offsetOrigin:ol.style.IconOrigin.BOTTOM_LEFT,rotation:rotation,scale:scale,size:size,src:src});styleObject["imageStyle"]=imageStyle}else styleObject["imageStyle"]=ol.format.KML.DEFAULT_NO_IMAGE_STYLE_};
ol.format.KML.LabelStyleParser_=function(node,objectStack){var object=ol.xml.pushParseAndPop({},ol.format.KML.LABEL_STYLE_PARSERS_,node,objectStack);if(!object)return;var styleObject=objectStack[objectStack.length-1];var textStyle=new ol.style.Text({fill:new ol.style.Fill({color:"color"in object?object["color"]:ol.format.KML.DEFAULT_COLOR_}),scale:object["scale"]});styleObject["textStyle"]=textStyle};
ol.format.KML.LineStyleParser_=function(node,objectStack){var object=ol.xml.pushParseAndPop({},ol.format.KML.LINE_STYLE_PARSERS_,node,objectStack);if(!object)return;var styleObject=objectStack[objectStack.length-1];var strokeStyle=new ol.style.Stroke({color:"color"in object?object["color"]:ol.format.KML.DEFAULT_COLOR_,width:"width"in object?object["width"]:1});styleObject["strokeStyle"]=strokeStyle};
ol.format.KML.PolyStyleParser_=function(node,objectStack){var object=ol.xml.pushParseAndPop({},ol.format.KML.POLY_STYLE_PARSERS_,node,objectStack);if(!object)return;var styleObject=objectStack[objectStack.length-1];var fillStyle=new ol.style.Fill({color:"color"in object?object["color"]:ol.format.KML.DEFAULT_COLOR_});styleObject["fillStyle"]=fillStyle;var fill=object["fill"];if(fill!==undefined)styleObject["fill"]=fill;var outline=object["outline"];if(outline!==undefined)styleObject["outline"]=outline};
ol.format.KML.readFlatLinearRing_=function(node,objectStack){return ol.xml.pushParseAndPop(null,ol.format.KML.FLAT_LINEAR_RING_PARSERS_,node,objectStack)};
ol.format.KML.gxCoordParser_=function(node,objectStack){var gxTrackObject=objectStack[objectStack.length-1];var flatCoordinates=gxTrackObject.flatCoordinates;var s=ol.xml.getAllTextContent(node,false);var re=/^\s*([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s+([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s+([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s*$/i;var m=re.exec(s);if(m){var x=parseFloat(m[1]);var y=parseFloat(m[2]);var z=parseFloat(m[3]);flatCoordinates.push(x,y,z,0)}else flatCoordinates.push(0,0,0,0)};
ol.format.KML.readGxMultiTrack_=function(node,objectStack){var lineStrings=ol.xml.pushParseAndPop([],ol.format.KML.GX_MULTITRACK_GEOMETRY_PARSERS_,node,objectStack);if(!lineStrings)return undefined;var multiLineString=new ol.geom.MultiLineString(null);multiLineString.setLineStrings(lineStrings);return multiLineString};
ol.format.KML.readGxTrack_=function(node,objectStack){var gxTrackObject=ol.xml.pushParseAndPop({flatCoordinates:[],whens:[]},ol.format.KML.GX_TRACK_PARSERS_,node,objectStack);if(!gxTrackObject)return undefined;var flatCoordinates=gxTrackObject.flatCoordinates;var whens=gxTrackObject.whens;var i,ii;for(i=0,ii=Math.min(flatCoordinates.length,whens.length);i<ii;++i)flatCoordinates[4*i+3]=whens[i];var lineString=new ol.geom.LineString(null);lineString.setFlatCoordinates(ol.geom.GeometryLayout.XYZM,flatCoordinates);
return lineString};ol.format.KML.readIcon_=function(node,objectStack){var iconObject=ol.xml.pushParseAndPop({},ol.format.KML.ICON_PARSERS_,node,objectStack);if(iconObject)return iconObject;else return null};ol.format.KML.readFlatCoordinatesFromNode_=function(node,objectStack){return ol.xml.pushParseAndPop(null,ol.format.KML.GEOMETRY_FLAT_COORDINATES_PARSERS_,node,objectStack)};
ol.format.KML.readLineString_=function(node,objectStack){var properties=ol.xml.pushParseAndPop({},ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_,node,objectStack);var flatCoordinates=ol.format.KML.readFlatCoordinatesFromNode_(node,objectStack);if(flatCoordinates){var lineString=new ol.geom.LineString(null);lineString.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates);lineString.setProperties(properties);return lineString}else return undefined};
ol.format.KML.readLinearRing_=function(node,objectStack){var properties=ol.xml.pushParseAndPop({},ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_,node,objectStack);var flatCoordinates=ol.format.KML.readFlatCoordinatesFromNode_(node,objectStack);if(flatCoordinates){var polygon=new ol.geom.Polygon(null);polygon.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates,[flatCoordinates.length]);polygon.setProperties(properties);return polygon}else return undefined};
ol.format.KML.readMultiGeometry_=function(node,objectStack){var geometries=ol.xml.pushParseAndPop([],ol.format.KML.MULTI_GEOMETRY_PARSERS_,node,objectStack);if(!geometries)return null;if(geometries.length===0)return new ol.geom.GeometryCollection(geometries);var multiGeometry;var homogeneous=true;var type=geometries[0].getType();var geometry,i,ii;for(i=1,ii=geometries.length;i<ii;++i){geometry=geometries[i];if(geometry.getType()!=type){homogeneous=false;break}}if(homogeneous){var layout;var flatCoordinates;
if(type==ol.geom.GeometryType.POINT){var point=geometries[0];layout=point.getLayout();flatCoordinates=point.getFlatCoordinates();for(i=1,ii=geometries.length;i<ii;++i){geometry=geometries[i];ol.array.extend(flatCoordinates,geometry.getFlatCoordinates())}multiGeometry=new ol.geom.MultiPoint(null);multiGeometry.setFlatCoordinates(layout,flatCoordinates);ol.format.KML.setCommonGeometryProperties_(multiGeometry,geometries)}else if(type==ol.geom.GeometryType.LINE_STRING){multiGeometry=new ol.geom.MultiLineString(null);
multiGeometry.setLineStrings(geometries);ol.format.KML.setCommonGeometryProperties_(multiGeometry,geometries)}else if(type==ol.geom.GeometryType.POLYGON){multiGeometry=new ol.geom.MultiPolygon(null);multiGeometry.setPolygons(geometries);ol.format.KML.setCommonGeometryProperties_(multiGeometry,geometries)}else if(type==ol.geom.GeometryType.GEOMETRY_COLLECTION)multiGeometry=new ol.geom.GeometryCollection(geometries);else ol.asserts.assert(false,37)}else multiGeometry=new ol.geom.GeometryCollection(geometries);
return multiGeometry};ol.format.KML.readPoint_=function(node,objectStack){var properties=ol.xml.pushParseAndPop({},ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_,node,objectStack);var flatCoordinates=ol.format.KML.readFlatCoordinatesFromNode_(node,objectStack);if(flatCoordinates){var point=new ol.geom.Point(null);point.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates);point.setProperties(properties);return point}else return undefined};
ol.format.KML.readPolygon_=function(node,objectStack){var properties=ol.xml.pushParseAndPop({},ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_,node,objectStack);var flatLinearRings=ol.xml.pushParseAndPop([null],ol.format.KML.FLAT_LINEAR_RINGS_PARSERS_,node,objectStack);if(flatLinearRings&&flatLinearRings[0]){var polygon=new ol.geom.Polygon(null);var flatCoordinates=flatLinearRings[0];var ends=[flatCoordinates.length];var i,ii;for(i=1,ii=flatLinearRings.length;i<ii;++i){ol.array.extend(flatCoordinates,
flatLinearRings[i]);ends.push(flatCoordinates.length)}polygon.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates,ends);polygon.setProperties(properties);return polygon}else return undefined};
ol.format.KML.readStyle_=function(node,objectStack){var styleObject=ol.xml.pushParseAndPop({},ol.format.KML.STYLE_PARSERS_,node,objectStack);if(!styleObject)return null;var fillStyle="fillStyle"in styleObject?styleObject["fillStyle"]:ol.format.KML.DEFAULT_FILL_STYLE_;var fill=styleObject["fill"];if(fill!==undefined&&!fill)fillStyle=null;var imageStyle="imageStyle"in styleObject?styleObject["imageStyle"]:ol.format.KML.DEFAULT_IMAGE_STYLE_;if(imageStyle==ol.format.KML.DEFAULT_NO_IMAGE_STYLE_)imageStyle=
undefined;var textStyle="textStyle"in styleObject?styleObject["textStyle"]:ol.format.KML.DEFAULT_TEXT_STYLE_;var strokeStyle="strokeStyle"in styleObject?styleObject["strokeStyle"]:ol.format.KML.DEFAULT_STROKE_STYLE_;var outline=styleObject["outline"];if(outline!==undefined&&!outline)strokeStyle=null;return[new ol.style.Style({fill:fillStyle,image:imageStyle,stroke:strokeStyle,text:textStyle,zIndex:undefined})]};
ol.format.KML.setCommonGeometryProperties_=function(multiGeometry,geometries){var ii=geometries.length;var extrudes=new Array(geometries.length);var tessellates=new Array(geometries.length);var altitudeModes=new Array(geometries.length);var geometry,i,hasExtrude,hasTessellate,hasAltitudeMode;hasExtrude=hasTessellate=hasAltitudeMode=false;for(i=0;i<ii;++i){geometry=geometries[i];extrudes[i]=geometry.get("extrude");tessellates[i]=geometry.get("tessellate");altitudeModes[i]=geometry.get("altitudeMode");
hasExtrude=hasExtrude||extrudes[i]!==undefined;hasTessellate=hasTessellate||tessellates[i]!==undefined;hasAltitudeMode=hasAltitudeMode||altitudeModes[i]}if(hasExtrude)multiGeometry.set("extrude",extrudes);if(hasTessellate)multiGeometry.set("tessellate",tessellates);if(hasAltitudeMode)multiGeometry.set("altitudeMode",altitudeModes)};
ol.format.KML.DataParser_=function(node,objectStack){var name=node.getAttribute("name");ol.xml.parseNode(ol.format.KML.DATA_PARSERS_,node,objectStack);var featureObject=objectStack[objectStack.length-1];if(name!==null)featureObject[name]=featureObject.value;else if(featureObject.displayName!==null)featureObject[featureObject.displayName]=featureObject.value;delete featureObject["value"]};
ol.format.KML.ExtendedDataParser_=function(node,objectStack){ol.xml.parseNode(ol.format.KML.EXTENDED_DATA_PARSERS_,node,objectStack)};ol.format.KML.RegionParser_=function(node,objectStack){ol.xml.parseNode(ol.format.KML.REGION_PARSERS_,node,objectStack)};
ol.format.KML.PairDataParser_=function(node,objectStack){var pairObject=ol.xml.pushParseAndPop({},ol.format.KML.PAIR_PARSERS_,node,objectStack);if(!pairObject)return;var key=pairObject["key"];if(key&&key=="normal"){var styleUrl=pairObject["styleUrl"];if(styleUrl)objectStack[objectStack.length-1]=styleUrl;var Style=pairObject["Style"];if(Style)objectStack[objectStack.length-1]=Style}};
ol.format.KML.PlacemarkStyleMapParser_=function(node,objectStack){var styleMapValue=ol.format.KML.readStyleMapValue_(node,objectStack);if(!styleMapValue)return;var placemarkObject=objectStack[objectStack.length-1];if(Array.isArray(styleMapValue))placemarkObject["Style"]=styleMapValue;else if(typeof styleMapValue==="string")placemarkObject["styleUrl"]=styleMapValue;else ol.asserts.assert(false,38)};
ol.format.KML.SchemaDataParser_=function(node,objectStack){ol.xml.parseNode(ol.format.KML.SCHEMA_DATA_PARSERS_,node,objectStack)};ol.format.KML.SimpleDataParser_=function(node,objectStack){var name=node.getAttribute("name");if(name!==null){var data=ol.format.XSD.readString(node);var featureObject=objectStack[objectStack.length-1];featureObject[name]=data}};
ol.format.KML.LatLonAltBoxParser_=function(node,objectStack){var object=ol.xml.pushParseAndPop({},ol.format.KML.LAT_LON_ALT_BOX_PARSERS_,node,objectStack);if(!object)return;var regionObject=objectStack[objectStack.length-1];var extent=[parseFloat(object["west"]),parseFloat(object["south"]),parseFloat(object["east"]),parseFloat(object["north"])];regionObject["extent"]=extent;regionObject["altitudeMode"]=object["altitudeMode"];regionObject["minAltitude"]=parseFloat(object["minAltitude"]);regionObject["maxAltitude"]=
parseFloat(object["maxAltitude"])};ol.format.KML.LodParser_=function(node,objectStack){var object=ol.xml.pushParseAndPop({},ol.format.KML.LOD_PARSERS_,node,objectStack);if(!object)return;var lodObject=objectStack[objectStack.length-1];lodObject["minLodPixels"]=parseFloat(object["minLodPixels"]);lodObject["maxLodPixels"]=parseFloat(object["maxLodPixels"]);lodObject["minFadeExtent"]=parseFloat(object["minFadeExtent"]);lodObject["maxFadeExtent"]=parseFloat(object["maxFadeExtent"])};
ol.format.KML.innerBoundaryIsParser_=function(node,objectStack){var flatLinearRing=ol.xml.pushParseAndPop(undefined,ol.format.KML.INNER_BOUNDARY_IS_PARSERS_,node,objectStack);if(flatLinearRing){var flatLinearRings=objectStack[objectStack.length-1];flatLinearRings.push(flatLinearRing)}};
ol.format.KML.outerBoundaryIsParser_=function(node,objectStack){var flatLinearRing=ol.xml.pushParseAndPop(undefined,ol.format.KML.OUTER_BOUNDARY_IS_PARSERS_,node,objectStack);if(flatLinearRing){var flatLinearRings=objectStack[objectStack.length-1];flatLinearRings[0]=flatLinearRing}};ol.format.KML.LinkParser_=function(node,objectStack){ol.xml.parseNode(ol.format.KML.LINK_PARSERS_,node,objectStack)};
ol.format.KML.whenParser_=function(node,objectStack){var gxTrackObject=objectStack[objectStack.length-1];var whens=gxTrackObject.whens;var s=ol.xml.getAllTextContent(node,false);var when=Date.parse(s);whens.push(isNaN(when)?0:when)};ol.format.KML.DATA_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"displayName":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"value":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)});
ol.format.KML.EXTENDED_DATA_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"Data":ol.format.KML.DataParser_,"SchemaData":ol.format.KML.SchemaDataParser_});ol.format.KML.REGION_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"LatLonAltBox":ol.format.KML.LatLonAltBoxParser_,"Lod":ol.format.KML.LodParser_});
ol.format.KML.LAT_LON_ALT_BOX_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"altitudeMode":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"minAltitude":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"maxAltitude":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"north":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"south":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"east":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
"west":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal)});ol.format.KML.LOD_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"minLodPixels":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"maxLodPixels":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"minFadeExtent":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"maxFadeExtent":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal)});
ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"extrude":ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean),"tessellate":ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean),"altitudeMode":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)});ol.format.KML.FLAT_LINEAR_RING_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"coordinates":ol.xml.makeReplacer(ol.format.KML.readFlatCoordinates_)});
ol.format.KML.FLAT_LINEAR_RINGS_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"innerBoundaryIs":ol.format.KML.innerBoundaryIsParser_,"outerBoundaryIs":ol.format.KML.outerBoundaryIsParser_});ol.format.KML.GX_TRACK_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"when":ol.format.KML.whenParser_},ol.xml.makeStructureNS(ol.format.KML.GX_NAMESPACE_URIS_,{"coord":ol.format.KML.gxCoordParser_}));
ol.format.KML.GEOMETRY_FLAT_COORDINATES_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"coordinates":ol.xml.makeReplacer(ol.format.KML.readFlatCoordinates_)});
ol.format.KML.ICON_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"href":ol.xml.makeObjectPropertySetter(ol.format.KML.readURI_)},ol.xml.makeStructureNS(ol.format.KML.GX_NAMESPACE_URIS_,{"x":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"y":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"w":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"h":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal)}));
ol.format.KML.ICON_STYLE_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"Icon":ol.xml.makeObjectPropertySetter(ol.format.KML.readIcon_),"heading":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"hotSpot":ol.xml.makeObjectPropertySetter(ol.format.KML.readVec2_),"scale":ol.xml.makeObjectPropertySetter(ol.format.KML.readScale_)});ol.format.KML.INNER_BOUNDARY_IS_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"LinearRing":ol.xml.makeReplacer(ol.format.KML.readFlatLinearRing_)});
ol.format.KML.LABEL_STYLE_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"color":ol.xml.makeObjectPropertySetter(ol.format.KML.readColor_),"scale":ol.xml.makeObjectPropertySetter(ol.format.KML.readScale_)});ol.format.KML.LINE_STYLE_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"color":ol.xml.makeObjectPropertySetter(ol.format.KML.readColor_),"width":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal)});
ol.format.KML.MULTI_GEOMETRY_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"LineString":ol.xml.makeArrayPusher(ol.format.KML.readLineString_),"LinearRing":ol.xml.makeArrayPusher(ol.format.KML.readLinearRing_),"MultiGeometry":ol.xml.makeArrayPusher(ol.format.KML.readMultiGeometry_),"Point":ol.xml.makeArrayPusher(ol.format.KML.readPoint_),"Polygon":ol.xml.makeArrayPusher(ol.format.KML.readPolygon_)});
ol.format.KML.GX_MULTITRACK_GEOMETRY_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.GX_NAMESPACE_URIS_,{"Track":ol.xml.makeArrayPusher(ol.format.KML.readGxTrack_)});
ol.format.KML.NETWORK_LINK_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"ExtendedData":ol.format.KML.ExtendedDataParser_,"Region":ol.format.KML.RegionParser_,"Link":ol.format.KML.LinkParser_,"address":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"description":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"name":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"open":ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean),"phoneNumber":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
"visibility":ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean)});ol.format.KML.LINK_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"href":ol.xml.makeObjectPropertySetter(ol.format.KML.readURI_)});ol.format.KML.OUTER_BOUNDARY_IS_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"LinearRing":ol.xml.makeReplacer(ol.format.KML.readFlatLinearRing_)});
ol.format.KML.PAIR_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"Style":ol.xml.makeObjectPropertySetter(ol.format.KML.readStyle_),"key":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"styleUrl":ol.xml.makeObjectPropertySetter(ol.format.KML.readURI_)});
ol.format.KML.PLACEMARK_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"ExtendedData":ol.format.KML.ExtendedDataParser_,"Region":ol.format.KML.RegionParser_,"MultiGeometry":ol.xml.makeObjectPropertySetter(ol.format.KML.readMultiGeometry_,"geometry"),"LineString":ol.xml.makeObjectPropertySetter(ol.format.KML.readLineString_,"geometry"),"LinearRing":ol.xml.makeObjectPropertySetter(ol.format.KML.readLinearRing_,"geometry"),"Point":ol.xml.makeObjectPropertySetter(ol.format.KML.readPoint_,
"geometry"),"Polygon":ol.xml.makeObjectPropertySetter(ol.format.KML.readPolygon_,"geometry"),"Style":ol.xml.makeObjectPropertySetter(ol.format.KML.readStyle_),"StyleMap":ol.format.KML.PlacemarkStyleMapParser_,"address":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"description":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"name":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"open":ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean),"phoneNumber":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
"styleUrl":ol.xml.makeObjectPropertySetter(ol.format.KML.readURI_),"visibility":ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean)},ol.xml.makeStructureNS(ol.format.KML.GX_NAMESPACE_URIS_,{"MultiTrack":ol.xml.makeObjectPropertySetter(ol.format.KML.readGxMultiTrack_,"geometry"),"Track":ol.xml.makeObjectPropertySetter(ol.format.KML.readGxTrack_,"geometry")}));
ol.format.KML.POLY_STYLE_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"color":ol.xml.makeObjectPropertySetter(ol.format.KML.readColor_),"fill":ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean),"outline":ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean)});ol.format.KML.SCHEMA_DATA_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"SimpleData":ol.format.KML.SimpleDataParser_});
ol.format.KML.STYLE_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"IconStyle":ol.format.KML.IconStyleParser_,"LabelStyle":ol.format.KML.LabelStyleParser_,"LineStyle":ol.format.KML.LineStyleParser_,"PolyStyle":ol.format.KML.PolyStyleParser_});ol.format.KML.STYLE_MAP_PARSERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"Pair":ol.format.KML.PairDataParser_});
ol.format.KML.prototype.readDocumentOrFolder_=function(node,objectStack){var parsersNS=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"Document":ol.xml.makeArrayExtender(this.readDocumentOrFolder_,this),"Folder":ol.xml.makeArrayExtender(this.readDocumentOrFolder_,this),"Placemark":ol.xml.makeArrayPusher(this.readPlacemark_,this),"Style":this.readSharedStyle_.bind(this),"StyleMap":this.readSharedStyleMap_.bind(this)});var features=ol.xml.pushParseAndPop([],parsersNS,node,objectStack,this);if(features)return features;
else return undefined};
ol.format.KML.prototype.readPlacemark_=function(node,objectStack){var object=ol.xml.pushParseAndPop({"geometry":null},ol.format.KML.PLACEMARK_PARSERS_,node,objectStack);if(!object)return undefined;var feature=new ol.Feature;var id=node.getAttribute("id");if(id!==null)feature.setId(id);var options=objectStack[0];var geometry=object["geometry"];if(geometry)ol.format.Feature.transformWithOptions(geometry,false,options);feature.setGeometry(geometry);delete object["geometry"];if(this.extractStyles_){var style=object["Style"];
var styleUrl=object["styleUrl"];var styleFunction=ol.format.KML.createFeatureStyleFunction_(style,styleUrl,this.defaultStyle_,this.sharedStyles_,this.showPointNames_);feature.setStyle(styleFunction)}delete object["Style"];feature.setProperties(object);return feature};
ol.format.KML.prototype.readSharedStyle_=function(node,objectStack){var id=node.getAttribute("id");if(id!==null){var style=ol.format.KML.readStyle_(node,objectStack);if(style){var styleUri;var baseURI=node.baseURI;if(!baseURI||baseURI=="about:blank")baseURI=window.location.href;if(baseURI){var url=new URL("#"+id,baseURI);styleUri=url.href}else styleUri="#"+id;this.sharedStyles_[styleUri]=style}}};
ol.format.KML.prototype.readSharedStyleMap_=function(node,objectStack){var id=node.getAttribute("id");if(id===null)return;var styleMapValue=ol.format.KML.readStyleMapValue_(node,objectStack);if(!styleMapValue)return;var styleUri;var baseURI=node.baseURI;if(!baseURI||baseURI=="about:blank")baseURI=window.location.href;if(baseURI){var url=new URL("#"+id,baseURI);styleUri=url.href}else styleUri="#"+id;this.sharedStyles_[styleUri]=styleMapValue};ol.format.KML.prototype.readFeature;
ol.format.KML.prototype.readFeatureFromNode=function(node,opt_options){if(!ol.array.includes(ol.format.KML.NAMESPACE_URIS_,node.namespaceURI))return null;var feature=this.readPlacemark_(node,[this.getReadOptions(node,opt_options)]);if(feature)return feature;else return null};ol.format.KML.prototype.readFeatures;
ol.format.KML.prototype.readFeaturesFromNode=function(node,opt_options){if(!ol.array.includes(ol.format.KML.NAMESPACE_URIS_,node.namespaceURI))return[];var features;var localName=node.localName;if(localName=="Document"||localName=="Folder"){features=this.readDocumentOrFolder_(node,[this.getReadOptions(node,opt_options)]);if(features)return features;else return[]}else if(localName=="Placemark"){var feature=this.readPlacemark_(node,[this.getReadOptions(node,opt_options)]);if(feature)return[feature];
else return[]}else if(localName=="kml"){features=[];var n;for(n=node.firstElementChild;n;n=n.nextElementSibling){var fs=this.readFeaturesFromNode(n,opt_options);if(fs)ol.array.extend(features,fs)}return features}else return[]};ol.format.KML.prototype.readName=function(source){if(ol.xml.isDocument(source))return this.readNameFromDocument(source);else if(ol.xml.isNode(source))return this.readNameFromNode(source);else if(typeof source==="string"){var doc=ol.xml.parse(source);return this.readNameFromDocument(doc)}else return undefined};
ol.format.KML.prototype.readNameFromDocument=function(doc){var n;for(n=doc.firstChild;n;n=n.nextSibling)if(n.nodeType==Node.ELEMENT_NODE){var name=this.readNameFromNode(n);if(name)return name}return undefined};
ol.format.KML.prototype.readNameFromNode=function(node){var n;for(n=node.firstElementChild;n;n=n.nextElementSibling)if(ol.array.includes(ol.format.KML.NAMESPACE_URIS_,n.namespaceURI)&&n.localName=="name")return ol.format.XSD.readString(n);for(n=node.firstElementChild;n;n=n.nextElementSibling){var localName=n.localName;if(ol.array.includes(ol.format.KML.NAMESPACE_URIS_,n.namespaceURI)&&(localName=="Document"||localName=="Folder"||localName=="Placemark"||localName=="kml")){var name=this.readNameFromNode(n);
if(name)return name}}return undefined};ol.format.KML.prototype.readNetworkLinks=function(source){var networkLinks=[];if(ol.xml.isDocument(source))ol.array.extend(networkLinks,this.readNetworkLinksFromDocument(source));else if(ol.xml.isNode(source))ol.array.extend(networkLinks,this.readNetworkLinksFromNode(source));else if(typeof source==="string"){var doc=ol.xml.parse(source);ol.array.extend(networkLinks,this.readNetworkLinksFromDocument(doc))}return networkLinks};
ol.format.KML.prototype.readNetworkLinksFromDocument=function(doc){var n,networkLinks=[];for(n=doc.firstChild;n;n=n.nextSibling)if(n.nodeType==Node.ELEMENT_NODE)ol.array.extend(networkLinks,this.readNetworkLinksFromNode(n));return networkLinks};
ol.format.KML.prototype.readNetworkLinksFromNode=function(node){var n,networkLinks=[];for(n=node.firstElementChild;n;n=n.nextElementSibling)if(ol.array.includes(ol.format.KML.NAMESPACE_URIS_,n.namespaceURI)&&n.localName=="NetworkLink"){var obj=ol.xml.pushParseAndPop({},ol.format.KML.NETWORK_LINK_PARSERS_,n,[]);networkLinks.push(obj)}for(n=node.firstElementChild;n;n=n.nextElementSibling){var localName=n.localName;if(ol.array.includes(ol.format.KML.NAMESPACE_URIS_,n.namespaceURI)&&(localName=="Document"||
localName=="Folder"||localName=="kml"))ol.array.extend(networkLinks,this.readNetworkLinksFromNode(n))}return networkLinks};ol.format.KML.prototype.readRegion=function(source){var regions=[];if(ol.xml.isDocument(source))ol.array.extend(regions,this.readRegionFromDocument(source));else if(ol.xml.isNode(source))ol.array.extend(regions,this.readRegionFromNode(source));else if(typeof source==="string"){var doc=ol.xml.parse(source);ol.array.extend(regions,this.readRegionFromDocument(doc))}return regions};
ol.format.KML.prototype.readRegionFromDocument=function(doc){var n,regions=[];for(n=doc.firstChild;n;n=n.nextSibling)if(n.nodeType==Node.ELEMENT_NODE)ol.array.extend(regions,this.readRegionFromNode(n));return regions};
ol.format.KML.prototype.readRegionFromNode=function(node){var n,regions=[];for(n=node.firstElementChild;n;n=n.nextElementSibling)if(ol.array.includes(ol.format.KML.NAMESPACE_URIS_,n.namespaceURI)&&n.localName=="Region"){var obj=ol.xml.pushParseAndPop({},ol.format.KML.REGION_PARSERS_,n,[]);regions.push(obj)}for(n=node.firstElementChild;n;n=n.nextElementSibling){var localName=n.localName;if(ol.array.includes(ol.format.KML.NAMESPACE_URIS_,n.namespaceURI)&&(localName=="Document"||localName=="Folder"||
localName=="kml"))ol.array.extend(regions,this.readRegionFromNode(n))}return regions};ol.format.KML.prototype.readProjection;ol.format.KML.writeColorTextNode_=function(node,color){var rgba=ol.color.asArray(color);var opacity=rgba.length==4?rgba[3]:1;var abgr=[opacity*255,rgba[2],rgba[1],rgba[0]];var i;for(i=0;i<4;++i){var hex=parseInt(abgr[i],10).toString(16);abgr[i]=hex.length==1?"0"+hex:hex}ol.format.XSD.writeStringTextNode(node,abgr.join(""))};
ol.format.KML.writeCoordinatesTextNode_=function(node,coordinates,objectStack){var context=objectStack[objectStack.length-1];var layout=context["layout"];var stride=context["stride"];var dimension;if(layout==ol.geom.GeometryLayout.XY||layout==ol.geom.GeometryLayout.XYM)dimension=2;else if(layout==ol.geom.GeometryLayout.XYZ||layout==ol.geom.GeometryLayout.XYZM)dimension=3;else ol.asserts.assert(false,34);var d,i;var ii=coordinates.length;var text="";if(ii>0){text+=coordinates[0];for(d=1;d<dimension;++d)text+=
","+coordinates[d];for(i=stride;i<ii;i+=stride){text+=" "+coordinates[i];for(d=1;d<dimension;++d)text+=","+coordinates[i+d]}}ol.format.XSD.writeStringTextNode(node,text)};
ol.format.KML.writeDataNode_=function(node,pair,objectStack){node.setAttribute("name",pair.name);var context={node:node};var value=pair.value;if(typeof value=="object"){if(value!==null&&value.displayName)ol.xml.pushSerializeAndPop(context,ol.format.KML.EXTENDEDDATA_NODE_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,[value.displayName],objectStack,["displayName"]);if(value!==null&&value.value)ol.xml.pushSerializeAndPop(context,ol.format.KML.EXTENDEDDATA_NODE_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,
[value.value],objectStack,["value"])}else ol.xml.pushSerializeAndPop(context,ol.format.KML.EXTENDEDDATA_NODE_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,[value],objectStack,["value"])};ol.format.KML.writeDataNodeName_=function(node,name){ol.format.XSD.writeCDATASection(node,name)};ol.format.KML.writeDataNodeValue_=function(node,value){ol.format.XSD.writeStringTextNode(node,value)};
ol.format.KML.writeDocument_=function(node,features,objectStack){var context={node:node};ol.xml.pushSerializeAndPop(context,ol.format.KML.DOCUMENT_SERIALIZERS_,ol.format.KML.DOCUMENT_NODE_FACTORY_,features,objectStack,undefined,this)};
ol.format.KML.writeExtendedData_=function(node,namesAndValues,objectStack){var context={node:node};var names=namesAndValues.names,values=namesAndValues.values;var length=names.length;for(var i=0;i<length;i++)ol.xml.pushSerializeAndPop(context,ol.format.KML.EXTENDEDDATA_NODE_SERIALIZERS_,ol.format.KML.DATA_NODE_FACTORY_,[{name:names[i],value:values[i]}],objectStack)};
ol.format.KML.writeIcon_=function(node,icon,objectStack){var context={node:node};var parentNode=objectStack[objectStack.length-1].node;var orderedKeys=ol.format.KML.ICON_SEQUENCE_[parentNode.namespaceURI];var values=ol.xml.makeSequence(icon,orderedKeys);ol.xml.pushSerializeAndPop(context,ol.format.KML.ICON_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,orderedKeys);orderedKeys=ol.format.KML.ICON_SEQUENCE_[ol.format.KML.GX_NAMESPACE_URIS_[0]];values=ol.xml.makeSequence(icon,orderedKeys);
ol.xml.pushSerializeAndPop(context,ol.format.KML.ICON_SERIALIZERS_,ol.format.KML.GX_NODE_FACTORY_,values,objectStack,orderedKeys)};
ol.format.KML.writeIconStyle_=function(node,style,objectStack){var context={node:node};var properties={};var src=style.getSrc();var size=style.getSize();var iconImageSize=style.getImageSize();var iconProperties={"href":src};if(size){iconProperties["w"]=size[0];iconProperties["h"]=size[1];var anchor=style.getAnchor();var origin=style.getOrigin();if(origin&&iconImageSize&&origin[0]!==0&&origin[1]!==size[1]){iconProperties["x"]=origin[0];iconProperties["y"]=iconImageSize[1]-(origin[1]+size[1])}if(anchor&&
(anchor[0]!==size[0]/2||anchor[1]!==size[1]/2)){var hotSpot={x:anchor[0],xunits:ol.style.IconAnchorUnits.PIXELS,y:size[1]-anchor[1],yunits:ol.style.IconAnchorUnits.PIXELS};properties["hotSpot"]=hotSpot}}properties["Icon"]=iconProperties;var scale=style.getScale();if(scale!==1)properties["scale"]=scale;var rotation=style.getRotation();if(rotation!==0)properties["heading"]=rotation;var parentNode=objectStack[objectStack.length-1].node;var orderedKeys=ol.format.KML.ICON_STYLE_SEQUENCE_[parentNode.namespaceURI];
var values=ol.xml.makeSequence(properties,orderedKeys);ol.xml.pushSerializeAndPop(context,ol.format.KML.ICON_STYLE_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,orderedKeys)};
ol.format.KML.writeLabelStyle_=function(node,style,objectStack){var context={node:node};var properties={};var fill=style.getFill();if(fill)properties["color"]=fill.getColor();var scale=style.getScale();if(scale&&scale!==1)properties["scale"]=scale;var parentNode=objectStack[objectStack.length-1].node;var orderedKeys=ol.format.KML.LABEL_STYLE_SEQUENCE_[parentNode.namespaceURI];var values=ol.xml.makeSequence(properties,orderedKeys);ol.xml.pushSerializeAndPop(context,ol.format.KML.LABEL_STYLE_SERIALIZERS_,
ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,orderedKeys)};
ol.format.KML.writeLineStyle_=function(node,style,objectStack){var context={node:node};var properties={"color":style.getColor(),"width":style.getWidth()};var parentNode=objectStack[objectStack.length-1].node;var orderedKeys=ol.format.KML.LINE_STYLE_SEQUENCE_[parentNode.namespaceURI];var values=ol.xml.makeSequence(properties,orderedKeys);ol.xml.pushSerializeAndPop(context,ol.format.KML.LINE_STYLE_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,orderedKeys)};
ol.format.KML.writeMultiGeometry_=function(node,geometry,objectStack){var context={node:node};var type=geometry.getType();var geometries;var factory;if(type==ol.geom.GeometryType.GEOMETRY_COLLECTION){geometries=geometry.getGeometries();factory=ol.format.KML.GEOMETRY_NODE_FACTORY_}else if(type==ol.geom.GeometryType.MULTI_POINT){geometries=geometry.getPoints();factory=ol.format.KML.POINT_NODE_FACTORY_}else if(type==ol.geom.GeometryType.MULTI_LINE_STRING){geometries=geometry.getLineStrings();factory=
ol.format.KML.LINE_STRING_NODE_FACTORY_}else if(type==ol.geom.GeometryType.MULTI_POLYGON){geometries=geometry.getPolygons();factory=ol.format.KML.POLYGON_NODE_FACTORY_}else ol.asserts.assert(false,39);ol.xml.pushSerializeAndPop(context,ol.format.KML.MULTI_GEOMETRY_SERIALIZERS_,factory,geometries,objectStack)};
ol.format.KML.writeBoundaryIs_=function(node,linearRing,objectStack){var context={node:node};ol.xml.pushSerializeAndPop(context,ol.format.KML.BOUNDARY_IS_SERIALIZERS_,ol.format.KML.LINEAR_RING_NODE_FACTORY_,[linearRing],objectStack)};
ol.format.KML.writePlacemark_=function(node,feature,objectStack){var context={node:node};if(feature.getId())node.setAttribute("id",feature.getId());var properties=feature.getProperties();var filter={"address":1,"description":1,"name":1,"open":1,"phoneNumber":1,"styleUrl":1,"visibility":1};filter[feature.getGeometryName()]=1;var keys=Object.keys(properties||{}).sort().filter(function(v){return!filter[v]});if(keys.length>0){var sequence=ol.xml.makeSequence(properties,keys);var namesAndValues={names:keys,
values:sequence};ol.xml.pushSerializeAndPop(context,ol.format.KML.PLACEMARK_SERIALIZERS_,ol.format.KML.EXTENDEDDATA_NODE_FACTORY_,[namesAndValues],objectStack)}var styleFunction=feature.getStyleFunction();if(styleFunction){var styles=styleFunction.call(feature,0);if(styles){var style=Array.isArray(styles)?styles[0]:styles;if(this.writeStyles_)properties["Style"]=style;var textStyle=style.getText();if(textStyle)properties["name"]=textStyle.getText()}}var parentNode=objectStack[objectStack.length-1].node;
var orderedKeys=ol.format.KML.PLACEMARK_SEQUENCE_[parentNode.namespaceURI];var values=ol.xml.makeSequence(properties,orderedKeys);ol.xml.pushSerializeAndPop(context,ol.format.KML.PLACEMARK_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,orderedKeys);var options=objectStack[0];var geometry=feature.getGeometry();if(geometry)geometry=ol.format.Feature.transformWithOptions(geometry,true,options);ol.xml.pushSerializeAndPop(context,ol.format.KML.PLACEMARK_SERIALIZERS_,ol.format.KML.GEOMETRY_NODE_FACTORY_,
[geometry],objectStack)};
ol.format.KML.writePrimitiveGeometry_=function(node,geometry,objectStack){var flatCoordinates=geometry.getFlatCoordinates();var context={node:node};context["layout"]=geometry.getLayout();context["stride"]=geometry.getStride();var properties=geometry.getProperties();properties.coordinates=flatCoordinates;var parentNode=objectStack[objectStack.length-1].node;var orderedKeys=ol.format.KML.PRIMITIVE_GEOMETRY_SEQUENCE_[parentNode.namespaceURI];var values=ol.xml.makeSequence(properties,orderedKeys);ol.xml.pushSerializeAndPop(context,
ol.format.KML.PRIMITIVE_GEOMETRY_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,orderedKeys)};
ol.format.KML.writePolygon_=function(node,polygon,objectStack){var linearRings=polygon.getLinearRings();var outerRing=linearRings.shift();var context={node:node};ol.xml.pushSerializeAndPop(context,ol.format.KML.POLYGON_SERIALIZERS_,ol.format.KML.INNER_BOUNDARY_NODE_FACTORY_,linearRings,objectStack);ol.xml.pushSerializeAndPop(context,ol.format.KML.POLYGON_SERIALIZERS_,ol.format.KML.OUTER_BOUNDARY_NODE_FACTORY_,[outerRing],objectStack)};
ol.format.KML.writePolyStyle_=function(node,style,objectStack){var context={node:node};ol.xml.pushSerializeAndPop(context,ol.format.KML.POLY_STYLE_SERIALIZERS_,ol.format.KML.COLOR_NODE_FACTORY_,[style.getColor()],objectStack)};ol.format.KML.writeScaleTextNode_=function(node,scale){ol.format.XSD.writeDecimalTextNode(node,Math.round(scale*1E6)/1E6)};
ol.format.KML.writeStyle_=function(node,style,objectStack){var context={node:node};var properties={};var fillStyle=style.getFill();var strokeStyle=style.getStroke();var imageStyle=style.getImage();var textStyle=style.getText();if(imageStyle instanceof ol.style.Icon)properties["IconStyle"]=imageStyle;if(textStyle)properties["LabelStyle"]=textStyle;if(strokeStyle)properties["LineStyle"]=strokeStyle;if(fillStyle)properties["PolyStyle"]=fillStyle;var parentNode=objectStack[objectStack.length-1].node;
var orderedKeys=ol.format.KML.STYLE_SEQUENCE_[parentNode.namespaceURI];var values=ol.xml.makeSequence(properties,orderedKeys);ol.xml.pushSerializeAndPop(context,ol.format.KML.STYLE_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,orderedKeys)};ol.format.KML.writeVec2_=function(node,vec2){node.setAttribute("x",vec2.x);node.setAttribute("y",vec2.y);node.setAttribute("xunits",vec2.xunits);node.setAttribute("yunits",vec2.yunits)};
ol.format.KML.KML_SEQUENCE_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,["Document","Placemark"]);ol.format.KML.KML_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"Document":ol.xml.makeChildAppender(ol.format.KML.writeDocument_),"Placemark":ol.xml.makeChildAppender(ol.format.KML.writePlacemark_)});ol.format.KML.DOCUMENT_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"Placemark":ol.xml.makeChildAppender(ol.format.KML.writePlacemark_)});
ol.format.KML.EXTENDEDDATA_NODE_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"Data":ol.xml.makeChildAppender(ol.format.KML.writeDataNode_),"value":ol.xml.makeChildAppender(ol.format.KML.writeDataNodeValue_),"displayName":ol.xml.makeChildAppender(ol.format.KML.writeDataNodeName_)});
ol.format.KML.GEOMETRY_TYPE_TO_NODENAME_={"Point":"Point","LineString":"LineString","LinearRing":"LinearRing","Polygon":"Polygon","MultiPoint":"MultiGeometry","MultiLineString":"MultiGeometry","MultiPolygon":"MultiGeometry","GeometryCollection":"MultiGeometry"};ol.format.KML.ICON_SEQUENCE_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,["href"],ol.xml.makeStructureNS(ol.format.KML.GX_NAMESPACE_URIS_,["x","y","w","h"]));
ol.format.KML.ICON_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"href":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)},ol.xml.makeStructureNS(ol.format.KML.GX_NAMESPACE_URIS_,{"x":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),"y":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),"w":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),"h":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode)}));
ol.format.KML.ICON_STYLE_SEQUENCE_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,["scale","heading","Icon","hotSpot"]);ol.format.KML.ICON_STYLE_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"Icon":ol.xml.makeChildAppender(ol.format.KML.writeIcon_),"heading":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),"hotSpot":ol.xml.makeChildAppender(ol.format.KML.writeVec2_),"scale":ol.xml.makeChildAppender(ol.format.KML.writeScaleTextNode_)});
ol.format.KML.LABEL_STYLE_SEQUENCE_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,["color","scale"]);ol.format.KML.LABEL_STYLE_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"color":ol.xml.makeChildAppender(ol.format.KML.writeColorTextNode_),"scale":ol.xml.makeChildAppender(ol.format.KML.writeScaleTextNode_)});ol.format.KML.LINE_STYLE_SEQUENCE_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,["color","width"]);
ol.format.KML.LINE_STYLE_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"color":ol.xml.makeChildAppender(ol.format.KML.writeColorTextNode_),"width":ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode)});ol.format.KML.BOUNDARY_IS_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"LinearRing":ol.xml.makeChildAppender(ol.format.KML.writePrimitiveGeometry_)});
ol.format.KML.MULTI_GEOMETRY_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"LineString":ol.xml.makeChildAppender(ol.format.KML.writePrimitiveGeometry_),"Point":ol.xml.makeChildAppender(ol.format.KML.writePrimitiveGeometry_),"Polygon":ol.xml.makeChildAppender(ol.format.KML.writePolygon_),"GeometryCollection":ol.xml.makeChildAppender(ol.format.KML.writeMultiGeometry_)});
ol.format.KML.PLACEMARK_SEQUENCE_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,["name","open","visibility","address","phoneNumber","description","styleUrl","Style"]);
ol.format.KML.PLACEMARK_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"ExtendedData":ol.xml.makeChildAppender(ol.format.KML.writeExtendedData_),"MultiGeometry":ol.xml.makeChildAppender(ol.format.KML.writeMultiGeometry_),"LineString":ol.xml.makeChildAppender(ol.format.KML.writePrimitiveGeometry_),"LinearRing":ol.xml.makeChildAppender(ol.format.KML.writePrimitiveGeometry_),"Point":ol.xml.makeChildAppender(ol.format.KML.writePrimitiveGeometry_),"Polygon":ol.xml.makeChildAppender(ol.format.KML.writePolygon_),
"Style":ol.xml.makeChildAppender(ol.format.KML.writeStyle_),"address":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"description":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"name":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"open":ol.xml.makeChildAppender(ol.format.XSD.writeBooleanTextNode),"phoneNumber":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"styleUrl":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"visibility":ol.xml.makeChildAppender(ol.format.XSD.writeBooleanTextNode)});
ol.format.KML.PRIMITIVE_GEOMETRY_SEQUENCE_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,["extrude","tessellate","altitudeMode","coordinates"]);ol.format.KML.PRIMITIVE_GEOMETRY_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"extrude":ol.xml.makeChildAppender(ol.format.XSD.writeBooleanTextNode),"tessellate":ol.xml.makeChildAppender(ol.format.XSD.writeBooleanTextNode),"altitudeMode":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"coordinates":ol.xml.makeChildAppender(ol.format.KML.writeCoordinatesTextNode_)});
ol.format.KML.POLYGON_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"outerBoundaryIs":ol.xml.makeChildAppender(ol.format.KML.writeBoundaryIs_),"innerBoundaryIs":ol.xml.makeChildAppender(ol.format.KML.writeBoundaryIs_)});ol.format.KML.POLY_STYLE_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"color":ol.xml.makeChildAppender(ol.format.KML.writeColorTextNode_)});
ol.format.KML.STYLE_SEQUENCE_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,["IconStyle","LabelStyle","LineStyle","PolyStyle"]);ol.format.KML.STYLE_SERIALIZERS_=ol.xml.makeStructureNS(ol.format.KML.NAMESPACE_URIS_,{"IconStyle":ol.xml.makeChildAppender(ol.format.KML.writeIconStyle_),"LabelStyle":ol.xml.makeChildAppender(ol.format.KML.writeLabelStyle_),"LineStyle":ol.xml.makeChildAppender(ol.format.KML.writeLineStyle_),"PolyStyle":ol.xml.makeChildAppender(ol.format.KML.writePolyStyle_)});
ol.format.KML.GX_NODE_FACTORY_=function(value,objectStack,opt_nodeName){return ol.xml.createElementNS(ol.format.KML.GX_NAMESPACE_URIS_[0],"gx:"+opt_nodeName)};ol.format.KML.DOCUMENT_NODE_FACTORY_=function(value,objectStack,opt_nodeName){var parentNode=objectStack[objectStack.length-1].node;return ol.xml.createElementNS(parentNode.namespaceURI,"Placemark")};
ol.format.KML.GEOMETRY_NODE_FACTORY_=function(value,objectStack,opt_nodeName){if(value){var parentNode=objectStack[objectStack.length-1].node;return ol.xml.createElementNS(parentNode.namespaceURI,ol.format.KML.GEOMETRY_TYPE_TO_NODENAME_[value.getType()])}};ol.format.KML.COLOR_NODE_FACTORY_=ol.xml.makeSimpleNodeFactory("color");ol.format.KML.DATA_NODE_FACTORY_=ol.xml.makeSimpleNodeFactory("Data");ol.format.KML.EXTENDEDDATA_NODE_FACTORY_=ol.xml.makeSimpleNodeFactory("ExtendedData");
ol.format.KML.INNER_BOUNDARY_NODE_FACTORY_=ol.xml.makeSimpleNodeFactory("innerBoundaryIs");ol.format.KML.POINT_NODE_FACTORY_=ol.xml.makeSimpleNodeFactory("Point");ol.format.KML.LINE_STRING_NODE_FACTORY_=ol.xml.makeSimpleNodeFactory("LineString");ol.format.KML.LINEAR_RING_NODE_FACTORY_=ol.xml.makeSimpleNodeFactory("LinearRing");ol.format.KML.POLYGON_NODE_FACTORY_=ol.xml.makeSimpleNodeFactory("Polygon");ol.format.KML.OUTER_BOUNDARY_NODE_FACTORY_=ol.xml.makeSimpleNodeFactory("outerBoundaryIs");ol.format.KML.prototype.writeFeatures;
ol.format.KML.prototype.writeFeaturesNode=function(features,opt_options){opt_options=this.adaptOptions(opt_options);var kml=ol.xml.createElementNS(ol.format.KML.NAMESPACE_URIS_[4],"kml");var xmlnsUri="http://www.w3.org/2000/xmlns/";var xmlSchemaInstanceUri="http://www.w3.org/2001/XMLSchema-instance";ol.xml.setAttributeNS(kml,xmlnsUri,"xmlns:gx",ol.format.KML.GX_NAMESPACE_URIS_[0]);ol.xml.setAttributeNS(kml,xmlnsUri,"xmlns:xsi",xmlSchemaInstanceUri);ol.xml.setAttributeNS(kml,xmlSchemaInstanceUri,"xsi:schemaLocation",
ol.format.KML.SCHEMA_LOCATION_);var context={node:kml};var properties={};if(features.length>1)properties["Document"]=features;else if(features.length==1)properties["Placemark"]=features[0];var orderedKeys=ol.format.KML.KML_SEQUENCE_[kml.namespaceURI];var values=ol.xml.makeSequence(properties,orderedKeys);ol.xml.pushSerializeAndPop(context,ol.format.KML.KML_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,[opt_options],orderedKeys,this);return kml};goog.provide("ol.ext.PBF");ol.ext.PBF=function(){};
(function(){(function(exports){var read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0)e=1-eBias;else if(e===eMax)return m?NaN:(s?-1:1)*Infinity;else{m=m+Math.pow(2,
mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};var write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1)value+=
rt/c;else value+=rt*Math.pow(2,1-eBias);if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128};var ieee754={read:read,write:write};var pbf=Pbf;function Pbf(buf){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(buf)?buf:new Uint8Array(buf||
0);this.pos=0;this.type=0;this.length=this.buf.length}Pbf.Varint=0;Pbf.Fixed64=1;Pbf.Bytes=2;Pbf.Fixed32=5;var SHIFT_LEFT_32=(1<<16)*(1<<16);var SHIFT_RIGHT_32=1/SHIFT_LEFT_32;Pbf.prototype={destroy:function(){this.buf=null},readFields:function(readField,result,end){end=end||this.length;while(this.pos<end){var val=this.readVarint(),tag=val>>3,startPos=this.pos;this.type=val&7;readField(tag,result,this);if(this.pos===startPos)this.skip(val)}return result},readMessage:function(readField,result){return this.readFields(readField,
result,this.readVarint()+this.pos)},readFixed32:function(){var val=readUInt32(this.buf,this.pos);this.pos+=4;return val},readSFixed32:function(){var val=readInt32(this.buf,this.pos);this.pos+=4;return val},readFixed64:function(){var val=readUInt32(this.buf,this.pos)+readUInt32(this.buf,this.pos+4)*SHIFT_LEFT_32;this.pos+=8;return val},readSFixed64:function(){var val=readUInt32(this.buf,this.pos)+readInt32(this.buf,this.pos+4)*SHIFT_LEFT_32;this.pos+=8;return val},readFloat:function(){var val=ieee754.read(this.buf,
this.pos,true,23,4);this.pos+=4;return val},readDouble:function(){var val=ieee754.read(this.buf,this.pos,true,52,8);this.pos+=8;return val},readVarint:function(isSigned){var buf=this.buf,val,b;b=buf[this.pos++];val=b&127;if(b<128)return val;b=buf[this.pos++];val|=(b&127)<<7;if(b<128)return val;b=buf[this.pos++];val|=(b&127)<<14;if(b<128)return val;b=buf[this.pos++];val|=(b&127)<<21;if(b<128)return val;b=buf[this.pos];val|=(b&15)<<28;return readVarintRemainder(val,isSigned,this)},readVarint64:function(){return this.readVarint(true)},
readSVarint:function(){var num=this.readVarint();return num%2===1?(num+1)/-2:num/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var end=this.readVarint()+this.pos,str=readUtf8(this.buf,this.pos,end);this.pos=end;return str},readBytes:function(){var end=this.readVarint()+this.pos,buffer=this.buf.subarray(this.pos,end);this.pos=end;return buffer},readPackedVarint:function(arr,isSigned){var end=readPackedEnd(this);arr=arr||[];while(this.pos<end)arr.push(this.readVarint(isSigned));
return arr},readPackedSVarint:function(arr){var end=readPackedEnd(this);arr=arr||[];while(this.pos<end)arr.push(this.readSVarint());return arr},readPackedBoolean:function(arr){var end=readPackedEnd(this);arr=arr||[];while(this.pos<end)arr.push(this.readBoolean());return arr},readPackedFloat:function(arr){var end=readPackedEnd(this);arr=arr||[];while(this.pos<end)arr.push(this.readFloat());return arr},readPackedDouble:function(arr){var end=readPackedEnd(this);arr=arr||[];while(this.pos<end)arr.push(this.readDouble());
return arr},readPackedFixed32:function(arr){var end=readPackedEnd(this);arr=arr||[];while(this.pos<end)arr.push(this.readFixed32());return arr},readPackedSFixed32:function(arr){var end=readPackedEnd(this);arr=arr||[];while(this.pos<end)arr.push(this.readSFixed32());return arr},readPackedFixed64:function(arr){var end=readPackedEnd(this);arr=arr||[];while(this.pos<end)arr.push(this.readFixed64());return arr},readPackedSFixed64:function(arr){var end=readPackedEnd(this);arr=arr||[];while(this.pos<end)arr.push(this.readSFixed64());
return arr},skip:function(val){var type=val&7;if(type===Pbf.Varint)while(this.buf[this.pos++]>127);else if(type===Pbf.Bytes)this.pos=this.readVarint()+this.pos;else if(type===Pbf.Fixed32)this.pos+=4;else if(type===Pbf.Fixed64)this.pos+=8;else throw new Error("Unimplemented type: "+type);},writeTag:function(tag,type){this.writeVarint(tag<<3|type)},realloc:function(min){var length=this.length||16;while(length<this.pos+min)length*=2;if(length!==this.length){var buf=new Uint8Array(length);buf.set(this.buf);
this.buf=buf;this.length=length}},finish:function(){this.length=this.pos;this.pos=0;return this.buf.subarray(0,this.length)},writeFixed32:function(val){this.realloc(4);writeInt32(this.buf,val,this.pos);this.pos+=4},writeSFixed32:function(val){this.realloc(4);writeInt32(this.buf,val,this.pos);this.pos+=4},writeFixed64:function(val){this.realloc(8);writeInt32(this.buf,val&-1,this.pos);writeInt32(this.buf,Math.floor(val*SHIFT_RIGHT_32),this.pos+4);this.pos+=8},writeSFixed64:function(val){this.realloc(8);
writeInt32(this.buf,val&-1,this.pos);writeInt32(this.buf,Math.floor(val*SHIFT_RIGHT_32),this.pos+4);this.pos+=8},writeVarint:function(val){val=+val||0;if(val>268435455||val<0){writeBigVarint(val,this);return}this.realloc(4);this.buf[this.pos++]=val&127|(val>127?128:0);if(val<=127)return;this.buf[this.pos++]=(val>>>=7)&127|(val>127?128:0);if(val<=127)return;this.buf[this.pos++]=(val>>>=7)&127|(val>127?128:0);if(val<=127)return;this.buf[this.pos++]=val>>>7&127},writeSVarint:function(val){this.writeVarint(val<
0?-val*2-1:val*2)},writeBoolean:function(val){this.writeVarint(Boolean(val))},writeString:function(str){str=String(str);this.realloc(str.length*4);this.pos++;var startPos=this.pos;this.pos=writeUtf8(this.buf,str,this.pos);var len=this.pos-startPos;if(len>=128)makeRoomForExtraLength(startPos,len,this);this.pos=startPos-1;this.writeVarint(len);this.pos+=len},writeFloat:function(val){this.realloc(4);ieee754.write(this.buf,val,this.pos,true,23,4);this.pos+=4},writeDouble:function(val){this.realloc(8);
ieee754.write(this.buf,val,this.pos,true,52,8);this.pos+=8},writeBytes:function(buffer){var len=buffer.length;this.writeVarint(len);this.realloc(len);for(var i=0;i<len;i++)this.buf[this.pos++]=buffer[i]},writeRawMessage:function(fn,obj){this.pos++;var startPos=this.pos;fn(obj,this);var len=this.pos-startPos;if(len>=128)makeRoomForExtraLength(startPos,len,this);this.pos=startPos-1;this.writeVarint(len);this.pos+=len},writeMessage:function(tag,fn,obj){this.writeTag(tag,Pbf.Bytes);this.writeRawMessage(fn,
obj)},writePackedVarint:function(tag,arr){this.writeMessage(tag,writePackedVarint,arr)},writePackedSVarint:function(tag,arr){this.writeMessage(tag,writePackedSVarint,arr)},writePackedBoolean:function(tag,arr){this.writeMessage(tag,writePackedBoolean,arr)},writePackedFloat:function(tag,arr){this.writeMessage(tag,writePackedFloat,arr)},writePackedDouble:function(tag,arr){this.writeMessage(tag,writePackedDouble,arr)},writePackedFixed32:function(tag,arr){this.writeMessage(tag,writePackedFixed32,arr)},
writePackedSFixed32:function(tag,arr){this.writeMessage(tag,writePackedSFixed32,arr)},writePackedFixed64:function(tag,arr){this.writeMessage(tag,writePackedFixed64,arr)},writePackedSFixed64:function(tag,arr){this.writeMessage(tag,writePackedSFixed64,arr)},writeBytesField:function(tag,buffer){this.writeTag(tag,Pbf.Bytes);this.writeBytes(buffer)},writeFixed32Field:function(tag,val){this.writeTag(tag,Pbf.Fixed32);this.writeFixed32(val)},writeSFixed32Field:function(tag,val){this.writeTag(tag,Pbf.Fixed32);
this.writeSFixed32(val)},writeFixed64Field:function(tag,val){this.writeTag(tag,Pbf.Fixed64);this.writeFixed64(val)},writeSFixed64Field:function(tag,val){this.writeTag(tag,Pbf.Fixed64);this.writeSFixed64(val)},writeVarintField:function(tag,val){this.writeTag(tag,Pbf.Varint);this.writeVarint(val)},writeSVarintField:function(tag,val){this.writeTag(tag,Pbf.Varint);this.writeSVarint(val)},writeStringField:function(tag,str){this.writeTag(tag,Pbf.Bytes);this.writeString(str)},writeFloatField:function(tag,
val){this.writeTag(tag,Pbf.Fixed32);this.writeFloat(val)},writeDoubleField:function(tag,val){this.writeTag(tag,Pbf.Fixed64);this.writeDouble(val)},writeBooleanField:function(tag,val){this.writeVarintField(tag,Boolean(val))}};function readVarintRemainder(l,s,p){var buf=p.buf,h,b;b=buf[p.pos++];h=(b&112)>>4;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&127)<<3;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&127)<<10;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&127)<<17;if(b<128)return toNum(l,
h,s);b=buf[p.pos++];h|=(b&127)<<24;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&1)<<31;if(b<128)return toNum(l,h,s);throw new Error("Expected varint not more than 10 bytes");}function readPackedEnd(pbf){return pbf.type===Pbf.Bytes?pbf.readVarint()+pbf.pos:pbf.pos+1}function toNum(low,high,isSigned){if(isSigned)return high*4294967296+(low>>>0);return(high>>>0)*4294967296+(low>>>0)}function writeBigVarint(val,pbf){var low,high;if(val>=0){low=val%4294967296|0;high=val/4294967296|0}else{low=~(-val%
4294967296);high=~(-val/4294967296);if(low^4294967295)low=low+1|0;else{low=0;high=high+1|0}}if(val>=1.8446744073709552E19||val<-1.8446744073709552E19)throw new Error("Given varint doesn't fit into 10 bytes");pbf.realloc(10);writeBigVarintLow(low,high,pbf);writeBigVarintHigh(high,pbf)}function writeBigVarintLow(low,high,pbf){pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos]=
low&127}function writeBigVarintHigh(high,pbf){var lsb=(high&7)<<4;pbf.buf[pbf.pos++]|=lsb|((high>>>=3)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127}function makeRoomForExtraLength(startPos,len,pbf){var extraLen=len<=16383?1:len<=2097151?2:
len<=268435455?3:Math.ceil(Math.log(len)/(Math.LN2*7));pbf.realloc(extraLen);for(var i=pbf.pos-1;i>=startPos;i--)pbf.buf[i+extraLen]=pbf.buf[i]}function writePackedVarint(arr,pbf){for(var i=0;i<arr.length;i++)pbf.writeVarint(arr[i])}function writePackedSVarint(arr,pbf){for(var i=0;i<arr.length;i++)pbf.writeSVarint(arr[i])}function writePackedFloat(arr,pbf){for(var i=0;i<arr.length;i++)pbf.writeFloat(arr[i])}function writePackedDouble(arr,pbf){for(var i=0;i<arr.length;i++)pbf.writeDouble(arr[i])}function writePackedBoolean(arr,
pbf){for(var i=0;i<arr.length;i++)pbf.writeBoolean(arr[i])}function writePackedFixed32(arr,pbf){for(var i=0;i<arr.length;i++)pbf.writeFixed32(arr[i])}function writePackedSFixed32(arr,pbf){for(var i=0;i<arr.length;i++)pbf.writeSFixed32(arr[i])}function writePackedFixed64(arr,pbf){for(var i=0;i<arr.length;i++)pbf.writeFixed64(arr[i])}function writePackedSFixed64(arr,pbf){for(var i=0;i<arr.length;i++)pbf.writeSFixed64(arr[i])}function readUInt32(buf,pos){return(buf[pos]|buf[pos+1]<<8|buf[pos+2]<<16)+
buf[pos+3]*16777216}function writeInt32(buf,val,pos){buf[pos]=val;buf[pos+1]=val>>>8;buf[pos+2]=val>>>16;buf[pos+3]=val>>>24}function readInt32(buf,pos){return(buf[pos]|buf[pos+1]<<8|buf[pos+2]<<16)+(buf[pos+3]<<24)}function readUtf8(buf,pos,end){var str="";var i=pos;while(i<end){var b0=buf[i];var c=null;var bytesPerSequence=b0>239?4:b0>223?3:b0>191?2:1;if(i+bytesPerSequence>end)break;var b1,b2,b3;if(bytesPerSequence===1){if(b0<128)c=b0}else if(bytesPerSequence===2){b1=buf[i+1];if((b1&192)===128){c=
(b0&31)<<6|b1&63;if(c<=127)c=null}}else if(bytesPerSequence===3){b1=buf[i+1];b2=buf[i+2];if((b1&192)===128&&(b2&192)===128){c=(b0&15)<<12|(b1&63)<<6|b2&63;if(c<=2047||c>=55296&&c<=57343)c=null}}else if(bytesPerSequence===4){b1=buf[i+1];b2=buf[i+2];b3=buf[i+3];if((b1&192)===128&&(b2&192)===128&&(b3&192)===128){c=(b0&15)<<18|(b1&63)<<12|(b2&63)<<6|b3&63;if(c<=65535||c>=1114112)c=null}}if(c===null){c=65533;bytesPerSequence=1}else if(c>65535){c-=65536;str+=String.fromCharCode(c>>>10&1023|55296);c=56320|
c&1023}str+=String.fromCharCode(c);i+=bytesPerSequence}return str}function writeUtf8(buf,str,pos){for(var i=0,c,lead;i<str.length;i++){c=str.charCodeAt(i);if(c>55295&&c<57344)if(lead)if(c<56320){buf[pos++]=239;buf[pos++]=191;buf[pos++]=189;lead=c;continue}else{c=lead-55296<<10|c-56320|65536;lead=null}else{if(c>56319||i+1===str.length){buf[pos++]=239;buf[pos++]=191;buf[pos++]=189}else lead=c;continue}else if(lead){buf[pos++]=239;buf[pos++]=191;buf[pos++]=189;lead=null}if(c<128)buf[pos++]=c;else{if(c<
2048)buf[pos++]=c>>6|192;else{if(c<65536)buf[pos++]=c>>12|224;else{buf[pos++]=c>>18|240;buf[pos++]=c>>12&63|128}buf[pos++]=c>>6&63|128}buf[pos++]=c&63|128}}return pos}exports["default"]=pbf})(this.PBF=this.PBF||{})}).call(ol.ext);ol.ext.PBF=ol.ext.PBF.default;goog.provide("ol.render.Feature");goog.require("ol");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.geom.GeometryType");goog.require("ol.geom.flat.center");goog.require("ol.geom.flat.interiorpoint");goog.require("ol.geom.flat.interpolate");goog.require("ol.geom.flat.transform");goog.require("ol.transform");
ol.render.Feature=function(type,flatCoordinates,ends,properties,id){this.extent_;this.id_=id;this.type_=type;this.flatCoordinates_=flatCoordinates;this.flatInteriorPoints_=null;this.flatMidpoints_=null;this.ends_=ends;this.properties_=properties;this.tmpTransform_=ol.transform.create()};ol.render.Feature.prototype.get=function(key){return this.properties_[key]};ol.render.Feature.prototype.getEnds=ol.render.Feature.prototype.getEndss=function(){return this.ends_};
ol.render.Feature.prototype.getExtent=function(){if(!this.extent_)this.extent_=this.type_===ol.geom.GeometryType.POINT?ol.extent.createOrUpdateFromCoordinate(this.flatCoordinates_):ol.extent.createOrUpdateFromFlatCoordinates(this.flatCoordinates_,0,this.flatCoordinates_.length,2);return this.extent_};
ol.render.Feature.prototype.getFlatInteriorPoint=function(){if(!this.flatInteriorPoints_){var flatCenter=ol.extent.getCenter(this.getExtent());this.flatInteriorPoints_=ol.geom.flat.interiorpoint.linearRings(this.flatCoordinates_,0,this.ends_,2,flatCenter,0)}return this.flatInteriorPoints_};
ol.render.Feature.prototype.getFlatInteriorPoints=function(){if(!this.flatInteriorPoints_){var flatCenters=ol.geom.flat.center.linearRingss(this.flatCoordinates_,0,this.ends_,2);this.flatInteriorPoints_=ol.geom.flat.interiorpoint.linearRingss(this.flatCoordinates_,0,this.ends_,2,flatCenters)}return this.flatInteriorPoints_};
ol.render.Feature.prototype.getFlatMidpoint=function(){if(!this.flatMidpoints_)this.flatMidpoints_=ol.geom.flat.interpolate.lineString(this.flatCoordinates_,0,this.flatCoordinates_.length,2,.5);return this.flatMidpoints_};
ol.render.Feature.prototype.getFlatMidpoints=function(){if(!this.flatMidpoints_){this.flatMidpoints_=[];var flatCoordinates=this.flatCoordinates_;var offset=0;var ends=this.ends_;for(var i=0,ii=ends.length;i<ii;++i){var end=ends[i];var midpoint=ol.geom.flat.interpolate.lineString(flatCoordinates,offset,end,2,.5);ol.array.extend(this.flatMidpoints_,midpoint);offset=end}}return this.flatMidpoints_};ol.render.Feature.prototype.getId=function(){return this.id_};
ol.render.Feature.prototype.getOrientedFlatCoordinates=function(){return this.flatCoordinates_};ol.render.Feature.prototype.getFlatCoordinates=ol.render.Feature.prototype.getOrientedFlatCoordinates;ol.render.Feature.prototype.getGeometry=function(){return this};ol.render.Feature.prototype.getProperties=function(){return this.properties_};ol.render.Feature.prototype.getSimplifiedGeometry=ol.render.Feature.prototype.getGeometry;ol.render.Feature.prototype.getStride=function(){return 2};
ol.render.Feature.prototype.getStyleFunction=ol.nullFunction;ol.render.Feature.prototype.getType=function(){return this.type_};
ol.render.Feature.prototype.transform=function(source,destination){var pixelExtent=source.getExtent();var projectedExtent=source.getWorldExtent();var scale=ol.extent.getHeight(projectedExtent)/ol.extent.getHeight(pixelExtent);var transform=this.tmpTransform_;ol.transform.compose(transform,projectedExtent[0],projectedExtent[3],scale,-scale,0,0,0);ol.geom.flat.transform.transform2D(this.flatCoordinates_,0,this.flatCoordinates_.length,2,transform,this.flatCoordinates_)};goog.provide("ol.format.MVT");goog.require("ol");goog.require("ol.asserts");goog.require("ol.ext.PBF");goog.require("ol.format.Feature");goog.require("ol.format.FormatType");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.GeometryType");goog.require("ol.geom.LineString");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.MultiPoint");goog.require("ol.geom.MultiPolygon");goog.require("ol.geom.Point");goog.require("ol.geom.Polygon");goog.require("ol.geom.flat.orient");goog.require("ol.proj.Projection");
goog.require("ol.proj.Units");goog.require("ol.render.Feature");
ol.format.MVT=function(opt_options){ol.format.Feature.call(this);var options=opt_options?opt_options:{};this.defaultDataProjection=new ol.proj.Projection({code:"EPSG:3857",units:ol.proj.Units.TILE_PIXELS});this.featureClass_=options.featureClass?options.featureClass:ol.render.Feature;this.geometryName_=options.geometryName;this.layerName_=options.layerName?options.layerName:"layer";this.layers_=options.layers?options.layers:null;this.extent_=null};ol.inherits(ol.format.MVT,ol.format.Feature);
ol.format.MVT.pbfReaders_={layers:function(tag,layers,pbf){if(tag===3){var layer={keys:[],values:[],features:[]};var end=pbf.readVarint()+pbf.pos;pbf.readFields(ol.format.MVT.pbfReaders_.layer,layer,end);layer.length=layer.features.length;if(layer.length)layers[layer.name]=layer}},layer:function(tag,layer,pbf){if(tag===15)layer.version=pbf.readVarint();else if(tag===1)layer.name=pbf.readString();else if(tag===5)layer.extent=pbf.readVarint();else if(tag===2)layer.features.push(pbf.pos);else if(tag===
3)layer.keys.push(pbf.readString());else if(tag===4){var value=null;var end=pbf.readVarint()+pbf.pos;while(pbf.pos<end){tag=pbf.readVarint()>>3;value=tag===1?pbf.readString():tag===2?pbf.readFloat():tag===3?pbf.readDouble():tag===4?pbf.readVarint64():tag===5?pbf.readVarint():tag===6?pbf.readSVarint():tag===7?pbf.readBoolean():null}layer.values.push(value)}},feature:function(tag,feature,pbf){if(tag==1)feature.id=pbf.readVarint();else if(tag==2){var end=pbf.readVarint()+pbf.pos;while(pbf.pos<end){var key=
feature.layer.keys[pbf.readVarint()];var value=feature.layer.values[pbf.readVarint()];feature.properties[key]=value}}else if(tag==3)feature.type=pbf.readVarint();else if(tag==4)feature.geometry=pbf.pos}};ol.format.MVT.readRawFeature_=function(pbf,layer,i){pbf.pos=layer.features[i];var end=pbf.readVarint()+pbf.pos;var feature={layer:layer,type:0,properties:{}};pbf.readFields(ol.format.MVT.pbfReaders_.feature,feature,end);return feature};
ol.format.MVT.readRawGeometry_=function(pbf,feature,flatCoordinates,ends){pbf.pos=feature.geometry;var end=pbf.readVarint()+pbf.pos;var cmd=1;var length=0;var x=0;var y=0;var coordsLen=0;var currentEnd=0;while(pbf.pos<end){if(!length){var cmdLen=pbf.readVarint();cmd=cmdLen&7;length=cmdLen>>3}length--;if(cmd===1||cmd===2){x+=pbf.readSVarint();y+=pbf.readSVarint();if(cmd===1)if(coordsLen>currentEnd){ends.push(coordsLen);currentEnd=coordsLen}flatCoordinates.push(x,y);coordsLen+=2}else if(cmd===7){if(coordsLen>
currentEnd){flatCoordinates.push(flatCoordinates[currentEnd],flatCoordinates[currentEnd+1]);coordsLen+=2}}else ol.asserts.assert(false,59)}if(coordsLen>currentEnd){ends.push(coordsLen);currentEnd=coordsLen}};
ol.format.MVT.getGeometryType_=function(type,numEnds){var geometryType;if(type===1)geometryType=numEnds===1?ol.geom.GeometryType.POINT:ol.geom.GeometryType.MULTI_POINT;else if(type===2)geometryType=numEnds===1?ol.geom.GeometryType.LINE_STRING:ol.geom.GeometryType.MULTI_LINE_STRING;else if(type===3)geometryType=ol.geom.GeometryType.POLYGON;return geometryType};
ol.format.MVT.prototype.createFeature_=function(pbf,rawFeature,opt_options){var type=rawFeature.type;if(type===0)return null;var feature;var id=rawFeature.id;var values=rawFeature.properties;values[this.layerName_]=rawFeature.layer.name;var flatCoordinates=[];var ends=[];ol.format.MVT.readRawGeometry_(pbf,rawFeature,flatCoordinates,ends);var geometryType=ol.format.MVT.getGeometryType_(type,ends.length);if(this.featureClass_===ol.render.Feature)feature=new this.featureClass_(geometryType,flatCoordinates,
ends,values,id);else{var geom;if(geometryType==ol.geom.GeometryType.POLYGON){var endss=[];var offset=0;var prevEndIndex=0;for(var i=0,ii=ends.length;i<ii;++i){var end=ends[i];if(!ol.geom.flat.orient.linearRingIsClockwise(flatCoordinates,offset,end,2)){endss.push(ends.slice(prevEndIndex,i));prevEndIndex=i}offset=end}if(endss.length>1){ends=endss;geom=new ol.geom.MultiPolygon(null)}else geom=new ol.geom.Polygon(null)}else geom=geometryType===ol.geom.GeometryType.POINT?new ol.geom.Point(null):geometryType===
ol.geom.GeometryType.LINE_STRING?new ol.geom.LineString(null):geometryType===ol.geom.GeometryType.POLYGON?new ol.geom.Polygon(null):geometryType===ol.geom.GeometryType.MULTI_POINT?new ol.geom.MultiPoint(null):geometryType===ol.geom.GeometryType.MULTI_LINE_STRING?new ol.geom.MultiLineString(null):null;geom.setFlatCoordinates(ol.geom.GeometryLayout.XY,flatCoordinates,ends);feature=new this.featureClass_;if(this.geometryName_)feature.setGeometryName(this.geometryName_);var geometry=ol.format.Feature.transformWithOptions(geom,
false,this.adaptOptions(opt_options));feature.setGeometry(geometry);feature.setId(id);feature.setProperties(values)}return feature};ol.format.MVT.prototype.getLastExtent=function(){return this.extent_};ol.format.MVT.prototype.getType=function(){return ol.format.FormatType.ARRAY_BUFFER};
ol.format.MVT.prototype.readFeatures=function(source,opt_options){var layers=this.layers_;var pbf=new ol.ext.PBF(source);var pbfLayers=pbf.readFields(ol.format.MVT.pbfReaders_.layers,{});var features=[];var pbfLayer;for(var name in pbfLayers){if(layers&&layers.indexOf(name)==-1)continue;pbfLayer=pbfLayers[name];var rawFeature;for(var i=0,ii=pbfLayer.length;i<ii;++i){rawFeature=ol.format.MVT.readRawFeature_(pbf,pbfLayer,i);features.push(this.createFeature_(pbf,rawFeature))}this.extent_=pbfLayer?[0,
0,pbfLayer.extent,pbfLayer.extent]:null}return features};ol.format.MVT.prototype.readProjection=function(source){return this.defaultDataProjection};ol.format.MVT.prototype.setLayers=function(layers){this.layers_=layers};ol.format.MVT.prototype.readFeature=function(){};ol.format.MVT.prototype.readGeometry=function(){};ol.format.MVT.prototype.writeFeature=function(){};ol.format.MVT.prototype.writeGeometry=function(){};ol.format.MVT.prototype.writeFeatures=function(){};goog.provide("ol.format.OSMXML");goog.require("ol");goog.require("ol.array");goog.require("ol.Feature");goog.require("ol.format.Feature");goog.require("ol.format.XMLFeature");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.LineString");goog.require("ol.geom.Point");goog.require("ol.geom.Polygon");goog.require("ol.obj");goog.require("ol.proj");goog.require("ol.xml");ol.format.OSMXML=function(){ol.format.XMLFeature.call(this);this.defaultDataProjection=ol.proj.get("EPSG:4326")};
ol.inherits(ol.format.OSMXML,ol.format.XMLFeature);
ol.format.OSMXML.readNode_=function(node,objectStack){var options=objectStack[0];var state=objectStack[objectStack.length-1];var id=node.getAttribute("id");var coordinates=[parseFloat(node.getAttribute("lon")),parseFloat(node.getAttribute("lat"))];state.nodes[id]=coordinates;var values=ol.xml.pushParseAndPop({tags:{}},ol.format.OSMXML.NODE_PARSERS_,node,objectStack);if(!ol.obj.isEmpty(values.tags)){var geometry=new ol.geom.Point(coordinates);ol.format.Feature.transformWithOptions(geometry,false,options);
var feature=new ol.Feature(geometry);feature.setId(id);feature.setProperties(values.tags);state.features.push(feature)}};ol.format.OSMXML.readWay_=function(node,objectStack){var id=node.getAttribute("id");var values=ol.xml.pushParseAndPop({id:id,ndrefs:[],tags:{}},ol.format.OSMXML.WAY_PARSERS_,node,objectStack);var state=objectStack[objectStack.length-1];state.ways.push(values)};ol.format.OSMXML.readNd_=function(node,objectStack){var values=objectStack[objectStack.length-1];values.ndrefs.push(node.getAttribute("ref"))};
ol.format.OSMXML.readTag_=function(node,objectStack){var values=objectStack[objectStack.length-1];values.tags[node.getAttribute("k")]=node.getAttribute("v")};ol.format.OSMXML.NAMESPACE_URIS_=[null];ol.format.OSMXML.WAY_PARSERS_=ol.xml.makeStructureNS(ol.format.OSMXML.NAMESPACE_URIS_,{"nd":ol.format.OSMXML.readNd_,"tag":ol.format.OSMXML.readTag_});ol.format.OSMXML.PARSERS_=ol.xml.makeStructureNS(ol.format.OSMXML.NAMESPACE_URIS_,{"node":ol.format.OSMXML.readNode_,"way":ol.format.OSMXML.readWay_});
ol.format.OSMXML.NODE_PARSERS_=ol.xml.makeStructureNS(ol.format.OSMXML.NAMESPACE_URIS_,{"tag":ol.format.OSMXML.readTag_});ol.format.OSMXML.prototype.readFeatures;
ol.format.OSMXML.prototype.readFeaturesFromNode=function(node,opt_options){var options=this.getReadOptions(node,opt_options);if(node.localName=="osm"){var state=ol.xml.pushParseAndPop({nodes:{},ways:[],features:[]},ol.format.OSMXML.PARSERS_,node,[options]);for(var j=0;j<state.ways.length;j++){var values=state.ways[j];var flatCoordinates=[];for(var i=0,ii=values.ndrefs.length;i<ii;i++){var point=state.nodes[values.ndrefs[i]];ol.array.extend(flatCoordinates,point)}var geometry;if(values.ndrefs[0]==
values.ndrefs[values.ndrefs.length-1]){geometry=new ol.geom.Polygon(null);geometry.setFlatCoordinates(ol.geom.GeometryLayout.XY,flatCoordinates,[flatCoordinates.length])}else{geometry=new ol.geom.LineString(null);geometry.setFlatCoordinates(ol.geom.GeometryLayout.XY,flatCoordinates)}ol.format.Feature.transformWithOptions(geometry,false,options);var feature=new ol.Feature(geometry);feature.setId(values.id);feature.setProperties(values.tags);state.features.push(feature)}if(state.features)return state.features}return[]};
ol.format.OSMXML.prototype.readProjection;ol.format.OSMXML.prototype.writeFeatureNode=function(feature,opt_options){};ol.format.OSMXML.prototype.writeFeaturesNode=function(features,opt_options){};ol.format.OSMXML.prototype.writeGeometryNode=function(geometry,opt_options){};goog.provide("ol.format.XLink");ol.format.XLink.NAMESPACE_URI="http://www.w3.org/1999/xlink";ol.format.XLink.readHref=function(node){return node.getAttributeNS(ol.format.XLink.NAMESPACE_URI,"href")};goog.provide("ol.format.XML");goog.require("ol.xml");ol.format.XML=function(){};ol.format.XML.prototype.read=function(source){if(ol.xml.isDocument(source))return this.readFromDocument(source);else if(ol.xml.isNode(source))return this.readFromNode(source);else if(typeof source==="string"){var doc=ol.xml.parse(source);return this.readFromDocument(doc)}else return null};ol.format.XML.prototype.readFromDocument=function(doc){};ol.format.XML.prototype.readFromNode=function(node){};goog.provide("ol.format.OWS");goog.require("ol");goog.require("ol.format.XLink");goog.require("ol.format.XML");goog.require("ol.format.XSD");goog.require("ol.xml");ol.format.OWS=function(){ol.format.XML.call(this)};ol.inherits(ol.format.OWS,ol.format.XML);ol.format.OWS.prototype.readFromDocument=function(doc){for(var n=doc.firstChild;n;n=n.nextSibling)if(n.nodeType==Node.ELEMENT_NODE)return this.readFromNode(n);return null};
ol.format.OWS.prototype.readFromNode=function(node){var owsObject=ol.xml.pushParseAndPop({},ol.format.OWS.PARSERS_,node,[]);return owsObject?owsObject:null};ol.format.OWS.readAddress_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.OWS.ADDRESS_PARSERS_,node,objectStack)};ol.format.OWS.readAllowedValues_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.OWS.ALLOWED_VALUES_PARSERS_,node,objectStack)};
ol.format.OWS.readConstraint_=function(node,objectStack){var name=node.getAttribute("name");if(!name)return undefined;return ol.xml.pushParseAndPop({"name":name},ol.format.OWS.CONSTRAINT_PARSERS_,node,objectStack)};ol.format.OWS.readContactInfo_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.OWS.CONTACT_INFO_PARSERS_,node,objectStack)};ol.format.OWS.readDcp_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.OWS.DCP_PARSERS_,node,objectStack)};
ol.format.OWS.readGet_=function(node,objectStack){var href=ol.format.XLink.readHref(node);if(!href)return undefined;return ol.xml.pushParseAndPop({"href":href},ol.format.OWS.REQUEST_METHOD_PARSERS_,node,objectStack)};ol.format.OWS.readHttp_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.OWS.HTTP_PARSERS_,node,objectStack)};
ol.format.OWS.readOperation_=function(node,objectStack){var name=node.getAttribute("name");var value=ol.xml.pushParseAndPop({},ol.format.OWS.OPERATION_PARSERS_,node,objectStack);if(!value)return undefined;var object=objectStack[objectStack.length-1];object[name]=value};ol.format.OWS.readOperationsMetadata_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.OWS.OPERATIONS_METADATA_PARSERS_,node,objectStack)};
ol.format.OWS.readPhone_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.OWS.PHONE_PARSERS_,node,objectStack)};ol.format.OWS.readServiceIdentification_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.OWS.SERVICE_IDENTIFICATION_PARSERS_,node,objectStack)};ol.format.OWS.readServiceContact_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.OWS.SERVICE_CONTACT_PARSERS_,node,objectStack)};
ol.format.OWS.readServiceProvider_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.OWS.SERVICE_PROVIDER_PARSERS_,node,objectStack)};ol.format.OWS.readValue_=function(node,objectStack){return ol.format.XSD.readString(node)};ol.format.OWS.NAMESPACE_URIS_=[null,"http://www.opengis.net/ows/1.1"];
ol.format.OWS.PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"ServiceIdentification":ol.xml.makeObjectPropertySetter(ol.format.OWS.readServiceIdentification_),"ServiceProvider":ol.xml.makeObjectPropertySetter(ol.format.OWS.readServiceProvider_),"OperationsMetadata":ol.xml.makeObjectPropertySetter(ol.format.OWS.readOperationsMetadata_)});
ol.format.OWS.ADDRESS_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"DeliveryPoint":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"City":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"AdministrativeArea":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"PostalCode":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Country":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"ElectronicMailAddress":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)});
ol.format.OWS.ALLOWED_VALUES_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"Value":ol.xml.makeObjectPropertyPusher(ol.format.OWS.readValue_)});ol.format.OWS.CONSTRAINT_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"AllowedValues":ol.xml.makeObjectPropertySetter(ol.format.OWS.readAllowedValues_)});ol.format.OWS.CONTACT_INFO_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"Phone":ol.xml.makeObjectPropertySetter(ol.format.OWS.readPhone_),"Address":ol.xml.makeObjectPropertySetter(ol.format.OWS.readAddress_)});
ol.format.OWS.DCP_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"HTTP":ol.xml.makeObjectPropertySetter(ol.format.OWS.readHttp_)});ol.format.OWS.HTTP_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"Get":ol.xml.makeObjectPropertyPusher(ol.format.OWS.readGet_),"Post":undefined});ol.format.OWS.OPERATION_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"DCP":ol.xml.makeObjectPropertySetter(ol.format.OWS.readDcp_)});
ol.format.OWS.OPERATIONS_METADATA_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"Operation":ol.format.OWS.readOperation_});ol.format.OWS.PHONE_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"Voice":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Facsimile":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)});ol.format.OWS.REQUEST_METHOD_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"Constraint":ol.xml.makeObjectPropertyPusher(ol.format.OWS.readConstraint_)});
ol.format.OWS.SERVICE_CONTACT_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"IndividualName":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"PositionName":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"ContactInfo":ol.xml.makeObjectPropertySetter(ol.format.OWS.readContactInfo_)});
ol.format.OWS.SERVICE_IDENTIFICATION_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"Abstract":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"AccessConstraints":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Fees":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Title":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"ServiceTypeVersion":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"ServiceType":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)});
ol.format.OWS.SERVICE_PROVIDER_PARSERS_=ol.xml.makeStructureNS(ol.format.OWS.NAMESPACE_URIS_,{"ProviderName":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"ProviderSite":ol.xml.makeObjectPropertySetter(ol.format.XLink.readHref),"ServiceContact":ol.xml.makeObjectPropertySetter(ol.format.OWS.readServiceContact_)});goog.provide("ol.geom.flat.flip");ol.geom.flat.flip.flipXY=function(flatCoordinates,offset,end,stride,opt_dest,opt_destOffset){var dest,destOffset;if(opt_dest!==undefined){dest=opt_dest;destOffset=opt_destOffset!==undefined?opt_destOffset:0}else{dest=[];destOffset=0}var j=offset;while(j<end){var x=flatCoordinates[j++];dest[destOffset++]=flatCoordinates[j++];dest[destOffset++]=x;for(var k=2;k<stride;++k)dest[destOffset++]=flatCoordinates[j++]}dest.length=destOffset;return dest};goog.provide("ol.format.Polyline");goog.require("ol");goog.require("ol.asserts");goog.require("ol.Feature");goog.require("ol.format.Feature");goog.require("ol.format.TextFeature");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.LineString");goog.require("ol.geom.SimpleGeometry");goog.require("ol.geom.flat.flip");goog.require("ol.geom.flat.inflate");goog.require("ol.proj");
ol.format.Polyline=function(opt_options){var options=opt_options?opt_options:{};ol.format.TextFeature.call(this);this.defaultDataProjection=ol.proj.get("EPSG:4326");this.factor_=options.factor?options.factor:1E5;this.geometryLayout_=options.geometryLayout?options.geometryLayout:ol.geom.GeometryLayout.XY};ol.inherits(ol.format.Polyline,ol.format.TextFeature);
ol.format.Polyline.encodeDeltas=function(numbers,stride,opt_factor){var factor=opt_factor?opt_factor:1E5;var d;var lastNumbers=new Array(stride);for(d=0;d<stride;++d)lastNumbers[d]=0;var i,ii;for(i=0,ii=numbers.length;i<ii;)for(d=0;d<stride;++d,++i){var num=numbers[i];var delta=num-lastNumbers[d];lastNumbers[d]=num;numbers[i]=delta}return ol.format.Polyline.encodeFloats(numbers,factor)};
ol.format.Polyline.decodeDeltas=function(encoded,stride,opt_factor){var factor=opt_factor?opt_factor:1E5;var d;var lastNumbers=new Array(stride);for(d=0;d<stride;++d)lastNumbers[d]=0;var numbers=ol.format.Polyline.decodeFloats(encoded,factor);var i,ii;for(i=0,ii=numbers.length;i<ii;)for(d=0;d<stride;++d,++i){lastNumbers[d]+=numbers[i];numbers[i]=lastNumbers[d]}return numbers};
ol.format.Polyline.encodeFloats=function(numbers,opt_factor){var factor=opt_factor?opt_factor:1E5;var i,ii;for(i=0,ii=numbers.length;i<ii;++i)numbers[i]=Math.round(numbers[i]*factor);return ol.format.Polyline.encodeSignedIntegers(numbers)};ol.format.Polyline.decodeFloats=function(encoded,opt_factor){var factor=opt_factor?opt_factor:1E5;var numbers=ol.format.Polyline.decodeSignedIntegers(encoded);var i,ii;for(i=0,ii=numbers.length;i<ii;++i)numbers[i]/=factor;return numbers};
ol.format.Polyline.encodeSignedIntegers=function(numbers){var i,ii;for(i=0,ii=numbers.length;i<ii;++i){var num=numbers[i];numbers[i]=num<0?~(num<<1):num<<1}return ol.format.Polyline.encodeUnsignedIntegers(numbers)};ol.format.Polyline.decodeSignedIntegers=function(encoded){var numbers=ol.format.Polyline.decodeUnsignedIntegers(encoded);var i,ii;for(i=0,ii=numbers.length;i<ii;++i){var num=numbers[i];numbers[i]=num&1?~(num>>1):num>>1}return numbers};
ol.format.Polyline.encodeUnsignedIntegers=function(numbers){var encoded="";var i,ii;for(i=0,ii=numbers.length;i<ii;++i)encoded+=ol.format.Polyline.encodeUnsignedInteger(numbers[i]);return encoded};ol.format.Polyline.decodeUnsignedIntegers=function(encoded){var numbers=[];var current=0;var shift=0;var i,ii;for(i=0,ii=encoded.length;i<ii;++i){var b=encoded.charCodeAt(i)-63;current|=(b&31)<<shift;if(b<32){numbers.push(current);current=0;shift=0}else shift+=5}return numbers};
ol.format.Polyline.encodeUnsignedInteger=function(num){var value,encoded="";while(num>=32){value=(32|num&31)+63;encoded+=String.fromCharCode(value);num>>=5}value=num+63;encoded+=String.fromCharCode(value);return encoded};ol.format.Polyline.prototype.readFeature;ol.format.Polyline.prototype.readFeatureFromText=function(text,opt_options){var geometry=this.readGeometryFromText(text,opt_options);return new ol.Feature(geometry)};ol.format.Polyline.prototype.readFeatures;
ol.format.Polyline.prototype.readFeaturesFromText=function(text,opt_options){var feature=this.readFeatureFromText(text,opt_options);return[feature]};ol.format.Polyline.prototype.readGeometry;
ol.format.Polyline.prototype.readGeometryFromText=function(text,opt_options){var stride=ol.geom.SimpleGeometry.getStrideForLayout(this.geometryLayout_);var flatCoordinates=ol.format.Polyline.decodeDeltas(text,stride,this.factor_);ol.geom.flat.flip.flipXY(flatCoordinates,0,flatCoordinates.length,stride,flatCoordinates);var coordinates=ol.geom.flat.inflate.coordinates(flatCoordinates,0,flatCoordinates.length,stride);return ol.format.Feature.transformWithOptions(new ol.geom.LineString(coordinates,this.geometryLayout_),
false,this.adaptOptions(opt_options))};ol.format.Polyline.prototype.readProjection;ol.format.Polyline.prototype.writeFeatureText=function(feature,opt_options){var geometry=feature.getGeometry();if(geometry)return this.writeGeometryText(geometry,opt_options);else{ol.asserts.assert(false,40);return""}};ol.format.Polyline.prototype.writeFeaturesText=function(features,opt_options){return this.writeFeatureText(features[0],opt_options)};ol.format.Polyline.prototype.writeGeometry;
ol.format.Polyline.prototype.writeGeometryText=function(geometry,opt_options){geometry=ol.format.Feature.transformWithOptions(geometry,true,this.adaptOptions(opt_options));var flatCoordinates=geometry.getFlatCoordinates();var stride=geometry.getStride();ol.geom.flat.flip.flipXY(flatCoordinates,0,flatCoordinates.length,stride,flatCoordinates);return ol.format.Polyline.encodeDeltas(flatCoordinates,stride,this.factor_)};goog.provide("ol.format.TopoJSON");goog.require("ol");goog.require("ol.Feature");goog.require("ol.format.Feature");goog.require("ol.format.JSONFeature");goog.require("ol.geom.LineString");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.MultiPoint");goog.require("ol.geom.MultiPolygon");goog.require("ol.geom.Point");goog.require("ol.geom.Polygon");goog.require("ol.proj");
ol.format.TopoJSON=function(opt_options){var options=opt_options?opt_options:{};ol.format.JSONFeature.call(this);this.layerName_=options.layerName;this.layers_=options.layers?options.layers:null;this.defaultDataProjection=ol.proj.get(options.defaultDataProjection?options.defaultDataProjection:"EPSG:4326")};ol.inherits(ol.format.TopoJSON,ol.format.JSONFeature);
ol.format.TopoJSON.concatenateArcs_=function(indices,arcs){var coordinates=[];var index,arc;var i,ii;var j,jj;for(i=0,ii=indices.length;i<ii;++i){index=indices[i];if(i>0)coordinates.pop();if(index>=0)arc=arcs[index];else arc=arcs[~index].slice().reverse();coordinates.push.apply(coordinates,arc)}for(j=0,jj=coordinates.length;j<jj;++j)coordinates[j]=coordinates[j].slice();return coordinates};
ol.format.TopoJSON.readPointGeometry_=function(object,scale,translate){var coordinates=object.coordinates;if(scale&&translate)ol.format.TopoJSON.transformVertex_(coordinates,scale,translate);return new ol.geom.Point(coordinates)};ol.format.TopoJSON.readMultiPointGeometry_=function(object,scale,translate){var coordinates=object.coordinates;var i,ii;if(scale&&translate)for(i=0,ii=coordinates.length;i<ii;++i)ol.format.TopoJSON.transformVertex_(coordinates[i],scale,translate);return new ol.geom.MultiPoint(coordinates)};
ol.format.TopoJSON.readLineStringGeometry_=function(object,arcs){var coordinates=ol.format.TopoJSON.concatenateArcs_(object.arcs,arcs);return new ol.geom.LineString(coordinates)};ol.format.TopoJSON.readMultiLineStringGeometry_=function(object,arcs){var coordinates=[];var i,ii;for(i=0,ii=object.arcs.length;i<ii;++i)coordinates[i]=ol.format.TopoJSON.concatenateArcs_(object.arcs[i],arcs);return new ol.geom.MultiLineString(coordinates)};
ol.format.TopoJSON.readPolygonGeometry_=function(object,arcs){var coordinates=[];var i,ii;for(i=0,ii=object.arcs.length;i<ii;++i)coordinates[i]=ol.format.TopoJSON.concatenateArcs_(object.arcs[i],arcs);return new ol.geom.Polygon(coordinates)};
ol.format.TopoJSON.readMultiPolygonGeometry_=function(object,arcs){var coordinates=[];var polyArray,ringCoords,j,jj;var i,ii;for(i=0,ii=object.arcs.length;i<ii;++i){polyArray=object.arcs[i];ringCoords=[];for(j=0,jj=polyArray.length;j<jj;++j)ringCoords[j]=ol.format.TopoJSON.concatenateArcs_(polyArray[j],arcs);coordinates[i]=ringCoords}return new ol.geom.MultiPolygon(coordinates)};
ol.format.TopoJSON.readFeaturesFromGeometryCollection_=function(collection,arcs,scale,translate,property,name,opt_options){var geometries=collection.geometries;var features=[];var i,ii;for(i=0,ii=geometries.length;i<ii;++i)features[i]=ol.format.TopoJSON.readFeatureFromGeometry_(geometries[i],arcs,scale,translate,property,name,opt_options);return features};
ol.format.TopoJSON.readFeatureFromGeometry_=function(object,arcs,scale,translate,property,name,opt_options){var geometry;var type=object.type;var geometryReader=ol.format.TopoJSON.GEOMETRY_READERS_[type];if(type==="Point"||type==="MultiPoint")geometry=geometryReader(object,scale,translate);else geometry=geometryReader(object,arcs);var feature=new ol.Feature;feature.setGeometry(ol.format.Feature.transformWithOptions(geometry,false,opt_options));if(object.id!==undefined)feature.setId(object.id);var properties=
object.properties;if(property){if(!properties)properties={};properties[property]=name}if(properties)feature.setProperties(properties);return feature};ol.format.TopoJSON.prototype.readFeatures;
ol.format.TopoJSON.prototype.readFeaturesFromObject=function(object,opt_options){if(object.type=="Topology"){var topoJSONTopology=object;var transform,scale=null,translate=null;if(topoJSONTopology.transform){transform=topoJSONTopology.transform;scale=transform.scale;translate=transform.translate}var arcs=topoJSONTopology.arcs;if(transform)ol.format.TopoJSON.transformArcs_(arcs,scale,translate);var features=[];var topoJSONFeatures=topoJSONTopology.objects;var property=this.layerName_;var objectName,
feature;for(objectName in topoJSONFeatures){if(this.layers_&&this.layers_.indexOf(objectName)==-1)continue;if(topoJSONFeatures[objectName].type==="GeometryCollection"){feature=topoJSONFeatures[objectName];features.push.apply(features,ol.format.TopoJSON.readFeaturesFromGeometryCollection_(feature,arcs,scale,translate,property,objectName,opt_options))}else{feature=topoJSONFeatures[objectName];features.push(ol.format.TopoJSON.readFeatureFromGeometry_(feature,arcs,scale,translate,property,objectName,
opt_options))}}return features}else return[]};ol.format.TopoJSON.transformArcs_=function(arcs,scale,translate){var i,ii;for(i=0,ii=arcs.length;i<ii;++i)ol.format.TopoJSON.transformArc_(arcs[i],scale,translate)};ol.format.TopoJSON.transformArc_=function(arc,scale,translate){var x=0;var y=0;var vertex;var i,ii;for(i=0,ii=arc.length;i<ii;++i){vertex=arc[i];x+=vertex[0];y+=vertex[1];vertex[0]=x;vertex[1]=y;ol.format.TopoJSON.transformVertex_(vertex,scale,translate)}};
ol.format.TopoJSON.transformVertex_=function(vertex,scale,translate){vertex[0]=vertex[0]*scale[0]+translate[0];vertex[1]=vertex[1]*scale[1]+translate[1]};ol.format.TopoJSON.prototype.readProjection;ol.format.TopoJSON.prototype.readProjectionFromObject=function(object){return this.defaultDataProjection};
ol.format.TopoJSON.GEOMETRY_READERS_={"Point":ol.format.TopoJSON.readPointGeometry_,"LineString":ol.format.TopoJSON.readLineStringGeometry_,"Polygon":ol.format.TopoJSON.readPolygonGeometry_,"MultiPoint":ol.format.TopoJSON.readMultiPointGeometry_,"MultiLineString":ol.format.TopoJSON.readMultiLineStringGeometry_,"MultiPolygon":ol.format.TopoJSON.readMultiPolygonGeometry_};ol.format.TopoJSON.prototype.writeFeatureObject=function(feature,opt_options){};
ol.format.TopoJSON.prototype.writeFeaturesObject=function(features,opt_options){};ol.format.TopoJSON.prototype.writeGeometryObject=function(geometry,opt_options){};ol.format.TopoJSON.prototype.readGeometryFromObject=function(){};ol.format.TopoJSON.prototype.readFeatureFromObject=function(){};goog.provide("ol.format.WFS");goog.require("ol");goog.require("ol.asserts");goog.require("ol.format.GML2");goog.require("ol.format.GML3");goog.require("ol.format.GMLBase");goog.require("ol.format.filter");goog.require("ol.format.XMLFeature");goog.require("ol.format.XSD");goog.require("ol.geom.Geometry");goog.require("ol.obj");goog.require("ol.proj");goog.require("ol.xml");
ol.format.WFS=function(opt_options){var options=opt_options?opt_options:{};this.featureType_=options.featureType;this.featureNS_=options.featureNS;this.gmlFormat_=options.gmlFormat?options.gmlFormat:new ol.format.GML3;this.schemaLocation_=options.schemaLocation?options.schemaLocation:ol.format.WFS.SCHEMA_LOCATIONS[ol.format.WFS.DEFAULT_VERSION];ol.format.XMLFeature.call(this)};ol.inherits(ol.format.WFS,ol.format.XMLFeature);ol.format.WFS.FEATURE_PREFIX="feature";ol.format.WFS.XMLNS="http://www.w3.org/2000/xmlns/";
ol.format.WFS.OGCNS="http://www.opengis.net/ogc";ol.format.WFS.WFSNS="http://www.opengis.net/wfs";ol.format.WFS.FESNS="http://www.opengis.net/fes";ol.format.WFS.SCHEMA_LOCATIONS={"1.1.0":"http://www.opengis.net/wfs "+"http://schemas.opengis.net/wfs/1.1.0/wfs.xsd","1.0.0":"http://www.opengis.net/wfs "+"http://schemas.opengis.net/wfs/1.0.0/wfs.xsd"};ol.format.WFS.DEFAULT_VERSION="1.1.0";ol.format.WFS.prototype.getFeatureType=function(){return this.featureType_};
ol.format.WFS.prototype.setFeatureType=function(featureType){this.featureType_=featureType};ol.format.WFS.prototype.readFeatures;
ol.format.WFS.prototype.readFeaturesFromNode=function(node,opt_options){var context={"featureType":this.featureType_,"featureNS":this.featureNS_};ol.obj.assign(context,this.getReadOptions(node,opt_options?opt_options:{}));var objectStack=[context];this.gmlFormat_.FEATURE_COLLECTION_PARSERS[ol.format.GMLBase.GMLNS]["featureMember"]=ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readFeaturesInternal);var features=ol.xml.pushParseAndPop([],this.gmlFormat_.FEATURE_COLLECTION_PARSERS,node,objectStack,
this.gmlFormat_);if(!features)features=[];return features};ol.format.WFS.prototype.readTransactionResponse=function(source){if(ol.xml.isDocument(source))return this.readTransactionResponseFromDocument(source);else if(ol.xml.isNode(source))return this.readTransactionResponseFromNode(source);else if(typeof source==="string"){var doc=ol.xml.parse(source);return this.readTransactionResponseFromDocument(doc)}else return undefined};
ol.format.WFS.prototype.readFeatureCollectionMetadata=function(source){if(ol.xml.isDocument(source))return this.readFeatureCollectionMetadataFromDocument(source);else if(ol.xml.isNode(source))return this.readFeatureCollectionMetadataFromNode(source);else if(typeof source==="string"){var doc=ol.xml.parse(source);return this.readFeatureCollectionMetadataFromDocument(doc)}else return undefined};
ol.format.WFS.prototype.readFeatureCollectionMetadataFromDocument=function(doc){for(var n=doc.firstChild;n;n=n.nextSibling)if(n.nodeType==Node.ELEMENT_NODE)return this.readFeatureCollectionMetadataFromNode(n);return undefined};ol.format.WFS.FEATURE_COLLECTION_PARSERS_={"http://www.opengis.net/gml":{"boundedBy":ol.xml.makeObjectPropertySetter(ol.format.GMLBase.prototype.readGeometryElement,"bounds")}};
ol.format.WFS.prototype.readFeatureCollectionMetadataFromNode=function(node){var result={};var value=ol.format.XSD.readNonNegativeIntegerString(node.getAttribute("numberOfFeatures"));result["numberOfFeatures"]=value;return ol.xml.pushParseAndPop(result,ol.format.WFS.FEATURE_COLLECTION_PARSERS_,node,[],this.gmlFormat_)};
ol.format.WFS.TRANSACTION_SUMMARY_PARSERS_={"http://www.opengis.net/wfs":{"totalInserted":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"totalUpdated":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"totalDeleted":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger)}};ol.format.WFS.readTransactionSummary_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WFS.TRANSACTION_SUMMARY_PARSERS_,node,objectStack)};
ol.format.WFS.OGC_FID_PARSERS_={"http://www.opengis.net/ogc":{"FeatureId":ol.xml.makeArrayPusher(function(node,objectStack){return node.getAttribute("fid")})}};ol.format.WFS.fidParser_=function(node,objectStack){ol.xml.parseNode(ol.format.WFS.OGC_FID_PARSERS_,node,objectStack)};ol.format.WFS.INSERT_RESULTS_PARSERS_={"http://www.opengis.net/wfs":{"Feature":ol.format.WFS.fidParser_}};
ol.format.WFS.readInsertResults_=function(node,objectStack){return ol.xml.pushParseAndPop([],ol.format.WFS.INSERT_RESULTS_PARSERS_,node,objectStack)};ol.format.WFS.TRANSACTION_RESPONSE_PARSERS_={"http://www.opengis.net/wfs":{"TransactionSummary":ol.xml.makeObjectPropertySetter(ol.format.WFS.readTransactionSummary_,"transactionSummary"),"InsertResults":ol.xml.makeObjectPropertySetter(ol.format.WFS.readInsertResults_,"insertIds")}};
ol.format.WFS.prototype.readTransactionResponseFromDocument=function(doc){for(var n=doc.firstChild;n;n=n.nextSibling)if(n.nodeType==Node.ELEMENT_NODE)return this.readTransactionResponseFromNode(n);return undefined};ol.format.WFS.prototype.readTransactionResponseFromNode=function(node){return ol.xml.pushParseAndPop({},ol.format.WFS.TRANSACTION_RESPONSE_PARSERS_,node,[])};ol.format.WFS.QUERY_SERIALIZERS_={"http://www.opengis.net/wfs":{"PropertyName":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)}};
ol.format.WFS.writeFeature_=function(node,feature,objectStack){var context=objectStack[objectStack.length-1];var featureType=context["featureType"];var featureNS=context["featureNS"];var gmlVersion=context["gmlVersion"];var child=ol.xml.createElementNS(featureNS,featureType);node.appendChild(child);if(gmlVersion===2)ol.format.GML2.prototype.writeFeatureElement(child,feature,objectStack);else ol.format.GML3.prototype.writeFeatureElement(child,feature,objectStack)};
ol.format.WFS.writeOgcFidFilter_=function(node,fid,objectStack){var filter=ol.xml.createElementNS(ol.format.WFS.OGCNS,"Filter");var child=ol.xml.createElementNS(ol.format.WFS.OGCNS,"FeatureId");filter.appendChild(child);child.setAttribute("fid",fid);node.appendChild(filter)};
ol.format.WFS.getTypeName_=function(featurePrefix,featureType){featurePrefix=featurePrefix?featurePrefix:ol.format.WFS.FEATURE_PREFIX;var prefix=featurePrefix+":";if(featureType.indexOf(prefix)===0)return featureType;else return prefix+featureType};
ol.format.WFS.writeDelete_=function(node,feature,objectStack){var context=objectStack[objectStack.length-1];ol.asserts.assert(feature.getId()!==undefined,26);var featureType=context["featureType"];var featurePrefix=context["featurePrefix"];var featureNS=context["featureNS"];var typeName=ol.format.WFS.getTypeName_(featurePrefix,featureType);node.setAttribute("typeName",typeName);ol.xml.setAttributeNS(node,ol.format.WFS.XMLNS,"xmlns:"+featurePrefix,featureNS);var fid=feature.getId();if(fid!==undefined)ol.format.WFS.writeOgcFidFilter_(node,
fid,objectStack)};
ol.format.WFS.writeUpdate_=function(node,feature,objectStack){var context=objectStack[objectStack.length-1];ol.asserts.assert(feature.getId()!==undefined,27);var featureType=context["featureType"];var featurePrefix=context["featurePrefix"];var featureNS=context["featureNS"];var typeName=ol.format.WFS.getTypeName_(featurePrefix,featureType);var geometryName=feature.getGeometryName();node.setAttribute("typeName",typeName);ol.xml.setAttributeNS(node,ol.format.WFS.XMLNS,"xmlns:"+featurePrefix,featureNS);
var fid=feature.getId();if(fid!==undefined){var keys=feature.getKeys();var values=[];for(var i=0,ii=keys.length;i<ii;i++){var value=feature.get(keys[i]);if(value!==undefined){var name=keys[i];if(value instanceof ol.geom.Geometry)name=geometryName;values.push({name:name,value:value})}}ol.xml.pushSerializeAndPop({"gmlVersion":context["gmlVersion"],node:node,"hasZ":context["hasZ"],"srsName":context["srsName"]},ol.format.WFS.TRANSACTION_SERIALIZERS_,ol.xml.makeSimpleNodeFactory("Property"),values,objectStack);
ol.format.WFS.writeOgcFidFilter_(node,fid,objectStack)}};
ol.format.WFS.writeProperty_=function(node,pair,objectStack){var name=ol.xml.createElementNS(ol.format.WFS.WFSNS,"Name");var context=objectStack[objectStack.length-1];var gmlVersion=context["gmlVersion"];node.appendChild(name);ol.format.XSD.writeStringTextNode(name,pair.name);if(pair.value!==undefined&&pair.value!==null){var value=ol.xml.createElementNS(ol.format.WFS.WFSNS,"Value");node.appendChild(value);if(pair.value instanceof ol.geom.Geometry)if(gmlVersion===2)ol.format.GML2.prototype.writeGeometryElement(value,
pair.value,objectStack);else ol.format.GML3.prototype.writeGeometryElement(value,pair.value,objectStack);else ol.format.XSD.writeStringTextNode(value,pair.value)}};ol.format.WFS.writeNative_=function(node,nativeElement,objectStack){if(nativeElement.vendorId)node.setAttribute("vendorId",nativeElement.vendorId);if(nativeElement.safeToIgnore!==undefined)node.setAttribute("safeToIgnore",nativeElement.safeToIgnore);if(nativeElement.value!==undefined)ol.format.XSD.writeStringTextNode(node,nativeElement.value)};
ol.format.WFS.TRANSACTION_SERIALIZERS_={"http://www.opengis.net/wfs":{"Insert":ol.xml.makeChildAppender(ol.format.WFS.writeFeature_),"Update":ol.xml.makeChildAppender(ol.format.WFS.writeUpdate_),"Delete":ol.xml.makeChildAppender(ol.format.WFS.writeDelete_),"Property":ol.xml.makeChildAppender(ol.format.WFS.writeProperty_),"Native":ol.xml.makeChildAppender(ol.format.WFS.writeNative_)}};
ol.format.WFS.writeQuery_=function(node,featureType,objectStack){var context=objectStack[objectStack.length-1];var featurePrefix=context["featurePrefix"];var featureNS=context["featureNS"];var propertyNames=context["propertyNames"];var srsName=context["srsName"];var typeName;if(featurePrefix)typeName=ol.format.WFS.getTypeName_(featurePrefix,featureType);else typeName=featureType;node.setAttribute("typeName",typeName);if(srsName)node.setAttribute("srsName",srsName);if(featureNS)ol.xml.setAttributeNS(node,
ol.format.WFS.XMLNS,"xmlns:"+featurePrefix,featureNS);var item=ol.obj.assign({},context);item.node=node;ol.xml.pushSerializeAndPop(item,ol.format.WFS.QUERY_SERIALIZERS_,ol.xml.makeSimpleNodeFactory("PropertyName"),propertyNames,objectStack);var filter=context["filter"];if(filter){var child=ol.xml.createElementNS(ol.format.WFS.OGCNS,"Filter");node.appendChild(child);ol.format.WFS.writeFilterCondition_(child,filter,objectStack)}};
ol.format.WFS.writeFilterCondition_=function(node,filter,objectStack){var item={node:node};ol.xml.pushSerializeAndPop(item,ol.format.WFS.GETFEATURE_SERIALIZERS_,ol.xml.makeSimpleNodeFactory(filter.getTagName()),[filter],objectStack)};
ol.format.WFS.writeBboxFilter_=function(node,filter,objectStack){var context=objectStack[objectStack.length-1];context["srsName"]=filter.srsName;ol.format.WFS.writeOgcPropertyName_(node,filter.geometryName);ol.format.GML3.prototype.writeGeometryElement(node,filter.extent,objectStack)};
ol.format.WFS.writeContainsFilter_=function(node,filter,objectStack){var context=objectStack[objectStack.length-1];context["srsName"]=filter.srsName;ol.format.WFS.writeOgcPropertyName_(node,filter.geometryName);ol.format.GML3.prototype.writeGeometryElement(node,filter.geometry,objectStack)};
ol.format.WFS.writeIntersectsFilter_=function(node,filter,objectStack){var context=objectStack[objectStack.length-1];context["srsName"]=filter.srsName;ol.format.WFS.writeOgcPropertyName_(node,filter.geometryName);ol.format.GML3.prototype.writeGeometryElement(node,filter.geometry,objectStack)};
ol.format.WFS.writeWithinFilter_=function(node,filter,objectStack){var context=objectStack[objectStack.length-1];context["srsName"]=filter.srsName;ol.format.WFS.writeOgcPropertyName_(node,filter.geometryName);ol.format.GML3.prototype.writeGeometryElement(node,filter.geometry,objectStack)};
ol.format.WFS.writeDuringFilter_=function(node,filter,objectStack){var valueReference=ol.xml.createElementNS(ol.format.WFS.FESNS,"ValueReference");ol.format.XSD.writeStringTextNode(valueReference,filter.propertyName);node.appendChild(valueReference);var timePeriod=ol.xml.createElementNS(ol.format.GMLBase.GMLNS,"TimePeriod");node.appendChild(timePeriod);var begin=ol.xml.createElementNS(ol.format.GMLBase.GMLNS,"begin");timePeriod.appendChild(begin);ol.format.WFS.writeTimeInstant_(begin,filter.begin);
var end=ol.xml.createElementNS(ol.format.GMLBase.GMLNS,"end");timePeriod.appendChild(end);ol.format.WFS.writeTimeInstant_(end,filter.end)};ol.format.WFS.writeLogicalFilter_=function(node,filter,objectStack){var item={node:node};var conditions=filter.conditions;for(var i=0,ii=conditions.length;i<ii;++i){var condition=conditions[i];ol.xml.pushSerializeAndPop(item,ol.format.WFS.GETFEATURE_SERIALIZERS_,ol.xml.makeSimpleNodeFactory(condition.getTagName()),[condition],objectStack)}};
ol.format.WFS.writeNotFilter_=function(node,filter,objectStack){var item={node:node};var condition=filter.condition;ol.xml.pushSerializeAndPop(item,ol.format.WFS.GETFEATURE_SERIALIZERS_,ol.xml.makeSimpleNodeFactory(condition.getTagName()),[condition],objectStack)};
ol.format.WFS.writeComparisonFilter_=function(node,filter,objectStack){if(filter.matchCase!==undefined)node.setAttribute("matchCase",filter.matchCase.toString());ol.format.WFS.writeOgcPropertyName_(node,filter.propertyName);ol.format.WFS.writeOgcLiteral_(node,""+filter.expression)};ol.format.WFS.writeIsNullFilter_=function(node,filter,objectStack){ol.format.WFS.writeOgcPropertyName_(node,filter.propertyName)};
ol.format.WFS.writeIsBetweenFilter_=function(node,filter,objectStack){ol.format.WFS.writeOgcPropertyName_(node,filter.propertyName);var lowerBoundary=ol.xml.createElementNS(ol.format.WFS.OGCNS,"LowerBoundary");node.appendChild(lowerBoundary);ol.format.WFS.writeOgcLiteral_(lowerBoundary,""+filter.lowerBoundary);var upperBoundary=ol.xml.createElementNS(ol.format.WFS.OGCNS,"UpperBoundary");node.appendChild(upperBoundary);ol.format.WFS.writeOgcLiteral_(upperBoundary,""+filter.upperBoundary)};
ol.format.WFS.writeIsLikeFilter_=function(node,filter,objectStack){node.setAttribute("wildCard",filter.wildCard);node.setAttribute("singleChar",filter.singleChar);node.setAttribute("escapeChar",filter.escapeChar);if(filter.matchCase!==undefined)node.setAttribute("matchCase",filter.matchCase.toString());ol.format.WFS.writeOgcPropertyName_(node,filter.propertyName);ol.format.WFS.writeOgcLiteral_(node,""+filter.pattern)};
ol.format.WFS.writeOgcExpression_=function(tagName,node,value){var property=ol.xml.createElementNS(ol.format.WFS.OGCNS,tagName);ol.format.XSD.writeStringTextNode(property,value);node.appendChild(property)};ol.format.WFS.writeOgcPropertyName_=function(node,value){ol.format.WFS.writeOgcExpression_("PropertyName",node,value)};ol.format.WFS.writeOgcLiteral_=function(node,value){ol.format.WFS.writeOgcExpression_("Literal",node,value)};
ol.format.WFS.writeTimeInstant_=function(node,time){var timeInstant=ol.xml.createElementNS(ol.format.GMLBase.GMLNS,"TimeInstant");node.appendChild(timeInstant);var timePosition=ol.xml.createElementNS(ol.format.GMLBase.GMLNS,"timePosition");timeInstant.appendChild(timePosition);ol.format.XSD.writeStringTextNode(timePosition,time)};
ol.format.WFS.GETFEATURE_SERIALIZERS_={"http://www.opengis.net/wfs":{"Query":ol.xml.makeChildAppender(ol.format.WFS.writeQuery_)},"http://www.opengis.net/ogc":{"During":ol.xml.makeChildAppender(ol.format.WFS.writeDuringFilter_),"And":ol.xml.makeChildAppender(ol.format.WFS.writeLogicalFilter_),"Or":ol.xml.makeChildAppender(ol.format.WFS.writeLogicalFilter_),"Not":ol.xml.makeChildAppender(ol.format.WFS.writeNotFilter_),"BBOX":ol.xml.makeChildAppender(ol.format.WFS.writeBboxFilter_),"Contains":ol.xml.makeChildAppender(ol.format.WFS.writeContainsFilter_),
"Intersects":ol.xml.makeChildAppender(ol.format.WFS.writeIntersectsFilter_),"Within":ol.xml.makeChildAppender(ol.format.WFS.writeWithinFilter_),"PropertyIsEqualTo":ol.xml.makeChildAppender(ol.format.WFS.writeComparisonFilter_),"PropertyIsNotEqualTo":ol.xml.makeChildAppender(ol.format.WFS.writeComparisonFilter_),"PropertyIsLessThan":ol.xml.makeChildAppender(ol.format.WFS.writeComparisonFilter_),"PropertyIsLessThanOrEqualTo":ol.xml.makeChildAppender(ol.format.WFS.writeComparisonFilter_),"PropertyIsGreaterThan":ol.xml.makeChildAppender(ol.format.WFS.writeComparisonFilter_),
"PropertyIsGreaterThanOrEqualTo":ol.xml.makeChildAppender(ol.format.WFS.writeComparisonFilter_),"PropertyIsNull":ol.xml.makeChildAppender(ol.format.WFS.writeIsNullFilter_),"PropertyIsBetween":ol.xml.makeChildAppender(ol.format.WFS.writeIsBetweenFilter_),"PropertyIsLike":ol.xml.makeChildAppender(ol.format.WFS.writeIsLikeFilter_)}};ol.format.WFS.writeFilter=function(filter){var child=ol.xml.createElementNS(ol.format.WFS.OGCNS,"Filter");ol.format.WFS.writeFilterCondition_(child,filter,[]);return child};
ol.format.WFS.writeGetFeature_=function(node,featureTypes,objectStack){var context=objectStack[objectStack.length-1];var item=ol.obj.assign({},context);item.node=node;ol.xml.pushSerializeAndPop(item,ol.format.WFS.GETFEATURE_SERIALIZERS_,ol.xml.makeSimpleNodeFactory("Query"),featureTypes,objectStack)};
ol.format.WFS.prototype.writeGetFeature=function(options){var node=ol.xml.createElementNS(ol.format.WFS.WFSNS,"GetFeature");node.setAttribute("service","WFS");node.setAttribute("version","1.1.0");var filter;if(options){if(options.handle)node.setAttribute("handle",options.handle);if(options.outputFormat)node.setAttribute("outputFormat",options.outputFormat);if(options.maxFeatures!==undefined)node.setAttribute("maxFeatures",options.maxFeatures);if(options.resultType)node.setAttribute("resultType",options.resultType);
if(options.startIndex!==undefined)node.setAttribute("startIndex",options.startIndex);if(options.count!==undefined)node.setAttribute("count",options.count);filter=options.filter;if(options.bbox){ol.asserts.assert(options.geometryName,12);var bbox=ol.format.filter.bbox(options.geometryName,options.bbox,options.srsName);if(filter)filter=ol.format.filter.and(filter,bbox);else filter=bbox}}ol.xml.setAttributeNS(node,"http://www.w3.org/2001/XMLSchema-instance","xsi:schemaLocation",this.schemaLocation_);
var context={node:node,"srsName":options.srsName,"featureNS":options.featureNS?options.featureNS:this.featureNS_,"featurePrefix":options.featurePrefix,"geometryName":options.geometryName,"filter":filter,"propertyNames":options.propertyNames?options.propertyNames:[]};ol.asserts.assert(Array.isArray(options.featureTypes),11);ol.format.WFS.writeGetFeature_(node,options.featureTypes,[context]);return node};
ol.format.WFS.prototype.writeTransaction=function(inserts,updates,deletes,options){var objectStack=[];var node=ol.xml.createElementNS(ol.format.WFS.WFSNS,"Transaction");var version=options.version?options.version:ol.format.WFS.DEFAULT_VERSION;var gmlVersion=version==="1.0.0"?2:3;node.setAttribute("service","WFS");node.setAttribute("version",version);var baseObj;var obj;if(options){baseObj=options.gmlOptions?options.gmlOptions:{};if(options.handle)node.setAttribute("handle",options.handle)}var schemaLocation=
ol.format.WFS.SCHEMA_LOCATIONS[version];ol.xml.setAttributeNS(node,"http://www.w3.org/2001/XMLSchema-instance","xsi:schemaLocation",schemaLocation);var featurePrefix=options.featurePrefix?options.featurePrefix:ol.format.WFS.FEATURE_PREFIX;if(inserts){obj={node:node,"featureNS":options.featureNS,"featureType":options.featureType,"featurePrefix":featurePrefix,"gmlVersion":gmlVersion,"hasZ":options.hasZ,"srsName":options.srsName};ol.obj.assign(obj,baseObj);ol.xml.pushSerializeAndPop(obj,ol.format.WFS.TRANSACTION_SERIALIZERS_,
ol.xml.makeSimpleNodeFactory("Insert"),inserts,objectStack)}if(updates){obj={node:node,"featureNS":options.featureNS,"featureType":options.featureType,"featurePrefix":featurePrefix,"gmlVersion":gmlVersion,"hasZ":options.hasZ,"srsName":options.srsName};ol.obj.assign(obj,baseObj);ol.xml.pushSerializeAndPop(obj,ol.format.WFS.TRANSACTION_SERIALIZERS_,ol.xml.makeSimpleNodeFactory("Update"),updates,objectStack)}if(deletes)ol.xml.pushSerializeAndPop({node:node,"featureNS":options.featureNS,"featureType":options.featureType,
"featurePrefix":featurePrefix,"gmlVersion":gmlVersion,"srsName":options.srsName},ol.format.WFS.TRANSACTION_SERIALIZERS_,ol.xml.makeSimpleNodeFactory("Delete"),deletes,objectStack);if(options.nativeElements)ol.xml.pushSerializeAndPop({node:node,"featureNS":options.featureNS,"featureType":options.featureType,"featurePrefix":featurePrefix,"gmlVersion":gmlVersion,"srsName":options.srsName},ol.format.WFS.TRANSACTION_SERIALIZERS_,ol.xml.makeSimpleNodeFactory("Native"),options.nativeElements,objectStack);
return node};ol.format.WFS.prototype.readProjection;ol.format.WFS.prototype.readProjectionFromDocument=function(doc){for(var n=doc.firstChild;n;n=n.nextSibling)if(n.nodeType==Node.ELEMENT_NODE)return this.readProjectionFromNode(n);return null};
ol.format.WFS.prototype.readProjectionFromNode=function(node){if(node.firstElementChild&&node.firstElementChild.firstElementChild){node=node.firstElementChild.firstElementChild;for(var n=node.firstElementChild;n;n=n.nextElementSibling)if(!(n.childNodes.length===0||n.childNodes.length===1&&n.firstChild.nodeType===3)){var objectStack=[{}];this.gmlFormat_.readGeometryElement(n,objectStack);return ol.proj.get(objectStack.pop().srsName)}}return null};goog.provide("ol.format.WKT");goog.require("ol");goog.require("ol.Feature");goog.require("ol.format.Feature");goog.require("ol.format.TextFeature");goog.require("ol.geom.GeometryCollection");goog.require("ol.geom.GeometryType");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.LineString");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.MultiPoint");goog.require("ol.geom.MultiPolygon");goog.require("ol.geom.Point");goog.require("ol.geom.Polygon");goog.require("ol.geom.SimpleGeometry");
ol.format.WKT=function(opt_options){var options=opt_options?opt_options:{};ol.format.TextFeature.call(this);this.splitCollection_=options.splitCollection!==undefined?options.splitCollection:false};ol.inherits(ol.format.WKT,ol.format.TextFeature);ol.format.WKT.EMPTY="EMPTY";ol.format.WKT.Z="Z";ol.format.WKT.M="M";ol.format.WKT.ZM="ZM";ol.format.WKT.encodePointGeometry_=function(geom){var coordinates=geom.getCoordinates();if(coordinates.length===0)return"";return coordinates.join(" ")};
ol.format.WKT.encodeMultiPointGeometry_=function(geom){var array=[];var components=geom.getPoints();for(var i=0,ii=components.length;i<ii;++i)array.push("("+ol.format.WKT.encodePointGeometry_(components[i])+")");return array.join(",")};ol.format.WKT.encodeGeometryCollectionGeometry_=function(geom){var array=[];var geoms=geom.getGeometries();for(var i=0,ii=geoms.length;i<ii;++i)array.push(ol.format.WKT.encode_(geoms[i]));return array.join(",")};
ol.format.WKT.encodeLineStringGeometry_=function(geom){var coordinates=geom.getCoordinates();var array=[];for(var i=0,ii=coordinates.length;i<ii;++i)array.push(coordinates[i].join(" "));return array.join(",")};ol.format.WKT.encodeMultiLineStringGeometry_=function(geom){var array=[];var components=geom.getLineStrings();for(var i=0,ii=components.length;i<ii;++i)array.push("("+ol.format.WKT.encodeLineStringGeometry_(components[i])+")");return array.join(",")};
ol.format.WKT.encodePolygonGeometry_=function(geom){var array=[];var rings=geom.getLinearRings();for(var i=0,ii=rings.length;i<ii;++i)array.push("("+ol.format.WKT.encodeLineStringGeometry_(rings[i])+")");return array.join(",")};ol.format.WKT.encodeMultiPolygonGeometry_=function(geom){var array=[];var components=geom.getPolygons();for(var i=0,ii=components.length;i<ii;++i)array.push("("+ol.format.WKT.encodePolygonGeometry_(components[i])+")");return array.join(",")};
ol.format.WKT.encodeGeometryLayout_=function(geom){var layout=geom.getLayout();var dimInfo="";if(layout===ol.geom.GeometryLayout.XYZ||layout===ol.geom.GeometryLayout.XYZM)dimInfo+=ol.format.WKT.Z;if(layout===ol.geom.GeometryLayout.XYM||layout===ol.geom.GeometryLayout.XYZM)dimInfo+=ol.format.WKT.M;return dimInfo};
ol.format.WKT.encode_=function(geom){var type=geom.getType();var geometryEncoder=ol.format.WKT.GeometryEncoder_[type];var enc=geometryEncoder(geom);type=type.toUpperCase();if(geom instanceof ol.geom.SimpleGeometry){var dimInfo=ol.format.WKT.encodeGeometryLayout_(geom);if(dimInfo.length>0)type+=" "+dimInfo}if(enc.length===0)return type+" "+ol.format.WKT.EMPTY;return type+"("+enc+")"};
ol.format.WKT.GeometryEncoder_={"Point":ol.format.WKT.encodePointGeometry_,"LineString":ol.format.WKT.encodeLineStringGeometry_,"Polygon":ol.format.WKT.encodePolygonGeometry_,"MultiPoint":ol.format.WKT.encodeMultiPointGeometry_,"MultiLineString":ol.format.WKT.encodeMultiLineStringGeometry_,"MultiPolygon":ol.format.WKT.encodeMultiPolygonGeometry_,"GeometryCollection":ol.format.WKT.encodeGeometryCollectionGeometry_};
ol.format.WKT.prototype.parse_=function(wkt){var lexer=new ol.format.WKT.Lexer(wkt);var parser=new ol.format.WKT.Parser(lexer);return parser.parse()};ol.format.WKT.prototype.readFeature;ol.format.WKT.prototype.readFeatureFromText=function(text,opt_options){var geom=this.readGeometryFromText(text,opt_options);if(geom){var feature=new ol.Feature;feature.setGeometry(geom);return feature}return null};ol.format.WKT.prototype.readFeatures;
ol.format.WKT.prototype.readFeaturesFromText=function(text,opt_options){var geometries=[];var geometry=this.readGeometryFromText(text,opt_options);if(this.splitCollection_&&geometry.getType()==ol.geom.GeometryType.GEOMETRY_COLLECTION)geometries=geometry.getGeometriesArray();else geometries=[geometry];var feature,features=[];for(var i=0,ii=geometries.length;i<ii;++i){feature=new ol.Feature;feature.setGeometry(geometries[i]);features.push(feature)}return features};ol.format.WKT.prototype.readGeometry;
ol.format.WKT.prototype.readGeometryFromText=function(text,opt_options){var geometry=this.parse_(text);if(geometry)return ol.format.Feature.transformWithOptions(geometry,false,opt_options);else return null};ol.format.WKT.prototype.writeFeature;ol.format.WKT.prototype.writeFeatureText=function(feature,opt_options){var geometry=feature.getGeometry();if(geometry)return this.writeGeometryText(geometry,opt_options);return""};ol.format.WKT.prototype.writeFeatures;
ol.format.WKT.prototype.writeFeaturesText=function(features,opt_options){if(features.length==1)return this.writeFeatureText(features[0],opt_options);var geometries=[];for(var i=0,ii=features.length;i<ii;++i)geometries.push(features[i].getGeometry());var collection=new ol.geom.GeometryCollection(geometries);return this.writeGeometryText(collection,opt_options)};ol.format.WKT.prototype.writeGeometry;
ol.format.WKT.prototype.writeGeometryText=function(geometry,opt_options){return ol.format.WKT.encode_(ol.format.Feature.transformWithOptions(geometry,true,opt_options))};ol.format.WKT.TokenType_={TEXT:1,LEFT_PAREN:2,RIGHT_PAREN:3,NUMBER:4,COMMA:5,EOF:6};ol.format.WKT.Lexer=function(wkt){this.wkt=wkt;this.index_=-1};ol.format.WKT.Lexer.prototype.isAlpha_=function(c){return c>="a"&&c<="z"||c>="A"&&c<="Z"};
ol.format.WKT.Lexer.prototype.isNumeric_=function(c,opt_decimal){var decimal=opt_decimal!==undefined?opt_decimal:false;return c>="0"&&c<="9"||c=="."&&!decimal};ol.format.WKT.Lexer.prototype.isWhiteSpace_=function(c){return c==" "||c=="\t"||c=="\r"||c=="\n"};ol.format.WKT.Lexer.prototype.nextChar_=function(){return this.wkt.charAt(++this.index_)};
ol.format.WKT.Lexer.prototype.nextToken=function(){var c=this.nextChar_();var token={position:this.index_,value:c};if(c=="(")token.type=ol.format.WKT.TokenType_.LEFT_PAREN;else if(c==",")token.type=ol.format.WKT.TokenType_.COMMA;else if(c==")")token.type=ol.format.WKT.TokenType_.RIGHT_PAREN;else if(this.isNumeric_(c)||c=="-"){token.type=ol.format.WKT.TokenType_.NUMBER;token.value=this.readNumber_()}else if(this.isAlpha_(c)){token.type=ol.format.WKT.TokenType_.TEXT;token.value=this.readText_()}else if(this.isWhiteSpace_(c))return this.nextToken();
else if(c==="")token.type=ol.format.WKT.TokenType_.EOF;else throw new Error("Unexpected character: "+c);return token};ol.format.WKT.Lexer.prototype.readNumber_=function(){var c,index=this.index_;var decimal=false;var scientificNotation=false;do{if(c==".")decimal=true;else if(c=="e"||c=="E")scientificNotation=true;c=this.nextChar_()}while(this.isNumeric_(c,decimal)||!scientificNotation&&(c=="e"||c=="E")||scientificNotation&&(c=="-"||c=="+"));return parseFloat(this.wkt.substring(index,this.index_--))};
ol.format.WKT.Lexer.prototype.readText_=function(){var c,index=this.index_;do c=this.nextChar_();while(this.isAlpha_(c));return this.wkt.substring(index,this.index_--).toUpperCase()};ol.format.WKT.Parser=function(lexer){this.lexer_=lexer;this.token_;this.layout_=ol.geom.GeometryLayout.XY};ol.format.WKT.Parser.prototype.consume_=function(){this.token_=this.lexer_.nextToken()};ol.format.WKT.Parser.prototype.isTokenType=function(type){var isMatch=this.token_.type==type;return isMatch};
ol.format.WKT.Parser.prototype.match=function(type){var isMatch=this.isTokenType(type);if(isMatch)this.consume_();return isMatch};ol.format.WKT.Parser.prototype.parse=function(){this.consume_();var geometry=this.parseGeometry_();return geometry};
ol.format.WKT.Parser.prototype.parseGeometryLayout_=function(){var layout=ol.geom.GeometryLayout.XY;var dimToken=this.token_;if(this.isTokenType(ol.format.WKT.TokenType_.TEXT)){var dimInfo=dimToken.value;if(dimInfo===ol.format.WKT.Z)layout=ol.geom.GeometryLayout.XYZ;else if(dimInfo===ol.format.WKT.M)layout=ol.geom.GeometryLayout.XYM;else if(dimInfo===ol.format.WKT.ZM)layout=ol.geom.GeometryLayout.XYZM;if(layout!==ol.geom.GeometryLayout.XY)this.consume_()}return layout};
ol.format.WKT.Parser.prototype.parseGeometry_=function(){var token=this.token_;if(this.match(ol.format.WKT.TokenType_.TEXT)){var geomType=token.value;this.layout_=this.parseGeometryLayout_();if(geomType==ol.geom.GeometryType.GEOMETRY_COLLECTION.toUpperCase()){var geometries=this.parseGeometryCollectionText_();return new ol.geom.GeometryCollection(geometries)}else{var parser=ol.format.WKT.Parser.GeometryParser_[geomType];var ctor=ol.format.WKT.Parser.GeometryConstructor_[geomType];if(!parser||!ctor)throw new Error("Invalid geometry type: "+
geomType);var coordinates=parser.call(this);return new ctor(coordinates,this.layout_)}}throw new Error(this.formatErrorMessage_());};
ol.format.WKT.Parser.prototype.parseGeometryCollectionText_=function(){if(this.match(ol.format.WKT.TokenType_.LEFT_PAREN)){var geometries=[];do geometries.push(this.parseGeometry_());while(this.match(ol.format.WKT.TokenType_.COMMA));if(this.match(ol.format.WKT.TokenType_.RIGHT_PAREN))return geometries}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_());};
ol.format.WKT.Parser.prototype.parsePointText_=function(){if(this.match(ol.format.WKT.TokenType_.LEFT_PAREN)){var coordinates=this.parsePoint_();if(this.match(ol.format.WKT.TokenType_.RIGHT_PAREN))return coordinates}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_());};
ol.format.WKT.Parser.prototype.parseLineStringText_=function(){if(this.match(ol.format.WKT.TokenType_.LEFT_PAREN)){var coordinates=this.parsePointList_();if(this.match(ol.format.WKT.TokenType_.RIGHT_PAREN))return coordinates}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_());};
ol.format.WKT.Parser.prototype.parsePolygonText_=function(){if(this.match(ol.format.WKT.TokenType_.LEFT_PAREN)){var coordinates=this.parseLineStringTextList_();if(this.match(ol.format.WKT.TokenType_.RIGHT_PAREN))return coordinates}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_());};
ol.format.WKT.Parser.prototype.parseMultiPointText_=function(){if(this.match(ol.format.WKT.TokenType_.LEFT_PAREN)){var coordinates;if(this.token_.type==ol.format.WKT.TokenType_.LEFT_PAREN)coordinates=this.parsePointTextList_();else coordinates=this.parsePointList_();if(this.match(ol.format.WKT.TokenType_.RIGHT_PAREN))return coordinates}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_());};
ol.format.WKT.Parser.prototype.parseMultiLineStringText_=function(){if(this.match(ol.format.WKT.TokenType_.LEFT_PAREN)){var coordinates=this.parseLineStringTextList_();if(this.match(ol.format.WKT.TokenType_.RIGHT_PAREN))return coordinates}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_());};
ol.format.WKT.Parser.prototype.parseMultiPolygonText_=function(){if(this.match(ol.format.WKT.TokenType_.LEFT_PAREN)){var coordinates=this.parsePolygonTextList_();if(this.match(ol.format.WKT.TokenType_.RIGHT_PAREN))return coordinates}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_());};
ol.format.WKT.Parser.prototype.parsePoint_=function(){var coordinates=[];var dimensions=this.layout_.length;for(var i=0;i<dimensions;++i){var token=this.token_;if(this.match(ol.format.WKT.TokenType_.NUMBER))coordinates.push(token.value);else break}if(coordinates.length==dimensions)return coordinates;throw new Error(this.formatErrorMessage_());};
ol.format.WKT.Parser.prototype.parsePointList_=function(){var coordinates=[this.parsePoint_()];while(this.match(ol.format.WKT.TokenType_.COMMA))coordinates.push(this.parsePoint_());return coordinates};ol.format.WKT.Parser.prototype.parsePointTextList_=function(){var coordinates=[this.parsePointText_()];while(this.match(ol.format.WKT.TokenType_.COMMA))coordinates.push(this.parsePointText_());return coordinates};
ol.format.WKT.Parser.prototype.parseLineStringTextList_=function(){var coordinates=[this.parseLineStringText_()];while(this.match(ol.format.WKT.TokenType_.COMMA))coordinates.push(this.parseLineStringText_());return coordinates};ol.format.WKT.Parser.prototype.parsePolygonTextList_=function(){var coordinates=[this.parsePolygonText_()];while(this.match(ol.format.WKT.TokenType_.COMMA))coordinates.push(this.parsePolygonText_());return coordinates};
ol.format.WKT.Parser.prototype.isEmptyGeometry_=function(){var isEmpty=this.isTokenType(ol.format.WKT.TokenType_.TEXT)&&this.token_.value==ol.format.WKT.EMPTY;if(isEmpty)this.consume_();return isEmpty};ol.format.WKT.Parser.prototype.formatErrorMessage_=function(){return"Unexpected `"+this.token_.value+"` at position "+this.token_.position+" in `"+this.lexer_.wkt+"`"};
ol.format.WKT.Parser.GeometryConstructor_={"POINT":ol.geom.Point,"LINESTRING":ol.geom.LineString,"POLYGON":ol.geom.Polygon,"MULTIPOINT":ol.geom.MultiPoint,"MULTILINESTRING":ol.geom.MultiLineString,"MULTIPOLYGON":ol.geom.MultiPolygon};
ol.format.WKT.Parser.GeometryParser_={"POINT":ol.format.WKT.Parser.prototype.parsePointText_,"LINESTRING":ol.format.WKT.Parser.prototype.parseLineStringText_,"POLYGON":ol.format.WKT.Parser.prototype.parsePolygonText_,"MULTIPOINT":ol.format.WKT.Parser.prototype.parseMultiPointText_,"MULTILINESTRING":ol.format.WKT.Parser.prototype.parseMultiLineStringText_,"MULTIPOLYGON":ol.format.WKT.Parser.prototype.parseMultiPolygonText_};goog.provide("ol.format.WMSCapabilities");goog.require("ol");goog.require("ol.format.XLink");goog.require("ol.format.XML");goog.require("ol.format.XSD");goog.require("ol.xml");ol.format.WMSCapabilities=function(){ol.format.XML.call(this);this.version=undefined};ol.inherits(ol.format.WMSCapabilities,ol.format.XML);ol.format.WMSCapabilities.prototype.read;
ol.format.WMSCapabilities.prototype.readFromDocument=function(doc){for(var n=doc.firstChild;n;n=n.nextSibling)if(n.nodeType==Node.ELEMENT_NODE)return this.readFromNode(n);return null};ol.format.WMSCapabilities.prototype.readFromNode=function(node){this.version=node.getAttribute("version").trim();var wmsCapabilityObject=ol.xml.pushParseAndPop({"version":this.version},ol.format.WMSCapabilities.PARSERS_,node,[]);return wmsCapabilityObject?wmsCapabilityObject:null};
ol.format.WMSCapabilities.readAttribution_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.ATTRIBUTION_PARSERS_,node,objectStack)};
ol.format.WMSCapabilities.readBoundingBox_=function(node,objectStack){var extent=[ol.format.XSD.readDecimalString(node.getAttribute("minx")),ol.format.XSD.readDecimalString(node.getAttribute("miny")),ol.format.XSD.readDecimalString(node.getAttribute("maxx")),ol.format.XSD.readDecimalString(node.getAttribute("maxy"))];var resolutions=[ol.format.XSD.readDecimalString(node.getAttribute("resx")),ol.format.XSD.readDecimalString(node.getAttribute("resy"))];return{"crs":node.getAttribute("CRS"),"extent":extent,
"res":resolutions}};
ol.format.WMSCapabilities.readEXGeographicBoundingBox_=function(node,objectStack){var geographicBoundingBox=ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS_,node,objectStack);if(!geographicBoundingBox)return undefined;var westBoundLongitude=geographicBoundingBox["westBoundLongitude"];var southBoundLatitude=geographicBoundingBox["southBoundLatitude"];var eastBoundLongitude=geographicBoundingBox["eastBoundLongitude"];var northBoundLatitude=geographicBoundingBox["northBoundLatitude"];
if(westBoundLongitude===undefined||southBoundLatitude===undefined||eastBoundLongitude===undefined||northBoundLatitude===undefined)return undefined;return[westBoundLongitude,southBoundLatitude,eastBoundLongitude,northBoundLatitude]};ol.format.WMSCapabilities.readCapability_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.CAPABILITY_PARSERS_,node,objectStack)};
ol.format.WMSCapabilities.readService_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.SERVICE_PARSERS_,node,objectStack)};ol.format.WMSCapabilities.readContactInformation_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.CONTACT_INFORMATION_PARSERS_,node,objectStack)};
ol.format.WMSCapabilities.readContactPersonPrimary_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.CONTACT_PERSON_PARSERS_,node,objectStack)};ol.format.WMSCapabilities.readContactAddress_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.CONTACT_ADDRESS_PARSERS_,node,objectStack)};
ol.format.WMSCapabilities.readException_=function(node,objectStack){return ol.xml.pushParseAndPop([],ol.format.WMSCapabilities.EXCEPTION_PARSERS_,node,objectStack)};ol.format.WMSCapabilities.readCapabilityLayer_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.LAYER_PARSERS_,node,objectStack)};
ol.format.WMSCapabilities.readLayer_=function(node,objectStack){var parentLayerObject=objectStack[objectStack.length-1];var layerObject=ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.LAYER_PARSERS_,node,objectStack);if(!layerObject)return undefined;var queryable=ol.format.XSD.readBooleanString(node.getAttribute("queryable"));if(queryable===undefined)queryable=parentLayerObject["queryable"];layerObject["queryable"]=queryable!==undefined?queryable:false;var cascaded=ol.format.XSD.readNonNegativeIntegerString(node.getAttribute("cascaded"));
if(cascaded===undefined)cascaded=parentLayerObject["cascaded"];layerObject["cascaded"]=cascaded;var opaque=ol.format.XSD.readBooleanString(node.getAttribute("opaque"));if(opaque===undefined)opaque=parentLayerObject["opaque"];layerObject["opaque"]=opaque!==undefined?opaque:false;var noSubsets=ol.format.XSD.readBooleanString(node.getAttribute("noSubsets"));if(noSubsets===undefined)noSubsets=parentLayerObject["noSubsets"];layerObject["noSubsets"]=noSubsets!==undefined?noSubsets:false;var fixedWidth=
ol.format.XSD.readDecimalString(node.getAttribute("fixedWidth"));if(!fixedWidth)fixedWidth=parentLayerObject["fixedWidth"];layerObject["fixedWidth"]=fixedWidth;var fixedHeight=ol.format.XSD.readDecimalString(node.getAttribute("fixedHeight"));if(!fixedHeight)fixedHeight=parentLayerObject["fixedHeight"];layerObject["fixedHeight"]=fixedHeight;var addKeys=["Style","CRS","AuthorityURL"];addKeys.forEach(function(key){if(key in parentLayerObject){var childValue=layerObject[key]||[];layerObject[key]=childValue.concat(parentLayerObject[key])}});
var replaceKeys=["EX_GeographicBoundingBox","BoundingBox","Dimension","Attribution","MinScaleDenominator","MaxScaleDenominator"];replaceKeys.forEach(function(key){if(!(key in layerObject)){var parentValue=parentLayerObject[key];layerObject[key]=parentValue}});return layerObject};
ol.format.WMSCapabilities.readDimension_=function(node,objectStack){var dimensionObject={"name":node.getAttribute("name"),"units":node.getAttribute("units"),"unitSymbol":node.getAttribute("unitSymbol"),"default":node.getAttribute("default"),"multipleValues":ol.format.XSD.readBooleanString(node.getAttribute("multipleValues")),"nearestValue":ol.format.XSD.readBooleanString(node.getAttribute("nearestValue")),"current":ol.format.XSD.readBooleanString(node.getAttribute("current")),"values":ol.format.XSD.readString(node)};
return dimensionObject};ol.format.WMSCapabilities.readFormatOnlineresource_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.FORMAT_ONLINERESOURCE_PARSERS_,node,objectStack)};ol.format.WMSCapabilities.readRequest_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.REQUEST_PARSERS_,node,objectStack)};
ol.format.WMSCapabilities.readDCPType_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.DCPTYPE_PARSERS_,node,objectStack)};ol.format.WMSCapabilities.readHTTP_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.HTTP_PARSERS_,node,objectStack)};ol.format.WMSCapabilities.readOperationType_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.OPERATIONTYPE_PARSERS_,node,objectStack)};
ol.format.WMSCapabilities.readSizedFormatOnlineresource_=function(node,objectStack){var formatOnlineresource=ol.format.WMSCapabilities.readFormatOnlineresource_(node,objectStack);if(formatOnlineresource){var size=[ol.format.XSD.readNonNegativeIntegerString(node.getAttribute("width")),ol.format.XSD.readNonNegativeIntegerString(node.getAttribute("height"))];formatOnlineresource["size"]=size;return formatOnlineresource}return undefined};
ol.format.WMSCapabilities.readAuthorityURL_=function(node,objectStack){var authorityObject=ol.format.WMSCapabilities.readFormatOnlineresource_(node,objectStack);if(authorityObject){authorityObject["name"]=node.getAttribute("name");return authorityObject}return undefined};ol.format.WMSCapabilities.readMetadataURL_=function(node,objectStack){var metadataObject=ol.format.WMSCapabilities.readFormatOnlineresource_(node,objectStack);if(metadataObject){metadataObject["type"]=node.getAttribute("type");return metadataObject}return undefined};
ol.format.WMSCapabilities.readStyle_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMSCapabilities.STYLE_PARSERS_,node,objectStack)};ol.format.WMSCapabilities.readKeywordList_=function(node,objectStack){return ol.xml.pushParseAndPop([],ol.format.WMSCapabilities.KEYWORDLIST_PARSERS_,node,objectStack)};ol.format.WMSCapabilities.NAMESPACE_URIS_=[null,"http://www.opengis.net/wms"];
ol.format.WMSCapabilities.PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"Service":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readService_),"Capability":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readCapability_)});
ol.format.WMSCapabilities.CAPABILITY_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"Request":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readRequest_),"Exception":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readException_),"Layer":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readCapabilityLayer_)});
ol.format.WMSCapabilities.SERVICE_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"Name":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Title":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Abstract":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"KeywordList":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readKeywordList_),"OnlineResource":ol.xml.makeObjectPropertySetter(ol.format.XLink.readHref),"ContactInformation":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readContactInformation_),
"Fees":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"AccessConstraints":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"LayerLimit":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"MaxWidth":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"MaxHeight":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger)});
ol.format.WMSCapabilities.CONTACT_INFORMATION_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"ContactPersonPrimary":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readContactPersonPrimary_),"ContactPosition":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"ContactAddress":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readContactAddress_),"ContactVoiceTelephone":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"ContactFacsimileTelephone":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
"ContactElectronicMailAddress":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)});ol.format.WMSCapabilities.CONTACT_PERSON_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"ContactPerson":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"ContactOrganization":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)});
ol.format.WMSCapabilities.CONTACT_ADDRESS_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"AddressType":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Address":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"City":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"StateOrProvince":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"PostCode":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Country":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)});
ol.format.WMSCapabilities.EXCEPTION_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"Format":ol.xml.makeArrayPusher(ol.format.XSD.readString)});
ol.format.WMSCapabilities.LAYER_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"Name":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Title":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Abstract":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"KeywordList":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readKeywordList_),"CRS":ol.xml.makeObjectPropertyPusher(ol.format.XSD.readString),"EX_GeographicBoundingBox":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readEXGeographicBoundingBox_),
"BoundingBox":ol.xml.makeObjectPropertyPusher(ol.format.WMSCapabilities.readBoundingBox_),"Dimension":ol.xml.makeObjectPropertyPusher(ol.format.WMSCapabilities.readDimension_),"Attribution":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readAttribution_),"AuthorityURL":ol.xml.makeObjectPropertyPusher(ol.format.WMSCapabilities.readAuthorityURL_),"Identifier":ol.xml.makeObjectPropertyPusher(ol.format.XSD.readString),"MetadataURL":ol.xml.makeObjectPropertyPusher(ol.format.WMSCapabilities.readMetadataURL_),
"DataURL":ol.xml.makeObjectPropertyPusher(ol.format.WMSCapabilities.readFormatOnlineresource_),"FeatureListURL":ol.xml.makeObjectPropertyPusher(ol.format.WMSCapabilities.readFormatOnlineresource_),"Style":ol.xml.makeObjectPropertyPusher(ol.format.WMSCapabilities.readStyle_),"MinScaleDenominator":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"MaxScaleDenominator":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"Layer":ol.xml.makeObjectPropertyPusher(ol.format.WMSCapabilities.readLayer_)});
ol.format.WMSCapabilities.ATTRIBUTION_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"Title":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"OnlineResource":ol.xml.makeObjectPropertySetter(ol.format.XLink.readHref),"LogoURL":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readSizedFormatOnlineresource_)});
ol.format.WMSCapabilities.EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"westBoundLongitude":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"eastBoundLongitude":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"southBoundLatitude":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"northBoundLatitude":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal)});
ol.format.WMSCapabilities.REQUEST_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"GetCapabilities":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readOperationType_),"GetMap":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readOperationType_),"GetFeatureInfo":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readOperationType_)});
ol.format.WMSCapabilities.OPERATIONTYPE_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"Format":ol.xml.makeObjectPropertyPusher(ol.format.XSD.readString),"DCPType":ol.xml.makeObjectPropertyPusher(ol.format.WMSCapabilities.readDCPType_)});ol.format.WMSCapabilities.DCPTYPE_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"HTTP":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readHTTP_)});
ol.format.WMSCapabilities.HTTP_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"Get":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readFormatOnlineresource_),"Post":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readFormatOnlineresource_)});
ol.format.WMSCapabilities.STYLE_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"Name":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Title":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Abstract":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"LegendURL":ol.xml.makeObjectPropertyPusher(ol.format.WMSCapabilities.readSizedFormatOnlineresource_),"StyleSheetURL":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readFormatOnlineresource_),
"StyleURL":ol.xml.makeObjectPropertySetter(ol.format.WMSCapabilities.readFormatOnlineresource_)});ol.format.WMSCapabilities.FORMAT_ONLINERESOURCE_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"Format":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"OnlineResource":ol.xml.makeObjectPropertySetter(ol.format.XLink.readHref)});ol.format.WMSCapabilities.KEYWORDLIST_PARSERS_=ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_,{"Keyword":ol.xml.makeArrayPusher(ol.format.XSD.readString)});goog.provide("ol.format.WMSGetFeatureInfo");goog.require("ol");goog.require("ol.array");goog.require("ol.format.GML2");goog.require("ol.format.XMLFeature");goog.require("ol.obj");goog.require("ol.xml");ol.format.WMSGetFeatureInfo=function(opt_options){var options=opt_options?opt_options:{};this.featureNS_="http://mapserver.gis.umn.edu/mapserver";this.gmlFormat_=new ol.format.GML2;this.layers_=options.layers?options.layers:null;ol.format.XMLFeature.call(this)};
ol.inherits(ol.format.WMSGetFeatureInfo,ol.format.XMLFeature);ol.format.WMSGetFeatureInfo.featureIdentifier_="_feature";ol.format.WMSGetFeatureInfo.layerIdentifier_="_layer";ol.format.WMSGetFeatureInfo.prototype.getLayers=function(){return this.layers_};ol.format.WMSGetFeatureInfo.prototype.setLayers=function(layers){this.layers_=layers};
ol.format.WMSGetFeatureInfo.prototype.readFeatures_=function(node,objectStack){node.setAttribute("namespaceURI",this.featureNS_);var localName=node.localName;var features=[];if(node.childNodes.length===0)return features;if(localName=="msGMLOutput")for(var i=0,ii=node.childNodes.length;i<ii;i++){var layer=node.childNodes[i];if(layer.nodeType!==Node.ELEMENT_NODE)continue;var context=objectStack[0];var toRemove=ol.format.WMSGetFeatureInfo.layerIdentifier_;var layerName=layer.localName.replace(toRemove,
"");if(this.layers_&&!ol.array.includes(this.layers_,layerName))continue;var featureType=layerName+ol.format.WMSGetFeatureInfo.featureIdentifier_;context["featureType"]=featureType;context["featureNS"]=this.featureNS_;var parsers={};parsers[featureType]=ol.xml.makeArrayPusher(this.gmlFormat_.readFeatureElement,this.gmlFormat_);var parsersNS=ol.xml.makeStructureNS([context["featureNS"],null],parsers);layer.setAttribute("namespaceURI",this.featureNS_);var layerFeatures=ol.xml.pushParseAndPop([],parsersNS,
layer,objectStack,this.gmlFormat_);if(layerFeatures)ol.array.extend(features,layerFeatures)}if(localName=="FeatureCollection"){var gmlFeatures=ol.xml.pushParseAndPop([],this.gmlFormat_.FEATURE_COLLECTION_PARSERS,node,[{}],this.gmlFormat_);if(gmlFeatures)features=gmlFeatures}return features};ol.format.WMSGetFeatureInfo.prototype.readFeatures;
ol.format.WMSGetFeatureInfo.prototype.readFeaturesFromNode=function(node,opt_options){var options={};if(opt_options)ol.obj.assign(options,this.getReadOptions(node,opt_options));return this.readFeatures_(node,[options])};ol.format.WMSGetFeatureInfo.prototype.writeFeatureNode=function(feature,opt_options){};ol.format.WMSGetFeatureInfo.prototype.writeFeaturesNode=function(features,opt_options){};ol.format.WMSGetFeatureInfo.prototype.writeGeometryNode=function(geometry,opt_options){};goog.provide("ol.format.WMTSCapabilities");goog.require("ol");goog.require("ol.extent");goog.require("ol.format.OWS");goog.require("ol.format.XLink");goog.require("ol.format.XML");goog.require("ol.format.XSD");goog.require("ol.xml");ol.format.WMTSCapabilities=function(){ol.format.XML.call(this);this.owsParser_=new ol.format.OWS};ol.inherits(ol.format.WMTSCapabilities,ol.format.XML);ol.format.WMTSCapabilities.prototype.read;
ol.format.WMTSCapabilities.prototype.readFromDocument=function(doc){for(var n=doc.firstChild;n;n=n.nextSibling)if(n.nodeType==Node.ELEMENT_NODE)return this.readFromNode(n);return null};
ol.format.WMTSCapabilities.prototype.readFromNode=function(node){var version=node.getAttribute("version").trim();var WMTSCapabilityObject=this.owsParser_.readFromNode(node);if(!WMTSCapabilityObject)return null;WMTSCapabilityObject["version"]=version;WMTSCapabilityObject=ol.xml.pushParseAndPop(WMTSCapabilityObject,ol.format.WMTSCapabilities.PARSERS_,node,[]);return WMTSCapabilityObject?WMTSCapabilityObject:null};
ol.format.WMTSCapabilities.readContents_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMTSCapabilities.CONTENTS_PARSERS_,node,objectStack)};ol.format.WMTSCapabilities.readLayer_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMTSCapabilities.LAYER_PARSERS_,node,objectStack)};ol.format.WMTSCapabilities.readTileMatrixSet_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMTSCapabilities.TMS_PARSERS_,node,objectStack)};
ol.format.WMTSCapabilities.readStyle_=function(node,objectStack){var style=ol.xml.pushParseAndPop({},ol.format.WMTSCapabilities.STYLE_PARSERS_,node,objectStack);if(!style)return undefined;var isDefault=node.getAttribute("isDefault")==="true";style["isDefault"]=isDefault;return style};ol.format.WMTSCapabilities.readTileMatrixSetLink_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMTSCapabilities.TMS_LINKS_PARSERS_,node,objectStack)};
ol.format.WMTSCapabilities.readDimensions_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMTSCapabilities.DIMENSION_PARSERS_,node,objectStack)};
ol.format.WMTSCapabilities.readResourceUrl_=function(node,objectStack){var format=node.getAttribute("format");var template=node.getAttribute("template");var resourceType=node.getAttribute("resourceType");var resource={};if(format)resource["format"]=format;if(template)resource["template"]=template;if(resourceType)resource["resourceType"]=resourceType;return resource};
ol.format.WMTSCapabilities.readWgs84BoundingBox_=function(node,objectStack){var coordinates=ol.xml.pushParseAndPop([],ol.format.WMTSCapabilities.WGS84_BBOX_READERS_,node,objectStack);if(coordinates.length!=2)return undefined;return ol.extent.boundingExtent(coordinates)};ol.format.WMTSCapabilities.readLegendUrl_=function(node,objectStack){var legend={};legend["format"]=node.getAttribute("format");legend["href"]=ol.format.XLink.readHref(node);return legend};
ol.format.WMTSCapabilities.readCoordinates_=function(node,objectStack){var coordinates=ol.format.XSD.readString(node).split(" ");if(!coordinates||coordinates.length!=2)return undefined;var x=+coordinates[0];var y=+coordinates[1];if(isNaN(x)||isNaN(y))return undefined;return[x,y]};ol.format.WMTSCapabilities.readTileMatrix_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMTSCapabilities.TM_PARSERS_,node,objectStack)};
ol.format.WMTSCapabilities.readTileMatrixLimitsList_=function(node,objectStack){return ol.xml.pushParseAndPop([],ol.format.WMTSCapabilities.TMS_LIMITS_LIST_PARSERS_,node,objectStack)};ol.format.WMTSCapabilities.readTileMatrixLimits_=function(node,objectStack){return ol.xml.pushParseAndPop({},ol.format.WMTSCapabilities.TMS_LIMITS_PARSERS_,node,objectStack)};ol.format.WMTSCapabilities.NAMESPACE_URIS_=[null,"http://www.opengis.net/wmts/1.0"];ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_=[null,"http://www.opengis.net/ows/1.1"];
ol.format.WMTSCapabilities.PARSERS_=ol.xml.makeStructureNS(ol.format.WMTSCapabilities.NAMESPACE_URIS_,{"Contents":ol.xml.makeObjectPropertySetter(ol.format.WMTSCapabilities.readContents_)});ol.format.WMTSCapabilities.CONTENTS_PARSERS_=ol.xml.makeStructureNS(ol.format.WMTSCapabilities.NAMESPACE_URIS_,{"Layer":ol.xml.makeObjectPropertyPusher(ol.format.WMTSCapabilities.readLayer_),"TileMatrixSet":ol.xml.makeObjectPropertyPusher(ol.format.WMTSCapabilities.readTileMatrixSet_)});
ol.format.WMTSCapabilities.LAYER_PARSERS_=ol.xml.makeStructureNS(ol.format.WMTSCapabilities.NAMESPACE_URIS_,{"Style":ol.xml.makeObjectPropertyPusher(ol.format.WMTSCapabilities.readStyle_),"Format":ol.xml.makeObjectPropertyPusher(ol.format.XSD.readString),"TileMatrixSetLink":ol.xml.makeObjectPropertyPusher(ol.format.WMTSCapabilities.readTileMatrixSetLink_),"Dimension":ol.xml.makeObjectPropertyPusher(ol.format.WMTSCapabilities.readDimensions_),"ResourceURL":ol.xml.makeObjectPropertyPusher(ol.format.WMTSCapabilities.readResourceUrl_)},
ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_,{"Title":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Abstract":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"WGS84BoundingBox":ol.xml.makeObjectPropertySetter(ol.format.WMTSCapabilities.readWgs84BoundingBox_),"Identifier":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)}));
ol.format.WMTSCapabilities.STYLE_PARSERS_=ol.xml.makeStructureNS(ol.format.WMTSCapabilities.NAMESPACE_URIS_,{"LegendURL":ol.xml.makeObjectPropertyPusher(ol.format.WMTSCapabilities.readLegendUrl_)},ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_,{"Title":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Identifier":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)}));
ol.format.WMTSCapabilities.TMS_LINKS_PARSERS_=ol.xml.makeStructureNS(ol.format.WMTSCapabilities.NAMESPACE_URIS_,{"TileMatrixSet":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"TileMatrixSetLimits":ol.xml.makeObjectPropertySetter(ol.format.WMTSCapabilities.readTileMatrixLimitsList_)});ol.format.WMTSCapabilities.TMS_LIMITS_LIST_PARSERS_=ol.xml.makeStructureNS(ol.format.WMTSCapabilities.NAMESPACE_URIS_,{"TileMatrixLimits":ol.xml.makeArrayPusher(ol.format.WMTSCapabilities.readTileMatrixLimits_)});
ol.format.WMTSCapabilities.TMS_LIMITS_PARSERS_=ol.xml.makeStructureNS(ol.format.WMTSCapabilities.NAMESPACE_URIS_,{"TileMatrix":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"MinTileRow":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"MaxTileRow":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"MinTileCol":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"MaxTileCol":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger)});
ol.format.WMTSCapabilities.DIMENSION_PARSERS_=ol.xml.makeStructureNS(ol.format.WMTSCapabilities.NAMESPACE_URIS_,{"Default":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Value":ol.xml.makeObjectPropertyPusher(ol.format.XSD.readString)},ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_,{"Identifier":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)}));
ol.format.WMTSCapabilities.WGS84_BBOX_READERS_=ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_,{"LowerCorner":ol.xml.makeArrayPusher(ol.format.WMTSCapabilities.readCoordinates_),"UpperCorner":ol.xml.makeArrayPusher(ol.format.WMTSCapabilities.readCoordinates_)});
ol.format.WMTSCapabilities.TMS_PARSERS_=ol.xml.makeStructureNS(ol.format.WMTSCapabilities.NAMESPACE_URIS_,{"WellKnownScaleSet":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"TileMatrix":ol.xml.makeObjectPropertyPusher(ol.format.WMTSCapabilities.readTileMatrix_)},ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_,{"SupportedCRS":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),"Identifier":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)}));
ol.format.WMTSCapabilities.TM_PARSERS_=ol.xml.makeStructureNS(ol.format.WMTSCapabilities.NAMESPACE_URIS_,{"TopLeftCorner":ol.xml.makeObjectPropertySetter(ol.format.WMTSCapabilities.readCoordinates_),"ScaleDenominator":ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),"TileWidth":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"TileHeight":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),"MatrixWidth":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),
"MatrixHeight":ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger)},ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_,{"Identifier":ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)}));goog.provide("ol.GeolocationProperty");ol.GeolocationProperty={ACCURACY:"accuracy",ACCURACY_GEOMETRY:"accuracyGeometry",ALTITUDE:"altitude",ALTITUDE_ACCURACY:"altitudeAccuracy",HEADING:"heading",POSITION:"position",PROJECTION:"projection",SPEED:"speed",TRACKING:"tracking",TRACKING_OPTIONS:"trackingOptions"};goog.provide("ol.Geolocation");goog.require("ol");goog.require("ol.GeolocationProperty");goog.require("ol.Object");goog.require("ol.Sphere");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.geom.Polygon");goog.require("ol.has");goog.require("ol.math");goog.require("ol.proj");goog.require("ol.proj.EPSG4326");
ol.Geolocation=function(opt_options){ol.Object.call(this);var options=opt_options||{};this.position_=null;this.transform_=ol.proj.identityTransform;this.sphere_=new ol.Sphere(ol.proj.EPSG4326.RADIUS);this.watchId_=undefined;ol.events.listen(this,ol.Object.getChangeEventType(ol.GeolocationProperty.PROJECTION),this.handleProjectionChanged_,this);ol.events.listen(this,ol.Object.getChangeEventType(ol.GeolocationProperty.TRACKING),this.handleTrackingChanged_,this);if(options.projection!==undefined)this.setProjection(options.projection);
if(options.trackingOptions!==undefined)this.setTrackingOptions(options.trackingOptions);this.setTracking(options.tracking!==undefined?options.tracking:false)};ol.inherits(ol.Geolocation,ol.Object);ol.Geolocation.prototype.disposeInternal=function(){this.setTracking(false);ol.Object.prototype.disposeInternal.call(this)};
ol.Geolocation.prototype.handleProjectionChanged_=function(){var projection=this.getProjection();if(projection){this.transform_=ol.proj.getTransformFromProjections(ol.proj.get("EPSG:4326"),projection);if(this.position_)this.set(ol.GeolocationProperty.POSITION,this.transform_(this.position_))}};
ol.Geolocation.prototype.handleTrackingChanged_=function(){if(ol.has.GEOLOCATION){var tracking=this.getTracking();if(tracking&&this.watchId_===undefined)this.watchId_=navigator.geolocation.watchPosition(this.positionChange_.bind(this),this.positionError_.bind(this),this.getTrackingOptions());else if(!tracking&&this.watchId_!==undefined){navigator.geolocation.clearWatch(this.watchId_);this.watchId_=undefined}}};
ol.Geolocation.prototype.positionChange_=function(position){var coords=position.coords;this.set(ol.GeolocationProperty.ACCURACY,coords.accuracy);this.set(ol.GeolocationProperty.ALTITUDE,coords.altitude===null?undefined:coords.altitude);this.set(ol.GeolocationProperty.ALTITUDE_ACCURACY,coords.altitudeAccuracy===null?undefined:coords.altitudeAccuracy);this.set(ol.GeolocationProperty.HEADING,coords.heading===null?undefined:ol.math.toRadians(coords.heading));if(!this.position_)this.position_=[coords.longitude,
coords.latitude];else{this.position_[0]=coords.longitude;this.position_[1]=coords.latitude}var projectedPosition=this.transform_(this.position_);this.set(ol.GeolocationProperty.POSITION,projectedPosition);this.set(ol.GeolocationProperty.SPEED,coords.speed===null?undefined:coords.speed);var geometry=ol.geom.Polygon.circular(this.sphere_,this.position_,coords.accuracy);geometry.applyTransform(this.transform_);this.set(ol.GeolocationProperty.ACCURACY_GEOMETRY,geometry);this.changed()};
ol.Geolocation.prototype.positionError_=function(error){error.type=ol.events.EventType.ERROR;this.setTracking(false);this.dispatchEvent(error)};ol.Geolocation.prototype.getAccuracy=function(){return this.get(ol.GeolocationProperty.ACCURACY)};ol.Geolocation.prototype.getAccuracyGeometry=function(){return this.get(ol.GeolocationProperty.ACCURACY_GEOMETRY)||null};ol.Geolocation.prototype.getAltitude=function(){return this.get(ol.GeolocationProperty.ALTITUDE)};
ol.Geolocation.prototype.getAltitudeAccuracy=function(){return this.get(ol.GeolocationProperty.ALTITUDE_ACCURACY)};ol.Geolocation.prototype.getHeading=function(){return this.get(ol.GeolocationProperty.HEADING)};ol.Geolocation.prototype.getPosition=function(){return this.get(ol.GeolocationProperty.POSITION)};ol.Geolocation.prototype.getProjection=function(){return this.get(ol.GeolocationProperty.PROJECTION)};ol.Geolocation.prototype.getSpeed=function(){return this.get(ol.GeolocationProperty.SPEED)};
ol.Geolocation.prototype.getTracking=function(){return this.get(ol.GeolocationProperty.TRACKING)};ol.Geolocation.prototype.getTrackingOptions=function(){return this.get(ol.GeolocationProperty.TRACKING_OPTIONS)};ol.Geolocation.prototype.setProjection=function(projection){this.set(ol.GeolocationProperty.PROJECTION,ol.proj.get(projection))};ol.Geolocation.prototype.setTracking=function(tracking){this.set(ol.GeolocationProperty.TRACKING,tracking)};
ol.Geolocation.prototype.setTrackingOptions=function(options){this.set(ol.GeolocationProperty.TRACKING_OPTIONS,options)};goog.provide("ol.geom.Circle");goog.require("ol");goog.require("ol.extent");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.GeometryType");goog.require("ol.geom.SimpleGeometry");goog.require("ol.geom.flat.deflate");ol.geom.Circle=function(center,opt_radius,opt_layout){ol.geom.SimpleGeometry.call(this);var radius=opt_radius?opt_radius:0;this.setCenterAndRadius(center,radius,opt_layout)};ol.inherits(ol.geom.Circle,ol.geom.SimpleGeometry);
ol.geom.Circle.prototype.clone=function(){var circle=new ol.geom.Circle(null);circle.setFlatCoordinates(this.layout,this.flatCoordinates.slice());return circle};
ol.geom.Circle.prototype.closestPointXY=function(x,y,closestPoint,minSquaredDistance){var flatCoordinates=this.flatCoordinates;var dx=x-flatCoordinates[0];var dy=y-flatCoordinates[1];var squaredDistance=dx*dx+dy*dy;if(squaredDistance<minSquaredDistance){var i;if(squaredDistance===0)for(i=0;i<this.stride;++i)closestPoint[i]=flatCoordinates[i];else{var delta=this.getRadius()/Math.sqrt(squaredDistance);closestPoint[0]=flatCoordinates[0]+delta*dx;closestPoint[1]=flatCoordinates[1]+delta*dy;for(i=2;i<
this.stride;++i)closestPoint[i]=flatCoordinates[i]}closestPoint.length=this.stride;return squaredDistance}else return minSquaredDistance};ol.geom.Circle.prototype.containsXY=function(x,y){var flatCoordinates=this.flatCoordinates;var dx=x-flatCoordinates[0];var dy=y-flatCoordinates[1];return dx*dx+dy*dy<=this.getRadiusSquared_()};ol.geom.Circle.prototype.getCenter=function(){return this.flatCoordinates.slice(0,this.stride)};
ol.geom.Circle.prototype.computeExtent=function(extent){var flatCoordinates=this.flatCoordinates;var radius=flatCoordinates[this.stride]-flatCoordinates[0];return ol.extent.createOrUpdate(flatCoordinates[0]-radius,flatCoordinates[1]-radius,flatCoordinates[0]+radius,flatCoordinates[1]+radius,extent)};ol.geom.Circle.prototype.getRadius=function(){return Math.sqrt(this.getRadiusSquared_())};
ol.geom.Circle.prototype.getRadiusSquared_=function(){var dx=this.flatCoordinates[this.stride]-this.flatCoordinates[0];var dy=this.flatCoordinates[this.stride+1]-this.flatCoordinates[1];return dx*dx+dy*dy};ol.geom.Circle.prototype.getType=function(){return ol.geom.GeometryType.CIRCLE};
ol.geom.Circle.prototype.intersectsExtent=function(extent){var circleExtent=this.getExtent();if(ol.extent.intersects(extent,circleExtent)){var center=this.getCenter();if(extent[0]<=center[0]&&extent[2]>=center[0])return true;if(extent[1]<=center[1]&&extent[3]>=center[1])return true;return ol.extent.forEachCorner(extent,this.intersectsCoordinate,this)}return false};
ol.geom.Circle.prototype.setCenter=function(center){var stride=this.stride;var radius=this.flatCoordinates[stride]-this.flatCoordinates[0];var flatCoordinates=center.slice();flatCoordinates[stride]=flatCoordinates[0]+radius;var i;for(i=1;i<stride;++i)flatCoordinates[stride+i]=center[i];this.setFlatCoordinates(this.layout,flatCoordinates)};
ol.geom.Circle.prototype.setCenterAndRadius=function(center,radius,opt_layout){if(!center)this.setFlatCoordinates(ol.geom.GeometryLayout.XY,null);else{this.setLayout(opt_layout,center,0);if(!this.flatCoordinates)this.flatCoordinates=[];var flatCoordinates=this.flatCoordinates;var offset=ol.geom.flat.deflate.coordinate(flatCoordinates,0,center,this.stride);flatCoordinates[offset++]=flatCoordinates[0]+radius;var i,ii;for(i=1,ii=this.stride;i<ii;++i)flatCoordinates[offset++]=flatCoordinates[i];flatCoordinates.length=
offset;this.changed()}};ol.geom.Circle.prototype.getCoordinates=function(){};ol.geom.Circle.prototype.setCoordinates=function(coordinates,opt_layout){};ol.geom.Circle.prototype.setFlatCoordinates=function(layout,flatCoordinates){this.setFlatCoordinatesInternal(layout,flatCoordinates);this.changed()};ol.geom.Circle.prototype.setRadius=function(radius){this.flatCoordinates[this.stride]=this.flatCoordinates[0]+radius;this.changed()};ol.geom.Circle.prototype.transform;goog.provide("ol.geom.flat.geodesic");goog.require("ol.math");goog.require("ol.proj");
ol.geom.flat.geodesic.line_=function(interpolate,transform,squaredTolerance){var flatCoordinates=[];var geoA=interpolate(0);var geoB=interpolate(1);var a=transform(geoA);var b=transform(geoB);var geoStack=[geoB,geoA];var stack=[b,a];var fractionStack=[1,0];var fractions={};var maxIterations=1E5;var geoM,m,fracA,fracB,fracM,key;while(--maxIterations>0&&fractionStack.length>0){fracA=fractionStack.pop();geoA=geoStack.pop();a=stack.pop();key=fracA.toString();if(!(key in fractions)){flatCoordinates.push(a[0],
a[1]);fractions[key]=true}fracB=fractionStack.pop();geoB=geoStack.pop();b=stack.pop();fracM=(fracA+fracB)/2;geoM=interpolate(fracM);m=transform(geoM);if(ol.math.squaredSegmentDistance(m[0],m[1],a[0],a[1],b[0],b[1])<squaredTolerance){flatCoordinates.push(b[0],b[1]);key=fracB.toString();fractions[key]=true}else{fractionStack.push(fracB,fracM,fracM,fracA);stack.push(b,m,m,a);geoStack.push(geoB,geoM,geoM,geoA)}}return flatCoordinates};
ol.geom.flat.geodesic.greatCircleArc=function(lon1,lat1,lon2,lat2,projection,squaredTolerance){var geoProjection=ol.proj.get("EPSG:4326");var cosLat1=Math.cos(ol.math.toRadians(lat1));var sinLat1=Math.sin(ol.math.toRadians(lat1));var cosLat2=Math.cos(ol.math.toRadians(lat2));var sinLat2=Math.sin(ol.math.toRadians(lat2));var cosDeltaLon=Math.cos(ol.math.toRadians(lon2-lon1));var sinDeltaLon=Math.sin(ol.math.toRadians(lon2-lon1));var d=sinLat1*sinLat2+cosLat1*cosLat2*cosDeltaLon;return ol.geom.flat.geodesic.line_(function(frac){if(1<=
d)return[lon2,lat2];var D=frac*Math.acos(d);var cosD=Math.cos(D);var sinD=Math.sin(D);var y=sinDeltaLon*cosLat2;var x=cosLat1*sinLat2-sinLat1*cosLat2*cosDeltaLon;var theta=Math.atan2(y,x);var lat=Math.asin(sinLat1*cosD+cosLat1*sinD*Math.cos(theta));var lon=ol.math.toRadians(lon1)+Math.atan2(Math.sin(theta)*sinD*cosLat1,cosD-sinLat1*Math.sin(lat));return[ol.math.toDegrees(lon),ol.math.toDegrees(lat)]},ol.proj.getTransform(geoProjection,projection),squaredTolerance)};
ol.geom.flat.geodesic.meridian=function(lon,lat1,lat2,projection,squaredTolerance){var epsg4326Projection=ol.proj.get("EPSG:4326");return ol.geom.flat.geodesic.line_(function(frac){return[lon,lat1+(lat2-lat1)*frac]},ol.proj.getTransform(epsg4326Projection,projection),squaredTolerance)};
ol.geom.flat.geodesic.parallel=function(lat,lon1,lon2,projection,squaredTolerance){var epsg4326Projection=ol.proj.get("EPSG:4326");return ol.geom.flat.geodesic.line_(function(frac){return[lon1+(lon2-lon1)*frac,lat]},ol.proj.getTransform(epsg4326Projection,projection),squaredTolerance)};goog.provide("ol.geom.flat.topology");goog.require("ol.geom.flat.area");ol.geom.flat.topology.lineStringIsClosed=function(flatCoordinates,offset,end,stride){var lastCoord=end-stride;if(flatCoordinates[offset]===flatCoordinates[lastCoord]&&flatCoordinates[offset+1]===flatCoordinates[lastCoord+1]&&(end-offset)/stride>3)return!!ol.geom.flat.area.linearRing(flatCoordinates,offset,end,stride);return false};goog.provide("ol.Graticule");goog.require("ol.coordinate");goog.require("ol.extent");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.LineString");goog.require("ol.geom.Point");goog.require("ol.geom.flat.geodesic");goog.require("ol.math");goog.require("ol.proj");goog.require("ol.render.EventType");goog.require("ol.style.Fill");goog.require("ol.style.Stroke");goog.require("ol.style.Text");
ol.Graticule=function(opt_options){var options=opt_options||{};this.map_=null;this.projection_=null;this.maxLat_=Infinity;this.maxLon_=Infinity;this.minLat_=-Infinity;this.minLon_=-Infinity;this.maxLatP_=Infinity;this.maxLonP_=Infinity;this.minLatP_=-Infinity;this.minLonP_=-Infinity;this.targetSize_=options.targetSize!==undefined?options.targetSize:100;this.maxLines_=options.maxLines!==undefined?options.maxLines:100;this.meridians_=[];this.parallels_=[];this.strokeStyle_=options.strokeStyle!==undefined?
options.strokeStyle:ol.Graticule.DEFAULT_STROKE_STYLE_;this.fromLonLatTransform_=undefined;this.toLonLatTransform_=undefined;this.projectionCenterLonLat_=null;this.meridiansLabels_=null;this.parallelsLabels_=null;if(options.showLabels==true){var degreesToString=ol.coordinate.degreesToStringHDMS;this.lonLabelFormatter_=options.lonLabelFormatter==undefined?degreesToString.bind(this,"EW"):options.lonLabelFormatter;this.latLabelFormatter_=options.latLabelFormatter==undefined?degreesToString.bind(this,
"NS"):options.latLabelFormatter;this.lonLabelPosition_=options.lonLabelPosition==undefined?0:options.lonLabelPosition;this.latLabelPosition_=options.latLabelPosition==undefined?1:options.latLabelPosition;this.lonLabelStyle_=options.lonLabelStyle!==undefined?options.lonLabelStyle:new ol.style.Text({font:"12px Calibri,sans-serif",textBaseline:"bottom",fill:new ol.style.Fill({color:"rgba(0,0,0,1)"}),stroke:new ol.style.Stroke({color:"rgba(255,255,255,1)",width:3})});this.latLabelStyle_=options.latLabelStyle!==
undefined?options.latLabelStyle:new ol.style.Text({font:"12px Calibri,sans-serif",textAlign:"end",fill:new ol.style.Fill({color:"rgba(0,0,0,1)"}),stroke:new ol.style.Stroke({color:"rgba(255,255,255,1)",width:3})});this.meridiansLabels_=[];this.parallelsLabels_=[]}this.setMap(options.map!==undefined?options.map:null)};ol.Graticule.DEFAULT_STROKE_STYLE_=new ol.style.Stroke({color:"rgba(0,0,0,0.2)"});ol.Graticule.intervals_=[90,45,30,20,10,5,2,1,.5,.2,.1,.05,.01,.005,.002,.001];
ol.Graticule.prototype.addMeridian_=function(lon,minLat,maxLat,squaredTolerance,extent,index){var lineString=this.getMeridian_(lon,minLat,maxLat,squaredTolerance,index);if(ol.extent.intersects(lineString.getExtent(),extent)){if(this.meridiansLabels_){var textPoint=this.getMeridianPoint_(lineString,extent,index);this.meridiansLabels_[index]={geom:textPoint,text:this.lonLabelFormatter_(lon)}}this.meridians_[index++]=lineString}return index};
ol.Graticule.prototype.getMeridianPoint_=function(lineString,extent,index){var flatCoordinates=lineString.getFlatCoordinates();var clampedBottom=Math.max(extent[1],flatCoordinates[1]);var clampedTop=Math.min(extent[3],flatCoordinates[flatCoordinates.length-1]);var lat=ol.math.clamp(extent[1]+Math.abs(extent[1]-extent[3])*this.lonLabelPosition_,clampedBottom,clampedTop);var coordinate=[flatCoordinates[0],lat];var point=this.meridiansLabels_[index]!==undefined?this.meridiansLabels_[index].geom:new ol.geom.Point(null);
point.setCoordinates(coordinate);return point};ol.Graticule.prototype.addParallel_=function(lat,minLon,maxLon,squaredTolerance,extent,index){var lineString=this.getParallel_(lat,minLon,maxLon,squaredTolerance,index);if(ol.extent.intersects(lineString.getExtent(),extent)){if(this.parallelsLabels_){var textPoint=this.getParallelPoint_(lineString,extent,index);this.parallelsLabels_[index]={geom:textPoint,text:this.latLabelFormatter_(lat)}}this.parallels_[index++]=lineString}return index};
ol.Graticule.prototype.getParallelPoint_=function(lineString,extent,index){var flatCoordinates=lineString.getFlatCoordinates();var clampedLeft=Math.max(extent[0],flatCoordinates[0]);var clampedRight=Math.min(extent[2],flatCoordinates[flatCoordinates.length-2]);var lon=ol.math.clamp(extent[0]+Math.abs(extent[0]-extent[2])*this.latLabelPosition_,clampedLeft,clampedRight);var coordinate=[lon,flatCoordinates[1]];var point=this.parallelsLabels_[index]!==undefined?this.parallelsLabels_[index].geom:new ol.geom.Point(null);
point.setCoordinates(coordinate);return point};
ol.Graticule.prototype.createGraticule_=function(extent,center,resolution,squaredTolerance){var interval=this.getInterval_(resolution);if(interval==-1){this.meridians_.length=this.parallels_.length=0;if(this.meridiansLabels_)this.meridiansLabels_.length=0;if(this.parallelsLabels_)this.parallelsLabels_.length=0;return}var centerLonLat=this.toLonLatTransform_(center);var centerLon=centerLonLat[0];var centerLat=centerLonLat[1];var maxLines=this.maxLines_;var cnt,idx,lat,lon;var validExtent=[Math.max(extent[0],
this.minLonP_),Math.max(extent[1],this.minLatP_),Math.min(extent[2],this.maxLonP_),Math.min(extent[3],this.maxLatP_)];validExtent=ol.proj.transformExtent(validExtent,this.projection_,"EPSG:4326");var maxLat=validExtent[3];var maxLon=validExtent[2];var minLat=validExtent[1];var minLon=validExtent[0];centerLon=Math.floor(centerLon/interval)*interval;lon=ol.math.clamp(centerLon,this.minLon_,this.maxLon_);idx=this.addMeridian_(lon,minLat,maxLat,squaredTolerance,extent,0);cnt=0;while(lon!=this.minLon_&&
cnt++<maxLines){lon=Math.max(lon-interval,this.minLon_);idx=this.addMeridian_(lon,minLat,maxLat,squaredTolerance,extent,idx)}lon=ol.math.clamp(centerLon,this.minLon_,this.maxLon_);cnt=0;while(lon!=this.maxLon_&&cnt++<maxLines){lon=Math.min(lon+interval,this.maxLon_);idx=this.addMeridian_(lon,minLat,maxLat,squaredTolerance,extent,idx)}this.meridians_.length=idx;if(this.meridiansLabels_)this.meridiansLabels_.length=idx;centerLat=Math.floor(centerLat/interval)*interval;lat=ol.math.clamp(centerLat,this.minLat_,
this.maxLat_);idx=this.addParallel_(lat,minLon,maxLon,squaredTolerance,extent,0);cnt=0;while(lat!=this.minLat_&&cnt++<maxLines){lat=Math.max(lat-interval,this.minLat_);idx=this.addParallel_(lat,minLon,maxLon,squaredTolerance,extent,idx)}lat=ol.math.clamp(centerLat,this.minLat_,this.maxLat_);cnt=0;while(lat!=this.maxLat_&&cnt++<maxLines){lat=Math.min(lat+interval,this.maxLat_);idx=this.addParallel_(lat,minLon,maxLon,squaredTolerance,extent,idx)}this.parallels_.length=idx;if(this.parallelsLabels_)this.parallelsLabels_.length=
idx};
ol.Graticule.prototype.getInterval_=function(resolution){var centerLon=this.projectionCenterLonLat_[0];var centerLat=this.projectionCenterLonLat_[1];var interval=-1;var i,ii,delta,dist;var target=Math.pow(this.targetSize_*resolution,2);var p1=[];var p2=[];for(i=0,ii=ol.Graticule.intervals_.length;i<ii;++i){delta=ol.Graticule.intervals_[i]/2;p1[0]=centerLon-delta;p1[1]=centerLat-delta;p2[0]=centerLon+delta;p2[1]=centerLat+delta;this.fromLonLatTransform_(p1,p1);this.fromLonLatTransform_(p2,p2);dist=
Math.pow(p2[0]-p1[0],2)+Math.pow(p2[1]-p1[1],2);if(dist<=target)break;interval=ol.Graticule.intervals_[i]}return interval};ol.Graticule.prototype.getMap=function(){return this.map_};
ol.Graticule.prototype.getMeridian_=function(lon,minLat,maxLat,squaredTolerance,index){var flatCoordinates=ol.geom.flat.geodesic.meridian(lon,minLat,maxLat,this.projection_,squaredTolerance);var lineString=this.meridians_[index]!==undefined?this.meridians_[index]:new ol.geom.LineString(null);lineString.setFlatCoordinates(ol.geom.GeometryLayout.XY,flatCoordinates);return lineString};ol.Graticule.prototype.getMeridians=function(){return this.meridians_};
ol.Graticule.prototype.getParallel_=function(lat,minLon,maxLon,squaredTolerance,index){var flatCoordinates=ol.geom.flat.geodesic.parallel(lat,minLon,maxLon,this.projection_,squaredTolerance);var lineString=this.parallels_[index]!==undefined?this.parallels_[index]:new ol.geom.LineString(null);lineString.setFlatCoordinates(ol.geom.GeometryLayout.XY,flatCoordinates);return lineString};ol.Graticule.prototype.getParallels=function(){return this.parallels_};
ol.Graticule.prototype.handlePostCompose_=function(e){var vectorContext=e.vectorContext;var frameState=e.frameState;var extent=frameState.extent;var viewState=frameState.viewState;var center=viewState.center;var projection=viewState.projection;var resolution=viewState.resolution;var pixelRatio=frameState.pixelRatio;var squaredTolerance=resolution*resolution/(4*pixelRatio*pixelRatio);var updateProjectionInfo=!this.projection_||!ol.proj.equivalent(this.projection_,projection);if(updateProjectionInfo)this.updateProjectionInfo_(projection);
this.createGraticule_(extent,center,resolution,squaredTolerance);vectorContext.setFillStrokeStyle(null,this.strokeStyle_);var i,l,line;for(i=0,l=this.meridians_.length;i<l;++i){line=this.meridians_[i];vectorContext.drawGeometry(line)}for(i=0,l=this.parallels_.length;i<l;++i){line=this.parallels_[i];vectorContext.drawGeometry(line)}var labelData;if(this.meridiansLabels_)for(i=0,l=this.meridiansLabels_.length;i<l;++i){labelData=this.meridiansLabels_[i];this.lonLabelStyle_.setText(labelData.text);vectorContext.setTextStyle(this.lonLabelStyle_);
vectorContext.drawGeometry(labelData.geom)}if(this.parallelsLabels_)for(i=0,l=this.parallelsLabels_.length;i<l;++i){labelData=this.parallelsLabels_[i];this.latLabelStyle_.setText(labelData.text);vectorContext.setTextStyle(this.latLabelStyle_);vectorContext.drawGeometry(labelData.geom)}};
ol.Graticule.prototype.updateProjectionInfo_=function(projection){var epsg4326Projection=ol.proj.get("EPSG:4326");var extent=projection.getExtent();var worldExtent=projection.getWorldExtent();var worldExtentP=ol.proj.transformExtent(worldExtent,epsg4326Projection,projection);var maxLat=worldExtent[3];var maxLon=worldExtent[2];var minLat=worldExtent[1];var minLon=worldExtent[0];var maxLatP=worldExtentP[3];var maxLonP=worldExtentP[2];var minLatP=worldExtentP[1];var minLonP=worldExtentP[0];this.maxLat_=
maxLat;this.maxLon_=maxLon;this.minLat_=minLat;this.minLon_=minLon;this.maxLatP_=maxLatP;this.maxLonP_=maxLonP;this.minLatP_=minLatP;this.minLonP_=minLonP;this.fromLonLatTransform_=ol.proj.getTransform(epsg4326Projection,projection);this.toLonLatTransform_=ol.proj.getTransform(projection,epsg4326Projection);this.projectionCenterLonLat_=this.toLonLatTransform_(ol.extent.getCenter(extent));this.projection_=projection};
ol.Graticule.prototype.setMap=function(map){if(this.map_){this.map_.un(ol.render.EventType.POSTCOMPOSE,this.handlePostCompose_,this);this.map_.render()}if(map){map.on(ol.render.EventType.POSTCOMPOSE,this.handlePostCompose_,this);map.render()}this.map_=map};goog.provide("ol.Image");goog.require("ol");goog.require("ol.ImageBase");goog.require("ol.ImageState");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");
ol.Image=function(extent,resolution,pixelRatio,src,crossOrigin,imageLoadFunction){ol.ImageBase.call(this,extent,resolution,pixelRatio,ol.ImageState.IDLE);this.src_=src;this.image_=new Image;if(crossOrigin!==null)this.image_.crossOrigin=crossOrigin;this.imageListenerKeys_=null;this.state=ol.ImageState.IDLE;this.imageLoadFunction_=imageLoadFunction};ol.inherits(ol.Image,ol.ImageBase);ol.Image.prototype.getImage=function(){return this.image_};
ol.Image.prototype.handleImageError_=function(){this.state=ol.ImageState.ERROR;this.unlistenImage_();this.changed()};ol.Image.prototype.handleImageLoad_=function(){if(this.resolution===undefined)this.resolution=ol.extent.getHeight(this.extent)/this.image_.height;this.state=ol.ImageState.LOADED;this.unlistenImage_();this.changed()};
ol.Image.prototype.load=function(){if(this.state==ol.ImageState.IDLE||this.state==ol.ImageState.ERROR){this.state=ol.ImageState.LOADING;this.changed();this.imageListenerKeys_=[ol.events.listenOnce(this.image_,ol.events.EventType.ERROR,this.handleImageError_,this),ol.events.listenOnce(this.image_,ol.events.EventType.LOAD,this.handleImageLoad_,this)];this.imageLoadFunction_(this,this.src_)}};ol.Image.prototype.setImage=function(image){this.image_=image};
ol.Image.prototype.unlistenImage_=function(){this.imageListenerKeys_.forEach(ol.events.unlistenByKey);this.imageListenerKeys_=null};goog.provide("ol.Tile");goog.require("ol");goog.require("ol.TileState");goog.require("ol.easing");goog.require("ol.events.EventTarget");goog.require("ol.events.EventType");ol.Tile=function(tileCoord,state,opt_options){ol.events.EventTarget.call(this);var options=opt_options?opt_options:{};this.tileCoord=tileCoord;this.state=state;this.interimTile=null;this.key="";this.transition_=options.transition===undefined?250:options.transition;this.transitionStarts_={}};ol.inherits(ol.Tile,ol.events.EventTarget);
ol.Tile.prototype.changed=function(){this.dispatchEvent(ol.events.EventType.CHANGE)};ol.Tile.prototype.getKey=function(){return this.key+"/"+this.tileCoord};ol.Tile.prototype.getInterimTile=function(){if(!this.interimTile)return this;var tile=this.interimTile;do{if(tile.getState()==ol.TileState.LOADED)return tile;tile=tile.interimTile}while(tile);return this};
ol.Tile.prototype.refreshInterimChain=function(){if(!this.interimTile)return;var tile=this.interimTile;var prev=this;do{if(tile.getState()==ol.TileState.LOADED){tile.interimTile=null;break}else if(tile.getState()==ol.TileState.LOADING)prev=tile;else if(tile.getState()==ol.TileState.IDLE)prev.interimTile=tile.interimTile;else prev=tile;tile=prev.interimTile}while(tile)};ol.Tile.prototype.getTileCoord=function(){return this.tileCoord};ol.Tile.prototype.getState=function(){return this.state};
ol.Tile.prototype.setState=function(state){this.state=state;this.changed()};ol.Tile.prototype.load=function(){};ol.Tile.prototype.getAlpha=function(id,time){if(!this.transition_)return 1;var start=this.transitionStarts_[id];if(!start){start=time;this.transitionStarts_[id]=start}else if(start===-1)return 1;var delta=time-start+1E3/60;if(delta>=this.transition_)return 1;return ol.easing.easeIn(delta/this.transition_)};
ol.Tile.prototype.inTransition=function(id){if(!this.transition_)return false;return this.transitionStarts_[id]!==-1};ol.Tile.prototype.endTransition=function(id){if(this.transition_)this.transitionStarts_[id]=-1};goog.provide("ol.ImageTile");goog.require("ol");goog.require("ol.Tile");goog.require("ol.TileState");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.events.EventType");ol.ImageTile=function(tileCoord,state,src,crossOrigin,tileLoadFunction,opt_options){ol.Tile.call(this,tileCoord,state,opt_options);this.crossOrigin_=crossOrigin;this.src_=src;this.image_=new Image;if(crossOrigin!==null)this.image_.crossOrigin=crossOrigin;this.imageListenerKeys_=null;this.tileLoadFunction_=tileLoadFunction};
ol.inherits(ol.ImageTile,ol.Tile);ol.ImageTile.prototype.disposeInternal=function(){if(this.state==ol.TileState.LOADING){this.unlistenImage_();this.image_=ol.ImageTile.getBlankImage()}if(this.interimTile)this.interimTile.dispose();this.state=ol.TileState.ABORT;this.changed();ol.Tile.prototype.disposeInternal.call(this)};ol.ImageTile.prototype.getImage=function(){return this.image_};ol.ImageTile.prototype.getKey=function(){return this.src_};
ol.ImageTile.prototype.handleImageError_=function(){this.state=ol.TileState.ERROR;this.unlistenImage_();this.image_=ol.ImageTile.getBlankImage();this.changed()};ol.ImageTile.prototype.handleImageLoad_=function(){if(this.image_.naturalWidth&&this.image_.naturalHeight)this.state=ol.TileState.LOADED;else this.state=ol.TileState.EMPTY;this.unlistenImage_();this.changed()};
ol.ImageTile.prototype.load=function(){if(this.state==ol.TileState.ERROR){this.state=ol.TileState.IDLE;this.image_=new Image;if(this.crossOrigin_!==null)this.image_.crossOrigin=this.crossOrigin_}if(this.state==ol.TileState.IDLE){this.state=ol.TileState.LOADING;this.changed();this.imageListenerKeys_=[ol.events.listenOnce(this.image_,ol.events.EventType.ERROR,this.handleImageError_,this),ol.events.listenOnce(this.image_,ol.events.EventType.LOAD,this.handleImageLoad_,this)];this.tileLoadFunction_(this,
this.src_)}};ol.ImageTile.prototype.unlistenImage_=function(){this.imageListenerKeys_.forEach(ol.events.unlistenByKey);this.imageListenerKeys_=null};ol.ImageTile.getBlankImage=function(){var ctx=ol.dom.createCanvasContext2D(1,1);ctx.fillStyle="rgba(0,0,0,0)";ctx.fillRect(0,0,1,1);return ctx.canvas};goog.provide("ol.interaction.DragAndDrop");goog.require("ol");goog.require("ol.functions");goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.events.EventType");goog.require("ol.interaction.Interaction");goog.require("ol.proj");
ol.interaction.DragAndDrop=function(opt_options){var options=opt_options?opt_options:{};ol.interaction.Interaction.call(this,{handleEvent:ol.interaction.DragAndDrop.handleEvent});this.formatConstructors_=options.formatConstructors?options.formatConstructors:[];this.projection_=options.projection?ol.proj.get(options.projection):null;this.dropListenKeys_=null;this.source_=options.source||null;this.target=options.target?options.target:null};ol.inherits(ol.interaction.DragAndDrop,ol.interaction.Interaction);
ol.interaction.DragAndDrop.handleDrop_=function(event){var files=event.dataTransfer.files;var i,ii,file;for(i=0,ii=files.length;i<ii;++i){file=files.item(i);var reader=new FileReader;reader.addEventListener(ol.events.EventType.LOAD,this.handleResult_.bind(this,file));reader.readAsText(file)}};ol.interaction.DragAndDrop.handleStop_=function(event){event.stopPropagation();event.preventDefault();event.dataTransfer.dropEffect="copy"};
ol.interaction.DragAndDrop.prototype.handleResult_=function(file,event){var result=event.target.result;var map=this.getMap();var projection=this.projection_;if(!projection){var view=map.getView();projection=view.getProjection()}var formatConstructors=this.formatConstructors_;var features=[];var i,ii;for(i=0,ii=formatConstructors.length;i<ii;++i){var formatConstructor=formatConstructors[i];var format=new formatConstructor;features=this.tryReadFeatures_(format,result,{featureProjection:projection});
if(features&&features.length>0)break}if(this.source_){this.source_.clear();this.source_.addFeatures(features)}this.dispatchEvent(new ol.interaction.DragAndDrop.Event(ol.interaction.DragAndDrop.EventType_.ADD_FEATURES,file,features,projection))};ol.interaction.DragAndDrop.handleEvent=ol.functions.TRUE;
ol.interaction.DragAndDrop.prototype.registerListeners_=function(){var map=this.getMap();if(map){var dropArea=this.target?this.target:map.getViewport();this.dropListenKeys_=[ol.events.listen(dropArea,ol.events.EventType.DROP,ol.interaction.DragAndDrop.handleDrop_,this),ol.events.listen(dropArea,ol.events.EventType.DRAGENTER,ol.interaction.DragAndDrop.handleStop_,this),ol.events.listen(dropArea,ol.events.EventType.DRAGOVER,ol.interaction.DragAndDrop.handleStop_,this),ol.events.listen(dropArea,ol.events.EventType.DROP,
ol.interaction.DragAndDrop.handleStop_,this)]}};ol.interaction.DragAndDrop.prototype.setActive=function(active){ol.interaction.Interaction.prototype.setActive.call(this,active);if(active)this.registerListeners_();else this.unregisterListeners_()};ol.interaction.DragAndDrop.prototype.setMap=function(map){this.unregisterListeners_();ol.interaction.Interaction.prototype.setMap.call(this,map);if(this.getActive())this.registerListeners_()};
ol.interaction.DragAndDrop.prototype.tryReadFeatures_=function(format,text,options){try{return format.readFeatures(text,options)}catch(e){return null}};ol.interaction.DragAndDrop.prototype.unregisterListeners_=function(){if(this.dropListenKeys_){this.dropListenKeys_.forEach(ol.events.unlistenByKey);this.dropListenKeys_=null}};ol.interaction.DragAndDrop.EventType_={ADD_FEATURES:"addfeatures"};
ol.interaction.DragAndDrop.Event=function(type,file,opt_features,opt_projection){ol.events.Event.call(this,type);this.features=opt_features;this.file=file;this.projection=opt_projection};ol.inherits(ol.interaction.DragAndDrop.Event,ol.events.Event);goog.provide("ol.interaction.DragRotateAndZoom");goog.require("ol");goog.require("ol.RotationConstraint");goog.require("ol.ViewHint");goog.require("ol.events.condition");goog.require("ol.interaction.Interaction");goog.require("ol.interaction.Pointer");
ol.interaction.DragRotateAndZoom=function(opt_options){var options=opt_options?opt_options:{};ol.interaction.Pointer.call(this,{handleDownEvent:ol.interaction.DragRotateAndZoom.handleDownEvent_,handleDragEvent:ol.interaction.DragRotateAndZoom.handleDragEvent_,handleUpEvent:ol.interaction.DragRotateAndZoom.handleUpEvent_});this.condition_=options.condition?options.condition:ol.events.condition.shiftKeyOnly;this.lastAngle_=undefined;this.lastMagnitude_=undefined;this.lastScaleDelta_=0;this.duration_=
options.duration!==undefined?options.duration:400};ol.inherits(ol.interaction.DragRotateAndZoom,ol.interaction.Pointer);
ol.interaction.DragRotateAndZoom.handleDragEvent_=function(mapBrowserEvent){if(!ol.events.condition.mouseOnly(mapBrowserEvent))return;var map=mapBrowserEvent.map;var size=map.getSize();var offset=mapBrowserEvent.pixel;var deltaX=offset[0]-size[0]/2;var deltaY=size[1]/2-offset[1];var theta=Math.atan2(deltaY,deltaX);var magnitude=Math.sqrt(deltaX*deltaX+deltaY*deltaY);var view=map.getView();if(view.getConstraints().rotation!==ol.RotationConstraint.disable&&this.lastAngle_!==undefined){var angleDelta=
theta-this.lastAngle_;ol.interaction.Interaction.rotateWithoutConstraints(view,view.getRotation()-angleDelta)}this.lastAngle_=theta;if(this.lastMagnitude_!==undefined){var resolution=this.lastMagnitude_*(view.getResolution()/magnitude);ol.interaction.Interaction.zoomWithoutConstraints(view,resolution)}if(this.lastMagnitude_!==undefined)this.lastScaleDelta_=this.lastMagnitude_/magnitude;this.lastMagnitude_=magnitude};
ol.interaction.DragRotateAndZoom.handleUpEvent_=function(mapBrowserEvent){if(!ol.events.condition.mouseOnly(mapBrowserEvent))return true;var map=mapBrowserEvent.map;var view=map.getView();view.setHint(ol.ViewHint.INTERACTING,-1);var direction=this.lastScaleDelta_-1;ol.interaction.Interaction.rotate(view,view.getRotation());ol.interaction.Interaction.zoom(view,view.getResolution(),undefined,this.duration_,direction);this.lastScaleDelta_=0;return false};
ol.interaction.DragRotateAndZoom.handleDownEvent_=function(mapBrowserEvent){if(!ol.events.condition.mouseOnly(mapBrowserEvent))return false;if(this.condition_(mapBrowserEvent)){mapBrowserEvent.map.getView().setHint(ol.ViewHint.INTERACTING,1);this.lastAngle_=undefined;this.lastMagnitude_=undefined;return true}else return false};goog.provide("ol.interaction.DrawEventType");ol.interaction.DrawEventType={DRAWSTART:"drawstart",DRAWEND:"drawend"};goog.provide("ol.layer.Vector");goog.require("ol");goog.require("ol.LayerType");goog.require("ol.layer.Layer");goog.require("ol.layer.VectorRenderType");goog.require("ol.obj");goog.require("ol.style.Style");
ol.layer.Vector=function(opt_options){var options=opt_options?opt_options:{};var baseOptions=ol.obj.assign({},options);delete baseOptions.style;delete baseOptions.renderBuffer;delete baseOptions.updateWhileAnimating;delete baseOptions.updateWhileInteracting;ol.layer.Layer.call(this,baseOptions);this.declutter_=options.declutter!==undefined?options.declutter:false;this.renderBuffer_=options.renderBuffer!==undefined?options.renderBuffer:100;this.style_=null;this.styleFunction_=undefined;this.setStyle(options.style);
this.updateWhileAnimating_=options.updateWhileAnimating!==undefined?options.updateWhileAnimating:false;this.updateWhileInteracting_=options.updateWhileInteracting!==undefined?options.updateWhileInteracting:false;this.renderMode_=options.renderMode||ol.layer.VectorRenderType.VECTOR;this.type=ol.LayerType.VECTOR};ol.inherits(ol.layer.Vector,ol.layer.Layer);ol.layer.Vector.prototype.getDeclutter=function(){return this.declutter_};
ol.layer.Vector.prototype.setDeclutter=function(declutter){this.declutter_=declutter};ol.layer.Vector.prototype.getRenderBuffer=function(){return this.renderBuffer_};ol.layer.Vector.prototype.getRenderOrder=function(){return this.get(ol.layer.Vector.Property_.RENDER_ORDER)};ol.layer.Vector.prototype.getSource;ol.layer.Vector.prototype.getStyle=function(){return this.style_};ol.layer.Vector.prototype.getStyleFunction=function(){return this.styleFunction_};
ol.layer.Vector.prototype.getUpdateWhileAnimating=function(){return this.updateWhileAnimating_};ol.layer.Vector.prototype.getUpdateWhileInteracting=function(){return this.updateWhileInteracting_};ol.layer.Vector.prototype.setRenderOrder=function(renderOrder){this.set(ol.layer.Vector.Property_.RENDER_ORDER,renderOrder)};
ol.layer.Vector.prototype.setStyle=function(style){this.style_=style!==undefined?style:ol.style.Style.defaultFunction;this.styleFunction_=style===null?undefined:ol.style.Style.createFunction(this.style_);this.changed()};ol.layer.Vector.prototype.getRenderMode=function(){return this.renderMode_};ol.layer.Vector.Property_={RENDER_ORDER:"renderOrder"};goog.provide("ol.loadingstrategy");ol.loadingstrategy.all=function(extent,resolution){return[[-Infinity,-Infinity,Infinity,Infinity]]};ol.loadingstrategy.bbox=function(extent,resolution){return[extent]};
ol.loadingstrategy.tile=function(tileGrid){return function(extent,resolution){var z=tileGrid.getZForResolution(resolution);var tileRange=tileGrid.getTileRangeForExtentAndZ(extent,z);var extents=[];var tileCoord=[z,0,0];for(tileCoord[1]=tileRange.minX;tileCoord[1]<=tileRange.maxX;++tileCoord[1])for(tileCoord[2]=tileRange.minY;tileCoord[2]<=tileRange.maxY;++tileCoord[2])extents.push(tileGrid.getTileCoordExtent(tileCoord));return extents}};goog.provide("ol.source.Source");goog.require("ol");goog.require("ol.Attribution");goog.require("ol.Object");goog.require("ol.proj");goog.require("ol.source.State");
ol.source.Source=function(options){ol.Object.call(this);this.projection_=ol.proj.get(options.projection);this.attributions_=null;this.attributions2_=this.adaptAttributions_(options.attributions);this.logo_=options.logo;this.state_=options.state!==undefined?options.state:ol.source.State.READY;this.wrapX_=options.wrapX!==undefined?options.wrapX:false};ol.inherits(ol.source.Source,ol.Object);
ol.source.Source.prototype.adaptAttributions_=function(attributionLike){if(!attributionLike)return null;if(attributionLike instanceof ol.Attribution){this.attributions_=[attributionLike];return function(frameState){return[attributionLike.getHTML()]}}if(Array.isArray(attributionLike)){if(attributionLike[0]instanceof ol.Attribution){this.attributions_=attributionLike;var attributions=attributionLike.map(function(attribution){return attribution.getHTML()});return function(frameState){return attributions}}this.attributions_=
attributionLike.map(function(attribution){return new ol.Attribution({html:attribution})});return function(frameState){return attributionLike}}if(typeof attributionLike==="function")return attributionLike;this.attributions_=[new ol.Attribution({html:attributionLike})];return function(frameState){return[attributionLike]}};ol.source.Source.prototype.forEachFeatureAtCoordinate=ol.nullFunction;ol.source.Source.prototype.getAttributions=function(){return this.attributions_};
ol.source.Source.prototype.getAttributions2=function(){return this.attributions2_};ol.source.Source.prototype.getLogo=function(){return this.logo_};ol.source.Source.prototype.getProjection=function(){return this.projection_};ol.source.Source.prototype.getResolutions=function(){};ol.source.Source.prototype.getState=function(){return this.state_};ol.source.Source.prototype.getWrapX=function(){return this.wrapX_};ol.source.Source.prototype.refresh=function(){this.changed()};
ol.source.Source.prototype.setAttributions=function(attributions){this.attributions2_=this.adaptAttributions_(attributions);this.changed()};ol.source.Source.prototype.setLogo=function(logo){this.logo_=logo};ol.source.Source.prototype.setState=function(state){this.state_=state;this.changed()};goog.provide("ol.source.VectorEventType");ol.source.VectorEventType={ADDFEATURE:"addfeature",CHANGEFEATURE:"changefeature",CLEAR:"clear",REMOVEFEATURE:"removefeature"};goog.provide("ol.structs.RBush");goog.require("ol");goog.require("ol.ext.rbush");goog.require("ol.extent");goog.require("ol.obj");ol.structs.RBush=function(opt_maxEntries){this.rbush_=ol.ext.rbush(opt_maxEntries);this.items_={}};ol.structs.RBush.prototype.insert=function(extent,value){var item={minX:extent[0],minY:extent[1],maxX:extent[2],maxY:extent[3],value:value};this.rbush_.insert(item);this.items_[ol.getUid(value)]=item};
ol.structs.RBush.prototype.load=function(extents,values){var items=new Array(values.length);for(var i=0,l=values.length;i<l;i++){var extent=extents[i];var value=values[i];var item={minX:extent[0],minY:extent[1],maxX:extent[2],maxY:extent[3],value:value};items[i]=item;this.items_[ol.getUid(value)]=item}this.rbush_.load(items)};ol.structs.RBush.prototype.remove=function(value){var uid=ol.getUid(value);var item=this.items_[uid];delete this.items_[uid];return this.rbush_.remove(item)!==null};
ol.structs.RBush.prototype.update=function(extent,value){var item=this.items_[ol.getUid(value)];var bbox=[item.minX,item.minY,item.maxX,item.maxY];if(!ol.extent.equals(bbox,extent)){this.remove(value);this.insert(extent,value)}};ol.structs.RBush.prototype.getAll=function(){var items=this.rbush_.all();return items.map(function(item){return item.value})};
ol.structs.RBush.prototype.getInExtent=function(extent){var bbox={minX:extent[0],minY:extent[1],maxX:extent[2],maxY:extent[3]};var items=this.rbush_.search(bbox);return items.map(function(item){return item.value})};ol.structs.RBush.prototype.forEach=function(callback,opt_this){return this.forEach_(this.getAll(),callback,opt_this)};ol.structs.RBush.prototype.forEachInExtent=function(extent,callback,opt_this){return this.forEach_(this.getInExtent(extent),callback,opt_this)};
ol.structs.RBush.prototype.forEach_=function(values,callback,opt_this){var result;for(var i=0,l=values.length;i<l;i++){result=callback.call(opt_this,values[i]);if(result)return result}return result};ol.structs.RBush.prototype.isEmpty=function(){return ol.obj.isEmpty(this.items_)};ol.structs.RBush.prototype.clear=function(){this.rbush_.clear();this.items_={}};
ol.structs.RBush.prototype.getExtent=function(opt_extent){var data=this.rbush_.data;return ol.extent.createOrUpdate(data.minX,data.minY,data.maxX,data.maxY,opt_extent)};ol.structs.RBush.prototype.concat=function(rbush){this.rbush_.load(rbush.rbush_.all());for(var i in rbush.items_)this.items_[i|0]=rbush.items_[i|0]};goog.provide("ol.source.Vector");goog.require("ol");goog.require("ol.Collection");goog.require("ol.CollectionEventType");goog.require("ol.ObjectEventType");goog.require("ol.array");goog.require("ol.asserts");goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.featureloader");goog.require("ol.functions");goog.require("ol.loadingstrategy");goog.require("ol.obj");goog.require("ol.source.Source");goog.require("ol.source.State");
goog.require("ol.source.VectorEventType");goog.require("ol.structs.RBush");
ol.source.Vector=function(opt_options){var options=opt_options||{};ol.source.Source.call(this,{attributions:options.attributions,logo:options.logo,projection:undefined,state:ol.source.State.READY,wrapX:options.wrapX!==undefined?options.wrapX:true});this.loader_=ol.nullFunction;this.format_=options.format;this.overlaps_=options.overlaps==undefined?true:options.overlaps;this.url_=options.url;if(options.loader!==undefined)this.loader_=options.loader;else if(this.url_!==undefined){ol.asserts.assert(this.format_,
7);this.loader_=ol.featureloader.xhr(this.url_,this.format_)}this.strategy_=options.strategy!==undefined?options.strategy:ol.loadingstrategy.all;var useSpatialIndex=options.useSpatialIndex!==undefined?options.useSpatialIndex:true;this.featuresRtree_=useSpatialIndex?new ol.structs.RBush:null;this.loadedExtentsRtree_=new ol.structs.RBush;this.nullGeometryFeatures_={};this.idIndex_={};this.undefIdIndex_={};this.featureChangeKeys_={};this.featuresCollection_=null;var collection,features;if(options.features instanceof
ol.Collection){collection=options.features;features=collection.getArray()}else if(Array.isArray(options.features))features=options.features;if(!useSpatialIndex&&collection===undefined)collection=new ol.Collection(features);if(features!==undefined)this.addFeaturesInternal(features);if(collection!==undefined)this.bindFeaturesCollection_(collection)};ol.inherits(ol.source.Vector,ol.source.Source);ol.source.Vector.prototype.addFeature=function(feature){this.addFeatureInternal(feature);this.changed()};
ol.source.Vector.prototype.addFeatureInternal=function(feature){var featureKey=ol.getUid(feature).toString();if(!this.addToIndex_(featureKey,feature))return;this.setupChangeEvents_(featureKey,feature);var geometry=feature.getGeometry();if(geometry){var extent=geometry.getExtent();if(this.featuresRtree_)this.featuresRtree_.insert(extent,feature)}else this.nullGeometryFeatures_[featureKey]=feature;this.dispatchEvent(new ol.source.Vector.Event(ol.source.VectorEventType.ADDFEATURE,feature))};
ol.source.Vector.prototype.setupChangeEvents_=function(featureKey,feature){this.featureChangeKeys_[featureKey]=[ol.events.listen(feature,ol.events.EventType.CHANGE,this.handleFeatureChange_,this),ol.events.listen(feature,ol.ObjectEventType.PROPERTYCHANGE,this.handleFeatureChange_,this)]};
ol.source.Vector.prototype.addToIndex_=function(featureKey,feature){var valid=true;var id=feature.getId();if(id!==undefined)if(!(id.toString()in this.idIndex_))this.idIndex_[id.toString()]=feature;else valid=false;else{ol.asserts.assert(!(featureKey in this.undefIdIndex_),30);this.undefIdIndex_[featureKey]=feature}return valid};ol.source.Vector.prototype.addFeatures=function(features){this.addFeaturesInternal(features);this.changed()};
ol.source.Vector.prototype.addFeaturesInternal=function(features){var featureKey,i,length,feature;var extents=[];var newFeatures=[];var geometryFeatures=[];for(i=0,length=features.length;i<length;i++){feature=features[i];featureKey=ol.getUid(feature).toString();if(this.addToIndex_(featureKey,feature))newFeatures.push(feature)}for(i=0,length=newFeatures.length;i<length;i++){feature=newFeatures[i];featureKey=ol.getUid(feature).toString();this.setupChangeEvents_(featureKey,feature);var geometry=feature.getGeometry();
if(geometry){var extent=geometry.getExtent();extents.push(extent);geometryFeatures.push(feature)}else this.nullGeometryFeatures_[featureKey]=feature}if(this.featuresRtree_)this.featuresRtree_.load(extents,geometryFeatures);for(i=0,length=newFeatures.length;i<length;i++)this.dispatchEvent(new ol.source.Vector.Event(ol.source.VectorEventType.ADDFEATURE,newFeatures[i]))};
ol.source.Vector.prototype.bindFeaturesCollection_=function(collection){var modifyingCollection=false;ol.events.listen(this,ol.source.VectorEventType.ADDFEATURE,function(evt){if(!modifyingCollection){modifyingCollection=true;collection.push(evt.feature);modifyingCollection=false}});ol.events.listen(this,ol.source.VectorEventType.REMOVEFEATURE,function(evt){if(!modifyingCollection){modifyingCollection=true;collection.remove(evt.feature);modifyingCollection=false}});ol.events.listen(collection,ol.CollectionEventType.ADD,
function(evt){if(!modifyingCollection){modifyingCollection=true;this.addFeature(evt.element);modifyingCollection=false}},this);ol.events.listen(collection,ol.CollectionEventType.REMOVE,function(evt){if(!modifyingCollection){modifyingCollection=true;this.removeFeature(evt.element);modifyingCollection=false}},this);this.featuresCollection_=collection};
ol.source.Vector.prototype.clear=function(opt_fast){if(opt_fast){for(var featureId in this.featureChangeKeys_){var keys=this.featureChangeKeys_[featureId];keys.forEach(ol.events.unlistenByKey)}if(!this.featuresCollection_){this.featureChangeKeys_={};this.idIndex_={};this.undefIdIndex_={}}}else if(this.featuresRtree_){this.featuresRtree_.forEach(this.removeFeatureInternal,this);for(var id in this.nullGeometryFeatures_)this.removeFeatureInternal(this.nullGeometryFeatures_[id])}if(this.featuresCollection_)this.featuresCollection_.clear();
if(this.featuresRtree_)this.featuresRtree_.clear();this.loadedExtentsRtree_.clear();this.nullGeometryFeatures_={};var clearEvent=new ol.source.Vector.Event(ol.source.VectorEventType.CLEAR);this.dispatchEvent(clearEvent);this.changed()};ol.source.Vector.prototype.forEachFeature=function(callback,opt_this){if(this.featuresRtree_)return this.featuresRtree_.forEach(callback,opt_this);else if(this.featuresCollection_)return this.featuresCollection_.forEach(callback,opt_this)};
ol.source.Vector.prototype.forEachFeatureAtCoordinateDirect=function(coordinate,callback,opt_this){var extent=[coordinate[0],coordinate[1],coordinate[0],coordinate[1]];return this.forEachFeatureInExtent(extent,function(feature){var geometry=feature.getGeometry();if(geometry.intersectsCoordinate(coordinate))return callback.call(opt_this,feature);else return undefined})};
ol.source.Vector.prototype.forEachFeatureInExtent=function(extent,callback,opt_this){if(this.featuresRtree_)return this.featuresRtree_.forEachInExtent(extent,callback,opt_this);else if(this.featuresCollection_)return this.featuresCollection_.forEach(callback,opt_this)};
ol.source.Vector.prototype.forEachFeatureIntersectingExtent=function(extent,callback,opt_this){return this.forEachFeatureInExtent(extent,function(feature){var geometry=feature.getGeometry();if(geometry.intersectsExtent(extent)){var result=callback.call(opt_this,feature);if(result)return result}})};ol.source.Vector.prototype.getFeaturesCollection=function(){return this.featuresCollection_};
ol.source.Vector.prototype.getFeatures=function(){var features;if(this.featuresCollection_)features=this.featuresCollection_.getArray();else if(this.featuresRtree_){features=this.featuresRtree_.getAll();if(!ol.obj.isEmpty(this.nullGeometryFeatures_))ol.array.extend(features,ol.obj.getValues(this.nullGeometryFeatures_))}return features};
ol.source.Vector.prototype.getFeaturesAtCoordinate=function(coordinate){var features=[];this.forEachFeatureAtCoordinateDirect(coordinate,function(feature){features.push(feature)});return features};ol.source.Vector.prototype.getFeaturesInExtent=function(extent){return this.featuresRtree_.getInExtent(extent)};
ol.source.Vector.prototype.getClosestFeatureToCoordinate=function(coordinate,opt_filter){var x=coordinate[0];var y=coordinate[1];var closestFeature=null;var closestPoint=[NaN,NaN];var minSquaredDistance=Infinity;var extent=[-Infinity,-Infinity,Infinity,Infinity];var filter=opt_filter?opt_filter:ol.functions.TRUE;this.featuresRtree_.forEachInExtent(extent,function(feature){if(filter(feature)){var geometry=feature.getGeometry();var previousMinSquaredDistance=minSquaredDistance;minSquaredDistance=geometry.closestPointXY(x,
y,closestPoint,minSquaredDistance);if(minSquaredDistance<previousMinSquaredDistance){closestFeature=feature;var minDistance=Math.sqrt(minSquaredDistance);extent[0]=x-minDistance;extent[1]=y-minDistance;extent[2]=x+minDistance;extent[3]=y+minDistance}}});return closestFeature};ol.source.Vector.prototype.getExtent=function(opt_extent){return this.featuresRtree_.getExtent(opt_extent)};
ol.source.Vector.prototype.getFeatureById=function(id){var feature=this.idIndex_[id.toString()];return feature!==undefined?feature:null};ol.source.Vector.prototype.getFormat=function(){return this.format_};ol.source.Vector.prototype.getOverlaps=function(){return this.overlaps_};ol.source.Vector.prototype.getResolutions=function(){};ol.source.Vector.prototype.getUrl=function(){return this.url_};
ol.source.Vector.prototype.handleFeatureChange_=function(event){var feature=event.target;var featureKey=ol.getUid(feature).toString();var geometry=feature.getGeometry();if(!geometry){if(!(featureKey in this.nullGeometryFeatures_)){if(this.featuresRtree_)this.featuresRtree_.remove(feature);this.nullGeometryFeatures_[featureKey]=feature}}else{var extent=geometry.getExtent();if(featureKey in this.nullGeometryFeatures_){delete this.nullGeometryFeatures_[featureKey];if(this.featuresRtree_)this.featuresRtree_.insert(extent,
feature)}else if(this.featuresRtree_)this.featuresRtree_.update(extent,feature)}var id=feature.getId();if(id!==undefined){var sid=id.toString();if(featureKey in this.undefIdIndex_){delete this.undefIdIndex_[featureKey];this.idIndex_[sid]=feature}else if(this.idIndex_[sid]!==feature){this.removeFromIdIndex_(feature);this.idIndex_[sid]=feature}}else if(!(featureKey in this.undefIdIndex_)){this.removeFromIdIndex_(feature);this.undefIdIndex_[featureKey]=feature}this.changed();this.dispatchEvent(new ol.source.Vector.Event(ol.source.VectorEventType.CHANGEFEATURE,
feature))};ol.source.Vector.prototype.isEmpty=function(){return this.featuresRtree_.isEmpty()&&ol.obj.isEmpty(this.nullGeometryFeatures_)};
ol.source.Vector.prototype.loadFeatures=function(extent,resolution,projection){var loadedExtentsRtree=this.loadedExtentsRtree_;var extentsToLoad=this.strategy_(extent,resolution);var i,ii;for(i=0,ii=extentsToLoad.length;i<ii;++i){var extentToLoad=extentsToLoad[i];var alreadyLoaded=loadedExtentsRtree.forEachInExtent(extentToLoad,function(object){return ol.extent.containsExtent(object.extent,extentToLoad)});if(!alreadyLoaded){this.loader_.call(this,extentToLoad,resolution,projection);loadedExtentsRtree.insert(extentToLoad,
{extent:extentToLoad.slice()})}}};ol.source.Vector.prototype.removeLoadedExtent=function(extent){var loadedExtentsRtree=this.loadedExtentsRtree_;var obj;loadedExtentsRtree.forEachInExtent(extent,function(object){if(ol.extent.equals(object.extent,extent)){obj=object;return true}});if(obj)loadedExtentsRtree.remove(obj)};
ol.source.Vector.prototype.removeFeature=function(feature){var featureKey=ol.getUid(feature).toString();if(featureKey in this.nullGeometryFeatures_)delete this.nullGeometryFeatures_[featureKey];else if(this.featuresRtree_)this.featuresRtree_.remove(feature);this.removeFeatureInternal(feature);this.changed()};
ol.source.Vector.prototype.removeFeatureInternal=function(feature){var featureKey=ol.getUid(feature).toString();this.featureChangeKeys_[featureKey].forEach(ol.events.unlistenByKey);delete this.featureChangeKeys_[featureKey];var id=feature.getId();if(id!==undefined)delete this.idIndex_[id.toString()];else delete this.undefIdIndex_[featureKey];this.dispatchEvent(new ol.source.Vector.Event(ol.source.VectorEventType.REMOVEFEATURE,feature))};
ol.source.Vector.prototype.removeFromIdIndex_=function(feature){var removed=false;for(var id in this.idIndex_)if(this.idIndex_[id]===feature){delete this.idIndex_[id];removed=true;break}return removed};ol.source.Vector.prototype.setLoader=function(loader){this.loader_=loader};ol.source.Vector.Event=function(type,opt_feature){ol.events.Event.call(this,type);this.feature=opt_feature};ol.inherits(ol.source.Vector.Event,ol.events.Event);goog.provide("ol.interaction.Draw");goog.require("ol");goog.require("ol.Feature");goog.require("ol.MapBrowserEventType");goog.require("ol.Object");goog.require("ol.coordinate");goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.events.condition");goog.require("ol.extent");goog.require("ol.functions");goog.require("ol.geom.Circle");goog.require("ol.geom.GeometryType");goog.require("ol.geom.LineString");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.MultiPoint");
goog.require("ol.geom.MultiPolygon");goog.require("ol.geom.Point");goog.require("ol.geom.Polygon");goog.require("ol.interaction.DrawEventType");goog.require("ol.interaction.Pointer");goog.require("ol.interaction.Property");goog.require("ol.layer.Vector");goog.require("ol.source.Vector");goog.require("ol.style.Style");
ol.interaction.Draw=function(options){ol.interaction.Pointer.call(this,{handleDownEvent:ol.interaction.Draw.handleDownEvent_,handleEvent:ol.interaction.Draw.handleEvent,handleUpEvent:ol.interaction.Draw.handleUpEvent_});this.shouldHandle_=false;this.downPx_=null;this.freehand_=false;this.source_=options.source?options.source:null;this.features_=options.features?options.features:null;this.snapTolerance_=options.snapTolerance?options.snapTolerance:12;this.type_=options.type;this.mode_=ol.interaction.Draw.getMode_(this.type_);
this.stopClick_=!!options.stopClick;this.minPoints_=options.minPoints?options.minPoints:this.mode_===ol.interaction.Draw.Mode_.POLYGON?3:2;this.maxPoints_=options.maxPoints?options.maxPoints:Infinity;this.finishCondition_=options.finishCondition?options.finishCondition:ol.functions.TRUE;var geometryFunction=options.geometryFunction;if(!geometryFunction)if(this.type_===ol.geom.GeometryType.CIRCLE)geometryFunction=function(coordinates,opt_geometry){var circle=opt_geometry?opt_geometry:new ol.geom.Circle([NaN,
NaN]);var squaredLength=ol.coordinate.squaredDistance(coordinates[0],coordinates[1]);circle.setCenterAndRadius(coordinates[0],Math.sqrt(squaredLength));return circle};else{var Constructor;var mode=this.mode_;if(mode===ol.interaction.Draw.Mode_.POINT)Constructor=ol.geom.Point;else if(mode===ol.interaction.Draw.Mode_.LINE_STRING)Constructor=ol.geom.LineString;else if(mode===ol.interaction.Draw.Mode_.POLYGON)Constructor=ol.geom.Polygon;geometryFunction=function(coordinates,opt_geometry){var geometry=
opt_geometry;if(geometry)if(mode===ol.interaction.Draw.Mode_.POLYGON)if(coordinates[0].length)geometry.setCoordinates([coordinates[0].concat([coordinates[0][0]])]);else geometry.setCoordinates([]);else geometry.setCoordinates(coordinates);else geometry=new Constructor(coordinates);return geometry}}this.geometryFunction_=geometryFunction;this.finishCoordinate_=null;this.sketchFeature_=null;this.sketchPoint_=null;this.sketchCoords_=null;this.sketchLine_=null;this.sketchLineCoords_=null;this.squaredClickTolerance_=
options.clickTolerance?options.clickTolerance*options.clickTolerance:36;this.overlay_=new ol.layer.Vector({source:new ol.source.Vector({useSpatialIndex:false,wrapX:options.wrapX?options.wrapX:false}),style:options.style?options.style:ol.interaction.Draw.getDefaultStyleFunction()});this.geometryName_=options.geometryName;this.condition_=options.condition?options.condition:ol.events.condition.noModifierKeys;this.freehandCondition_;if(options.freehand)this.freehandCondition_=ol.events.condition.always;
else this.freehandCondition_=options.freehandCondition?options.freehandCondition:ol.events.condition.shiftKeyOnly;ol.events.listen(this,ol.Object.getChangeEventType(ol.interaction.Property.ACTIVE),this.updateState_,this)};ol.inherits(ol.interaction.Draw,ol.interaction.Pointer);ol.interaction.Draw.getDefaultStyleFunction=function(){var styles=ol.style.Style.createDefaultEditing();return function(feature,resolution){return styles[feature.getGeometry().getType()]}};
ol.interaction.Draw.prototype.setMap=function(map){ol.interaction.Pointer.prototype.setMap.call(this,map);this.updateState_()};
ol.interaction.Draw.handleEvent=function(event){this.freehand_=this.mode_!==ol.interaction.Draw.Mode_.POINT&&this.freehandCondition_(event);var pass=true;if(this.freehand_&&event.type===ol.MapBrowserEventType.POINTERDRAG&&this.sketchFeature_!==null){this.addToDrawing_(event);pass=false}else if(this.freehand_&&event.type===ol.MapBrowserEventType.POINTERDOWN)pass=false;else if(event.type===ol.MapBrowserEventType.POINTERMOVE)pass=this.handlePointerMove_(event);else if(event.type===ol.MapBrowserEventType.DBLCLICK)pass=
false;return ol.interaction.Pointer.handleEvent.call(this,event)&&pass};ol.interaction.Draw.handleDownEvent_=function(event){this.shouldHandle_=!this.freehand_;if(this.freehand_){this.downPx_=event.pixel;if(!this.finishCoordinate_)this.startDrawing_(event);return true}else if(this.condition_(event)){this.downPx_=event.pixel;return true}else return false};
ol.interaction.Draw.handleUpEvent_=function(event){var pass=true;this.handlePointerMove_(event);var circleMode=this.mode_===ol.interaction.Draw.Mode_.CIRCLE;if(this.shouldHandle_){if(!this.finishCoordinate_){this.startDrawing_(event);if(this.mode_===ol.interaction.Draw.Mode_.POINT)this.finishDrawing()}else if(this.freehand_||circleMode)this.finishDrawing();else if(this.atFinish_(event)){if(this.finishCondition_(event))this.finishDrawing()}else this.addToDrawing_(event);pass=false}else if(this.freehand_){this.finishCoordinate_=
null;this.abortDrawing_()}if(!pass&&this.stopClick_)event.stopPropagation();return pass};
ol.interaction.Draw.prototype.handlePointerMove_=function(event){if(this.downPx_&&(!this.freehand_&&this.shouldHandle_||this.freehand_&&!this.shouldHandle_)){var downPx=this.downPx_;var clickPx=event.pixel;var dx=downPx[0]-clickPx[0];var dy=downPx[1]-clickPx[1];var squaredDistance=dx*dx+dy*dy;this.shouldHandle_=this.freehand_?squaredDistance>this.squaredClickTolerance_:squaredDistance<=this.squaredClickTolerance_}if(this.finishCoordinate_)this.modifyDrawing_(event);else this.createOrUpdateSketchPoint_(event);
return true};
ol.interaction.Draw.prototype.atFinish_=function(event){var at=false;if(this.sketchFeature_){var potentiallyDone=false;var potentiallyFinishCoordinates=[this.finishCoordinate_];if(this.mode_===ol.interaction.Draw.Mode_.LINE_STRING)potentiallyDone=this.sketchCoords_.length>this.minPoints_;else if(this.mode_===ol.interaction.Draw.Mode_.POLYGON){potentiallyDone=this.sketchCoords_[0].length>this.minPoints_;potentiallyFinishCoordinates=[this.sketchCoords_[0][0],this.sketchCoords_[0][this.sketchCoords_[0].length-2]]}if(potentiallyDone){var map=
event.map;for(var i=0,ii=potentiallyFinishCoordinates.length;i<ii;i++){var finishCoordinate=potentiallyFinishCoordinates[i];var finishPixel=map.getPixelFromCoordinate(finishCoordinate);var pixel=event.pixel;var dx=pixel[0]-finishPixel[0];var dy=pixel[1]-finishPixel[1];var snapTolerance=this.freehand_?1:this.snapTolerance_;at=Math.sqrt(dx*dx+dy*dy)<=snapTolerance;if(at){this.finishCoordinate_=finishCoordinate;break}}}}return at};
ol.interaction.Draw.prototype.createOrUpdateSketchPoint_=function(event){var coordinates=event.coordinate.slice();if(!this.sketchPoint_){this.sketchPoint_=new ol.Feature(new ol.geom.Point(coordinates));this.updateSketchFeatures_()}else{var sketchPointGeom=this.sketchPoint_.getGeometry();sketchPointGeom.setCoordinates(coordinates)}};
ol.interaction.Draw.prototype.startDrawing_=function(event){var start=event.coordinate;this.finishCoordinate_=start;if(this.mode_===ol.interaction.Draw.Mode_.POINT)this.sketchCoords_=start.slice();else if(this.mode_===ol.interaction.Draw.Mode_.POLYGON){this.sketchCoords_=[[start.slice(),start.slice()]];this.sketchLineCoords_=this.sketchCoords_[0]}else{this.sketchCoords_=[start.slice(),start.slice()];if(this.mode_===ol.interaction.Draw.Mode_.CIRCLE)this.sketchLineCoords_=this.sketchCoords_}if(this.sketchLineCoords_)this.sketchLine_=
new ol.Feature(new ol.geom.LineString(this.sketchLineCoords_));var geometry=this.geometryFunction_(this.sketchCoords_);this.sketchFeature_=new ol.Feature;if(this.geometryName_)this.sketchFeature_.setGeometryName(this.geometryName_);this.sketchFeature_.setGeometry(geometry);this.updateSketchFeatures_();this.dispatchEvent(new ol.interaction.Draw.Event(ol.interaction.DrawEventType.DRAWSTART,this.sketchFeature_))};
ol.interaction.Draw.prototype.modifyDrawing_=function(event){var coordinate=event.coordinate;var geometry=this.sketchFeature_.getGeometry();var coordinates,last;if(this.mode_===ol.interaction.Draw.Mode_.POINT)last=this.sketchCoords_;else if(this.mode_===ol.interaction.Draw.Mode_.POLYGON){coordinates=this.sketchCoords_[0];last=coordinates[coordinates.length-1];if(this.atFinish_(event))coordinate=this.finishCoordinate_.slice()}else{coordinates=this.sketchCoords_;last=coordinates[coordinates.length-
1]}last[0]=coordinate[0];last[1]=coordinate[1];this.geometryFunction_(this.sketchCoords_,geometry);if(this.sketchPoint_){var sketchPointGeom=this.sketchPoint_.getGeometry();sketchPointGeom.setCoordinates(coordinate)}var sketchLineGeom;if(geometry instanceof ol.geom.Polygon&&this.mode_!==ol.interaction.Draw.Mode_.POLYGON){if(!this.sketchLine_)this.sketchLine_=new ol.Feature(new ol.geom.LineString(null));var ring=geometry.getLinearRing(0);sketchLineGeom=this.sketchLine_.getGeometry();sketchLineGeom.setFlatCoordinates(ring.getLayout(),
ring.getFlatCoordinates())}else if(this.sketchLineCoords_){sketchLineGeom=this.sketchLine_.getGeometry();sketchLineGeom.setCoordinates(this.sketchLineCoords_)}this.updateSketchFeatures_()};
ol.interaction.Draw.prototype.addToDrawing_=function(event){var coordinate=event.coordinate;var geometry=this.sketchFeature_.getGeometry();var done;var coordinates;if(this.mode_===ol.interaction.Draw.Mode_.LINE_STRING){this.finishCoordinate_=coordinate.slice();coordinates=this.sketchCoords_;if(coordinates.length>=this.maxPoints_)if(this.freehand_)coordinates.pop();else done=true;coordinates.push(coordinate.slice());this.geometryFunction_(coordinates,geometry)}else if(this.mode_===ol.interaction.Draw.Mode_.POLYGON){coordinates=
this.sketchCoords_[0];if(coordinates.length>=this.maxPoints_)if(this.freehand_)coordinates.pop();else done=true;coordinates.push(coordinate.slice());if(done)this.finishCoordinate_=coordinates[0];this.geometryFunction_(this.sketchCoords_,geometry)}this.updateSketchFeatures_();if(done)this.finishDrawing()};
ol.interaction.Draw.prototype.removeLastPoint=function(){if(!this.sketchFeature_)return;var geometry=this.sketchFeature_.getGeometry();var coordinates,sketchLineGeom;if(this.mode_===ol.interaction.Draw.Mode_.LINE_STRING){coordinates=this.sketchCoords_;coordinates.splice(-2,1);this.geometryFunction_(coordinates,geometry);if(coordinates.length>=2)this.finishCoordinate_=coordinates[coordinates.length-2].slice()}else if(this.mode_===ol.interaction.Draw.Mode_.POLYGON){coordinates=this.sketchCoords_[0];
coordinates.splice(-2,1);sketchLineGeom=this.sketchLine_.getGeometry();sketchLineGeom.setCoordinates(coordinates);this.geometryFunction_(this.sketchCoords_,geometry)}if(coordinates.length===0)this.finishCoordinate_=null;this.updateSketchFeatures_()};
ol.interaction.Draw.prototype.finishDrawing=function(){var sketchFeature=this.abortDrawing_();var coordinates=this.sketchCoords_;var geometry=sketchFeature.getGeometry();if(this.mode_===ol.interaction.Draw.Mode_.LINE_STRING){coordinates.pop();this.geometryFunction_(coordinates,geometry)}else if(this.mode_===ol.interaction.Draw.Mode_.POLYGON){coordinates[0].pop();this.geometryFunction_(coordinates,geometry);coordinates=geometry.getCoordinates()}if(this.type_===ol.geom.GeometryType.MULTI_POINT)sketchFeature.setGeometry(new ol.geom.MultiPoint([coordinates]));
else if(this.type_===ol.geom.GeometryType.MULTI_LINE_STRING)sketchFeature.setGeometry(new ol.geom.MultiLineString([coordinates]));else if(this.type_===ol.geom.GeometryType.MULTI_POLYGON)sketchFeature.setGeometry(new ol.geom.MultiPolygon([coordinates]));this.dispatchEvent(new ol.interaction.Draw.Event(ol.interaction.DrawEventType.DRAWEND,sketchFeature));if(this.features_)this.features_.push(sketchFeature);if(this.source_)this.source_.addFeature(sketchFeature)};
ol.interaction.Draw.prototype.abortDrawing_=function(){this.finishCoordinate_=null;var sketchFeature=this.sketchFeature_;if(sketchFeature){this.sketchFeature_=null;this.sketchPoint_=null;this.sketchLine_=null;this.overlay_.getSource().clear(true)}return sketchFeature};
ol.interaction.Draw.prototype.extend=function(feature){var geometry=feature.getGeometry();var lineString=geometry;this.sketchFeature_=feature;this.sketchCoords_=lineString.getCoordinates();var last=this.sketchCoords_[this.sketchCoords_.length-1];this.finishCoordinate_=last.slice();this.sketchCoords_.push(last.slice());this.updateSketchFeatures_();this.dispatchEvent(new ol.interaction.Draw.Event(ol.interaction.DrawEventType.DRAWSTART,this.sketchFeature_))};
ol.interaction.Draw.prototype.shouldStopEvent=ol.functions.FALSE;ol.interaction.Draw.prototype.updateSketchFeatures_=function(){var sketchFeatures=[];if(this.sketchFeature_)sketchFeatures.push(this.sketchFeature_);if(this.sketchLine_)sketchFeatures.push(this.sketchLine_);if(this.sketchPoint_)sketchFeatures.push(this.sketchPoint_);var overlaySource=this.overlay_.getSource();overlaySource.clear(true);overlaySource.addFeatures(sketchFeatures)};
ol.interaction.Draw.prototype.updateState_=function(){var map=this.getMap();var active=this.getActive();if(!map||!active)this.abortDrawing_();this.overlay_.setMap(active?map:null)};
ol.interaction.Draw.createRegularPolygon=function(opt_sides,opt_angle){return function(coordinates,opt_geometry){var center=coordinates[0];var end=coordinates[1];var radius=Math.sqrt(ol.coordinate.squaredDistance(center,end));var geometry=opt_geometry?opt_geometry:ol.geom.Polygon.fromCircle(new ol.geom.Circle(center),opt_sides);var angle=opt_angle?opt_angle:Math.atan((end[1]-center[1])/(end[0]-center[0]));ol.geom.Polygon.makeRegular(geometry,center,radius,angle);return geometry}};
ol.interaction.Draw.createBox=function(){return function(coordinates,opt_geometry){var extent=ol.extent.boundingExtent(coordinates);var geometry=opt_geometry||new ol.geom.Polygon(null);geometry.setCoordinates([[ol.extent.getBottomLeft(extent),ol.extent.getBottomRight(extent),ol.extent.getTopRight(extent),ol.extent.getTopLeft(extent),ol.extent.getBottomLeft(extent)]]);return geometry}};
ol.interaction.Draw.getMode_=function(type){var mode;if(type===ol.geom.GeometryType.POINT||type===ol.geom.GeometryType.MULTI_POINT)mode=ol.interaction.Draw.Mode_.POINT;else if(type===ol.geom.GeometryType.LINE_STRING||type===ol.geom.GeometryType.MULTI_LINE_STRING)mode=ol.interaction.Draw.Mode_.LINE_STRING;else if(type===ol.geom.GeometryType.POLYGON||type===ol.geom.GeometryType.MULTI_POLYGON)mode=ol.interaction.Draw.Mode_.POLYGON;else if(type===ol.geom.GeometryType.CIRCLE)mode=ol.interaction.Draw.Mode_.CIRCLE;
return mode};ol.interaction.Draw.Mode_={POINT:"Point",LINE_STRING:"LineString",POLYGON:"Polygon",CIRCLE:"Circle"};ol.interaction.Draw.Event=function(type,feature){ol.events.Event.call(this,type);this.feature=feature};ol.inherits(ol.interaction.Draw.Event,ol.events.Event);goog.provide("ol.interaction.ExtentEventType");ol.interaction.ExtentEventType={EXTENTCHANGED:"extentchanged"};goog.provide("ol.interaction.Extent");goog.require("ol");goog.require("ol.Feature");goog.require("ol.MapBrowserEventType");goog.require("ol.MapBrowserPointerEvent");goog.require("ol.coordinate");goog.require("ol.events.Event");goog.require("ol.extent");goog.require("ol.geom.GeometryType");goog.require("ol.geom.Point");goog.require("ol.geom.Polygon");goog.require("ol.interaction.ExtentEventType");goog.require("ol.interaction.Pointer");goog.require("ol.layer.Vector");goog.require("ol.source.Vector");
goog.require("ol.style.Style");
ol.interaction.Extent=function(opt_options){var options=opt_options||{};this.extent_=null;this.pointerHandler_=null;this.pixelTolerance_=options.pixelTolerance!==undefined?options.pixelTolerance:10;this.snappedToVertex_=false;this.extentFeature_=null;this.vertexFeature_=null;if(!opt_options)opt_options={};ol.interaction.Pointer.call(this,{handleDownEvent:ol.interaction.Extent.handleDownEvent_,handleDragEvent:ol.interaction.Extent.handleDragEvent_,handleEvent:ol.interaction.Extent.handleEvent_,handleUpEvent:ol.interaction.Extent.handleUpEvent_});
this.extentOverlay_=new ol.layer.Vector({source:new ol.source.Vector({useSpatialIndex:false,wrapX:!!opt_options.wrapX}),style:opt_options.boxStyle?opt_options.boxStyle:ol.interaction.Extent.getDefaultExtentStyleFunction_(),updateWhileAnimating:true,updateWhileInteracting:true});this.vertexOverlay_=new ol.layer.Vector({source:new ol.source.Vector({useSpatialIndex:false,wrapX:!!opt_options.wrapX}),style:opt_options.pointerStyle?opt_options.pointerStyle:ol.interaction.Extent.getDefaultPointerStyleFunction_(),
updateWhileAnimating:true,updateWhileInteracting:true});if(opt_options.extent)this.setExtent(opt_options.extent)};ol.inherits(ol.interaction.Extent,ol.interaction.Pointer);ol.interaction.Extent.handleEvent_=function(mapBrowserEvent){if(!(mapBrowserEvent instanceof ol.MapBrowserPointerEvent))return true;if(mapBrowserEvent.type==ol.MapBrowserEventType.POINTERMOVE&&!this.handlingDownUpSequence)this.handlePointerMove_(mapBrowserEvent);ol.interaction.Pointer.handleEvent.call(this,mapBrowserEvent);return false};
ol.interaction.Extent.handleDownEvent_=function(mapBrowserEvent){var pixel=mapBrowserEvent.pixel;var map=mapBrowserEvent.map;var extent=this.getExtent();var vertex=this.snapToVertex_(pixel,map);var getOpposingPoint=function(point){var x_=null;var y_=null;if(point[0]==extent[0])x_=extent[2];else if(point[0]==extent[2])x_=extent[0];if(point[1]==extent[1])y_=extent[3];else if(point[1]==extent[3])y_=extent[1];if(x_!==null&&y_!==null)return[x_,y_];return null};if(vertex&&extent){var x=vertex[0]==extent[0]||
vertex[0]==extent[2]?vertex[0]:null;var y=vertex[1]==extent[1]||vertex[1]==extent[3]?vertex[1]:null;if(x!==null&&y!==null)this.pointerHandler_=ol.interaction.Extent.getPointHandler_(getOpposingPoint(vertex));else if(x!==null)this.pointerHandler_=ol.interaction.Extent.getEdgeHandler_(getOpposingPoint([x,extent[1]]),getOpposingPoint([x,extent[3]]));else if(y!==null)this.pointerHandler_=ol.interaction.Extent.getEdgeHandler_(getOpposingPoint([extent[0],y]),getOpposingPoint([extent[2],y]))}else{vertex=
map.getCoordinateFromPixel(pixel);this.setExtent([vertex[0],vertex[1],vertex[0],vertex[1]]);this.pointerHandler_=ol.interaction.Extent.getPointHandler_(vertex)}return true};ol.interaction.Extent.handleDragEvent_=function(mapBrowserEvent){if(this.pointerHandler_){var pixelCoordinate=mapBrowserEvent.coordinate;this.setExtent(this.pointerHandler_(pixelCoordinate));this.createOrUpdatePointerFeature_(pixelCoordinate)}return true};
ol.interaction.Extent.handleUpEvent_=function(mapBrowserEvent){this.pointerHandler_=null;var extent=this.getExtent();if(!extent||ol.extent.getArea(extent)===0)this.setExtent(null);return false};ol.interaction.Extent.getDefaultExtentStyleFunction_=function(){var style=ol.style.Style.createDefaultEditing();return function(feature,resolution){return style[ol.geom.GeometryType.POLYGON]}};
ol.interaction.Extent.getDefaultPointerStyleFunction_=function(){var style=ol.style.Style.createDefaultEditing();return function(feature,resolution){return style[ol.geom.GeometryType.POINT]}};ol.interaction.Extent.getPointHandler_=function(fixedPoint){return function(point){return ol.extent.boundingExtent([fixedPoint,point])}};
ol.interaction.Extent.getEdgeHandler_=function(fixedP1,fixedP2){if(fixedP1[0]==fixedP2[0])return function(point){return ol.extent.boundingExtent([fixedP1,[point[0],fixedP2[1]]])};else if(fixedP1[1]==fixedP2[1])return function(point){return ol.extent.boundingExtent([fixedP1,[fixedP2[0],point[1]]])};else return null};
ol.interaction.Extent.getSegments_=function(extent){return[[[extent[0],extent[1]],[extent[0],extent[3]]],[[extent[0],extent[3]],[extent[2],extent[3]]],[[extent[2],extent[3]],[extent[2],extent[1]]],[[extent[2],extent[1]],[extent[0],extent[1]]]]};
ol.interaction.Extent.prototype.snapToVertex_=function(pixel,map){var pixelCoordinate=map.getCoordinateFromPixel(pixel);var sortByDistance=function(a,b){return ol.coordinate.squaredDistanceToSegment(pixelCoordinate,a)-ol.coordinate.squaredDistanceToSegment(pixelCoordinate,b)};var extent=this.getExtent();if(extent){var segments=ol.interaction.Extent.getSegments_(extent);segments.sort(sortByDistance);var closestSegment=segments[0];var vertex=ol.coordinate.closestOnSegment(pixelCoordinate,closestSegment);
var vertexPixel=map.getPixelFromCoordinate(vertex);if(ol.coordinate.distance(pixel,vertexPixel)<=this.pixelTolerance_){var pixel1=map.getPixelFromCoordinate(closestSegment[0]);var pixel2=map.getPixelFromCoordinate(closestSegment[1]);var squaredDist1=ol.coordinate.squaredDistance(vertexPixel,pixel1);var squaredDist2=ol.coordinate.squaredDistance(vertexPixel,pixel2);var dist=Math.sqrt(Math.min(squaredDist1,squaredDist2));this.snappedToVertex_=dist<=this.pixelTolerance_;if(this.snappedToVertex_)vertex=
squaredDist1>squaredDist2?closestSegment[1]:closestSegment[0];return vertex}}return null};ol.interaction.Extent.prototype.handlePointerMove_=function(mapBrowserEvent){var pixel=mapBrowserEvent.pixel;var map=mapBrowserEvent.map;var vertex=this.snapToVertex_(pixel,map);if(!vertex)vertex=map.getCoordinateFromPixel(pixel);this.createOrUpdatePointerFeature_(vertex)};
ol.interaction.Extent.prototype.createOrUpdateExtentFeature_=function(extent){var extentFeature=this.extentFeature_;if(!extentFeature){if(!extent)extentFeature=new ol.Feature({});else extentFeature=new ol.Feature(ol.geom.Polygon.fromExtent(extent));this.extentFeature_=extentFeature;this.extentOverlay_.getSource().addFeature(extentFeature)}else if(!extent)extentFeature.setGeometry(undefined);else extentFeature.setGeometry(ol.geom.Polygon.fromExtent(extent));return extentFeature};
ol.interaction.Extent.prototype.createOrUpdatePointerFeature_=function(vertex){var vertexFeature=this.vertexFeature_;if(!vertexFeature){vertexFeature=new ol.Feature(new ol.geom.Point(vertex));this.vertexFeature_=vertexFeature;this.vertexOverlay_.getSource().addFeature(vertexFeature)}else{var geometry=vertexFeature.getGeometry();geometry.setCoordinates(vertex)}return vertexFeature};
ol.interaction.Extent.prototype.setMap=function(map){this.extentOverlay_.setMap(map);this.vertexOverlay_.setMap(map);ol.interaction.Pointer.prototype.setMap.call(this,map)};ol.interaction.Extent.prototype.getExtent=function(){return this.extent_};ol.interaction.Extent.prototype.setExtent=function(extent){this.extent_=extent?extent:null;this.createOrUpdateExtentFeature_(extent);this.dispatchEvent(new ol.interaction.Extent.Event(this.extent_))};
ol.interaction.Extent.Event=function(extent){ol.events.Event.call(this,ol.interaction.ExtentEventType.EXTENTCHANGED);this.extent=extent};ol.inherits(ol.interaction.Extent.Event,ol.events.Event);goog.provide("ol.interaction.ModifyEventType");ol.interaction.ModifyEventType={MODIFYSTART:"modifystart",MODIFYEND:"modifyend"};goog.provide("ol.interaction.Modify");goog.require("ol");goog.require("ol.Collection");goog.require("ol.CollectionEventType");goog.require("ol.Feature");goog.require("ol.MapBrowserEventType");goog.require("ol.MapBrowserPointerEvent");goog.require("ol.array");goog.require("ol.coordinate");goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.events.EventType");goog.require("ol.events.condition");goog.require("ol.extent");goog.require("ol.geom.GeometryType");goog.require("ol.geom.Point");
goog.require("ol.interaction.ModifyEventType");goog.require("ol.interaction.Pointer");goog.require("ol.layer.Vector");goog.require("ol.source.Vector");goog.require("ol.source.VectorEventType");goog.require("ol.structs.RBush");goog.require("ol.style.Style");
ol.interaction.Modify=function(options){ol.interaction.Pointer.call(this,{handleDownEvent:ol.interaction.Modify.handleDownEvent_,handleDragEvent:ol.interaction.Modify.handleDragEvent_,handleEvent:ol.interaction.Modify.handleEvent,handleUpEvent:ol.interaction.Modify.handleUpEvent_});this.condition_=options.condition?options.condition:ol.events.condition.primaryAction;this.defaultDeleteCondition_=function(mapBrowserEvent){return ol.events.condition.altKeyOnly(mapBrowserEvent)&&ol.events.condition.singleClick(mapBrowserEvent)};
this.deleteCondition_=options.deleteCondition?options.deleteCondition:this.defaultDeleteCondition_;this.insertVertexCondition_=options.insertVertexCondition?options.insertVertexCondition:ol.events.condition.always;this.vertexFeature_=null;this.vertexSegments_=null;this.lastPixel_=[0,0];this.ignoreNextSingleClick_=false;this.modified_=false;this.rBush_=new ol.structs.RBush;this.pixelTolerance_=options.pixelTolerance!==undefined?options.pixelTolerance:10;this.snappedToVertex_=false;this.changingFeature_=
false;this.dragSegments_=[];this.overlay_=new ol.layer.Vector({source:new ol.source.Vector({useSpatialIndex:false,wrapX:!!options.wrapX}),style:options.style?options.style:ol.interaction.Modify.getDefaultStyleFunction(),updateWhileAnimating:true,updateWhileInteracting:true});this.SEGMENT_WRITERS_={"Point":this.writePointGeometry_,"LineString":this.writeLineStringGeometry_,"LinearRing":this.writeLineStringGeometry_,"Polygon":this.writePolygonGeometry_,"MultiPoint":this.writeMultiPointGeometry_,"MultiLineString":this.writeMultiLineStringGeometry_,
"MultiPolygon":this.writeMultiPolygonGeometry_,"Circle":this.writeCircleGeometry_,"GeometryCollection":this.writeGeometryCollectionGeometry_};this.source_=null;var features;if(options.source){this.source_=options.source;features=new ol.Collection(this.source_.getFeatures());ol.events.listen(this.source_,ol.source.VectorEventType.ADDFEATURE,this.handleSourceAdd_,this);ol.events.listen(this.source_,ol.source.VectorEventType.REMOVEFEATURE,this.handleSourceRemove_,this)}else features=options.features;
if(!features)throw new Error("The modify interaction requires features or a source");this.features_=features;this.features_.forEach(this.addFeature_,this);ol.events.listen(this.features_,ol.CollectionEventType.ADD,this.handleFeatureAdd_,this);ol.events.listen(this.features_,ol.CollectionEventType.REMOVE,this.handleFeatureRemove_,this);this.lastPointerEvent_=null};ol.inherits(ol.interaction.Modify,ol.interaction.Pointer);ol.interaction.Modify.MODIFY_SEGMENT_CIRCLE_CENTER_INDEX=0;
ol.interaction.Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX=1;ol.interaction.Modify.prototype.addFeature_=function(feature){var geometry=feature.getGeometry();if(geometry&&geometry.getType()in this.SEGMENT_WRITERS_)this.SEGMENT_WRITERS_[geometry.getType()].call(this,feature,geometry);var map=this.getMap();if(map&&map.isRendered()&&this.getActive())this.handlePointerAtPixel_(this.lastPixel_,map);ol.events.listen(feature,ol.events.EventType.CHANGE,this.handleFeatureChange_,this)};
ol.interaction.Modify.prototype.willModifyFeatures_=function(evt){if(!this.modified_){this.modified_=true;this.dispatchEvent(new ol.interaction.Modify.Event(ol.interaction.ModifyEventType.MODIFYSTART,this.features_,evt))}};
ol.interaction.Modify.prototype.removeFeature_=function(feature){this.removeFeatureSegmentData_(feature);if(this.vertexFeature_&&this.features_.getLength()===0){this.overlay_.getSource().removeFeature(this.vertexFeature_);this.vertexFeature_=null}ol.events.unlisten(feature,ol.events.EventType.CHANGE,this.handleFeatureChange_,this)};
ol.interaction.Modify.prototype.removeFeatureSegmentData_=function(feature){var rBush=this.rBush_;var nodesToRemove=[];rBush.forEach(function(node){if(feature===node.feature)nodesToRemove.push(node)});for(var i=nodesToRemove.length-1;i>=0;--i)rBush.remove(nodesToRemove[i])};
ol.interaction.Modify.prototype.setActive=function(active){if(this.vertexFeature_&&!active){this.overlay_.getSource().removeFeature(this.vertexFeature_);this.vertexFeature_=null}ol.interaction.Pointer.prototype.setActive.call(this,active)};ol.interaction.Modify.prototype.setMap=function(map){this.overlay_.setMap(map);ol.interaction.Pointer.prototype.setMap.call(this,map)};ol.interaction.Modify.prototype.handleSourceAdd_=function(event){if(event.feature)this.features_.push(event.feature)};
ol.interaction.Modify.prototype.handleSourceRemove_=function(event){if(event.feature)this.features_.remove(event.feature)};ol.interaction.Modify.prototype.handleFeatureAdd_=function(evt){this.addFeature_(evt.element)};ol.interaction.Modify.prototype.handleFeatureChange_=function(evt){if(!this.changingFeature_){var feature=evt.target;this.removeFeature_(feature);this.addFeature_(feature)}};ol.interaction.Modify.prototype.handleFeatureRemove_=function(evt){var feature=evt.element;this.removeFeature_(feature)};
ol.interaction.Modify.prototype.writePointGeometry_=function(feature,geometry){var coordinates=geometry.getCoordinates();var segmentData={feature:feature,geometry:geometry,segment:[coordinates,coordinates]};this.rBush_.insert(geometry.getExtent(),segmentData)};
ol.interaction.Modify.prototype.writeMultiPointGeometry_=function(feature,geometry){var points=geometry.getCoordinates();var coordinates,i,ii,segmentData;for(i=0,ii=points.length;i<ii;++i){coordinates=points[i];segmentData={feature:feature,geometry:geometry,depth:[i],index:i,segment:[coordinates,coordinates]};this.rBush_.insert(geometry.getExtent(),segmentData)}};
ol.interaction.Modify.prototype.writeLineStringGeometry_=function(feature,geometry){var coordinates=geometry.getCoordinates();var i,ii,segment,segmentData;for(i=0,ii=coordinates.length-1;i<ii;++i){segment=coordinates.slice(i,i+2);segmentData={feature:feature,geometry:geometry,index:i,segment:segment};this.rBush_.insert(ol.extent.boundingExtent(segment),segmentData)}};
ol.interaction.Modify.prototype.writeMultiLineStringGeometry_=function(feature,geometry){var lines=geometry.getCoordinates();var coordinates,i,ii,j,jj,segment,segmentData;for(j=0,jj=lines.length;j<jj;++j){coordinates=lines[j];for(i=0,ii=coordinates.length-1;i<ii;++i){segment=coordinates.slice(i,i+2);segmentData={feature:feature,geometry:geometry,depth:[j],index:i,segment:segment};this.rBush_.insert(ol.extent.boundingExtent(segment),segmentData)}}};
ol.interaction.Modify.prototype.writePolygonGeometry_=function(feature,geometry){var rings=geometry.getCoordinates();var coordinates,i,ii,j,jj,segment,segmentData;for(j=0,jj=rings.length;j<jj;++j){coordinates=rings[j];for(i=0,ii=coordinates.length-1;i<ii;++i){segment=coordinates.slice(i,i+2);segmentData={feature:feature,geometry:geometry,depth:[j],index:i,segment:segment};this.rBush_.insert(ol.extent.boundingExtent(segment),segmentData)}}};
ol.interaction.Modify.prototype.writeMultiPolygonGeometry_=function(feature,geometry){var polygons=geometry.getCoordinates();var coordinates,i,ii,j,jj,k,kk,rings,segment,segmentData;for(k=0,kk=polygons.length;k<kk;++k){rings=polygons[k];for(j=0,jj=rings.length;j<jj;++j){coordinates=rings[j];for(i=0,ii=coordinates.length-1;i<ii;++i){segment=coordinates.slice(i,i+2);segmentData={feature:feature,geometry:geometry,depth:[j,k],index:i,segment:segment};this.rBush_.insert(ol.extent.boundingExtent(segment),
segmentData)}}}};
ol.interaction.Modify.prototype.writeCircleGeometry_=function(feature,geometry){var coordinates=geometry.getCenter();var centerSegmentData={feature:feature,geometry:geometry,index:ol.interaction.Modify.MODIFY_SEGMENT_CIRCLE_CENTER_INDEX,segment:[coordinates,coordinates]};var circumferenceSegmentData={feature:feature,geometry:geometry,index:ol.interaction.Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX,segment:[coordinates,coordinates]};var featureSegments=[centerSegmentData,circumferenceSegmentData];centerSegmentData.featureSegments=
circumferenceSegmentData.featureSegments=featureSegments;this.rBush_.insert(ol.extent.createOrUpdateFromCoordinate(coordinates),centerSegmentData);this.rBush_.insert(geometry.getExtent(),circumferenceSegmentData)};ol.interaction.Modify.prototype.writeGeometryCollectionGeometry_=function(feature,geometry){var i,geometries=geometry.getGeometriesArray();for(i=0;i<geometries.length;++i)this.SEGMENT_WRITERS_[geometries[i].getType()].call(this,feature,geometries[i])};
ol.interaction.Modify.prototype.createOrUpdateVertexFeature_=function(coordinates){var vertexFeature=this.vertexFeature_;if(!vertexFeature){vertexFeature=new ol.Feature(new ol.geom.Point(coordinates));this.vertexFeature_=vertexFeature;this.overlay_.getSource().addFeature(vertexFeature)}else{var geometry=vertexFeature.getGeometry();geometry.setCoordinates(coordinates)}return vertexFeature};ol.interaction.Modify.compareIndexes_=function(a,b){return a.index-b.index};
ol.interaction.Modify.handleDownEvent_=function(evt){if(!this.condition_(evt))return false;this.handlePointerAtPixel_(evt.pixel,evt.map);var pixelCoordinate=evt.map.getCoordinateFromPixel(evt.pixel);this.dragSegments_.length=0;this.modified_=false;var vertexFeature=this.vertexFeature_;if(vertexFeature){var insertVertices=[];var geometry=vertexFeature.getGeometry();var vertex=geometry.getCoordinates();var vertexExtent=ol.extent.boundingExtent([vertex]);var segmentDataMatches=this.rBush_.getInExtent(vertexExtent);
var componentSegments={};segmentDataMatches.sort(ol.interaction.Modify.compareIndexes_);for(var i=0,ii=segmentDataMatches.length;i<ii;++i){var segmentDataMatch=segmentDataMatches[i];var segment=segmentDataMatch.segment;var uid=ol.getUid(segmentDataMatch.feature);var depth=segmentDataMatch.depth;if(depth)uid+="-"+depth.join("-");if(!componentSegments[uid])componentSegments[uid]=new Array(2);if(segmentDataMatch.geometry.getType()===ol.geom.GeometryType.CIRCLE&&segmentDataMatch.index===ol.interaction.Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX){var closestVertex=
ol.interaction.Modify.closestOnSegmentData_(pixelCoordinate,segmentDataMatch);if(ol.coordinate.equals(closestVertex,vertex)&&!componentSegments[uid][0]){this.dragSegments_.push([segmentDataMatch,0]);componentSegments[uid][0]=segmentDataMatch}}else if(ol.coordinate.equals(segment[0],vertex)&&!componentSegments[uid][0]){this.dragSegments_.push([segmentDataMatch,0]);componentSegments[uid][0]=segmentDataMatch}else if(ol.coordinate.equals(segment[1],vertex)&&!componentSegments[uid][1]){if((segmentDataMatch.geometry.getType()===
ol.geom.GeometryType.LINE_STRING||segmentDataMatch.geometry.getType()===ol.geom.GeometryType.MULTI_LINE_STRING)&&componentSegments[uid][0]&&componentSegments[uid][0].index===0)continue;this.dragSegments_.push([segmentDataMatch,1]);componentSegments[uid][1]=segmentDataMatch}else if(this.insertVertexCondition_(evt)&&ol.getUid(segment)in this.vertexSegments_&&(!componentSegments[uid][0]&&!componentSegments[uid][1]))insertVertices.push([segmentDataMatch,vertex])}if(insertVertices.length)this.willModifyFeatures_(evt);
for(var j=insertVertices.length-1;j>=0;--j)this.insertVertex_.apply(this,insertVertices[j])}return!!this.vertexFeature_};
ol.interaction.Modify.handleDragEvent_=function(evt){this.ignoreNextSingleClick_=false;this.willModifyFeatures_(evt);var vertex=evt.coordinate;for(var i=0,ii=this.dragSegments_.length;i<ii;++i){var dragSegment=this.dragSegments_[i];var segmentData=dragSegment[0];var depth=segmentData.depth;var geometry=segmentData.geometry;var coordinates;var segment=segmentData.segment;var index=dragSegment[1];while(vertex.length<geometry.getStride())vertex.push(segment[index][vertex.length]);switch(geometry.getType()){case ol.geom.GeometryType.POINT:coordinates=
vertex;segment[0]=segment[1]=vertex;break;case ol.geom.GeometryType.MULTI_POINT:coordinates=geometry.getCoordinates();coordinates[segmentData.index]=vertex;segment[0]=segment[1]=vertex;break;case ol.geom.GeometryType.LINE_STRING:coordinates=geometry.getCoordinates();coordinates[segmentData.index+index]=vertex;segment[index]=vertex;break;case ol.geom.GeometryType.MULTI_LINE_STRING:coordinates=geometry.getCoordinates();coordinates[depth[0]][segmentData.index+index]=vertex;segment[index]=vertex;break;
case ol.geom.GeometryType.POLYGON:coordinates=geometry.getCoordinates();coordinates[depth[0]][segmentData.index+index]=vertex;segment[index]=vertex;break;case ol.geom.GeometryType.MULTI_POLYGON:coordinates=geometry.getCoordinates();coordinates[depth[1]][depth[0]][segmentData.index+index]=vertex;segment[index]=vertex;break;case ol.geom.GeometryType.CIRCLE:segment[0]=segment[1]=vertex;if(segmentData.index===ol.interaction.Modify.MODIFY_SEGMENT_CIRCLE_CENTER_INDEX){this.changingFeature_=true;geometry.setCenter(vertex);
this.changingFeature_=false}else{this.changingFeature_=true;geometry.setRadius(ol.coordinate.distance(geometry.getCenter(),vertex));this.changingFeature_=false}break;default:}if(coordinates)this.setGeometryCoordinates_(geometry,coordinates)}this.createOrUpdateVertexFeature_(vertex)};
ol.interaction.Modify.handleUpEvent_=function(evt){var segmentData;var geometry;for(var i=this.dragSegments_.length-1;i>=0;--i){segmentData=this.dragSegments_[i][0];geometry=segmentData.geometry;if(geometry.getType()===ol.geom.GeometryType.CIRCLE){var coordinates=geometry.getCenter();var centerSegmentData=segmentData.featureSegments[0];var circumferenceSegmentData=segmentData.featureSegments[1];centerSegmentData.segment[0]=centerSegmentData.segment[1]=coordinates;circumferenceSegmentData.segment[0]=
circumferenceSegmentData.segment[1]=coordinates;this.rBush_.update(ol.extent.createOrUpdateFromCoordinate(coordinates),centerSegmentData);this.rBush_.update(geometry.getExtent(),circumferenceSegmentData)}else this.rBush_.update(ol.extent.boundingExtent(segmentData.segment),segmentData)}if(this.modified_){this.dispatchEvent(new ol.interaction.Modify.Event(ol.interaction.ModifyEventType.MODIFYEND,this.features_,evt));this.modified_=false}return false};
ol.interaction.Modify.handleEvent=function(mapBrowserEvent){if(!(mapBrowserEvent instanceof ol.MapBrowserPointerEvent))return true;this.lastPointerEvent_=mapBrowserEvent;var handled;if(!mapBrowserEvent.map.getView().getInteracting()&&mapBrowserEvent.type==ol.MapBrowserEventType.POINTERMOVE&&!this.handlingDownUpSequence)this.handlePointerMove_(mapBrowserEvent);if(this.vertexFeature_&&this.deleteCondition_(mapBrowserEvent))if(mapBrowserEvent.type!=ol.MapBrowserEventType.SINGLECLICK||!this.ignoreNextSingleClick_)handled=
this.removePoint();else handled=true;if(mapBrowserEvent.type==ol.MapBrowserEventType.SINGLECLICK)this.ignoreNextSingleClick_=false;return ol.interaction.Pointer.handleEvent.call(this,mapBrowserEvent)&&!handled};ol.interaction.Modify.prototype.handlePointerMove_=function(evt){this.lastPixel_=evt.pixel;this.handlePointerAtPixel_(evt.pixel,evt.map)};
ol.interaction.Modify.prototype.handlePointerAtPixel_=function(pixel,map){var pixelCoordinate=map.getCoordinateFromPixel(pixel);var sortByDistance=function(a,b){return ol.interaction.Modify.pointDistanceToSegmentDataSquared_(pixelCoordinate,a)-ol.interaction.Modify.pointDistanceToSegmentDataSquared_(pixelCoordinate,b)};var box=ol.extent.buffer(ol.extent.createOrUpdateFromCoordinate(pixelCoordinate),map.getView().getResolution()*this.pixelTolerance_);var rBush=this.rBush_;var nodes=rBush.getInExtent(box);
if(nodes.length>0){nodes.sort(sortByDistance);var node=nodes[0];var closestSegment=node.segment;var vertex=ol.interaction.Modify.closestOnSegmentData_(pixelCoordinate,node);var vertexPixel=map.getPixelFromCoordinate(vertex);var dist=ol.coordinate.distance(pixel,vertexPixel);if(dist<=this.pixelTolerance_){var vertexSegments={};if(node.geometry.getType()===ol.geom.GeometryType.CIRCLE&&node.index===ol.interaction.Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX){this.snappedToVertex_=true;this.createOrUpdateVertexFeature_(vertex)}else{var pixel1=
map.getPixelFromCoordinate(closestSegment[0]);var pixel2=map.getPixelFromCoordinate(closestSegment[1]);var squaredDist1=ol.coordinate.squaredDistance(vertexPixel,pixel1);var squaredDist2=ol.coordinate.squaredDistance(vertexPixel,pixel2);dist=Math.sqrt(Math.min(squaredDist1,squaredDist2));this.snappedToVertex_=dist<=this.pixelTolerance_;if(this.snappedToVertex_)vertex=squaredDist1>squaredDist2?closestSegment[1]:closestSegment[0];this.createOrUpdateVertexFeature_(vertex);var segment;for(var i=1,ii=
nodes.length;i<ii;++i){segment=nodes[i].segment;if(ol.coordinate.equals(closestSegment[0],segment[0])&&ol.coordinate.equals(closestSegment[1],segment[1])||ol.coordinate.equals(closestSegment[0],segment[1])&&ol.coordinate.equals(closestSegment[1],segment[0]))vertexSegments[ol.getUid(segment)]=true;else break}}vertexSegments[ol.getUid(closestSegment)]=true;this.vertexSegments_=vertexSegments;return}}if(this.vertexFeature_){this.overlay_.getSource().removeFeature(this.vertexFeature_);this.vertexFeature_=
null}};
ol.interaction.Modify.pointDistanceToSegmentDataSquared_=function(pointCoordinates,segmentData){var geometry=segmentData.geometry;if(geometry.getType()===ol.geom.GeometryType.CIRCLE){var circleGeometry=geometry;if(segmentData.index===ol.interaction.Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX){var distanceToCenterSquared=ol.coordinate.squaredDistance(circleGeometry.getCenter(),pointCoordinates);var distanceToCircumference=Math.sqrt(distanceToCenterSquared)-circleGeometry.getRadius();return distanceToCircumference*distanceToCircumference}}return ol.coordinate.squaredDistanceToSegment(pointCoordinates,
segmentData.segment)};ol.interaction.Modify.closestOnSegmentData_=function(pointCoordinates,segmentData){var geometry=segmentData.geometry;if(geometry.getType()===ol.geom.GeometryType.CIRCLE&&segmentData.index===ol.interaction.Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX)return geometry.getClosestPoint(pointCoordinates);return ol.coordinate.closestOnSegment(pointCoordinates,segmentData.segment)};
ol.interaction.Modify.prototype.insertVertex_=function(segmentData,vertex){var segment=segmentData.segment;var feature=segmentData.feature;var geometry=segmentData.geometry;var depth=segmentData.depth;var index=segmentData.index;var coordinates;while(vertex.length<geometry.getStride())vertex.push(0);switch(geometry.getType()){case ol.geom.GeometryType.MULTI_LINE_STRING:coordinates=geometry.getCoordinates();coordinates[depth[0]].splice(index+1,0,vertex);break;case ol.geom.GeometryType.POLYGON:coordinates=
geometry.getCoordinates();coordinates[depth[0]].splice(index+1,0,vertex);break;case ol.geom.GeometryType.MULTI_POLYGON:coordinates=geometry.getCoordinates();coordinates[depth[1]][depth[0]].splice(index+1,0,vertex);break;case ol.geom.GeometryType.LINE_STRING:coordinates=geometry.getCoordinates();coordinates.splice(index+1,0,vertex);break;default:return}this.setGeometryCoordinates_(geometry,coordinates);var rTree=this.rBush_;rTree.remove(segmentData);this.updateSegmentIndices_(geometry,index,depth,
1);var newSegmentData={segment:[segment[0],vertex],feature:feature,geometry:geometry,depth:depth,index:index};rTree.insert(ol.extent.boundingExtent(newSegmentData.segment),newSegmentData);this.dragSegments_.push([newSegmentData,1]);var newSegmentData2={segment:[vertex,segment[1]],feature:feature,geometry:geometry,depth:depth,index:index+1};rTree.insert(ol.extent.boundingExtent(newSegmentData2.segment),newSegmentData2);this.dragSegments_.push([newSegmentData2,0]);this.ignoreNextSingleClick_=true};
ol.interaction.Modify.prototype.removePoint=function(){if(this.lastPointerEvent_&&this.lastPointerEvent_.type!=ol.MapBrowserEventType.POINTERDRAG){var evt=this.lastPointerEvent_;this.willModifyFeatures_(evt);this.removeVertex_();this.dispatchEvent(new ol.interaction.Modify.Event(ol.interaction.ModifyEventType.MODIFYEND,this.features_,evt));this.modified_=false;return true}return false};
ol.interaction.Modify.prototype.removeVertex_=function(){var dragSegments=this.dragSegments_;var segmentsByFeature={};var deleted=false;var component,coordinates,dragSegment,geometry,i,index,left;var newIndex,right,segmentData,uid;for(i=dragSegments.length-1;i>=0;--i){dragSegment=dragSegments[i];segmentData=dragSegment[0];uid=ol.getUid(segmentData.feature);if(segmentData.depth)uid+="-"+segmentData.depth.join("-");if(!(uid in segmentsByFeature))segmentsByFeature[uid]={};if(dragSegment[1]===0){segmentsByFeature[uid].right=
segmentData;segmentsByFeature[uid].index=segmentData.index}else if(dragSegment[1]==1){segmentsByFeature[uid].left=segmentData;segmentsByFeature[uid].index=segmentData.index+1}}for(uid in segmentsByFeature){right=segmentsByFeature[uid].right;left=segmentsByFeature[uid].left;index=segmentsByFeature[uid].index;newIndex=index-1;if(left!==undefined)segmentData=left;else segmentData=right;if(newIndex<0)newIndex=0;geometry=segmentData.geometry;coordinates=geometry.getCoordinates();component=coordinates;
deleted=false;switch(geometry.getType()){case ol.geom.GeometryType.MULTI_LINE_STRING:if(coordinates[segmentData.depth[0]].length>2){coordinates[segmentData.depth[0]].splice(index,1);deleted=true}break;case ol.geom.GeometryType.LINE_STRING:if(coordinates.length>2){coordinates.splice(index,1);deleted=true}break;case ol.geom.GeometryType.MULTI_POLYGON:component=component[segmentData.depth[1]];case ol.geom.GeometryType.POLYGON:component=component[segmentData.depth[0]];if(component.length>4){if(index==
component.length-1)index=0;component.splice(index,1);deleted=true;if(index===0){component.pop();component.push(component[0]);newIndex=component.length-1}}break;default:}if(deleted){this.setGeometryCoordinates_(geometry,coordinates);var segments=[];if(left!==undefined){this.rBush_.remove(left);segments.push(left.segment[0])}if(right!==undefined){this.rBush_.remove(right);segments.push(right.segment[1])}if(left!==undefined&&right!==undefined){var newSegmentData={depth:segmentData.depth,feature:segmentData.feature,
geometry:segmentData.geometry,index:newIndex,segment:segments};this.rBush_.insert(ol.extent.boundingExtent(newSegmentData.segment),newSegmentData)}this.updateSegmentIndices_(geometry,index,segmentData.depth,-1);if(this.vertexFeature_){this.overlay_.getSource().removeFeature(this.vertexFeature_);this.vertexFeature_=null}dragSegments.length=0}}return deleted};
ol.interaction.Modify.prototype.setGeometryCoordinates_=function(geometry,coordinates){this.changingFeature_=true;geometry.setCoordinates(coordinates);this.changingFeature_=false};
ol.interaction.Modify.prototype.updateSegmentIndices_=function(geometry,index,depth,delta){this.rBush_.forEachInExtent(geometry.getExtent(),function(segmentDataMatch){if(segmentDataMatch.geometry===geometry&&(depth===undefined||segmentDataMatch.depth===undefined||ol.array.equals(segmentDataMatch.depth,depth))&&segmentDataMatch.index>index)segmentDataMatch.index+=delta})};
ol.interaction.Modify.getDefaultStyleFunction=function(){var style=ol.style.Style.createDefaultEditing();return function(feature,resolution){return style[ol.geom.GeometryType.POINT]}};ol.interaction.Modify.Event=function(type,features,mapBrowserPointerEvent){ol.events.Event.call(this,type);this.features=features;this.mapBrowserEvent=mapBrowserPointerEvent};ol.inherits(ol.interaction.Modify.Event,ol.events.Event);goog.provide("ol.interaction.Select");goog.require("ol");goog.require("ol.CollectionEventType");goog.require("ol.array");goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.events.condition");goog.require("ol.functions");goog.require("ol.geom.GeometryType");goog.require("ol.interaction.Interaction");goog.require("ol.layer.Vector");goog.require("ol.obj");goog.require("ol.source.Vector");goog.require("ol.style.Style");
ol.interaction.Select=function(opt_options){ol.interaction.Interaction.call(this,{handleEvent:ol.interaction.Select.handleEvent});var options=opt_options?opt_options:{};this.condition_=options.condition?options.condition:ol.events.condition.singleClick;this.addCondition_=options.addCondition?options.addCondition:ol.events.condition.never;this.removeCondition_=options.removeCondition?options.removeCondition:ol.events.condition.never;this.toggleCondition_=options.toggleCondition?options.toggleCondition:
ol.events.condition.shiftKeyOnly;this.multi_=options.multi?options.multi:false;this.filter_=options.filter?options.filter:ol.functions.TRUE;this.hitTolerance_=options.hitTolerance?options.hitTolerance:0;var featureOverlay=new ol.layer.Vector({source:new ol.source.Vector({useSpatialIndex:false,features:options.features,wrapX:options.wrapX}),style:options.style?options.style:ol.interaction.Select.getDefaultStyleFunction(),updateWhileAnimating:true,updateWhileInteracting:true});this.featureOverlay_=
featureOverlay;var layerFilter;if(options.layers)if(typeof options.layers==="function")layerFilter=options.layers;else{var layers=options.layers;layerFilter=function(layer){return ol.array.includes(layers,layer)}}else layerFilter=ol.functions.TRUE;this.layerFilter_=layerFilter;this.featureLayerAssociation_={};var features=this.featureOverlay_.getSource().getFeaturesCollection();ol.events.listen(features,ol.CollectionEventType.ADD,this.addFeature_,this);ol.events.listen(features,ol.CollectionEventType.REMOVE,
this.removeFeature_,this)};ol.inherits(ol.interaction.Select,ol.interaction.Interaction);ol.interaction.Select.prototype.addFeatureLayerAssociation_=function(feature,layer){var key=ol.getUid(feature);this.featureLayerAssociation_[key]=layer};ol.interaction.Select.prototype.getFeatures=function(){return this.featureOverlay_.getSource().getFeaturesCollection()};ol.interaction.Select.prototype.getHitTolerance=function(){return this.hitTolerance_};
ol.interaction.Select.prototype.getLayer=function(feature){var key=ol.getUid(feature);return this.featureLayerAssociation_[key]};
ol.interaction.Select.handleEvent=function(mapBrowserEvent){if(!this.condition_(mapBrowserEvent))return true;var add=this.addCondition_(mapBrowserEvent);var remove=this.removeCondition_(mapBrowserEvent);var toggle=this.toggleCondition_(mapBrowserEvent);var set=!add&&!remove&&!toggle;var map=mapBrowserEvent.map;var features=this.featureOverlay_.getSource().getFeaturesCollection();var deselected=[];var selected=[];if(set){ol.obj.clear(this.featureLayerAssociation_);map.forEachFeatureAtPixel(mapBrowserEvent.pixel,
function(feature,layer){if(this.filter_(feature,layer)){selected.push(feature);this.addFeatureLayerAssociation_(feature,layer);return!this.multi_}}.bind(this),{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});var i;for(i=features.getLength()-1;i>=0;--i){var feature=features.item(i);var index=selected.indexOf(feature);if(index>-1)selected.splice(index,1);else{features.remove(feature);deselected.push(feature)}}if(selected.length!==0)features.extend(selected)}else{map.forEachFeatureAtPixel(mapBrowserEvent.pixel,
function(feature,layer){if(this.filter_(feature,layer)){if((add||toggle)&&!ol.array.includes(features.getArray(),feature)){selected.push(feature);this.addFeatureLayerAssociation_(feature,layer)}else if((remove||toggle)&&ol.array.includes(features.getArray(),feature)){deselected.push(feature);this.removeFeatureLayerAssociation_(feature)}return!this.multi_}}.bind(this),{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});var j;for(j=deselected.length-1;j>=0;--j)features.remove(deselected[j]);
features.extend(selected)}if(selected.length>0||deselected.length>0)this.dispatchEvent(new ol.interaction.Select.Event(ol.interaction.Select.EventType_.SELECT,selected,deselected,mapBrowserEvent));return ol.events.condition.pointerMove(mapBrowserEvent)};ol.interaction.Select.prototype.setHitTolerance=function(hitTolerance){this.hitTolerance_=hitTolerance};
ol.interaction.Select.prototype.setMap=function(map){var currentMap=this.getMap();var selectedFeatures=this.featureOverlay_.getSource().getFeaturesCollection();if(currentMap)selectedFeatures.forEach(currentMap.unskipFeature,currentMap);ol.interaction.Interaction.prototype.setMap.call(this,map);this.featureOverlay_.setMap(map);if(map)selectedFeatures.forEach(map.skipFeature,map)};
ol.interaction.Select.getDefaultStyleFunction=function(){var styles=ol.style.Style.createDefaultEditing();ol.array.extend(styles[ol.geom.GeometryType.POLYGON],styles[ol.geom.GeometryType.LINE_STRING]);ol.array.extend(styles[ol.geom.GeometryType.GEOMETRY_COLLECTION],styles[ol.geom.GeometryType.LINE_STRING]);return function(feature,resolution){if(!feature.getGeometry())return null;return styles[feature.getGeometry().getType()]}};
ol.interaction.Select.prototype.addFeature_=function(evt){var map=this.getMap();if(map)map.skipFeature(evt.element)};ol.interaction.Select.prototype.removeFeature_=function(evt){var map=this.getMap();if(map)map.unskipFeature(evt.element)};ol.interaction.Select.prototype.removeFeatureLayerAssociation_=function(feature){var key=ol.getUid(feature);delete this.featureLayerAssociation_[key]};
ol.interaction.Select.Event=function(type,selected,deselected,mapBrowserEvent){ol.events.Event.call(this,type);this.selected=selected;this.deselected=deselected;this.mapBrowserEvent=mapBrowserEvent};ol.inherits(ol.interaction.Select.Event,ol.events.Event);ol.interaction.Select.EventType_={SELECT:"select"};goog.provide("ol.interaction.Snap");goog.require("ol");goog.require("ol.Collection");goog.require("ol.CollectionEventType");goog.require("ol.coordinate");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.functions");goog.require("ol.geom.GeometryType");goog.require("ol.geom.Polygon");goog.require("ol.interaction.Pointer");goog.require("ol.obj");goog.require("ol.source.Vector");goog.require("ol.source.VectorEventType");goog.require("ol.structs.RBush");
ol.interaction.Snap=function(opt_options){ol.interaction.Pointer.call(this,{handleEvent:ol.interaction.Snap.handleEvent_,handleDownEvent:ol.functions.TRUE,handleUpEvent:ol.interaction.Snap.handleUpEvent_});var options=opt_options?opt_options:{};this.source_=options.source?options.source:null;this.vertex_=options.vertex!==undefined?options.vertex:true;this.edge_=options.edge!==undefined?options.edge:true;this.features_=options.features?options.features:null;this.featuresListenerKeys_=[];this.featureChangeListenerKeys_=
{};this.indexedFeaturesExtents_={};this.pendingFeatures_={};this.pixelCoordinate_=null;this.pixelTolerance_=options.pixelTolerance!==undefined?options.pixelTolerance:10;this.sortByDistance_=ol.interaction.Snap.sortByDistance.bind(this);this.rBush_=new ol.structs.RBush;this.SEGMENT_WRITERS_={"Point":this.writePointGeometry_,"LineString":this.writeLineStringGeometry_,"LinearRing":this.writeLineStringGeometry_,"Polygon":this.writePolygonGeometry_,"MultiPoint":this.writeMultiPointGeometry_,"MultiLineString":this.writeMultiLineStringGeometry_,
"MultiPolygon":this.writeMultiPolygonGeometry_,"GeometryCollection":this.writeGeometryCollectionGeometry_,"Circle":this.writeCircleGeometry_}};ol.inherits(ol.interaction.Snap,ol.interaction.Pointer);
ol.interaction.Snap.prototype.addFeature=function(feature,opt_listen){var listen=opt_listen!==undefined?opt_listen:true;var feature_uid=ol.getUid(feature);var geometry=feature.getGeometry();if(geometry){var segmentWriter=this.SEGMENT_WRITERS_[geometry.getType()];if(segmentWriter){this.indexedFeaturesExtents_[feature_uid]=geometry.getExtent(ol.extent.createEmpty());segmentWriter.call(this,feature,geometry)}}if(listen)this.featureChangeListenerKeys_[feature_uid]=ol.events.listen(feature,ol.events.EventType.CHANGE,
this.handleFeatureChange_,this)};ol.interaction.Snap.prototype.forEachFeatureAdd_=function(feature){this.addFeature(feature)};ol.interaction.Snap.prototype.forEachFeatureRemove_=function(feature){this.removeFeature(feature)};ol.interaction.Snap.prototype.getFeatures_=function(){var features;if(this.features_)features=this.features_;else if(this.source_)features=this.source_.getFeatures();return features};
ol.interaction.Snap.prototype.handleFeatureAdd_=function(evt){var feature;if(evt instanceof ol.source.Vector.Event)feature=evt.feature;else if(evt instanceof ol.Collection.Event)feature=evt.element;this.addFeature(feature)};ol.interaction.Snap.prototype.handleFeatureRemove_=function(evt){var feature;if(evt instanceof ol.source.Vector.Event)feature=evt.feature;else if(evt instanceof ol.Collection.Event)feature=evt.element;this.removeFeature(feature)};
ol.interaction.Snap.prototype.handleFeatureChange_=function(evt){var feature=evt.target;if(this.handlingDownUpSequence){var uid=ol.getUid(feature);if(!(uid in this.pendingFeatures_))this.pendingFeatures_[uid]=feature}else this.updateFeature_(feature)};
ol.interaction.Snap.prototype.removeFeature=function(feature,opt_unlisten){var unlisten=opt_unlisten!==undefined?opt_unlisten:true;var feature_uid=ol.getUid(feature);var extent=this.indexedFeaturesExtents_[feature_uid];if(extent){var rBush=this.rBush_;var i,nodesToRemove=[];rBush.forEachInExtent(extent,function(node){if(feature===node.feature)nodesToRemove.push(node)});for(i=nodesToRemove.length-1;i>=0;--i)rBush.remove(nodesToRemove[i])}if(unlisten){ol.events.unlistenByKey(this.featureChangeListenerKeys_[feature_uid]);
delete this.featureChangeListenerKeys_[feature_uid]}};
ol.interaction.Snap.prototype.setMap=function(map){var currentMap=this.getMap();var keys=this.featuresListenerKeys_;var features=this.getFeatures_();if(currentMap){keys.forEach(ol.events.unlistenByKey);keys.length=0;features.forEach(this.forEachFeatureRemove_,this)}ol.interaction.Pointer.prototype.setMap.call(this,map);if(map){if(this.features_)keys.push(ol.events.listen(this.features_,ol.CollectionEventType.ADD,this.handleFeatureAdd_,this),ol.events.listen(this.features_,ol.CollectionEventType.REMOVE,
this.handleFeatureRemove_,this));else if(this.source_)keys.push(ol.events.listen(this.source_,ol.source.VectorEventType.ADDFEATURE,this.handleFeatureAdd_,this),ol.events.listen(this.source_,ol.source.VectorEventType.REMOVEFEATURE,this.handleFeatureRemove_,this));features.forEach(this.forEachFeatureAdd_,this)}};ol.interaction.Snap.prototype.shouldStopEvent=ol.functions.FALSE;
ol.interaction.Snap.prototype.snapTo=function(pixel,pixelCoordinate,map){var lowerLeft=map.getCoordinateFromPixel([pixel[0]-this.pixelTolerance_,pixel[1]+this.pixelTolerance_]);var upperRight=map.getCoordinateFromPixel([pixel[0]+this.pixelTolerance_,pixel[1]-this.pixelTolerance_]);var box=ol.extent.boundingExtent([lowerLeft,upperRight]);var segments=this.rBush_.getInExtent(box);if(this.vertex_&&!this.edge_)segments=segments.filter(function(segment){return segment.feature.getGeometry().getType()!==
ol.geom.GeometryType.CIRCLE});var snappedToVertex=false;var snapped=false;var vertex=null;var vertexPixel=null;var dist,pixel1,pixel2,squaredDist1,squaredDist2;if(segments.length>0){this.pixelCoordinate_=pixelCoordinate;segments.sort(this.sortByDistance_);var closestSegment=segments[0].segment;var isCircle=segments[0].feature.getGeometry().getType()===ol.geom.GeometryType.CIRCLE;if(this.vertex_&&!this.edge_){pixel1=map.getPixelFromCoordinate(closestSegment[0]);pixel2=map.getPixelFromCoordinate(closestSegment[1]);
squaredDist1=ol.coordinate.squaredDistance(pixel,pixel1);squaredDist2=ol.coordinate.squaredDistance(pixel,pixel2);dist=Math.sqrt(Math.min(squaredDist1,squaredDist2));snappedToVertex=dist<=this.pixelTolerance_;if(snappedToVertex){snapped=true;vertex=squaredDist1>squaredDist2?closestSegment[1]:closestSegment[0];vertexPixel=map.getPixelFromCoordinate(vertex)}}else if(this.edge_){if(isCircle)vertex=ol.coordinate.closestOnCircle(pixelCoordinate,segments[0].feature.getGeometry());else vertex=ol.coordinate.closestOnSegment(pixelCoordinate,
closestSegment);vertexPixel=map.getPixelFromCoordinate(vertex);if(ol.coordinate.distance(pixel,vertexPixel)<=this.pixelTolerance_){snapped=true;if(this.vertex_&&!isCircle){pixel1=map.getPixelFromCoordinate(closestSegment[0]);pixel2=map.getPixelFromCoordinate(closestSegment[1]);squaredDist1=ol.coordinate.squaredDistance(vertexPixel,pixel1);squaredDist2=ol.coordinate.squaredDistance(vertexPixel,pixel2);dist=Math.sqrt(Math.min(squaredDist1,squaredDist2));snappedToVertex=dist<=this.pixelTolerance_;if(snappedToVertex){vertex=
squaredDist1>squaredDist2?closestSegment[1]:closestSegment[0];vertexPixel=map.getPixelFromCoordinate(vertex)}}}}if(snapped)vertexPixel=[Math.round(vertexPixel[0]),Math.round(vertexPixel[1])]}return{snapped:snapped,vertex:vertex,vertexPixel:vertexPixel}};ol.interaction.Snap.prototype.updateFeature_=function(feature){this.removeFeature(feature,false);this.addFeature(feature,false)};
ol.interaction.Snap.prototype.writeCircleGeometry_=function(feature,geometry){var polygon=ol.geom.Polygon.fromCircle(geometry);var coordinates=polygon.getCoordinates()[0];var i,ii,segment,segmentData;for(i=0,ii=coordinates.length-1;i<ii;++i){segment=coordinates.slice(i,i+2);segmentData={feature:feature,segment:segment};this.rBush_.insert(ol.extent.boundingExtent(segment),segmentData)}};
ol.interaction.Snap.prototype.writeGeometryCollectionGeometry_=function(feature,geometry){var i,geometries=geometry.getGeometriesArray();for(i=0;i<geometries.length;++i){var segmentWriter=this.SEGMENT_WRITERS_[geometries[i].getType()];if(segmentWriter)segmentWriter.call(this,feature,geometries[i])}};
ol.interaction.Snap.prototype.writeLineStringGeometry_=function(feature,geometry){var coordinates=geometry.getCoordinates();var i,ii,segment,segmentData;for(i=0,ii=coordinates.length-1;i<ii;++i){segment=coordinates.slice(i,i+2);segmentData={feature:feature,segment:segment};this.rBush_.insert(ol.extent.boundingExtent(segment),segmentData)}};
ol.interaction.Snap.prototype.writeMultiLineStringGeometry_=function(feature,geometry){var lines=geometry.getCoordinates();var coordinates,i,ii,j,jj,segment,segmentData;for(j=0,jj=lines.length;j<jj;++j){coordinates=lines[j];for(i=0,ii=coordinates.length-1;i<ii;++i){segment=coordinates.slice(i,i+2);segmentData={feature:feature,segment:segment};this.rBush_.insert(ol.extent.boundingExtent(segment),segmentData)}}};
ol.interaction.Snap.prototype.writeMultiPointGeometry_=function(feature,geometry){var points=geometry.getCoordinates();var coordinates,i,ii,segmentData;for(i=0,ii=points.length;i<ii;++i){coordinates=points[i];segmentData={feature:feature,segment:[coordinates,coordinates]};this.rBush_.insert(geometry.getExtent(),segmentData)}};
ol.interaction.Snap.prototype.writeMultiPolygonGeometry_=function(feature,geometry){var polygons=geometry.getCoordinates();var coordinates,i,ii,j,jj,k,kk,rings,segment,segmentData;for(k=0,kk=polygons.length;k<kk;++k){rings=polygons[k];for(j=0,jj=rings.length;j<jj;++j){coordinates=rings[j];for(i=0,ii=coordinates.length-1;i<ii;++i){segment=coordinates.slice(i,i+2);segmentData={feature:feature,segment:segment};this.rBush_.insert(ol.extent.boundingExtent(segment),segmentData)}}}};
ol.interaction.Snap.prototype.writePointGeometry_=function(feature,geometry){var coordinates=geometry.getCoordinates();var segmentData={feature:feature,segment:[coordinates,coordinates]};this.rBush_.insert(geometry.getExtent(),segmentData)};
ol.interaction.Snap.prototype.writePolygonGeometry_=function(feature,geometry){var rings=geometry.getCoordinates();var coordinates,i,ii,j,jj,segment,segmentData;for(j=0,jj=rings.length;j<jj;++j){coordinates=rings[j];for(i=0,ii=coordinates.length-1;i<ii;++i){segment=coordinates.slice(i,i+2);segmentData={feature:feature,segment:segment};this.rBush_.insert(ol.extent.boundingExtent(segment),segmentData)}}};
ol.interaction.Snap.handleEvent_=function(evt){var result=this.snapTo(evt.pixel,evt.coordinate,evt.map);if(result.snapped){evt.coordinate=result.vertex.slice(0,2);evt.pixel=result.vertexPixel}return ol.interaction.Pointer.handleEvent.call(this,evt)};ol.interaction.Snap.handleUpEvent_=function(evt){var featuresToUpdate=ol.obj.getValues(this.pendingFeatures_);if(featuresToUpdate.length){featuresToUpdate.forEach(this.updateFeature_,this);this.pendingFeatures_={}}return false};
ol.interaction.Snap.sortByDistance=function(a,b){return ol.coordinate.squaredDistanceToSegment(this.pixelCoordinate_,a.segment)-ol.coordinate.squaredDistanceToSegment(this.pixelCoordinate_,b.segment)};goog.provide("ol.interaction.TranslateEventType");ol.interaction.TranslateEventType={TRANSLATESTART:"translatestart",TRANSLATING:"translating",TRANSLATEEND:"translateend"};goog.provide("ol.interaction.Translate");goog.require("ol");goog.require("ol.Collection");goog.require("ol.Object");goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.functions");goog.require("ol.array");goog.require("ol.interaction.Pointer");goog.require("ol.interaction.Property");goog.require("ol.interaction.TranslateEventType");
ol.interaction.Translate=function(opt_options){ol.interaction.Pointer.call(this,{handleDownEvent:ol.interaction.Translate.handleDownEvent_,handleDragEvent:ol.interaction.Translate.handleDragEvent_,handleMoveEvent:ol.interaction.Translate.handleMoveEvent_,handleUpEvent:ol.interaction.Translate.handleUpEvent_});var options=opt_options?opt_options:{};this.lastCoordinate_=null;this.features_=options.features!==undefined?options.features:null;var layerFilter;if(options.layers)if(typeof options.layers===
"function")layerFilter=options.layers;else{var layers=options.layers;layerFilter=function(layer){return ol.array.includes(layers,layer)}}else layerFilter=ol.functions.TRUE;this.layerFilter_=layerFilter;this.hitTolerance_=options.hitTolerance?options.hitTolerance:0;this.lastFeature_=null;ol.events.listen(this,ol.Object.getChangeEventType(ol.interaction.Property.ACTIVE),this.handleActiveChanged_,this)};ol.inherits(ol.interaction.Translate,ol.interaction.Pointer);
ol.interaction.Translate.handleDownEvent_=function(event){this.lastFeature_=this.featuresAtPixel_(event.pixel,event.map);if(!this.lastCoordinate_&&this.lastFeature_){this.lastCoordinate_=event.coordinate;ol.interaction.Translate.handleMoveEvent_.call(this,event);var features=this.features_||new ol.Collection([this.lastFeature_]);this.dispatchEvent(new ol.interaction.Translate.Event(ol.interaction.TranslateEventType.TRANSLATESTART,features,event.coordinate));return true}return false};
ol.interaction.Translate.handleUpEvent_=function(event){if(this.lastCoordinate_){this.lastCoordinate_=null;ol.interaction.Translate.handleMoveEvent_.call(this,event);var features=this.features_||new ol.Collection([this.lastFeature_]);this.dispatchEvent(new ol.interaction.Translate.Event(ol.interaction.TranslateEventType.TRANSLATEEND,features,event.coordinate));return true}return false};
ol.interaction.Translate.handleDragEvent_=function(event){if(this.lastCoordinate_){var newCoordinate=event.coordinate;var deltaX=newCoordinate[0]-this.lastCoordinate_[0];var deltaY=newCoordinate[1]-this.lastCoordinate_[1];var features=this.features_||new ol.Collection([this.lastFeature_]);features.forEach(function(feature){var geom=feature.getGeometry();geom.translate(deltaX,deltaY);feature.setGeometry(geom)});this.lastCoordinate_=newCoordinate;this.dispatchEvent(new ol.interaction.Translate.Event(ol.interaction.TranslateEventType.TRANSLATING,
features,newCoordinate))}};ol.interaction.Translate.handleMoveEvent_=function(event){var elem=event.map.getViewport();if(this.featuresAtPixel_(event.pixel,event.map)){elem.classList.remove(this.lastCoordinate_?"ol-grab":"ol-grabbing");elem.classList.add(this.lastCoordinate_?"ol-grabbing":"ol-grab")}else elem.classList.remove("ol-grab","ol-grabbing")};
ol.interaction.Translate.prototype.featuresAtPixel_=function(pixel,map){return map.forEachFeatureAtPixel(pixel,function(feature){if(!this.features_||ol.array.includes(this.features_.getArray(),feature))return feature}.bind(this),{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_})};ol.interaction.Translate.prototype.getHitTolerance=function(){return this.hitTolerance_};ol.interaction.Translate.prototype.setHitTolerance=function(hitTolerance){this.hitTolerance_=hitTolerance};
ol.interaction.Translate.prototype.setMap=function(map){var oldMap=this.getMap();ol.interaction.Pointer.prototype.setMap.call(this,map);this.updateState_(oldMap)};ol.interaction.Translate.prototype.handleActiveChanged_=function(){this.updateState_(null)};ol.interaction.Translate.prototype.updateState_=function(oldMap){var map=this.getMap();var active=this.getActive();if(!map||!active){map=map||oldMap;if(map){var elem=map.getViewport();elem.classList.remove("ol-grab","ol-grabbing")}}};
ol.interaction.Translate.Event=function(type,features,coordinate){ol.events.Event.call(this,type);this.features=features;this.coordinate=coordinate};ol.inherits(ol.interaction.Translate.Event,ol.events.Event);goog.provide("ol.layer.Heatmap");goog.require("ol.events");goog.require("ol");goog.require("ol.Object");goog.require("ol.dom");goog.require("ol.layer.Vector");goog.require("ol.math");goog.require("ol.obj");goog.require("ol.render.EventType");goog.require("ol.style.Icon");goog.require("ol.style.Style");
ol.layer.Heatmap=function(opt_options){var options=opt_options?opt_options:{};var baseOptions=ol.obj.assign({},options);delete baseOptions.gradient;delete baseOptions.radius;delete baseOptions.blur;delete baseOptions.shadow;delete baseOptions.weight;ol.layer.Vector.call(this,baseOptions);this.gradient_=null;this.shadow_=options.shadow!==undefined?options.shadow:250;this.circleImage_=undefined;this.styleCache_=null;ol.events.listen(this,ol.Object.getChangeEventType(ol.layer.Heatmap.Property_.GRADIENT),
this.handleGradientChanged_,this);this.setGradient(options.gradient?options.gradient:ol.layer.Heatmap.DEFAULT_GRADIENT);this.setBlur(options.blur!==undefined?options.blur:15);this.setRadius(options.radius!==undefined?options.radius:8);ol.events.listen(this,ol.Object.getChangeEventType(ol.layer.Heatmap.Property_.BLUR),this.handleStyleChanged_,this);ol.events.listen(this,ol.Object.getChangeEventType(ol.layer.Heatmap.Property_.RADIUS),this.handleStyleChanged_,this);this.handleStyleChanged_();var weight=
options.weight?options.weight:"weight";var weightFunction;if(typeof weight==="string")weightFunction=function(feature){return feature.get(weight)};else weightFunction=weight;this.setStyle(function(feature,resolution){var weight=weightFunction(feature);var opacity=weight!==undefined?ol.math.clamp(weight,0,1):1;var index=255*opacity|0;var style=this.styleCache_[index];if(!style){style=[new ol.style.Style({image:new ol.style.Icon({opacity:opacity,src:this.circleImage_})})];this.styleCache_[index]=style}return style}.bind(this));
this.setRenderOrder(null);ol.events.listen(this,ol.render.EventType.RENDER,this.handleRender_,this)};ol.inherits(ol.layer.Heatmap,ol.layer.Vector);ol.layer.Heatmap.DEFAULT_GRADIENT=["#00f","#0ff","#0f0","#ff0","#f00"];
ol.layer.Heatmap.createGradient_=function(colors){var width=1;var height=256;var context=ol.dom.createCanvasContext2D(width,height);var gradient=context.createLinearGradient(0,0,width,height);var step=1/(colors.length-1);for(var i=0,ii=colors.length;i<ii;++i)gradient.addColorStop(i*step,colors[i]);context.fillStyle=gradient;context.fillRect(0,0,width,height);return context.getImageData(0,0,width,height).data};
ol.layer.Heatmap.prototype.createCircle_=function(){var radius=this.getRadius();var blur=this.getBlur();var halfSize=radius+blur+1;var size=2*halfSize;var context=ol.dom.createCanvasContext2D(size,size);context.shadowOffsetX=context.shadowOffsetY=this.shadow_;context.shadowBlur=blur;context.shadowColor="#000";context.beginPath();var center=halfSize-this.shadow_;context.arc(center,center,radius,0,Math.PI*2,true);context.fill();return context.canvas.toDataURL()};ol.layer.Heatmap.prototype.getBlur=function(){return this.get(ol.layer.Heatmap.Property_.BLUR)};
ol.layer.Heatmap.prototype.getGradient=function(){return this.get(ol.layer.Heatmap.Property_.GRADIENT)};ol.layer.Heatmap.prototype.getRadius=function(){return this.get(ol.layer.Heatmap.Property_.RADIUS)};ol.layer.Heatmap.prototype.handleGradientChanged_=function(){this.gradient_=ol.layer.Heatmap.createGradient_(this.getGradient())};ol.layer.Heatmap.prototype.handleStyleChanged_=function(){this.circleImage_=this.createCircle_();this.styleCache_=new Array(256);this.changed()};
ol.layer.Heatmap.prototype.handleRender_=function(event){var context=event.context;var canvas=context.canvas;var image=context.getImageData(0,0,canvas.width,canvas.height);var view8=image.data;var i,ii,alpha;for(i=0,ii=view8.length;i<ii;i+=4){alpha=view8[i+3]*4;if(alpha){view8[i]=this.gradient_[alpha];view8[i+1]=this.gradient_[alpha+1];view8[i+2]=this.gradient_[alpha+2]}}context.putImageData(image,0,0)};ol.layer.Heatmap.prototype.setBlur=function(blur){this.set(ol.layer.Heatmap.Property_.BLUR,blur)};
ol.layer.Heatmap.prototype.setGradient=function(colors){this.set(ol.layer.Heatmap.Property_.GRADIENT,colors)};ol.layer.Heatmap.prototype.setRadius=function(radius){this.set(ol.layer.Heatmap.Property_.RADIUS,radius)};ol.layer.Heatmap.Property_={BLUR:"blur",GRADIENT:"gradient",RADIUS:"radius"};goog.provide("ol.layer.Image");goog.require("ol");goog.require("ol.LayerType");goog.require("ol.layer.Layer");ol.layer.Image=function(opt_options){var options=opt_options?opt_options:{};ol.layer.Layer.call(this,options);this.type=ol.LayerType.IMAGE};ol.inherits(ol.layer.Image,ol.layer.Layer);ol.layer.Image.prototype.getSource;goog.provide("ol.layer.TileProperty");ol.layer.TileProperty={PRELOAD:"preload",USE_INTERIM_TILES_ON_ERROR:"useInterimTilesOnError"};goog.provide("ol.layer.Tile");goog.require("ol");goog.require("ol.LayerType");goog.require("ol.layer.Layer");goog.require("ol.layer.TileProperty");goog.require("ol.obj");
ol.layer.Tile=function(opt_options){var options=opt_options?opt_options:{};var baseOptions=ol.obj.assign({},options);delete baseOptions.preload;delete baseOptions.useInterimTilesOnError;ol.layer.Layer.call(this,baseOptions);this.setPreload(options.preload!==undefined?options.preload:0);this.setUseInterimTilesOnError(options.useInterimTilesOnError!==undefined?options.useInterimTilesOnError:true);this.type=ol.LayerType.TILE};ol.inherits(ol.layer.Tile,ol.layer.Layer);
ol.layer.Tile.prototype.getPreload=function(){return this.get(ol.layer.TileProperty.PRELOAD)};ol.layer.Tile.prototype.getSource;ol.layer.Tile.prototype.setPreload=function(preload){this.set(ol.layer.TileProperty.PRELOAD,preload)};ol.layer.Tile.prototype.getUseInterimTilesOnError=function(){return this.get(ol.layer.TileProperty.USE_INTERIM_TILES_ON_ERROR)};ol.layer.Tile.prototype.setUseInterimTilesOnError=function(useInterimTilesOnError){this.set(ol.layer.TileProperty.USE_INTERIM_TILES_ON_ERROR,useInterimTilesOnError)};goog.provide("ol.layer.VectorTile");goog.require("ol");goog.require("ol.LayerType");goog.require("ol.asserts");goog.require("ol.layer.TileProperty");goog.require("ol.layer.Vector");goog.require("ol.layer.VectorTileRenderType");goog.require("ol.obj");
ol.layer.VectorTile=function(opt_options){var options=opt_options?opt_options:{};var renderMode=options.renderMode||ol.layer.VectorTileRenderType.HYBRID;ol.asserts.assert(renderMode==undefined||renderMode==ol.layer.VectorTileRenderType.IMAGE||renderMode==ol.layer.VectorTileRenderType.HYBRID||renderMode==ol.layer.VectorTileRenderType.VECTOR,28);if(options.declutter&&renderMode==ol.layer.VectorTileRenderType.IMAGE)renderMode=ol.layer.VectorTileRenderType.HYBRID;options.renderMode=renderMode;var baseOptions=
ol.obj.assign({},options);delete baseOptions.preload;delete baseOptions.useInterimTilesOnError;ol.layer.Vector.call(this,baseOptions);this.setPreload(options.preload?options.preload:0);this.setUseInterimTilesOnError(options.useInterimTilesOnError?options.useInterimTilesOnError:true);this.type=ol.LayerType.VECTOR_TILE};ol.inherits(ol.layer.VectorTile,ol.layer.Vector);ol.layer.VectorTile.prototype.getPreload=function(){return this.get(ol.layer.TileProperty.PRELOAD)};
ol.layer.VectorTile.prototype.getUseInterimTilesOnError=function(){return this.get(ol.layer.TileProperty.USE_INTERIM_TILES_ON_ERROR)};ol.layer.VectorTile.prototype.setPreload=function(preload){this.set(ol.layer.TileProperty.PRELOAD,preload)};ol.layer.VectorTile.prototype.setUseInterimTilesOnError=function(useInterimTilesOnError){this.set(ol.layer.TileProperty.USE_INTERIM_TILES_ON_ERROR,useInterimTilesOnError)};ol.layer.VectorTile.prototype.getSource;goog.provide("ol.webgl.Shader");goog.require("ol.functions");ol.webgl.Shader=function(source){this.source_=source};ol.webgl.Shader.prototype.getType=function(){};ol.webgl.Shader.prototype.getSource=function(){return this.source_};ol.webgl.Shader.prototype.isAnimated=ol.functions.FALSE;goog.provide("ol.webgl.Fragment");goog.require("ol");goog.require("ol.webgl");goog.require("ol.webgl.Shader");ol.webgl.Fragment=function(source){ol.webgl.Shader.call(this,source)};ol.inherits(ol.webgl.Fragment,ol.webgl.Shader);ol.webgl.Fragment.prototype.getType=function(){return ol.webgl.FRAGMENT_SHADER};goog.provide("ol.webgl.Vertex");goog.require("ol");goog.require("ol.webgl");goog.require("ol.webgl.Shader");ol.webgl.Vertex=function(source){ol.webgl.Shader.call(this,source)};ol.inherits(ol.webgl.Vertex,ol.webgl.Shader);ol.webgl.Vertex.prototype.getType=function(){return ol.webgl.VERTEX_SHADER};goog.provide("ol.render.webgl.circlereplay.defaultshader");goog.require("ol");goog.require("ol.webgl.Fragment");goog.require("ol.webgl.Vertex");
ol.render.webgl.circlereplay.defaultshader.fragment=new ol.webgl.Fragment(ol.DEBUG_WEBGL?"precision mediump float;\nvarying vec2 v_center;\nvarying vec2 v_offset;\nvarying float v_halfWidth;\nvarying float v_pixelRatio;\n\n\n\nuniform float u_opacity;\nuniform vec4 u_fillColor;\nuniform vec4 u_strokeColor;\nuniform vec2 u_size;\n\nvoid main(void) {\n  vec2 windowCenter = vec2((v_center.x + 1.0) / 2.0 * u_size.x * v_pixelRatio,\n      (v_center.y + 1.0) / 2.0 * u_size.y * v_pixelRatio);\n  vec2 windowOffset = vec2((v_offset.x + 1.0) / 2.0 * u_size.x * v_pixelRatio,\n      (v_offset.y + 1.0) / 2.0 * u_size.y * v_pixelRatio);\n  float radius = length(windowCenter - windowOffset);\n  float dist = length(windowCenter - gl_FragCoord.xy);\n  if (dist > radius + v_halfWidth) {\n    if (u_strokeColor.a == 0.0) {\n      gl_FragColor = u_fillColor;\n    } else {\n      gl_FragColor = u_strokeColor;\n    }\n    gl_FragColor.a = gl_FragColor.a - (dist - (radius + v_halfWidth));\n  } else if (u_fillColor.a == 0.0) {\n    // Hooray, no fill, just stroke. We can use real antialiasing.\n    gl_FragColor = u_strokeColor;\n    if (dist < radius - v_halfWidth) {\n      gl_FragColor.a = gl_FragColor.a - (radius - v_halfWidth - dist);\n    }\n  } else {\n    gl_FragColor = u_fillColor;\n    float strokeDist = radius - v_halfWidth;\n    float antialias = 2.0 * v_pixelRatio;\n    if (dist > strokeDist) {\n      gl_FragColor = u_strokeColor;\n    } else if (dist >= strokeDist - antialias) {\n      float step = smoothstep(strokeDist - antialias, strokeDist, dist);\n      gl_FragColor = mix(u_fillColor, u_strokeColor, step);\n    }\n  }\n  gl_FragColor.a = gl_FragColor.a * u_opacity;\n  if (gl_FragColor.a <= 0.0) {\n    discard;\n  }\n}\n":"precision mediump float;varying vec2 a;varying vec2 b;varying float c;varying float d;uniform float m;uniform vec4 n;uniform vec4 o;uniform vec2 p;void main(void){vec2 windowCenter=vec2((a.x+1.0)/2.0*p.x*d,(a.y+1.0)/2.0*p.y*d);vec2 windowOffset=vec2((b.x+1.0)/2.0*p.x*d,(b.y+1.0)/2.0*p.y*d);float radius=length(windowCenter-windowOffset);float dist=length(windowCenter-gl_FragCoord.xy);if(dist>radius+c){if(o.a==0.0){gl_FragColor=n;}else{gl_FragColor=o;}gl_FragColor.a=gl_FragColor.a-(dist-(radius+c));}else if(n.a==0.0){gl_FragColor=o;if(dist<radius-c){gl_FragColor.a=gl_FragColor.a-(radius-c-dist);}} else{gl_FragColor=n;float strokeDist=radius-c;float antialias=2.0*d;if(dist>strokeDist){gl_FragColor=o;}else if(dist>=strokeDist-antialias){float step=smoothstep(strokeDist-antialias,strokeDist,dist);gl_FragColor=mix(n,o,step);}} gl_FragColor.a=gl_FragColor.a*m;if(gl_FragColor.a<=0.0){discard;}}");
ol.render.webgl.circlereplay.defaultshader.vertex=new ol.webgl.Vertex(ol.DEBUG_WEBGL?"varying vec2 v_center;\nvarying vec2 v_offset;\nvarying float v_halfWidth;\nvarying float v_pixelRatio;\n\n\nattribute vec2 a_position;\nattribute float a_instruction;\nattribute float a_radius;\n\nuniform mat4 u_projectionMatrix;\nuniform mat4 u_offsetScaleMatrix;\nuniform mat4 u_offsetRotateMatrix;\nuniform float u_lineWidth;\nuniform float u_pixelRatio;\n\nvoid main(void) {\n  mat4 offsetMatrix = u_offsetScaleMatrix * u_offsetRotateMatrix;\n  v_center = vec4(u_projectionMatrix * vec4(a_position, 0.0, 1.0)).xy;\n  v_pixelRatio = u_pixelRatio;\n  float lineWidth = u_lineWidth * u_pixelRatio;\n  v_halfWidth = lineWidth / 2.0;\n  if (lineWidth == 0.0) {\n    lineWidth = 2.0 * u_pixelRatio;\n  }\n  vec2 offset;\n  // Radius with anitaliasing (roughly).\n  float radius = a_radius + 3.0 * u_pixelRatio;\n  // Until we get gl_VertexID in WebGL, we store an instruction.\n  if (a_instruction == 0.0) {\n    // Offsetting the edges of the triangle by lineWidth / 2 is necessary, however\n    // we should also leave some space for the antialiasing, thus we offset by lineWidth.\n    offset = vec2(-1.0, 1.0);\n  } else if (a_instruction == 1.0) {\n    offset = vec2(-1.0, -1.0);\n  } else if (a_instruction == 2.0) {\n    offset = vec2(1.0, -1.0);\n  } else {\n    offset = vec2(1.0, 1.0);\n  }\n\n  gl_Position = u_projectionMatrix * vec4(a_position + offset * radius, 0.0, 1.0) +\n      offsetMatrix * vec4(offset * lineWidth, 0.0, 0.0);\n  v_offset = vec4(u_projectionMatrix * vec4(a_position.x + a_radius, a_position.y,\n      0.0, 1.0)).xy;\n\n  if (distance(v_center, v_offset) > 20000.0) {\n    gl_Position = vec4(v_center, 0.0, 1.0);\n  }\n}\n\n\n":
"varying vec2 a;varying vec2 b;varying float c;varying float d;attribute vec2 e;attribute float f;attribute float g;uniform mat4 h;uniform mat4 i;uniform mat4 j;uniform float k;uniform float l;void main(void){mat4 offsetMatrix=i*j;a=vec4(h*vec4(e,0.0,1.0)).xy;d=l;float lineWidth=k*l;c=lineWidth/2.0;if(lineWidth==0.0){lineWidth=2.0*l;}vec2 offset;float radius=g+3.0*l;//Until we get gl_VertexID in WebGL,we store an instruction.if(f==0.0){//Offsetting the edges of the triangle by lineWidth/2 is necessary,however//we should also leave some space for the antialiasing,thus we offset by lineWidth.offset=vec2(-1.0,1.0);}else if(f==1.0){offset=vec2(-1.0,-1.0);}else if(f==2.0){offset=vec2(1.0,-1.0);}else{offset=vec2(1.0,1.0);}gl_Position=h*vec4(e+offset*radius,0.0,1.0)+offsetMatrix*vec4(offset*lineWidth,0.0,0.0);b=vec4(h*vec4(e.x+g,e.y,0.0,1.0)).xy;if(distance(a,b)>20000.0){gl_Position=vec4(a,0.0,1.0);}}");goog.provide("ol.render.webgl.circlereplay.defaultshader.Locations");goog.require("ol");
ol.render.webgl.circlereplay.defaultshader.Locations=function(gl,program){this.u_projectionMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_projectionMatrix":"h");this.u_offsetScaleMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_offsetScaleMatrix":"i");this.u_offsetRotateMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_offsetRotateMatrix":"j");this.u_lineWidth=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_lineWidth":"k");this.u_pixelRatio=gl.getUniformLocation(program,ol.DEBUG_WEBGL?
"u_pixelRatio":"l");this.u_opacity=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_opacity":"m");this.u_fillColor=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_fillColor":"n");this.u_strokeColor=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_strokeColor":"o");this.u_size=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_size":"p");this.a_position=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_position":"e");this.a_instruction=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_instruction":"f");this.a_radius=
gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_radius":"g")};goog.provide("ol.vec.Mat4");ol.vec.Mat4.create=function(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]};ol.vec.Mat4.fromTransform=function(mat4,transform){mat4[0]=transform[0];mat4[1]=transform[1];mat4[4]=transform[2];mat4[5]=transform[3];mat4[12]=transform[4];mat4[13]=transform[5];return mat4};goog.provide("ol.render.webgl.Replay");goog.require("ol");goog.require("ol.extent");goog.require("ol.render.VectorContext");goog.require("ol.transform");goog.require("ol.vec.Mat4");goog.require("ol.webgl");
ol.render.webgl.Replay=function(tolerance,maxExtent){ol.render.VectorContext.call(this);this.tolerance=tolerance;this.maxExtent=maxExtent;this.origin=ol.extent.getCenter(maxExtent);this.projectionMatrix_=ol.transform.create();this.offsetRotateMatrix_=ol.transform.create();this.offsetScaleMatrix_=ol.transform.create();this.tmpMat4_=ol.vec.Mat4.create();this.indices=[];this.indicesBuffer=null;this.startIndices=[];this.startIndicesFeature=[];this.vertices=[];this.verticesBuffer=null;this.lineStringReplay=
undefined};ol.inherits(ol.render.webgl.Replay,ol.render.VectorContext);ol.render.webgl.Replay.prototype.getDeleteResourcesFunction=function(context){};ol.render.webgl.Replay.prototype.finish=function(context){};ol.render.webgl.Replay.prototype.setUpProgram=function(gl,context,size,pixelRatio){};ol.render.webgl.Replay.prototype.shutDownProgram=function(gl,locations){};ol.render.webgl.Replay.prototype.drawReplay=function(gl,context,skippedFeaturesHash,hitDetection){};
ol.render.webgl.Replay.prototype.drawHitDetectionReplayOneByOne=function(gl,context,skippedFeaturesHash,featureCallback,opt_hitExtent){};ol.render.webgl.Replay.prototype.drawHitDetectionReplay=function(gl,context,skippedFeaturesHash,featureCallback,oneByOne,opt_hitExtent){if(!oneByOne)return this.drawHitDetectionReplayAll(gl,context,skippedFeaturesHash,featureCallback);else return this.drawHitDetectionReplayOneByOne(gl,context,skippedFeaturesHash,featureCallback,opt_hitExtent)};
ol.render.webgl.Replay.prototype.drawHitDetectionReplayAll=function(gl,context,skippedFeaturesHash,featureCallback){gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);this.drawReplay(gl,context,skippedFeaturesHash,true);var result=featureCallback(null);if(result)return result;else return undefined};
ol.render.webgl.Replay.prototype.replay=function(context,center,resolution,rotation,size,pixelRatio,opacity,skippedFeaturesHash,featureCallback,oneByOne,opt_hitExtent){var gl=context.getGL();var tmpStencil,tmpStencilFunc,tmpStencilMaskVal,tmpStencilRef,tmpStencilMask,tmpStencilOpFail,tmpStencilOpPass,tmpStencilOpZFail;if(this.lineStringReplay){tmpStencil=gl.isEnabled(gl.STENCIL_TEST);tmpStencilFunc=gl.getParameter(gl.STENCIL_FUNC);tmpStencilMaskVal=gl.getParameter(gl.STENCIL_VALUE_MASK);tmpStencilRef=
gl.getParameter(gl.STENCIL_REF);tmpStencilMask=gl.getParameter(gl.STENCIL_WRITEMASK);tmpStencilOpFail=gl.getParameter(gl.STENCIL_FAIL);tmpStencilOpPass=gl.getParameter(gl.STENCIL_PASS_DEPTH_PASS);tmpStencilOpZFail=gl.getParameter(gl.STENCIL_PASS_DEPTH_FAIL);gl.enable(gl.STENCIL_TEST);gl.clear(gl.STENCIL_BUFFER_BIT);gl.stencilMask(255);gl.stencilFunc(gl.ALWAYS,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.REPLACE);this.lineStringReplay.replay(context,center,resolution,rotation,size,pixelRatio,opacity,skippedFeaturesHash,
featureCallback,oneByOne,opt_hitExtent);gl.stencilMask(0);gl.stencilFunc(gl.NOTEQUAL,1,255)}context.bindBuffer(ol.webgl.ARRAY_BUFFER,this.verticesBuffer);context.bindBuffer(ol.webgl.ELEMENT_ARRAY_BUFFER,this.indicesBuffer);var locations=this.setUpProgram(gl,context,size,pixelRatio);var projectionMatrix=ol.transform.reset(this.projectionMatrix_);ol.transform.scale(projectionMatrix,2/(resolution*size[0]),2/(resolution*size[1]));ol.transform.rotate(projectionMatrix,-rotation);ol.transform.translate(projectionMatrix,
-(center[0]-this.origin[0]),-(center[1]-this.origin[1]));var offsetScaleMatrix=ol.transform.reset(this.offsetScaleMatrix_);ol.transform.scale(offsetScaleMatrix,2/size[0],2/size[1]);var offsetRotateMatrix=ol.transform.reset(this.offsetRotateMatrix_);if(rotation!==0)ol.transform.rotate(offsetRotateMatrix,-rotation);gl.uniformMatrix4fv(locations.u_projectionMatrix,false,ol.vec.Mat4.fromTransform(this.tmpMat4_,projectionMatrix));gl.uniformMatrix4fv(locations.u_offsetScaleMatrix,false,ol.vec.Mat4.fromTransform(this.tmpMat4_,
offsetScaleMatrix));gl.uniformMatrix4fv(locations.u_offsetRotateMatrix,false,ol.vec.Mat4.fromTransform(this.tmpMat4_,offsetRotateMatrix));gl.uniform1f(locations.u_opacity,opacity);var result;if(featureCallback===undefined)this.drawReplay(gl,context,skippedFeaturesHash,false);else result=this.drawHitDetectionReplay(gl,context,skippedFeaturesHash,featureCallback,oneByOne,opt_hitExtent);this.shutDownProgram(gl,locations);if(this.lineStringReplay){if(!tmpStencil)gl.disable(gl.STENCIL_TEST);gl.clear(gl.STENCIL_BUFFER_BIT);
gl.stencilFunc(tmpStencilFunc,tmpStencilRef,tmpStencilMaskVal);gl.stencilMask(tmpStencilMask);gl.stencilOp(tmpStencilOpFail,tmpStencilOpZFail,tmpStencilOpPass)}return result};
ol.render.webgl.Replay.prototype.drawElements=function(gl,context,start,end){var elementType=context.hasOESElementIndexUint?ol.webgl.UNSIGNED_INT:ol.webgl.UNSIGNED_SHORT;var elementSize=context.hasOESElementIndexUint?4:2;var numItems=end-start;var offsetInBytes=start*elementSize;gl.drawElements(ol.webgl.TRIANGLES,numItems,elementType,offsetInBytes)};goog.provide("ol.render.webgl");ol.render.webgl.defaultFont="10px sans-serif";ol.render.webgl.defaultFillStyle=[0,0,0,1];ol.render.webgl.defaultLineCap="round";ol.render.webgl.defaultLineDash=[];ol.render.webgl.defaultLineDashOffset=0;ol.render.webgl.defaultLineJoin="round";ol.render.webgl.defaultMiterLimit=10;ol.render.webgl.defaultStrokeStyle=[0,0,0,1];ol.render.webgl.defaultTextAlign=.5;ol.render.webgl.defaultTextBaseline=.5;ol.render.webgl.defaultLineWidth=1;
ol.render.webgl.triangleIsCounterClockwise=function(x1,y1,x2,y2,x3,y3){var area=(x2-x1)*(y3-y1)-(x3-x1)*(y2-y1);return area<=ol.render.webgl.EPSILON&&area>=-ol.render.webgl.EPSILON?undefined:area>0};ol.render.webgl.EPSILON=Number.EPSILON||2.220446049250313E-16;goog.provide("ol.webgl.Buffer");goog.require("ol.webgl");ol.webgl.Buffer=function(opt_arr,opt_usage){this.arr_=opt_arr!==undefined?opt_arr:[];this.usage_=opt_usage!==undefined?opt_usage:ol.webgl.Buffer.Usage_.STATIC_DRAW};ol.webgl.Buffer.prototype.getArray=function(){return this.arr_};ol.webgl.Buffer.prototype.getUsage=function(){return this.usage_};ol.webgl.Buffer.Usage_={STATIC_DRAW:ol.webgl.STATIC_DRAW,STREAM_DRAW:ol.webgl.STREAM_DRAW,DYNAMIC_DRAW:ol.webgl.DYNAMIC_DRAW};goog.provide("ol.render.webgl.CircleReplay");goog.require("ol");goog.require("ol.array");goog.require("ol.color");goog.require("ol.extent");goog.require("ol.obj");goog.require("ol.geom.flat.transform");goog.require("ol.render.webgl.circlereplay.defaultshader");goog.require("ol.render.webgl.circlereplay.defaultshader.Locations");goog.require("ol.render.webgl.Replay");goog.require("ol.render.webgl");goog.require("ol.webgl");goog.require("ol.webgl.Buffer");
ol.render.webgl.CircleReplay=function(tolerance,maxExtent){ol.render.webgl.Replay.call(this,tolerance,maxExtent);this.defaultLocations_=null;this.styles_=[];this.styleIndices_=[];this.radius_=0;this.state_={fillColor:null,strokeColor:null,lineDash:null,lineDashOffset:undefined,lineWidth:undefined,changed:false}};ol.inherits(ol.render.webgl.CircleReplay,ol.render.webgl.Replay);
ol.render.webgl.CircleReplay.prototype.drawCoordinates_=function(flatCoordinates,offset,end,stride){var numVertices=this.vertices.length;var numIndices=this.indices.length;var n=numVertices/4;var i,ii;for(i=offset,ii=end;i<ii;i+=stride){this.vertices[numVertices++]=flatCoordinates[i];this.vertices[numVertices++]=flatCoordinates[i+1];this.vertices[numVertices++]=0;this.vertices[numVertices++]=this.radius_;this.vertices[numVertices++]=flatCoordinates[i];this.vertices[numVertices++]=flatCoordinates[i+
1];this.vertices[numVertices++]=1;this.vertices[numVertices++]=this.radius_;this.vertices[numVertices++]=flatCoordinates[i];this.vertices[numVertices++]=flatCoordinates[i+1];this.vertices[numVertices++]=2;this.vertices[numVertices++]=this.radius_;this.vertices[numVertices++]=flatCoordinates[i];this.vertices[numVertices++]=flatCoordinates[i+1];this.vertices[numVertices++]=3;this.vertices[numVertices++]=this.radius_;this.indices[numIndices++]=n;this.indices[numIndices++]=n+1;this.indices[numIndices++]=
n+2;this.indices[numIndices++]=n+2;this.indices[numIndices++]=n+3;this.indices[numIndices++]=n;n+=4}};
ol.render.webgl.CircleReplay.prototype.drawCircle=function(circleGeometry,feature){var radius=circleGeometry.getRadius();var stride=circleGeometry.getStride();if(radius){this.startIndices.push(this.indices.length);this.startIndicesFeature.push(feature);if(this.state_.changed){this.styleIndices_.push(this.indices.length);this.state_.changed=false}this.radius_=radius;var flatCoordinates=circleGeometry.getFlatCoordinates();flatCoordinates=ol.geom.flat.transform.translate(flatCoordinates,0,2,stride,-this.origin[0],
-this.origin[1]);this.drawCoordinates_(flatCoordinates,0,2,stride)}else if(this.state_.changed){this.styles_.pop();if(this.styles_.length){var lastState=this.styles_[this.styles_.length-1];this.state_.fillColor=lastState[0];this.state_.strokeColor=lastState[1];this.state_.lineWidth=lastState[2];this.state_.changed=false}}};
ol.render.webgl.CircleReplay.prototype.finish=function(context){this.verticesBuffer=new ol.webgl.Buffer(this.vertices);this.indicesBuffer=new ol.webgl.Buffer(this.indices);this.startIndices.push(this.indices.length);if(this.styleIndices_.length===0&&this.styles_.length>0)this.styles_=[];this.vertices=null;this.indices=null};
ol.render.webgl.CircleReplay.prototype.getDeleteResourcesFunction=function(context){var verticesBuffer=this.verticesBuffer;var indicesBuffer=this.indicesBuffer;return function(){context.deleteBuffer(verticesBuffer);context.deleteBuffer(indicesBuffer)}};
ol.render.webgl.CircleReplay.prototype.setUpProgram=function(gl,context,size,pixelRatio){var fragmentShader,vertexShader;fragmentShader=ol.render.webgl.circlereplay.defaultshader.fragment;vertexShader=ol.render.webgl.circlereplay.defaultshader.vertex;var program=context.getProgram(fragmentShader,vertexShader);var locations;if(!this.defaultLocations_){locations=new ol.render.webgl.circlereplay.defaultshader.Locations(gl,program);this.defaultLocations_=locations}else locations=this.defaultLocations_;
context.useProgram(program);gl.enableVertexAttribArray(locations.a_position);gl.vertexAttribPointer(locations.a_position,2,ol.webgl.FLOAT,false,16,0);gl.enableVertexAttribArray(locations.a_instruction);gl.vertexAttribPointer(locations.a_instruction,1,ol.webgl.FLOAT,false,16,8);gl.enableVertexAttribArray(locations.a_radius);gl.vertexAttribPointer(locations.a_radius,1,ol.webgl.FLOAT,false,16,12);gl.uniform2fv(locations.u_size,size);gl.uniform1f(locations.u_pixelRatio,pixelRatio);return locations};
ol.render.webgl.CircleReplay.prototype.shutDownProgram=function(gl,locations){gl.disableVertexAttribArray(locations.a_position);gl.disableVertexAttribArray(locations.a_instruction);gl.disableVertexAttribArray(locations.a_radius)};
ol.render.webgl.CircleReplay.prototype.drawReplay=function(gl,context,skippedFeaturesHash,hitDetection){if(!ol.obj.isEmpty(skippedFeaturesHash))this.drawReplaySkipping_(gl,context,skippedFeaturesHash);else{var i,start,end,nextStyle;end=this.startIndices[this.startIndices.length-1];for(i=this.styleIndices_.length-1;i>=0;--i){start=this.styleIndices_[i];nextStyle=this.styles_[i];this.setFillStyle_(gl,nextStyle[0]);this.setStrokeStyle_(gl,nextStyle[1],nextStyle[2]);this.drawElements(gl,context,start,
end);end=start}}};
ol.render.webgl.CircleReplay.prototype.drawHitDetectionReplayOneByOne=function(gl,context,skippedFeaturesHash,featureCallback,opt_hitExtent){var i,start,end,nextStyle,groupStart,feature,featureUid,featureIndex;featureIndex=this.startIndices.length-2;end=this.startIndices[featureIndex+1];for(i=this.styleIndices_.length-1;i>=0;--i){nextStyle=this.styles_[i];this.setFillStyle_(gl,nextStyle[0]);this.setStrokeStyle_(gl,nextStyle[1],nextStyle[2]);groupStart=this.styleIndices_[i];while(featureIndex>=0&&
this.startIndices[featureIndex]>=groupStart){start=this.startIndices[featureIndex];feature=this.startIndicesFeature[featureIndex];featureUid=ol.getUid(feature).toString();if(skippedFeaturesHash[featureUid]===undefined&&feature.getGeometry()&&(opt_hitExtent===undefined||ol.extent.intersects(opt_hitExtent,feature.getGeometry().getExtent()))){gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);this.drawElements(gl,context,start,end);var result=featureCallback(feature);if(result)return result}featureIndex--;
end=start}}return undefined};
ol.render.webgl.CircleReplay.prototype.drawReplaySkipping_=function(gl,context,skippedFeaturesHash){var i,start,end,nextStyle,groupStart,feature,featureUid,featureIndex,featureStart;featureIndex=this.startIndices.length-2;end=start=this.startIndices[featureIndex+1];for(i=this.styleIndices_.length-1;i>=0;--i){nextStyle=this.styles_[i];this.setFillStyle_(gl,nextStyle[0]);this.setStrokeStyle_(gl,nextStyle[1],nextStyle[2]);groupStart=this.styleIndices_[i];while(featureIndex>=0&&this.startIndices[featureIndex]>=
groupStart){featureStart=this.startIndices[featureIndex];feature=this.startIndicesFeature[featureIndex];featureUid=ol.getUid(feature).toString();if(skippedFeaturesHash[featureUid]){if(start!==end)this.drawElements(gl,context,start,end);end=featureStart}featureIndex--;start=featureStart}if(start!==end)this.drawElements(gl,context,start,end);start=end=groupStart}};ol.render.webgl.CircleReplay.prototype.setFillStyle_=function(gl,color){gl.uniform4fv(this.defaultLocations_.u_fillColor,color)};
ol.render.webgl.CircleReplay.prototype.setStrokeStyle_=function(gl,color,lineWidth){gl.uniform4fv(this.defaultLocations_.u_strokeColor,color);gl.uniform1f(this.defaultLocations_.u_lineWidth,lineWidth)};
ol.render.webgl.CircleReplay.prototype.setFillStrokeStyle=function(fillStyle,strokeStyle){var strokeStyleColor,strokeStyleWidth;if(strokeStyle){var strokeStyleLineDash=strokeStyle.getLineDash();this.state_.lineDash=strokeStyleLineDash?strokeStyleLineDash:ol.render.webgl.defaultLineDash;var strokeStyleLineDashOffset=strokeStyle.getLineDashOffset();this.state_.lineDashOffset=strokeStyleLineDashOffset?strokeStyleLineDashOffset:ol.render.webgl.defaultLineDashOffset;strokeStyleColor=strokeStyle.getColor();
if(!(strokeStyleColor instanceof CanvasGradient)&&!(strokeStyleColor instanceof CanvasPattern))strokeStyleColor=ol.color.asArray(strokeStyleColor).map(function(c,i){return i!=3?c/255:c})||ol.render.webgl.defaultStrokeStyle;else strokeStyleColor=ol.render.webgl.defaultStrokeStyle;strokeStyleWidth=strokeStyle.getWidth();strokeStyleWidth=strokeStyleWidth!==undefined?strokeStyleWidth:ol.render.webgl.defaultLineWidth}else{strokeStyleColor=[0,0,0,0];strokeStyleWidth=0}var fillStyleColor=fillStyle?fillStyle.getColor():
[0,0,0,0];if(!(fillStyleColor instanceof CanvasGradient)&&!(fillStyleColor instanceof CanvasPattern))fillStyleColor=ol.color.asArray(fillStyleColor).map(function(c,i){return i!=3?c/255:c})||ol.render.webgl.defaultFillStyle;else fillStyleColor=ol.render.webgl.defaultFillStyle;if(!this.state_.strokeColor||!ol.array.equals(this.state_.strokeColor,strokeStyleColor)||!this.state_.fillColor||!ol.array.equals(this.state_.fillColor,fillStyleColor)||this.state_.lineWidth!==strokeStyleWidth){this.state_.changed=
true;this.state_.fillColor=fillStyleColor;this.state_.strokeColor=strokeStyleColor;this.state_.lineWidth=strokeStyleWidth;this.styles_.push([fillStyleColor,strokeStyleColor,strokeStyleWidth])}};goog.provide("ol.render.webgl.texturereplay.defaultshader");goog.require("ol");goog.require("ol.webgl.Fragment");goog.require("ol.webgl.Vertex");
ol.render.webgl.texturereplay.defaultshader.fragment=new ol.webgl.Fragment(ol.DEBUG_WEBGL?"precision mediump float;\nvarying vec2 v_texCoord;\nvarying float v_opacity;\n\nuniform float u_opacity;\nuniform sampler2D u_image;\n\nvoid main(void) {\n  vec4 texColor = texture2D(u_image, v_texCoord);\n  gl_FragColor.rgb = texColor.rgb;\n  float alpha = texColor.a * v_opacity * u_opacity;\n  if (alpha == 0.0) {\n    discard;\n  }\n  gl_FragColor.a = alpha;\n}\n":"precision mediump float;varying vec2 a;varying float b;uniform float k;uniform sampler2D l;void main(void){vec4 texColor=texture2D(l,a);gl_FragColor.rgb=texColor.rgb;float alpha=texColor.a*b*k;if(alpha==0.0){discard;}gl_FragColor.a=alpha;}");
ol.render.webgl.texturereplay.defaultshader.vertex=new ol.webgl.Vertex(ol.DEBUG_WEBGL?"varying vec2 v_texCoord;\nvarying float v_opacity;\n\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nattribute vec2 a_offsets;\nattribute float a_opacity;\nattribute float a_rotateWithView;\n\nuniform mat4 u_projectionMatrix;\nuniform mat4 u_offsetScaleMatrix;\nuniform mat4 u_offsetRotateMatrix;\n\nvoid main(void) {\n  mat4 offsetMatrix = u_offsetScaleMatrix;\n  if (a_rotateWithView == 1.0) {\n    offsetMatrix = u_offsetScaleMatrix * u_offsetRotateMatrix;\n  }\n  vec4 offsets = offsetMatrix * vec4(a_offsets, 0.0, 0.0);\n  gl_Position = u_projectionMatrix * vec4(a_position, 0.0, 1.0) + offsets;\n  v_texCoord = a_texCoord;\n  v_opacity = a_opacity;\n}\n\n\n":
"varying vec2 a;varying float b;attribute vec2 c;attribute vec2 d;attribute vec2 e;attribute float f;attribute float g;uniform mat4 h;uniform mat4 i;uniform mat4 j;void main(void){mat4 offsetMatrix=i;if(g==1.0){offsetMatrix=i*j;}vec4 offsets=offsetMatrix*vec4(e,0.0,0.0);gl_Position=h*vec4(c,0.0,1.0)+offsets;a=d;b=f;}");goog.provide("ol.render.webgl.texturereplay.defaultshader.Locations");goog.require("ol");
ol.render.webgl.texturereplay.defaultshader.Locations=function(gl,program){this.u_projectionMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_projectionMatrix":"h");this.u_offsetScaleMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_offsetScaleMatrix":"i");this.u_offsetRotateMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_offsetRotateMatrix":"j");this.u_opacity=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_opacity":"k");this.u_image=gl.getUniformLocation(program,ol.DEBUG_WEBGL?
"u_image":"l");this.a_position=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_position":"c");this.a_texCoord=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_texCoord":"d");this.a_offsets=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_offsets":"e");this.a_opacity=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_opacity":"f");this.a_rotateWithView=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_rotateWithView":"g")};goog.provide("ol.webgl.ContextEventType");ol.webgl.ContextEventType={LOST:"webglcontextlost",RESTORED:"webglcontextrestored"};goog.provide("ol.webgl.Context");goog.require("ol");goog.require("ol.Disposable");goog.require("ol.array");goog.require("ol.events");goog.require("ol.obj");goog.require("ol.webgl");goog.require("ol.webgl.ContextEventType");
ol.webgl.Context=function(canvas,gl){this.canvas_=canvas;this.gl_=gl;this.bufferCache_={};this.shaderCache_={};this.programCache_={};this.currentProgram_=null;this.hitDetectionFramebuffer_=null;this.hitDetectionTexture_=null;this.hitDetectionRenderbuffer_=null;this.hasOESElementIndexUint=ol.array.includes(ol.WEBGL_EXTENSIONS,"OES_element_index_uint");if(this.hasOESElementIndexUint)gl.getExtension("OES_element_index_uint");ol.events.listen(this.canvas_,ol.webgl.ContextEventType.LOST,this.handleWebGLContextLost,
this);ol.events.listen(this.canvas_,ol.webgl.ContextEventType.RESTORED,this.handleWebGLContextRestored,this)};ol.inherits(ol.webgl.Context,ol.Disposable);
ol.webgl.Context.prototype.bindBuffer=function(target,buf){var gl=this.getGL();var arr=buf.getArray();var bufferKey=String(ol.getUid(buf));if(bufferKey in this.bufferCache_){var bufferCacheEntry=this.bufferCache_[bufferKey];gl.bindBuffer(target,bufferCacheEntry.buffer)}else{var buffer=gl.createBuffer();gl.bindBuffer(target,buffer);var arrayBuffer;if(target==ol.webgl.ARRAY_BUFFER)arrayBuffer=new Float32Array(arr);else if(target==ol.webgl.ELEMENT_ARRAY_BUFFER)arrayBuffer=this.hasOESElementIndexUint?
new Uint32Array(arr):new Uint16Array(arr);gl.bufferData(target,arrayBuffer,buf.getUsage());this.bufferCache_[bufferKey]={buf:buf,buffer:buffer}}};ol.webgl.Context.prototype.deleteBuffer=function(buf){var gl=this.getGL();var bufferKey=String(ol.getUid(buf));var bufferCacheEntry=this.bufferCache_[bufferKey];if(!gl.isContextLost())gl.deleteBuffer(bufferCacheEntry.buffer);delete this.bufferCache_[bufferKey]};
ol.webgl.Context.prototype.disposeInternal=function(){ol.events.unlistenAll(this.canvas_);var gl=this.getGL();if(!gl.isContextLost()){var key;for(key in this.bufferCache_)gl.deleteBuffer(this.bufferCache_[key].buffer);for(key in this.programCache_)gl.deleteProgram(this.programCache_[key]);for(key in this.shaderCache_)gl.deleteShader(this.shaderCache_[key]);gl.deleteFramebuffer(this.hitDetectionFramebuffer_);gl.deleteRenderbuffer(this.hitDetectionRenderbuffer_);gl.deleteTexture(this.hitDetectionTexture_)}};
ol.webgl.Context.prototype.getCanvas=function(){return this.canvas_};ol.webgl.Context.prototype.getGL=function(){return this.gl_};ol.webgl.Context.prototype.getHitDetectionFramebuffer=function(){if(!this.hitDetectionFramebuffer_)this.initHitDetectionFramebuffer_();return this.hitDetectionFramebuffer_};
ol.webgl.Context.prototype.getShader=function(shaderObject){var shaderKey=String(ol.getUid(shaderObject));if(shaderKey in this.shaderCache_)return this.shaderCache_[shaderKey];else{var gl=this.getGL();var shader=gl.createShader(shaderObject.getType());gl.shaderSource(shader,shaderObject.getSource());gl.compileShader(shader);this.shaderCache_[shaderKey]=shader;return shader}};
ol.webgl.Context.prototype.getProgram=function(fragmentShaderObject,vertexShaderObject){var programKey=ol.getUid(fragmentShaderObject)+"/"+ol.getUid(vertexShaderObject);if(programKey in this.programCache_)return this.programCache_[programKey];else{var gl=this.getGL();var program=gl.createProgram();gl.attachShader(program,this.getShader(fragmentShaderObject));gl.attachShader(program,this.getShader(vertexShaderObject));gl.linkProgram(program);this.programCache_[programKey]=program;return program}};
ol.webgl.Context.prototype.handleWebGLContextLost=function(){ol.obj.clear(this.bufferCache_);ol.obj.clear(this.shaderCache_);ol.obj.clear(this.programCache_);this.currentProgram_=null;this.hitDetectionFramebuffer_=null;this.hitDetectionTexture_=null;this.hitDetectionRenderbuffer_=null};ol.webgl.Context.prototype.handleWebGLContextRestored=function(){};
ol.webgl.Context.prototype.initHitDetectionFramebuffer_=function(){var gl=this.gl_;var framebuffer=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer);var texture=ol.webgl.Context.createEmptyTexture(gl,1,1);var renderbuffer=gl.createRenderbuffer();gl.bindRenderbuffer(gl.RENDERBUFFER,renderbuffer);gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16,1,1);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);gl.framebufferRenderbuffer(gl.FRAMEBUFFER,
gl.DEPTH_ATTACHMENT,gl.RENDERBUFFER,renderbuffer);gl.bindTexture(gl.TEXTURE_2D,null);gl.bindRenderbuffer(gl.RENDERBUFFER,null);gl.bindFramebuffer(gl.FRAMEBUFFER,null);this.hitDetectionFramebuffer_=framebuffer;this.hitDetectionTexture_=texture;this.hitDetectionRenderbuffer_=renderbuffer};ol.webgl.Context.prototype.useProgram=function(program){if(program==this.currentProgram_)return false;else{var gl=this.getGL();gl.useProgram(program);this.currentProgram_=program;return true}};
ol.webgl.Context.createTexture_=function(gl,opt_wrapS,opt_wrapT){var texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);if(opt_wrapS!==undefined)gl.texParameteri(ol.webgl.TEXTURE_2D,ol.webgl.TEXTURE_WRAP_S,opt_wrapS);if(opt_wrapT!==undefined)gl.texParameteri(ol.webgl.TEXTURE_2D,ol.webgl.TEXTURE_WRAP_T,opt_wrapT);return texture};
ol.webgl.Context.createEmptyTexture=function(gl,width,height,opt_wrapS,opt_wrapT){var texture=ol.webgl.Context.createTexture_(gl,opt_wrapS,opt_wrapT);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,width,height,0,gl.RGBA,gl.UNSIGNED_BYTE,null);return texture};ol.webgl.Context.createTexture=function(gl,image,opt_wrapS,opt_wrapT){var texture=ol.webgl.Context.createTexture_(gl,opt_wrapS,opt_wrapT);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,image);return texture};goog.provide("ol.render.webgl.TextureReplay");goog.require("ol");goog.require("ol.extent");goog.require("ol.obj");goog.require("ol.render.webgl.texturereplay.defaultshader");goog.require("ol.render.webgl.texturereplay.defaultshader.Locations");goog.require("ol.render.webgl.Replay");goog.require("ol.webgl");goog.require("ol.webgl.Context");
ol.render.webgl.TextureReplay=function(tolerance,maxExtent){ol.render.webgl.Replay.call(this,tolerance,maxExtent);this.anchorX=undefined;this.anchorY=undefined;this.groupIndices=[];this.hitDetectionGroupIndices=[];this.height=undefined;this.imageHeight=undefined;this.imageWidth=undefined;this.defaultLocations=null;this.opacity=undefined;this.originX=undefined;this.originY=undefined;this.rotateWithView=undefined;this.rotation=undefined;this.scale=undefined;this.width=undefined};
ol.inherits(ol.render.webgl.TextureReplay,ol.render.webgl.Replay);ol.render.webgl.TextureReplay.prototype.getDeleteResourcesFunction=function(context){var verticesBuffer=this.verticesBuffer;var indicesBuffer=this.indicesBuffer;var textures=this.getTextures(true);var gl=context.getGL();return function(){if(!gl.isContextLost()){var i,ii;for(i=0,ii=textures.length;i<ii;++i)gl.deleteTexture(textures[i])}context.deleteBuffer(verticesBuffer);context.deleteBuffer(indicesBuffer)}};
ol.render.webgl.TextureReplay.prototype.drawCoordinates=function(flatCoordinates,offset,end,stride){var anchorX=this.anchorX;var anchorY=this.anchorY;var height=this.height;var imageHeight=this.imageHeight;var imageWidth=this.imageWidth;var opacity=this.opacity;var originX=this.originX;var originY=this.originY;var rotateWithView=this.rotateWithView?1:0;var rotation=-this.rotation;var scale=this.scale;var width=this.width;var cos=Math.cos(rotation);var sin=Math.sin(rotation);var numIndices=this.indices.length;
var numVertices=this.vertices.length;var i,n,offsetX,offsetY,x,y;for(i=offset;i<end;i+=stride){x=flatCoordinates[i]-this.origin[0];y=flatCoordinates[i+1]-this.origin[1];n=numVertices/8;offsetX=-scale*anchorX;offsetY=-scale*(height-anchorY);this.vertices[numVertices++]=x;this.vertices[numVertices++]=y;this.vertices[numVertices++]=offsetX*cos-offsetY*sin;this.vertices[numVertices++]=offsetX*sin+offsetY*cos;this.vertices[numVertices++]=originX/imageWidth;this.vertices[numVertices++]=(originY+height)/
imageHeight;this.vertices[numVertices++]=opacity;this.vertices[numVertices++]=rotateWithView;offsetX=scale*(width-anchorX);offsetY=-scale*(height-anchorY);this.vertices[numVertices++]=x;this.vertices[numVertices++]=y;this.vertices[numVertices++]=offsetX*cos-offsetY*sin;this.vertices[numVertices++]=offsetX*sin+offsetY*cos;this.vertices[numVertices++]=(originX+width)/imageWidth;this.vertices[numVertices++]=(originY+height)/imageHeight;this.vertices[numVertices++]=opacity;this.vertices[numVertices++]=
rotateWithView;offsetX=scale*(width-anchorX);offsetY=scale*anchorY;this.vertices[numVertices++]=x;this.vertices[numVertices++]=y;this.vertices[numVertices++]=offsetX*cos-offsetY*sin;this.vertices[numVertices++]=offsetX*sin+offsetY*cos;this.vertices[numVertices++]=(originX+width)/imageWidth;this.vertices[numVertices++]=originY/imageHeight;this.vertices[numVertices++]=opacity;this.vertices[numVertices++]=rotateWithView;offsetX=-scale*anchorX;offsetY=scale*anchorY;this.vertices[numVertices++]=x;this.vertices[numVertices++]=
y;this.vertices[numVertices++]=offsetX*cos-offsetY*sin;this.vertices[numVertices++]=offsetX*sin+offsetY*cos;this.vertices[numVertices++]=originX/imageWidth;this.vertices[numVertices++]=originY/imageHeight;this.vertices[numVertices++]=opacity;this.vertices[numVertices++]=rotateWithView;this.indices[numIndices++]=n;this.indices[numIndices++]=n+1;this.indices[numIndices++]=n+2;this.indices[numIndices++]=n;this.indices[numIndices++]=n+2;this.indices[numIndices++]=n+3}return numVertices};
ol.render.webgl.TextureReplay.prototype.createTextures=function(textures,images,texturePerImage,gl){var texture,image,uid,i;var ii=images.length;for(i=0;i<ii;++i){image=images[i];uid=ol.getUid(image).toString();if(uid in texturePerImage)texture=texturePerImage[uid];else{texture=ol.webgl.Context.createTexture(gl,image,ol.webgl.CLAMP_TO_EDGE,ol.webgl.CLAMP_TO_EDGE);texturePerImage[uid]=texture}textures[i]=texture}};
ol.render.webgl.TextureReplay.prototype.setUpProgram=function(gl,context,size,pixelRatio){var fragmentShader=ol.render.webgl.texturereplay.defaultshader.fragment;var vertexShader=ol.render.webgl.texturereplay.defaultshader.vertex;var program=context.getProgram(fragmentShader,vertexShader);var locations;if(!this.defaultLocations){locations=new ol.render.webgl.texturereplay.defaultshader.Locations(gl,program);this.defaultLocations=locations}else locations=this.defaultLocations;context.useProgram(program);
gl.enableVertexAttribArray(locations.a_position);gl.vertexAttribPointer(locations.a_position,2,ol.webgl.FLOAT,false,32,0);gl.enableVertexAttribArray(locations.a_offsets);gl.vertexAttribPointer(locations.a_offsets,2,ol.webgl.FLOAT,false,32,8);gl.enableVertexAttribArray(locations.a_texCoord);gl.vertexAttribPointer(locations.a_texCoord,2,ol.webgl.FLOAT,false,32,16);gl.enableVertexAttribArray(locations.a_opacity);gl.vertexAttribPointer(locations.a_opacity,1,ol.webgl.FLOAT,false,32,24);gl.enableVertexAttribArray(locations.a_rotateWithView);
gl.vertexAttribPointer(locations.a_rotateWithView,1,ol.webgl.FLOAT,false,32,28);return locations};ol.render.webgl.TextureReplay.prototype.shutDownProgram=function(gl,locations){gl.disableVertexAttribArray(locations.a_position);gl.disableVertexAttribArray(locations.a_offsets);gl.disableVertexAttribArray(locations.a_texCoord);gl.disableVertexAttribArray(locations.a_opacity);gl.disableVertexAttribArray(locations.a_rotateWithView)};
ol.render.webgl.TextureReplay.prototype.drawReplay=function(gl,context,skippedFeaturesHash,hitDetection){var textures=hitDetection?this.getHitDetectionTextures():this.getTextures();var groupIndices=hitDetection?this.hitDetectionGroupIndices:this.groupIndices;if(!ol.obj.isEmpty(skippedFeaturesHash))this.drawReplaySkipping(gl,context,skippedFeaturesHash,textures,groupIndices);else{var i,ii,start;for(i=0,ii=textures.length,start=0;i<ii;++i){gl.bindTexture(ol.webgl.TEXTURE_2D,textures[i]);var end=groupIndices[i];
this.drawElements(gl,context,start,end);start=end}}};
ol.render.webgl.TextureReplay.prototype.drawReplaySkipping=function(gl,context,skippedFeaturesHash,textures,groupIndices){var featureIndex=0;var i,ii;for(i=0,ii=textures.length;i<ii;++i){gl.bindTexture(ol.webgl.TEXTURE_2D,textures[i]);var groupStart=i>0?groupIndices[i-1]:0;var groupEnd=groupIndices[i];var start=groupStart;var end=groupStart;while(featureIndex<this.startIndices.length&&this.startIndices[featureIndex]<=groupEnd){var feature=this.startIndicesFeature[featureIndex];var featureUid=ol.getUid(feature).toString();
if(skippedFeaturesHash[featureUid]!==undefined){if(start!==end)this.drawElements(gl,context,start,end);start=featureIndex===this.startIndices.length-1?groupEnd:this.startIndices[featureIndex+1];end=start}else end=featureIndex===this.startIndices.length-1?groupEnd:this.startIndices[featureIndex+1];featureIndex++}if(start!==end)this.drawElements(gl,context,start,end)}};
ol.render.webgl.TextureReplay.prototype.drawHitDetectionReplayOneByOne=function(gl,context,skippedFeaturesHash,featureCallback,opt_hitExtent){var i,groupStart,start,end,feature,featureUid;var featureIndex=this.startIndices.length-1;var hitDetectionTextures=this.getHitDetectionTextures();for(i=hitDetectionTextures.length-1;i>=0;--i){gl.bindTexture(ol.webgl.TEXTURE_2D,hitDetectionTextures[i]);groupStart=i>0?this.hitDetectionGroupIndices[i-1]:0;end=this.hitDetectionGroupIndices[i];while(featureIndex>=
0&&this.startIndices[featureIndex]>=groupStart){start=this.startIndices[featureIndex];feature=this.startIndicesFeature[featureIndex];featureUid=ol.getUid(feature).toString();if(skippedFeaturesHash[featureUid]===undefined&&feature.getGeometry()&&(opt_hitExtent===undefined||ol.extent.intersects(opt_hitExtent,feature.getGeometry().getExtent()))){gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);this.drawElements(gl,context,start,end);var result=featureCallback(feature);if(result)return result}end=start;
featureIndex--}}return undefined};ol.render.webgl.TextureReplay.prototype.finish=function(context){this.anchorX=undefined;this.anchorY=undefined;this.height=undefined;this.imageHeight=undefined;this.imageWidth=undefined;this.indices=null;this.opacity=undefined;this.originX=undefined;this.originY=undefined;this.rotateWithView=undefined;this.rotation=undefined;this.scale=undefined;this.vertices=null;this.width=undefined};ol.render.webgl.TextureReplay.prototype.getTextures=function(opt_all){};
ol.render.webgl.TextureReplay.prototype.getHitDetectionTextures=function(){};goog.provide("ol.render.webgl.ImageReplay");goog.require("ol");goog.require("ol.render.webgl.TextureReplay");goog.require("ol.webgl.Buffer");ol.render.webgl.ImageReplay=function(tolerance,maxExtent){ol.render.webgl.TextureReplay.call(this,tolerance,maxExtent);this.images_=[];this.hitDetectionImages_=[];this.textures_=[];this.hitDetectionTextures_=[]};ol.inherits(ol.render.webgl.ImageReplay,ol.render.webgl.TextureReplay);
ol.render.webgl.ImageReplay.prototype.drawMultiPoint=function(multiPointGeometry,feature){this.startIndices.push(this.indices.length);this.startIndicesFeature.push(feature);var flatCoordinates=multiPointGeometry.getFlatCoordinates();var stride=multiPointGeometry.getStride();this.drawCoordinates(flatCoordinates,0,flatCoordinates.length,stride)};
ol.render.webgl.ImageReplay.prototype.drawPoint=function(pointGeometry,feature){this.startIndices.push(this.indices.length);this.startIndicesFeature.push(feature);var flatCoordinates=pointGeometry.getFlatCoordinates();var stride=pointGeometry.getStride();this.drawCoordinates(flatCoordinates,0,flatCoordinates.length,stride)};
ol.render.webgl.ImageReplay.prototype.finish=function(context){var gl=context.getGL();this.groupIndices.push(this.indices.length);this.hitDetectionGroupIndices.push(this.indices.length);this.verticesBuffer=new ol.webgl.Buffer(this.vertices);var indices=this.indices;this.indicesBuffer=new ol.webgl.Buffer(indices);var texturePerImage={};this.createTextures(this.textures_,this.images_,texturePerImage,gl);this.createTextures(this.hitDetectionTextures_,this.hitDetectionImages_,texturePerImage,gl);this.images_=
null;this.hitDetectionImages_=null;ol.render.webgl.TextureReplay.prototype.finish.call(this,context)};
ol.render.webgl.ImageReplay.prototype.setImageStyle=function(imageStyle){var anchor=imageStyle.getAnchor();var image=imageStyle.getImage(1);var imageSize=imageStyle.getImageSize();var hitDetectionImage=imageStyle.getHitDetectionImage(1);var opacity=imageStyle.getOpacity();var origin=imageStyle.getOrigin();var rotateWithView=imageStyle.getRotateWithView();var rotation=imageStyle.getRotation();var size=imageStyle.getSize();var scale=imageStyle.getScale();var currentImage;if(this.images_.length===0)this.images_.push(image);
else{currentImage=this.images_[this.images_.length-1];if(ol.getUid(currentImage)!=ol.getUid(image)){this.groupIndices.push(this.indices.length);this.images_.push(image)}}if(this.hitDetectionImages_.length===0)this.hitDetectionImages_.push(hitDetectionImage);else{currentImage=this.hitDetectionImages_[this.hitDetectionImages_.length-1];if(ol.getUid(currentImage)!=ol.getUid(hitDetectionImage)){this.hitDetectionGroupIndices.push(this.indices.length);this.hitDetectionImages_.push(hitDetectionImage)}}this.anchorX=
anchor[0];this.anchorY=anchor[1];this.height=size[1];this.imageHeight=imageSize[1];this.imageWidth=imageSize[0];this.opacity=opacity;this.originX=origin[0];this.originY=origin[1];this.rotation=rotation;this.rotateWithView=rotateWithView;this.scale=scale;this.width=size[0]};ol.render.webgl.ImageReplay.prototype.getTextures=function(opt_all){return opt_all?this.textures_.concat(this.hitDetectionTextures_):this.textures_};ol.render.webgl.ImageReplay.prototype.getHitDetectionTextures=function(){return this.hitDetectionTextures_};goog.provide("ol.render.webgl.linestringreplay.defaultshader");goog.require("ol");goog.require("ol.webgl.Fragment");goog.require("ol.webgl.Vertex");
ol.render.webgl.linestringreplay.defaultshader.fragment=new ol.webgl.Fragment(ol.DEBUG_WEBGL?"precision mediump float;\nvarying float v_round;\nvarying vec2 v_roundVertex;\nvarying float v_halfWidth;\n\n\n\nuniform float u_opacity;\nuniform vec4 u_color;\nuniform vec2 u_size;\nuniform float u_pixelRatio;\n\nvoid main(void) {\n  if (v_round > 0.0) {\n    vec2 windowCoords = vec2((v_roundVertex.x + 1.0) / 2.0 * u_size.x * u_pixelRatio,\n        (v_roundVertex.y + 1.0) / 2.0 * u_size.y * u_pixelRatio);\n    if (length(windowCoords - gl_FragCoord.xy) > v_halfWidth * u_pixelRatio) {\n      discard;\n    }\n  }\n  gl_FragColor = u_color;\n  float alpha = u_color.a * u_opacity;\n  if (alpha == 0.0) {\n    discard;\n  }\n  gl_FragColor.a = alpha;\n}\n":"precision mediump float;varying float a;varying vec2 aVertex;varying float c;uniform float m;uniform vec4 n;uniform vec2 o;uniform float p;void main(void){if(a>0.0){vec2 windowCoords=vec2((aVertex.x+1.0)/2.0*o.x*p,(aVertex.y+1.0)/2.0*o.y*p);if(length(windowCoords-gl_FragCoord.xy)>c*p){discard;}} gl_FragColor=n;float alpha=n.a*m;if(alpha==0.0){discard;}gl_FragColor.a=alpha;}");
ol.render.webgl.linestringreplay.defaultshader.vertex=new ol.webgl.Vertex(ol.DEBUG_WEBGL?"varying float v_round;\nvarying vec2 v_roundVertex;\nvarying float v_halfWidth;\n\n\nattribute vec2 a_lastPos;\nattribute vec2 a_position;\nattribute vec2 a_nextPos;\nattribute float a_direction;\n\nuniform mat4 u_projectionMatrix;\nuniform mat4 u_offsetScaleMatrix;\nuniform mat4 u_offsetRotateMatrix;\nuniform float u_lineWidth;\nuniform float u_miterLimit;\n\nbool nearlyEquals(in float value, in float ref) {\n  float epsilon = 0.000000000001;\n  return value >= ref - epsilon && value <= ref + epsilon;\n}\n\nvoid alongNormal(out vec2 offset, in vec2 nextP, in float turnDir, in float direction) {\n  vec2 dirVect = nextP - a_position;\n  vec2 normal = normalize(vec2(-turnDir * dirVect.y, turnDir * dirVect.x));\n  offset = u_lineWidth / 2.0 * normal * direction;\n}\n\nvoid miterUp(out vec2 offset, out float round, in bool isRound, in float direction) {\n  float halfWidth = u_lineWidth / 2.0;\n  vec2 tangent = normalize(normalize(a_nextPos - a_position) + normalize(a_position - a_lastPos));\n  vec2 normal = vec2(-tangent.y, tangent.x);\n  vec2 dirVect = a_nextPos - a_position;\n  vec2 tmpNormal = normalize(vec2(-dirVect.y, dirVect.x));\n  float miterLength = abs(halfWidth / dot(normal, tmpNormal));\n  offset = normal * direction * miterLength;\n  round = 0.0;\n  if (isRound) {\n    round = 1.0;\n  } else if (miterLength > u_miterLimit + u_lineWidth) {\n    offset = halfWidth * tmpNormal * direction;\n  }\n}\n\nbool miterDown(out vec2 offset, in vec4 projPos, in mat4 offsetMatrix, in float direction) {\n  bool degenerate = false;\n  vec2 tangent = normalize(normalize(a_nextPos - a_position) + normalize(a_position - a_lastPos));\n  vec2 normal = vec2(-tangent.y, tangent.x);\n  vec2 dirVect = a_lastPos - a_position;\n  vec2 tmpNormal = normalize(vec2(-dirVect.y, dirVect.x));\n  vec2 longOffset, shortOffset, longVertex;\n  vec4 shortProjVertex;\n  float halfWidth = u_lineWidth / 2.0;\n  if (length(a_nextPos - a_position) > length(a_lastPos - a_position)) {\n    longOffset = tmpNormal * direction * halfWidth;\n    shortOffset = normalize(vec2(dirVect.y, -dirVect.x)) * direction * halfWidth;\n    longVertex = a_nextPos;\n    shortProjVertex = u_projectionMatrix * vec4(a_lastPos, 0.0, 1.0);\n  } else {\n    shortOffset = tmpNormal * direction * halfWidth;\n    longOffset = normalize(vec2(dirVect.y, -dirVect.x)) * direction * halfWidth;\n    longVertex = a_lastPos;\n    shortProjVertex = u_projectionMatrix * vec4(a_nextPos, 0.0, 1.0);\n  }\n  //Intersection algorithm based on theory by Paul Bourke (http://paulbourke.net/geometry/pointlineplane/).\n  vec4 p1 = u_projectionMatrix * vec4(longVertex, 0.0, 1.0) + offsetMatrix * vec4(longOffset, 0.0, 0.0);\n  vec4 p2 = projPos + offsetMatrix * vec4(longOffset, 0.0, 0.0);\n  vec4 p3 = shortProjVertex + offsetMatrix * vec4(-shortOffset, 0.0, 0.0);\n  vec4 p4 = shortProjVertex + offsetMatrix * vec4(shortOffset, 0.0, 0.0);\n  float denom = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);\n  float firstU = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denom;\n  float secondU = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denom;\n  float epsilon = 0.000000000001;\n  if (firstU > epsilon && firstU < 1.0 - epsilon && secondU > epsilon && secondU < 1.0 - epsilon) {\n    shortProjVertex.x = p1.x + firstU * (p2.x - p1.x);\n    shortProjVertex.y = p1.y + firstU * (p2.y - p1.y);\n    offset = shortProjVertex.xy;\n    degenerate = true;\n  } else {\n    float miterLength = abs(halfWidth / dot(normal, tmpNormal));\n    offset = normal * direction * miterLength;\n  }\n  return degenerate;\n}\n\nvoid squareCap(out vec2 offset, out float round, in bool isRound, in vec2 nextP,\n    in float turnDir, in float direction) {\n  round = 0.0;\n  vec2 dirVect = a_position - nextP;\n  vec2 firstNormal = normalize(dirVect);\n  vec2 secondNormal = vec2(turnDir * firstNormal.y * direction, -turnDir * firstNormal.x * direction);\n  vec2 hypotenuse = normalize(firstNormal - secondNormal);\n  vec2 normal = vec2(turnDir * hypotenuse.y * direction, -turnDir * hypotenuse.x * direction);\n  float length = sqrt(v_halfWidth * v_halfWidth * 2.0);\n  offset = normal * length;\n  if (isRound) {\n    round = 1.0;\n  }\n}\n\nvoid main(void) {\n  bool degenerate = false;\n  float direction = float(sign(a_direction));\n  mat4 offsetMatrix = u_offsetScaleMatrix * u_offsetRotateMatrix;\n  vec2 offset;\n  vec4 projPos = u_projectionMatrix * vec4(a_position, 0.0, 1.0);\n  bool round = nearlyEquals(mod(a_direction, 2.0), 0.0);\n\n  v_round = 0.0;\n  v_halfWidth = u_lineWidth / 2.0;\n  v_roundVertex = projPos.xy;\n\n  if (nearlyEquals(mod(a_direction, 3.0), 0.0) || nearlyEquals(mod(a_direction, 17.0), 0.0)) {\n    alongNormal(offset, a_nextPos, 1.0, direction);\n  } else if (nearlyEquals(mod(a_direction, 5.0), 0.0) || nearlyEquals(mod(a_direction, 13.0), 0.0)) {\n    alongNormal(offset, a_lastPos, -1.0, direction);\n  } else if (nearlyEquals(mod(a_direction, 23.0), 0.0)) {\n    miterUp(offset, v_round, round, direction);\n  } else if (nearlyEquals(mod(a_direction, 19.0), 0.0)) {\n    degenerate = miterDown(offset, projPos, offsetMatrix, direction);\n  } else if (nearlyEquals(mod(a_direction, 7.0), 0.0)) {\n    squareCap(offset, v_round, round, a_nextPos, 1.0, direction);\n  } else if (nearlyEquals(mod(a_direction, 11.0), 0.0)) {\n    squareCap(offset, v_round, round, a_lastPos, -1.0, direction);\n  }\n  if (!degenerate) {\n    vec4 offsets = offsetMatrix * vec4(offset, 0.0, 0.0);\n    gl_Position = projPos + offsets;\n  } else {\n    gl_Position = vec4(offset, 0.0, 1.0);\n  }\n}\n\n\n":
"varying float a;varying vec2 aVertex;varying float c;attribute vec2 d;attribute vec2 e;attribute vec2 f;attribute float g;uniform mat4 h;uniform mat4 i;uniform mat4 j;uniform float k;uniform float l;bool nearlyEquals(in float value,in float ref){float epsilon=0.000000000001;return value>=ref-epsilon&&value<=ref+epsilon;}void alongNormal(out vec2 offset,in vec2 nextP,in float turnDir,in float direction){vec2 dirVect=nextP-e;vec2 normal=normalize(vec2(-turnDir*dirVect.y,turnDir*dirVect.x));offset=k/2.0*normal*direction;}void miterUp(out vec2 offset,out float round,in bool isRound,in float direction){float halfWidth=k/2.0;vec2 tangent=normalize(normalize(f-e)+normalize(e-d));vec2 normal=vec2(-tangent.y,tangent.x);vec2 dirVect=f-e;vec2 tmpNormal=normalize(vec2(-dirVect.y,dirVect.x));float miterLength=abs(halfWidth/dot(normal,tmpNormal));offset=normal*direction*miterLength;round=0.0;if(isRound){round=1.0;}else if(miterLength>l+k){offset=halfWidth*tmpNormal*direction;}} bool miterDown(out vec2 offset,in vec4 projPos,in mat4 offsetMatrix,in float direction){bool degenerate=false;vec2 tangent=normalize(normalize(f-e)+normalize(e-d));vec2 normal=vec2(-tangent.y,tangent.x);vec2 dirVect=d-e;vec2 tmpNormal=normalize(vec2(-dirVect.y,dirVect.x));vec2 longOffset,shortOffset,longVertex;vec4 shortProjVertex;float halfWidth=k/2.0;if(length(f-e)>length(d-e)){longOffset=tmpNormal*direction*halfWidth;shortOffset=normalize(vec2(dirVect.y,-dirVect.x))*direction*halfWidth;longVertex=f;shortProjVertex=h*vec4(d,0.0,1.0);}else{shortOffset=tmpNormal*direction*halfWidth;longOffset=normalize(vec2(dirVect.y,-dirVect.x))*direction*halfWidth;longVertex=d;shortProjVertex=h*vec4(f,0.0,1.0);}vec4 p1=h*vec4(longVertex,0.0,1.0)+offsetMatrix*vec4(longOffset,0.0,0.0);vec4 p2=projPos+offsetMatrix*vec4(longOffset,0.0,0.0);vec4 p3=shortProjVertex+offsetMatrix*vec4(-shortOffset,0.0,0.0);vec4 p4=shortProjVertex+offsetMatrix*vec4(shortOffset,0.0,0.0);float denom=(p4.y-p3.y)*(p2.x-p1.x)-(p4.x-p3.x)*(p2.y-p1.y);float firstU=((p4.x-p3.x)*(p1.y-p3.y)-(p4.y-p3.y)*(p1.x-p3.x))/denom;float secondU=((p2.x-p1.x)*(p1.y-p3.y)-(p2.y-p1.y)*(p1.x-p3.x))/denom;float epsilon=0.000000000001;if(firstU>epsilon&&firstU<1.0-epsilon&&secondU>epsilon&&secondU<1.0-epsilon){shortProjVertex.x=p1.x+firstU*(p2.x-p1.x);shortProjVertex.y=p1.y+firstU*(p2.y-p1.y);offset=shortProjVertex.xy;degenerate=true;}else{float miterLength=abs(halfWidth/dot(normal,tmpNormal));offset=normal*direction*miterLength;}return degenerate;}void squareCap(out vec2 offset,out float round,in bool isRound,in vec2 nextP,in float turnDir,in float direction){round=0.0;vec2 dirVect=e-nextP;vec2 firstNormal=normalize(dirVect);vec2 secondNormal=vec2(turnDir*firstNormal.y*direction,-turnDir*firstNormal.x*direction);vec2 hypotenuse=normalize(firstNormal-secondNormal);vec2 normal=vec2(turnDir*hypotenuse.y*direction,-turnDir*hypotenuse.x*direction);float length=sqrt(c*c*2.0);offset=normal*length;if(isRound){round=1.0;}} void main(void){bool degenerate=false;float direction=float(sign(g));mat4 offsetMatrix=i*j;vec2 offset;vec4 projPos=h*vec4(e,0.0,1.0);bool round=nearlyEquals(mod(g,2.0),0.0);a=0.0;c=k/2.0;aVertex=projPos.xy;if(nearlyEquals(mod(g,3.0),0.0)||nearlyEquals(mod(g,17.0),0.0)){alongNormal(offset,f,1.0,direction);}else if(nearlyEquals(mod(g,5.0),0.0)||nearlyEquals(mod(g,13.0),0.0)){alongNormal(offset,d,-1.0,direction);}else if(nearlyEquals(mod(g,23.0),0.0)){miterUp(offset,a,round,direction);}else if(nearlyEquals(mod(g,19.0),0.0)){degenerate=miterDown(offset,projPos,offsetMatrix,direction);}else if(nearlyEquals(mod(g,7.0),0.0)){squareCap(offset,a,round,f,1.0,direction);}else if(nearlyEquals(mod(g,11.0),0.0)){squareCap(offset,a,round,d,-1.0,direction);}if(!degenerate){vec4 offsets=offsetMatrix*vec4(offset,0.0,0.0);gl_Position=projPos+offsets;}else{gl_Position=vec4(offset,0.0,1.0);}}");goog.provide("ol.render.webgl.linestringreplay.defaultshader.Locations");goog.require("ol");
ol.render.webgl.linestringreplay.defaultshader.Locations=function(gl,program){this.u_projectionMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_projectionMatrix":"h");this.u_offsetScaleMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_offsetScaleMatrix":"i");this.u_offsetRotateMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_offsetRotateMatrix":"j");this.u_lineWidth=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_lineWidth":"k");this.u_miterLimit=gl.getUniformLocation(program,ol.DEBUG_WEBGL?
"u_miterLimit":"l");this.u_opacity=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_opacity":"m");this.u_color=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_color":"n");this.u_size=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_size":"o");this.u_pixelRatio=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_pixelRatio":"p");this.a_lastPos=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_lastPos":"d");this.a_position=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_position":"e");this.a_nextPos=gl.getAttribLocation(program,
ol.DEBUG_WEBGL?"a_nextPos":"f");this.a_direction=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_direction":"g")};goog.provide("ol.render.webgl.LineStringReplay");goog.require("ol");goog.require("ol.array");goog.require("ol.color");goog.require("ol.extent");goog.require("ol.geom.flat.orient");goog.require("ol.geom.flat.transform");goog.require("ol.geom.flat.topology");goog.require("ol.obj");goog.require("ol.render.webgl");goog.require("ol.render.webgl.Replay");goog.require("ol.render.webgl.linestringreplay.defaultshader");goog.require("ol.render.webgl.linestringreplay.defaultshader.Locations");goog.require("ol.webgl");
goog.require("ol.webgl.Buffer");ol.render.webgl.LineStringReplay=function(tolerance,maxExtent){ol.render.webgl.Replay.call(this,tolerance,maxExtent);this.defaultLocations_=null;this.styles_=[];this.styleIndices_=[];this.state_={strokeColor:null,lineCap:undefined,lineDash:null,lineDashOffset:undefined,lineJoin:undefined,lineWidth:undefined,miterLimit:undefined,changed:false}};ol.inherits(ol.render.webgl.LineStringReplay,ol.render.webgl.Replay);
ol.render.webgl.LineStringReplay.prototype.drawCoordinates_=function(flatCoordinates,offset,end,stride){var i,ii;var numVertices=this.vertices.length;var numIndices=this.indices.length;var lineJoin=this.state_.lineJoin==="bevel"?0:this.state_.lineJoin==="miter"?1:2;var lineCap=this.state_.lineCap==="butt"?0:this.state_.lineCap==="square"?1:2;var closed=ol.geom.flat.topology.lineStringIsClosed(flatCoordinates,offset,end,stride);var startCoords,sign,n;var lastIndex=numIndices;var lastSign=1;var p0,
p1,p2;for(i=offset,ii=end;i<ii;i+=stride){n=numVertices/7;p0=p1;p1=p2||[flatCoordinates[i],flatCoordinates[i+1]];if(i===offset){p2=[flatCoordinates[i+stride],flatCoordinates[i+stride+1]];if(end-offset===stride*2&&ol.array.equals(p1,p2))break;if(closed){p0=[flatCoordinates[end-stride*2],flatCoordinates[end-stride*2+1]];startCoords=p2}else{if(lineCap){numVertices=this.addVertices_([0,0],p1,p2,lastSign*ol.render.webgl.LineStringReplay.Instruction_.BEGIN_LINE_CAP*lineCap,numVertices);numVertices=this.addVertices_([0,
0],p1,p2,-lastSign*ol.render.webgl.LineStringReplay.Instruction_.BEGIN_LINE_CAP*lineCap,numVertices);this.indices[numIndices++]=n+2;this.indices[numIndices++]=n;this.indices[numIndices++]=n+1;this.indices[numIndices++]=n+1;this.indices[numIndices++]=n+3;this.indices[numIndices++]=n+2}numVertices=this.addVertices_([0,0],p1,p2,lastSign*ol.render.webgl.LineStringReplay.Instruction_.BEGIN_LINE*(lineCap||1),numVertices);numVertices=this.addVertices_([0,0],p1,p2,-lastSign*ol.render.webgl.LineStringReplay.Instruction_.BEGIN_LINE*
(lineCap||1),numVertices);lastIndex=numVertices/7-1;continue}}else if(i===end-stride)if(closed){p2=startCoords;break}else{p0=p0||[0,0];numVertices=this.addVertices_(p0,p1,[0,0],lastSign*ol.render.webgl.LineStringReplay.Instruction_.END_LINE*(lineCap||1),numVertices);numVertices=this.addVertices_(p0,p1,[0,0],-lastSign*ol.render.webgl.LineStringReplay.Instruction_.END_LINE*(lineCap||1),numVertices);this.indices[numIndices++]=n;this.indices[numIndices++]=lastIndex-1;this.indices[numIndices++]=lastIndex;
this.indices[numIndices++]=lastIndex;this.indices[numIndices++]=n+1;this.indices[numIndices++]=n;if(lineCap){numVertices=this.addVertices_(p0,p1,[0,0],lastSign*ol.render.webgl.LineStringReplay.Instruction_.END_LINE_CAP*lineCap,numVertices);numVertices=this.addVertices_(p0,p1,[0,0],-lastSign*ol.render.webgl.LineStringReplay.Instruction_.END_LINE_CAP*lineCap,numVertices);this.indices[numIndices++]=n+2;this.indices[numIndices++]=n;this.indices[numIndices++]=n+1;this.indices[numIndices++]=n+1;this.indices[numIndices++]=
n+3;this.indices[numIndices++]=n+2}break}else p2=[flatCoordinates[i+stride],flatCoordinates[i+stride+1]];sign=ol.render.webgl.triangleIsCounterClockwise(p0[0],p0[1],p1[0],p1[1],p2[0],p2[1])?-1:1;numVertices=this.addVertices_(p0,p1,p2,sign*ol.render.webgl.LineStringReplay.Instruction_.BEVEL_FIRST*(lineJoin||1),numVertices);numVertices=this.addVertices_(p0,p1,p2,sign*ol.render.webgl.LineStringReplay.Instruction_.BEVEL_SECOND*(lineJoin||1),numVertices);numVertices=this.addVertices_(p0,p1,p2,-sign*ol.render.webgl.LineStringReplay.Instruction_.MITER_BOTTOM*
(lineJoin||1),numVertices);if(i>offset){this.indices[numIndices++]=n;this.indices[numIndices++]=lastIndex-1;this.indices[numIndices++]=lastIndex;this.indices[numIndices++]=n+2;this.indices[numIndices++]=n;this.indices[numIndices++]=lastSign*sign>0?lastIndex:lastIndex-1}this.indices[numIndices++]=n;this.indices[numIndices++]=n+2;this.indices[numIndices++]=n+1;lastIndex=n+2;lastSign=sign;if(lineJoin){numVertices=this.addVertices_(p0,p1,p2,sign*ol.render.webgl.LineStringReplay.Instruction_.MITER_TOP*
lineJoin,numVertices);this.indices[numIndices++]=n+1;this.indices[numIndices++]=n+3;this.indices[numIndices++]=n}}if(closed){n=n||numVertices/7;sign=ol.geom.flat.orient.linearRingIsClockwise([p0[0],p0[1],p1[0],p1[1],p2[0],p2[1]],0,6,2)?1:-1;numVertices=this.addVertices_(p0,p1,p2,sign*ol.render.webgl.LineStringReplay.Instruction_.BEVEL_FIRST*(lineJoin||1),numVertices);numVertices=this.addVertices_(p0,p1,p2,-sign*ol.render.webgl.LineStringReplay.Instruction_.MITER_BOTTOM*(lineJoin||1),numVertices);
this.indices[numIndices++]=n;this.indices[numIndices++]=lastIndex-1;this.indices[numIndices++]=lastIndex;this.indices[numIndices++]=n+1;this.indices[numIndices++]=n;this.indices[numIndices++]=lastSign*sign>0?lastIndex:lastIndex-1}};
ol.render.webgl.LineStringReplay.prototype.addVertices_=function(p0,p1,p2,product,numVertices){this.vertices[numVertices++]=p0[0];this.vertices[numVertices++]=p0[1];this.vertices[numVertices++]=p1[0];this.vertices[numVertices++]=p1[1];this.vertices[numVertices++]=p2[0];this.vertices[numVertices++]=p2[1];this.vertices[numVertices++]=product;return numVertices};
ol.render.webgl.LineStringReplay.prototype.isValid_=function(flatCoordinates,offset,end,stride){var range=end-offset;if(range<stride*2)return false;else if(range===stride*2){var firstP=[flatCoordinates[offset],flatCoordinates[offset+1]];var lastP=[flatCoordinates[offset+stride],flatCoordinates[offset+stride+1]];return!ol.array.equals(firstP,lastP)}return true};
ol.render.webgl.LineStringReplay.prototype.drawLineString=function(lineStringGeometry,feature){var flatCoordinates=lineStringGeometry.getFlatCoordinates();var stride=lineStringGeometry.getStride();if(this.isValid_(flatCoordinates,0,flatCoordinates.length,stride)){flatCoordinates=ol.geom.flat.transform.translate(flatCoordinates,0,flatCoordinates.length,stride,-this.origin[0],-this.origin[1]);if(this.state_.changed){this.styleIndices_.push(this.indices.length);this.state_.changed=false}this.startIndices.push(this.indices.length);
this.startIndicesFeature.push(feature);this.drawCoordinates_(flatCoordinates,0,flatCoordinates.length,stride)}};
ol.render.webgl.LineStringReplay.prototype.drawMultiLineString=function(multiLineStringGeometry,feature){var indexCount=this.indices.length;var ends=multiLineStringGeometry.getEnds();ends.unshift(0);var flatCoordinates=multiLineStringGeometry.getFlatCoordinates();var stride=multiLineStringGeometry.getStride();var i,ii;if(ends.length>1)for(i=1,ii=ends.length;i<ii;++i)if(this.isValid_(flatCoordinates,ends[i-1],ends[i],stride)){var lineString=ol.geom.flat.transform.translate(flatCoordinates,ends[i-1],
ends[i],stride,-this.origin[0],-this.origin[1]);this.drawCoordinates_(lineString,0,lineString.length,stride)}if(this.indices.length>indexCount){this.startIndices.push(indexCount);this.startIndicesFeature.push(feature);if(this.state_.changed){this.styleIndices_.push(indexCount);this.state_.changed=false}}};
ol.render.webgl.LineStringReplay.prototype.drawPolygonCoordinates=function(flatCoordinates,holeFlatCoordinates,stride){if(!ol.geom.flat.topology.lineStringIsClosed(flatCoordinates,0,flatCoordinates.length,stride)){flatCoordinates.push(flatCoordinates[0]);flatCoordinates.push(flatCoordinates[1])}this.drawCoordinates_(flatCoordinates,0,flatCoordinates.length,stride);if(holeFlatCoordinates.length){var i,ii;for(i=0,ii=holeFlatCoordinates.length;i<ii;++i){if(!ol.geom.flat.topology.lineStringIsClosed(holeFlatCoordinates[i],
0,holeFlatCoordinates[i].length,stride)){holeFlatCoordinates[i].push(holeFlatCoordinates[i][0]);holeFlatCoordinates[i].push(holeFlatCoordinates[i][1])}this.drawCoordinates_(holeFlatCoordinates[i],0,holeFlatCoordinates[i].length,stride)}}};
ol.render.webgl.LineStringReplay.prototype.setPolygonStyle=function(feature,opt_index){var index=opt_index===undefined?this.indices.length:opt_index;this.startIndices.push(index);this.startIndicesFeature.push(feature);if(this.state_.changed){this.styleIndices_.push(index);this.state_.changed=false}};ol.render.webgl.LineStringReplay.prototype.getCurrentIndex=function(){return this.indices.length};
ol.render.webgl.LineStringReplay.prototype.finish=function(context){this.verticesBuffer=new ol.webgl.Buffer(this.vertices);this.indicesBuffer=new ol.webgl.Buffer(this.indices);this.startIndices.push(this.indices.length);if(this.styleIndices_.length===0&&this.styles_.length>0)this.styles_=[];this.vertices=null;this.indices=null};
ol.render.webgl.LineStringReplay.prototype.getDeleteResourcesFunction=function(context){var verticesBuffer=this.verticesBuffer;var indicesBuffer=this.indicesBuffer;return function(){context.deleteBuffer(verticesBuffer);context.deleteBuffer(indicesBuffer)}};
ol.render.webgl.LineStringReplay.prototype.setUpProgram=function(gl,context,size,pixelRatio){var fragmentShader,vertexShader;fragmentShader=ol.render.webgl.linestringreplay.defaultshader.fragment;vertexShader=ol.render.webgl.linestringreplay.defaultshader.vertex;var program=context.getProgram(fragmentShader,vertexShader);var locations;if(!this.defaultLocations_){locations=new ol.render.webgl.linestringreplay.defaultshader.Locations(gl,program);this.defaultLocations_=locations}else locations=this.defaultLocations_;
context.useProgram(program);gl.enableVertexAttribArray(locations.a_lastPos);gl.vertexAttribPointer(locations.a_lastPos,2,ol.webgl.FLOAT,false,28,0);gl.enableVertexAttribArray(locations.a_position);gl.vertexAttribPointer(locations.a_position,2,ol.webgl.FLOAT,false,28,8);gl.enableVertexAttribArray(locations.a_nextPos);gl.vertexAttribPointer(locations.a_nextPos,2,ol.webgl.FLOAT,false,28,16);gl.enableVertexAttribArray(locations.a_direction);gl.vertexAttribPointer(locations.a_direction,1,ol.webgl.FLOAT,
false,28,24);gl.uniform2fv(locations.u_size,size);gl.uniform1f(locations.u_pixelRatio,pixelRatio);return locations};ol.render.webgl.LineStringReplay.prototype.shutDownProgram=function(gl,locations){gl.disableVertexAttribArray(locations.a_lastPos);gl.disableVertexAttribArray(locations.a_position);gl.disableVertexAttribArray(locations.a_nextPos);gl.disableVertexAttribArray(locations.a_direction)};
ol.render.webgl.LineStringReplay.prototype.drawReplay=function(gl,context,skippedFeaturesHash,hitDetection){var tmpDepthFunc=gl.getParameter(gl.DEPTH_FUNC);var tmpDepthMask=gl.getParameter(gl.DEPTH_WRITEMASK);if(!hitDetection){gl.enable(gl.DEPTH_TEST);gl.depthMask(true);gl.depthFunc(gl.NOTEQUAL)}if(!ol.obj.isEmpty(skippedFeaturesHash))this.drawReplaySkipping_(gl,context,skippedFeaturesHash);else{var i,start,end,nextStyle;end=this.startIndices[this.startIndices.length-1];for(i=this.styleIndices_.length-
1;i>=0;--i){start=this.styleIndices_[i];nextStyle=this.styles_[i];this.setStrokeStyle_(gl,nextStyle[0],nextStyle[1],nextStyle[2]);this.drawElements(gl,context,start,end);gl.clear(gl.DEPTH_BUFFER_BIT);end=start}}if(!hitDetection){gl.disable(gl.DEPTH_TEST);gl.clear(gl.DEPTH_BUFFER_BIT);gl.depthMask(tmpDepthMask);gl.depthFunc(tmpDepthFunc)}};
ol.render.webgl.LineStringReplay.prototype.drawReplaySkipping_=function(gl,context,skippedFeaturesHash){var i,start,end,nextStyle,groupStart,feature,featureUid,featureIndex,featureStart;featureIndex=this.startIndices.length-2;end=start=this.startIndices[featureIndex+1];for(i=this.styleIndices_.length-1;i>=0;--i){nextStyle=this.styles_[i];this.setStrokeStyle_(gl,nextStyle[0],nextStyle[1],nextStyle[2]);groupStart=this.styleIndices_[i];while(featureIndex>=0&&this.startIndices[featureIndex]>=groupStart){featureStart=
this.startIndices[featureIndex];feature=this.startIndicesFeature[featureIndex];featureUid=ol.getUid(feature).toString();if(skippedFeaturesHash[featureUid]){if(start!==end){this.drawElements(gl,context,start,end);gl.clear(gl.DEPTH_BUFFER_BIT)}end=featureStart}featureIndex--;start=featureStart}if(start!==end){this.drawElements(gl,context,start,end);gl.clear(gl.DEPTH_BUFFER_BIT)}start=end=groupStart}};
ol.render.webgl.LineStringReplay.prototype.drawHitDetectionReplayOneByOne=function(gl,context,skippedFeaturesHash,featureCallback,opt_hitExtent){var i,start,end,nextStyle,groupStart,feature,featureUid,featureIndex;featureIndex=this.startIndices.length-2;end=this.startIndices[featureIndex+1];for(i=this.styleIndices_.length-1;i>=0;--i){nextStyle=this.styles_[i];this.setStrokeStyle_(gl,nextStyle[0],nextStyle[1],nextStyle[2]);groupStart=this.styleIndices_[i];while(featureIndex>=0&&this.startIndices[featureIndex]>=
groupStart){start=this.startIndices[featureIndex];feature=this.startIndicesFeature[featureIndex];featureUid=ol.getUid(feature).toString();if(skippedFeaturesHash[featureUid]===undefined&&feature.getGeometry()&&(opt_hitExtent===undefined||ol.extent.intersects(opt_hitExtent,feature.getGeometry().getExtent()))){gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);this.drawElements(gl,context,start,end);var result=featureCallback(feature);if(result)return result}featureIndex--;end=start}}return undefined};
ol.render.webgl.LineStringReplay.prototype.setStrokeStyle_=function(gl,color,lineWidth,miterLimit){gl.uniform4fv(this.defaultLocations_.u_color,color);gl.uniform1f(this.defaultLocations_.u_lineWidth,lineWidth);gl.uniform1f(this.defaultLocations_.u_miterLimit,miterLimit)};
ol.render.webgl.LineStringReplay.prototype.setFillStrokeStyle=function(fillStyle,strokeStyle){var strokeStyleLineCap=strokeStyle.getLineCap();this.state_.lineCap=strokeStyleLineCap!==undefined?strokeStyleLineCap:ol.render.webgl.defaultLineCap;var strokeStyleLineDash=strokeStyle.getLineDash();this.state_.lineDash=strokeStyleLineDash?strokeStyleLineDash:ol.render.webgl.defaultLineDash;var strokeStyleLineDashOffset=strokeStyle.getLineDashOffset();this.state_.lineDashOffset=strokeStyleLineDashOffset?
strokeStyleLineDashOffset:ol.render.webgl.defaultLineDashOffset;var strokeStyleLineJoin=strokeStyle.getLineJoin();this.state_.lineJoin=strokeStyleLineJoin!==undefined?strokeStyleLineJoin:ol.render.webgl.defaultLineJoin;var strokeStyleColor=strokeStyle.getColor();if(!(strokeStyleColor instanceof CanvasGradient)&&!(strokeStyleColor instanceof CanvasPattern))strokeStyleColor=ol.color.asArray(strokeStyleColor).map(function(c,i){return i!=3?c/255:c})||ol.render.webgl.defaultStrokeStyle;else strokeStyleColor=
ol.render.webgl.defaultStrokeStyle;var strokeStyleWidth=strokeStyle.getWidth();strokeStyleWidth=strokeStyleWidth!==undefined?strokeStyleWidth:ol.render.webgl.defaultLineWidth;var strokeStyleMiterLimit=strokeStyle.getMiterLimit();strokeStyleMiterLimit=strokeStyleMiterLimit!==undefined?strokeStyleMiterLimit:ol.render.webgl.defaultMiterLimit;if(!this.state_.strokeColor||!ol.array.equals(this.state_.strokeColor,strokeStyleColor)||this.state_.lineWidth!==strokeStyleWidth||this.state_.miterLimit!==strokeStyleMiterLimit){this.state_.changed=
true;this.state_.strokeColor=strokeStyleColor;this.state_.lineWidth=strokeStyleWidth;this.state_.miterLimit=strokeStyleMiterLimit;this.styles_.push([strokeStyleColor,strokeStyleWidth,strokeStyleMiterLimit])}};ol.render.webgl.LineStringReplay.Instruction_={ROUND:2,BEGIN_LINE:3,END_LINE:5,BEGIN_LINE_CAP:7,END_LINE_CAP:11,BEVEL_FIRST:13,BEVEL_SECOND:17,MITER_BOTTOM:19,MITER_TOP:23};goog.provide("ol.render.webgl.polygonreplay.defaultshader");goog.require("ol");goog.require("ol.webgl.Fragment");goog.require("ol.webgl.Vertex");ol.render.webgl.polygonreplay.defaultshader.fragment=new ol.webgl.Fragment(ol.DEBUG_WEBGL?"precision mediump float;\n\n\n\nuniform vec4 u_color;\nuniform float u_opacity;\n\nvoid main(void) {\n  gl_FragColor = u_color;\n  float alpha = u_color.a * u_opacity;\n  if (alpha == 0.0) {\n    discard;\n  }\n  gl_FragColor.a = alpha;\n}\n":"precision mediump float;uniform vec4 e;uniform float f;void main(void){gl_FragColor=e;float alpha=e.a*f;if(alpha==0.0){discard;}gl_FragColor.a=alpha;}");
ol.render.webgl.polygonreplay.defaultshader.vertex=new ol.webgl.Vertex(ol.DEBUG_WEBGL?"\n\nattribute vec2 a_position;\n\nuniform mat4 u_projectionMatrix;\nuniform mat4 u_offsetScaleMatrix;\nuniform mat4 u_offsetRotateMatrix;\n\nvoid main(void) {\n  gl_Position = u_projectionMatrix * vec4(a_position, 0.0, 1.0);\n}\n\n\n":"attribute vec2 a;uniform mat4 b;uniform mat4 c;uniform mat4 d;void main(void){gl_Position=b*vec4(a,0.0,1.0);}");goog.provide("ol.render.webgl.polygonreplay.defaultshader.Locations");goog.require("ol");
ol.render.webgl.polygonreplay.defaultshader.Locations=function(gl,program){this.u_projectionMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_projectionMatrix":"b");this.u_offsetScaleMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_offsetScaleMatrix":"c");this.u_offsetRotateMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_offsetRotateMatrix":"d");this.u_color=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_color":"e");this.u_opacity=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_opacity":
"f");this.a_position=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_position":"a")};goog.provide("ol.structs.LinkedList");ol.structs.LinkedList=function(opt_circular){this.first_=undefined;this.last_=undefined;this.head_=undefined;this.circular_=opt_circular===undefined?true:opt_circular;this.length_=0};
ol.structs.LinkedList.prototype.insertItem=function(data){var item={prev:undefined,next:undefined,data:data};var head=this.head_;if(!head){this.first_=item;this.last_=item;if(this.circular_){item.next=item;item.prev=item}}else{var next=head.next;item.prev=head;item.next=next;head.next=item;if(next)next.prev=item;if(head===this.last_)this.last_=item}this.head_=item;this.length_++};
ol.structs.LinkedList.prototype.removeItem=function(){var head=this.head_;if(head){var next=head.next;var prev=head.prev;if(next)next.prev=prev;if(prev)prev.next=next;this.head_=next||prev;if(this.first_===this.last_){this.head_=undefined;this.first_=undefined;this.last_=undefined}else if(this.first_===head)this.first_=this.head_;else if(this.last_===head)this.last_=prev?this.head_.prev:this.head_;this.length_--}};
ol.structs.LinkedList.prototype.firstItem=function(){this.head_=this.first_;if(this.head_)return this.head_.data;return undefined};ol.structs.LinkedList.prototype.lastItem=function(){this.head_=this.last_;if(this.head_)return this.head_.data;return undefined};ol.structs.LinkedList.prototype.nextItem=function(){if(this.head_&&this.head_.next){this.head_=this.head_.next;return this.head_.data}return undefined};
ol.structs.LinkedList.prototype.getNextItem=function(){if(this.head_&&this.head_.next)return this.head_.next.data;return undefined};ol.structs.LinkedList.prototype.prevItem=function(){if(this.head_&&this.head_.prev){this.head_=this.head_.prev;return this.head_.data}return undefined};ol.structs.LinkedList.prototype.getPrevItem=function(){if(this.head_&&this.head_.prev)return this.head_.prev.data;return undefined};
ol.structs.LinkedList.prototype.getCurrItem=function(){if(this.head_)return this.head_.data;return undefined};ol.structs.LinkedList.prototype.setFirstItem=function(){if(this.circular_&&this.head_){this.first_=this.head_;this.last_=this.head_.prev}};
ol.structs.LinkedList.prototype.concat=function(list){if(list.head_){if(this.head_){var end=this.head_.next;this.head_.next=list.first_;list.first_.prev=this.head_;end.prev=list.last_;list.last_.next=end;this.length_+=list.length_}else{this.head_=list.head_;this.first_=list.first_;this.last_=list.last_;this.length_=list.length_}list.head_=undefined;list.first_=undefined;list.last_=undefined;list.length_=0}};ol.structs.LinkedList.prototype.getLength=function(){return this.length_};goog.provide("ol.render.webgl.PolygonReplay");goog.require("ol");goog.require("ol.array");goog.require("ol.color");goog.require("ol.extent");goog.require("ol.obj");goog.require("ol.geom.flat.contains");goog.require("ol.geom.flat.orient");goog.require("ol.geom.flat.transform");goog.require("ol.render.webgl.polygonreplay.defaultshader");goog.require("ol.render.webgl.polygonreplay.defaultshader.Locations");goog.require("ol.render.webgl.LineStringReplay");goog.require("ol.render.webgl.Replay");goog.require("ol.render.webgl");
goog.require("ol.style.Stroke");goog.require("ol.structs.LinkedList");goog.require("ol.structs.RBush");goog.require("ol.webgl");goog.require("ol.webgl.Buffer");ol.render.webgl.PolygonReplay=function(tolerance,maxExtent){ol.render.webgl.Replay.call(this,tolerance,maxExtent);this.lineStringReplay=new ol.render.webgl.LineStringReplay(tolerance,maxExtent);this.defaultLocations_=null;this.styles_=[];this.styleIndices_=[];this.state_={fillColor:null,changed:false}};
ol.inherits(ol.render.webgl.PolygonReplay,ol.render.webgl.Replay);
ol.render.webgl.PolygonReplay.prototype.drawCoordinates_=function(flatCoordinates,holeFlatCoordinates,stride){var outerRing=new ol.structs.LinkedList;var rtree=new ol.structs.RBush;this.processFlatCoordinates_(flatCoordinates,stride,outerRing,rtree,true);var maxCoords=this.getMaxCoords_(outerRing);if(holeFlatCoordinates.length){var i,ii;var holeLists=[];for(i=0,ii=holeFlatCoordinates.length;i<ii;++i){var holeList={list:new ol.structs.LinkedList,maxCoords:undefined,rtree:new ol.structs.RBush};holeLists.push(holeList);
this.processFlatCoordinates_(holeFlatCoordinates[i],stride,holeList.list,holeList.rtree,false);this.classifyPoints_(holeList.list,holeList.rtree,true);holeList.maxCoords=this.getMaxCoords_(holeList.list)}holeLists.sort(function(a,b){return b.maxCoords[0]===a.maxCoords[0]?a.maxCoords[1]-b.maxCoords[1]:b.maxCoords[0]-a.maxCoords[0]});for(i=0;i<holeLists.length;++i){var currList=holeLists[i].list;var start=currList.firstItem();var currItem=start;var intersection;do{if(this.getIntersections_(currItem,
rtree).length){intersection=true;break}currItem=currList.nextItem()}while(start!==currItem);if(!intersection)if(this.bridgeHole_(currList,holeLists[i].maxCoords[0],outerRing,maxCoords[0],rtree)){rtree.concat(holeLists[i].rtree);this.classifyPoints_(outerRing,rtree,false)}}}else this.classifyPoints_(outerRing,rtree,false);this.triangulate_(outerRing,rtree)};
ol.render.webgl.PolygonReplay.prototype.processFlatCoordinates_=function(flatCoordinates,stride,list,rtree,clockwise){var isClockwise=ol.geom.flat.orient.linearRingIsClockwise(flatCoordinates,0,flatCoordinates.length,stride);var i,ii;var n=this.vertices.length/2;var start;var p0;var p1;var extents=[];var segments=[];if(clockwise===isClockwise){start=this.createPoint_(flatCoordinates[0],flatCoordinates[1],n++);p0=start;for(i=stride,ii=flatCoordinates.length;i<ii;i+=stride){p1=this.createPoint_(flatCoordinates[i],
flatCoordinates[i+1],n++);segments.push(this.insertItem_(p0,p1,list));extents.push([Math.min(p0.x,p1.x),Math.min(p0.y,p1.y),Math.max(p0.x,p1.x),Math.max(p0.y,p1.y)]);p0=p1}segments.push(this.insertItem_(p1,start,list));extents.push([Math.min(p0.x,p1.x),Math.min(p0.y,p1.y),Math.max(p0.x,p1.x),Math.max(p0.y,p1.y)])}else{var end=flatCoordinates.length-stride;start=this.createPoint_(flatCoordinates[end],flatCoordinates[end+1],n++);p0=start;for(i=end-stride,ii=0;i>=ii;i-=stride){p1=this.createPoint_(flatCoordinates[i],
flatCoordinates[i+1],n++);segments.push(this.insertItem_(p0,p1,list));extents.push([Math.min(p0.x,p1.x),Math.min(p0.y,p1.y),Math.max(p0.x,p1.x),Math.max(p0.y,p1.y)]);p0=p1}segments.push(this.insertItem_(p1,start,list));extents.push([Math.min(p0.x,p1.x),Math.min(p0.y,p1.y),Math.max(p0.x,p1.x),Math.max(p0.y,p1.y)])}rtree.load(extents,segments)};
ol.render.webgl.PolygonReplay.prototype.getMaxCoords_=function(list){var start=list.firstItem();var seg=start;var maxCoords=[seg.p0.x,seg.p0.y];do{seg=list.nextItem();if(seg.p0.x>maxCoords[0])maxCoords=[seg.p0.x,seg.p0.y]}while(seg!==start);return maxCoords};
ol.render.webgl.PolygonReplay.prototype.classifyPoints_=function(list,rtree,ccw){var start=list.firstItem();var s0=start;var s1=list.nextItem();var pointsReclassified=false;do{var reflex=ccw?ol.render.webgl.triangleIsCounterClockwise(s1.p1.x,s1.p1.y,s0.p1.x,s0.p1.y,s0.p0.x,s0.p0.y):ol.render.webgl.triangleIsCounterClockwise(s0.p0.x,s0.p0.y,s0.p1.x,s0.p1.y,s1.p1.x,s1.p1.y);if(reflex===undefined){this.removeItem_(s0,s1,list,rtree);pointsReclassified=true;if(s1===start)start=list.getNextItem();s1=s0;
list.prevItem()}else if(s0.p1.reflex!==reflex){s0.p1.reflex=reflex;pointsReclassified=true}s0=s1;s1=list.nextItem()}while(s0!==start);return pointsReclassified};
ol.render.webgl.PolygonReplay.prototype.bridgeHole_=function(hole,holeMaxX,list,listMaxX,rtree){var seg=hole.firstItem();while(seg.p1.x!==holeMaxX)seg=hole.nextItem();var p1=seg.p1;var p2={x:listMaxX,y:p1.y,i:-1};var minDist=Infinity;var i,ii,bestPoint;var p5;var intersectingSegments=this.getIntersections_({p0:p1,p1:p2},rtree,true);for(i=0,ii=intersectingSegments.length;i<ii;++i){var currSeg=intersectingSegments[i];var intersection=this.calculateIntersection_(p1,p2,currSeg.p0,currSeg.p1,true);var dist=
Math.abs(p1.x-intersection[0]);if(dist<minDist&&ol.render.webgl.triangleIsCounterClockwise(p1.x,p1.y,currSeg.p0.x,currSeg.p0.y,currSeg.p1.x,currSeg.p1.y)!==undefined){minDist=dist;p5={x:intersection[0],y:intersection[1],i:-1};seg=currSeg}}if(minDist===Infinity)return false;bestPoint=seg.p1;if(minDist>0){var pointsInTriangle=this.getPointsInTriangle_(p1,p5,seg.p1,rtree);if(pointsInTriangle.length){var theta=Infinity;for(i=0,ii=pointsInTriangle.length;i<ii;++i){var currPoint=pointsInTriangle[i];var currTheta=
Math.atan2(p1.y-currPoint.y,p2.x-currPoint.x);if(currTheta<theta||currTheta===theta&&currPoint.x<bestPoint.x){theta=currTheta;bestPoint=currPoint}}}}seg=list.firstItem();while(seg.p1.x!==bestPoint.x||seg.p1.y!==bestPoint.y)seg=list.nextItem();var p0Bridge={x:p1.x,y:p1.y,i:p1.i,reflex:undefined};var p1Bridge={x:seg.p1.x,y:seg.p1.y,i:seg.p1.i,reflex:undefined};hole.getNextItem().p0=p0Bridge;this.insertItem_(p1,seg.p1,hole,rtree);this.insertItem_(p1Bridge,p0Bridge,hole,rtree);seg.p1=p1Bridge;hole.setFirstItem();
list.concat(hole);return true};
ol.render.webgl.PolygonReplay.prototype.triangulate_=function(list,rtree){var ccw=false;var simple=this.isSimple_(list,rtree);while(list.getLength()>3)if(simple){if(!this.clipEars_(list,rtree,simple,ccw))if(!this.classifyPoints_(list,rtree,ccw))if(!this.resolveSelfIntersections_(list,rtree,true))break}else if(!this.clipEars_(list,rtree,simple,ccw))if(!this.classifyPoints_(list,rtree,ccw))if(!this.resolveSelfIntersections_(list,rtree)){simple=this.isSimple_(list,rtree);if(!simple){this.splitPolygon_(list,
rtree);break}else{ccw=!this.isClockwise_(list);this.classifyPoints_(list,rtree,ccw)}}if(list.getLength()===3){var numIndices=this.indices.length;this.indices[numIndices++]=list.getPrevItem().p0.i;this.indices[numIndices++]=list.getCurrItem().p0.i;this.indices[numIndices++]=list.getNextItem().p0.i}};
ol.render.webgl.PolygonReplay.prototype.clipEars_=function(list,rtree,simple,ccw){var numIndices=this.indices.length;var start=list.firstItem();var s0=list.getPrevItem();var s1=start;var s2=list.nextItem();var s3=list.getNextItem();var p0,p1,p2;var processedEars=false;do{p0=s1.p0;p1=s1.p1;p2=s2.p1;if(p1.reflex===false){var variableCriterion;if(simple)variableCriterion=this.getPointsInTriangle_(p0,p1,p2,rtree,true).length===0;else variableCriterion=ccw?this.diagonalIsInside_(s3.p1,p2,p1,p0,s0.p0):
this.diagonalIsInside_(s0.p0,p0,p1,p2,s3.p1);if((simple||this.getIntersections_({p0:p0,p1:p2},rtree).length===0)&&variableCriterion)if(simple||p0.reflex===false||p2.reflex===false||ol.geom.flat.orient.linearRingIsClockwise([s0.p0.x,s0.p0.y,p0.x,p0.y,p1.x,p1.y,p2.x,p2.y,s3.p1.x,s3.p1.y],0,10,2)===!ccw){this.indices[numIndices++]=p0.i;this.indices[numIndices++]=p1.i;this.indices[numIndices++]=p2.i;this.removeItem_(s1,s2,list,rtree);if(s2===start)start=s3;processedEars=true}}s0=list.getPrevItem();s1=
list.getCurrItem();s2=list.nextItem();s3=list.getNextItem()}while(s1!==start&&list.getLength()>3);return processedEars};
ol.render.webgl.PolygonReplay.prototype.resolveSelfIntersections_=function(list,rtree,opt_touch){var start=list.firstItem();list.nextItem();var s0=start;var s1=list.nextItem();var resolvedIntersections=false;do{var intersection=this.calculateIntersection_(s0.p0,s0.p1,s1.p0,s1.p1,opt_touch);if(intersection){var breakCond=false;var numVertices=this.vertices.length;var numIndices=this.indices.length;var n=numVertices/2;var seg=list.prevItem();list.removeItem();rtree.remove(seg);breakCond=seg===start;
var p;if(opt_touch){if(intersection[0]===s0.p0.x&&intersection[1]===s0.p0.y){list.prevItem();p=s0.p0;s1.p0=p;rtree.remove(s0);breakCond=breakCond||s0===start}else{p=s1.p1;s0.p1=p;rtree.remove(s1);breakCond=breakCond||s1===start}list.removeItem()}else{p=this.createPoint_(intersection[0],intersection[1],n);s0.p1=p;s1.p0=p;rtree.update([Math.min(s0.p0.x,s0.p1.x),Math.min(s0.p0.y,s0.p1.y),Math.max(s0.p0.x,s0.p1.x),Math.max(s0.p0.y,s0.p1.y)],s0);rtree.update([Math.min(s1.p0.x,s1.p1.x),Math.min(s1.p0.y,
s1.p1.y),Math.max(s1.p0.x,s1.p1.x),Math.max(s1.p0.y,s1.p1.y)],s1)}this.indices[numIndices++]=seg.p0.i;this.indices[numIndices++]=seg.p1.i;this.indices[numIndices++]=p.i;resolvedIntersections=true;if(breakCond)break}s0=list.getPrevItem();s1=list.nextItem()}while(s0!==start);return resolvedIntersections};
ol.render.webgl.PolygonReplay.prototype.isSimple_=function(list,rtree){var start=list.firstItem();var seg=start;do{if(this.getIntersections_(seg,rtree).length)return false;seg=list.nextItem()}while(seg!==start);return true};
ol.render.webgl.PolygonReplay.prototype.isClockwise_=function(list){var length=list.getLength()*2;var flatCoordinates=new Array(length);var start=list.firstItem();var seg=start;var i=0;do{flatCoordinates[i++]=seg.p0.x;flatCoordinates[i++]=seg.p0.y;seg=list.nextItem()}while(seg!==start);return ol.geom.flat.orient.linearRingIsClockwise(flatCoordinates,0,length,2)};
ol.render.webgl.PolygonReplay.prototype.splitPolygon_=function(list,rtree){var start=list.firstItem();var s0=start;do{var intersections=this.getIntersections_(s0,rtree);if(intersections.length){var s1=intersections[0];var n=this.vertices.length/2;var intersection=this.calculateIntersection_(s0.p0,s0.p1,s1.p0,s1.p1);var p=this.createPoint_(intersection[0],intersection[1],n);var newPolygon=new ol.structs.LinkedList;var newRtree=new ol.structs.RBush;this.insertItem_(p,s0.p1,newPolygon,newRtree);s0.p1=
p;rtree.update([Math.min(s0.p0.x,p.x),Math.min(s0.p0.y,p.y),Math.max(s0.p0.x,p.x),Math.max(s0.p0.y,p.y)],s0);var currItem=list.nextItem();while(currItem!==s1){this.insertItem_(currItem.p0,currItem.p1,newPolygon,newRtree);rtree.remove(currItem);list.removeItem();currItem=list.getCurrItem()}this.insertItem_(s1.p0,p,newPolygon,newRtree);s1.p0=p;rtree.update([Math.min(s1.p1.x,p.x),Math.min(s1.p1.y,p.y),Math.max(s1.p1.x,p.x),Math.max(s1.p1.y,p.y)],s1);this.classifyPoints_(list,rtree,false);this.triangulate_(list,
rtree);this.classifyPoints_(newPolygon,newRtree,false);this.triangulate_(newPolygon,newRtree);break}s0=list.nextItem()}while(s0!==start)};ol.render.webgl.PolygonReplay.prototype.createPoint_=function(x,y,i){var numVertices=this.vertices.length;this.vertices[numVertices++]=x;this.vertices[numVertices++]=y;var p={x:x,y:y,i:i,reflex:undefined};return p};
ol.render.webgl.PolygonReplay.prototype.insertItem_=function(p0,p1,list,opt_rtree){var seg={p0:p0,p1:p1};list.insertItem(seg);if(opt_rtree)opt_rtree.insert([Math.min(p0.x,p1.x),Math.min(p0.y,p1.y),Math.max(p0.x,p1.x),Math.max(p0.y,p1.y)],seg);return seg};
ol.render.webgl.PolygonReplay.prototype.removeItem_=function(s0,s1,list,rtree){if(list.getCurrItem()===s1){list.removeItem();s0.p1=s1.p1;rtree.remove(s1);rtree.update([Math.min(s0.p0.x,s0.p1.x),Math.min(s0.p0.y,s0.p1.y),Math.max(s0.p0.x,s0.p1.x),Math.max(s0.p0.y,s0.p1.y)],s0)}};
ol.render.webgl.PolygonReplay.prototype.getPointsInTriangle_=function(p0,p1,p2,rtree,opt_reflex){var i,ii,j,p;var result=[];var segmentsInExtent=rtree.getInExtent([Math.min(p0.x,p1.x,p2.x),Math.min(p0.y,p1.y,p2.y),Math.max(p0.x,p1.x,p2.x),Math.max(p0.y,p1.y,p2.y)]);for(i=0,ii=segmentsInExtent.length;i<ii;++i)for(j in segmentsInExtent[i]){p=segmentsInExtent[i][j];if(typeof p==="object"&&(!opt_reflex||p.reflex))if((p.x!==p0.x||p.y!==p0.y)&&(p.x!==p1.x||p.y!==p1.y)&&(p.x!==p2.x||p.y!==p2.y)&&result.indexOf(p)===
-1&&ol.geom.flat.contains.linearRingContainsXY([p0.x,p0.y,p1.x,p1.y,p2.x,p2.y],0,6,2,p.x,p.y))result.push(p)}return result};
ol.render.webgl.PolygonReplay.prototype.getIntersections_=function(segment,rtree,opt_touch){var p0=segment.p0;var p1=segment.p1;var segmentsInExtent=rtree.getInExtent([Math.min(p0.x,p1.x),Math.min(p0.y,p1.y),Math.max(p0.x,p1.x),Math.max(p0.y,p1.y)]);var result=[];var i,ii;for(i=0,ii=segmentsInExtent.length;i<ii;++i){var currSeg=segmentsInExtent[i];if(segment!==currSeg&&(opt_touch||currSeg.p0!==p1||currSeg.p1!==p0)&&this.calculateIntersection_(p0,p1,currSeg.p0,currSeg.p1,opt_touch))result.push(currSeg)}return result};
ol.render.webgl.PolygonReplay.prototype.calculateIntersection_=function(p0,p1,p2,p3,opt_touch){var denom=(p3.y-p2.y)*(p1.x-p0.x)-(p3.x-p2.x)*(p1.y-p0.y);if(denom!==0){var ua=((p3.x-p2.x)*(p0.y-p2.y)-(p3.y-p2.y)*(p0.x-p2.x))/denom;var ub=((p1.x-p0.x)*(p0.y-p2.y)-(p1.y-p0.y)*(p0.x-p2.x))/denom;if(!opt_touch&&ua>ol.render.webgl.EPSILON&&ua<1-ol.render.webgl.EPSILON&&ub>ol.render.webgl.EPSILON&&ub<1-ol.render.webgl.EPSILON||opt_touch&&ua>=0&&ua<=1&&ub>=0&&ub<=1)return[p0.x+ua*(p1.x-p0.x),p0.y+ua*(p1.y-
p0.y)]}return undefined};
ol.render.webgl.PolygonReplay.prototype.diagonalIsInside_=function(p0,p1,p2,p3,p4){if(p1.reflex===undefined||p3.reflex===undefined)return false;var p1IsLeftOf=(p2.x-p3.x)*(p1.y-p3.y)>(p2.y-p3.y)*(p1.x-p3.x);var p1IsRightOf=(p4.x-p3.x)*(p1.y-p3.y)<(p4.y-p3.y)*(p1.x-p3.x);var p3IsLeftOf=(p0.x-p1.x)*(p3.y-p1.y)>(p0.y-p1.y)*(p3.x-p1.x);var p3IsRightOf=(p2.x-p1.x)*(p3.y-p1.y)<(p2.y-p1.y)*(p3.x-p1.x);var p1InCone=p3.reflex?p1IsRightOf||p1IsLeftOf:p1IsRightOf&&p1IsLeftOf;var p3InCone=p1.reflex?p3IsRightOf||
p3IsLeftOf:p3IsRightOf&&p3IsLeftOf;return p1InCone&&p3InCone};
ol.render.webgl.PolygonReplay.prototype.drawMultiPolygon=function(multiPolygonGeometry,feature){var endss=multiPolygonGeometry.getEndss();var stride=multiPolygonGeometry.getStride();var currIndex=this.indices.length;var currLineIndex=this.lineStringReplay.getCurrentIndex();var flatCoordinates=multiPolygonGeometry.getFlatCoordinates();var i,ii,j,jj;var start=0;for(i=0,ii=endss.length;i<ii;++i){var ends=endss[i];if(ends.length>0){var outerRing=ol.geom.flat.transform.translate(flatCoordinates,start,
ends[0],stride,-this.origin[0],-this.origin[1]);if(outerRing.length){var holes=[];var holeFlatCoords;for(j=1,jj=ends.length;j<jj;++j)if(ends[j]!==ends[j-1]){holeFlatCoords=ol.geom.flat.transform.translate(flatCoordinates,ends[j-1],ends[j],stride,-this.origin[0],-this.origin[1]);holes.push(holeFlatCoords)}this.lineStringReplay.drawPolygonCoordinates(outerRing,holes,stride);this.drawCoordinates_(outerRing,holes,stride)}}start=ends[ends.length-1]}if(this.indices.length>currIndex){this.startIndices.push(currIndex);
this.startIndicesFeature.push(feature);if(this.state_.changed){this.styleIndices_.push(currIndex);this.state_.changed=false}}if(this.lineStringReplay.getCurrentIndex()>currLineIndex)this.lineStringReplay.setPolygonStyle(feature,currLineIndex)};
ol.render.webgl.PolygonReplay.prototype.drawPolygon=function(polygonGeometry,feature){var ends=polygonGeometry.getEnds();var stride=polygonGeometry.getStride();if(ends.length>0){var flatCoordinates=polygonGeometry.getFlatCoordinates().map(Number);var outerRing=ol.geom.flat.transform.translate(flatCoordinates,0,ends[0],stride,-this.origin[0],-this.origin[1]);if(outerRing.length){var holes=[];var i,ii,holeFlatCoords;for(i=1,ii=ends.length;i<ii;++i)if(ends[i]!==ends[i-1]){holeFlatCoords=ol.geom.flat.transform.translate(flatCoordinates,
ends[i-1],ends[i],stride,-this.origin[0],-this.origin[1]);holes.push(holeFlatCoords)}this.startIndices.push(this.indices.length);this.startIndicesFeature.push(feature);if(this.state_.changed){this.styleIndices_.push(this.indices.length);this.state_.changed=false}this.lineStringReplay.setPolygonStyle(feature);this.lineStringReplay.drawPolygonCoordinates(outerRing,holes,stride);this.drawCoordinates_(outerRing,holes,stride)}}};
ol.render.webgl.PolygonReplay.prototype.finish=function(context){this.verticesBuffer=new ol.webgl.Buffer(this.vertices);this.indicesBuffer=new ol.webgl.Buffer(this.indices);this.startIndices.push(this.indices.length);this.lineStringReplay.finish(context);if(this.styleIndices_.length===0&&this.styles_.length>0)this.styles_=[];this.vertices=null;this.indices=null};
ol.render.webgl.PolygonReplay.prototype.getDeleteResourcesFunction=function(context){var verticesBuffer=this.verticesBuffer;var indicesBuffer=this.indicesBuffer;var lineDeleter=this.lineStringReplay.getDeleteResourcesFunction(context);return function(){context.deleteBuffer(verticesBuffer);context.deleteBuffer(indicesBuffer);lineDeleter()}};
ol.render.webgl.PolygonReplay.prototype.setUpProgram=function(gl,context,size,pixelRatio){var fragmentShader,vertexShader;fragmentShader=ol.render.webgl.polygonreplay.defaultshader.fragment;vertexShader=ol.render.webgl.polygonreplay.defaultshader.vertex;var program=context.getProgram(fragmentShader,vertexShader);var locations;if(!this.defaultLocations_){locations=new ol.render.webgl.polygonreplay.defaultshader.Locations(gl,program);this.defaultLocations_=locations}else locations=this.defaultLocations_;
context.useProgram(program);gl.enableVertexAttribArray(locations.a_position);gl.vertexAttribPointer(locations.a_position,2,ol.webgl.FLOAT,false,8,0);return locations};ol.render.webgl.PolygonReplay.prototype.shutDownProgram=function(gl,locations){gl.disableVertexAttribArray(locations.a_position)};
ol.render.webgl.PolygonReplay.prototype.drawReplay=function(gl,context,skippedFeaturesHash,hitDetection){var tmpDepthFunc=gl.getParameter(gl.DEPTH_FUNC);var tmpDepthMask=gl.getParameter(gl.DEPTH_WRITEMASK);if(!hitDetection){gl.enable(gl.DEPTH_TEST);gl.depthMask(true);gl.depthFunc(gl.NOTEQUAL)}if(!ol.obj.isEmpty(skippedFeaturesHash))this.drawReplaySkipping_(gl,context,skippedFeaturesHash);else{var i,start,end,nextStyle;end=this.startIndices[this.startIndices.length-1];for(i=this.styleIndices_.length-
1;i>=0;--i){start=this.styleIndices_[i];nextStyle=this.styles_[i];this.setFillStyle_(gl,nextStyle);this.drawElements(gl,context,start,end);end=start}}if(!hitDetection){gl.disable(gl.DEPTH_TEST);gl.clear(gl.DEPTH_BUFFER_BIT);gl.depthMask(tmpDepthMask);gl.depthFunc(tmpDepthFunc)}};
ol.render.webgl.PolygonReplay.prototype.drawHitDetectionReplayOneByOne=function(gl,context,skippedFeaturesHash,featureCallback,opt_hitExtent){var i,start,end,nextStyle,groupStart,feature,featureUid,featureIndex;featureIndex=this.startIndices.length-2;end=this.startIndices[featureIndex+1];for(i=this.styleIndices_.length-1;i>=0;--i){nextStyle=this.styles_[i];this.setFillStyle_(gl,nextStyle);groupStart=this.styleIndices_[i];while(featureIndex>=0&&this.startIndices[featureIndex]>=groupStart){start=this.startIndices[featureIndex];
feature=this.startIndicesFeature[featureIndex];featureUid=ol.getUid(feature).toString();if(skippedFeaturesHash[featureUid]===undefined&&feature.getGeometry()&&(opt_hitExtent===undefined||ol.extent.intersects(opt_hitExtent,feature.getGeometry().getExtent()))){gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);this.drawElements(gl,context,start,end);var result=featureCallback(feature);if(result)return result}featureIndex--;end=start}}return undefined};
ol.render.webgl.PolygonReplay.prototype.drawReplaySkipping_=function(gl,context,skippedFeaturesHash){var i,start,end,nextStyle,groupStart,feature,featureUid,featureIndex,featureStart;featureIndex=this.startIndices.length-2;end=start=this.startIndices[featureIndex+1];for(i=this.styleIndices_.length-1;i>=0;--i){nextStyle=this.styles_[i];this.setFillStyle_(gl,nextStyle);groupStart=this.styleIndices_[i];while(featureIndex>=0&&this.startIndices[featureIndex]>=groupStart){featureStart=this.startIndices[featureIndex];
feature=this.startIndicesFeature[featureIndex];featureUid=ol.getUid(feature).toString();if(skippedFeaturesHash[featureUid]){if(start!==end){this.drawElements(gl,context,start,end);gl.clear(gl.DEPTH_BUFFER_BIT)}end=featureStart}featureIndex--;start=featureStart}if(start!==end){this.drawElements(gl,context,start,end);gl.clear(gl.DEPTH_BUFFER_BIT)}start=end=groupStart}};ol.render.webgl.PolygonReplay.prototype.setFillStyle_=function(gl,color){gl.uniform4fv(this.defaultLocations_.u_color,color)};
ol.render.webgl.PolygonReplay.prototype.setFillStrokeStyle=function(fillStyle,strokeStyle){var fillStyleColor=fillStyle?fillStyle.getColor():[0,0,0,0];if(!(fillStyleColor instanceof CanvasGradient)&&!(fillStyleColor instanceof CanvasPattern))fillStyleColor=ol.color.asArray(fillStyleColor).map(function(c,i){return i!=3?c/255:c})||ol.render.webgl.defaultFillStyle;else fillStyleColor=ol.render.webgl.defaultFillStyle;if(!this.state_.fillColor||!ol.array.equals(fillStyleColor,this.state_.fillColor)){this.state_.fillColor=
fillStyleColor;this.state_.changed=true;this.styles_.push(fillStyleColor)}if(strokeStyle)this.lineStringReplay.setFillStrokeStyle(null,strokeStyle);else{var nullStrokeStyle=new ol.style.Stroke({color:[0,0,0,0],lineWidth:0});this.lineStringReplay.setFillStrokeStyle(null,nullStrokeStyle)}};goog.provide("ol.style.Atlas");goog.require("ol.dom");ol.style.Atlas=function(size,space){this.space_=space;this.emptyBlocks_=[{x:0,y:0,width:size,height:size}];this.entries_={};this.context_=ol.dom.createCanvasContext2D(size,size);this.canvas_=this.context_.canvas};ol.style.Atlas.prototype.get=function(id){return this.entries_[id]||null};
ol.style.Atlas.prototype.add=function(id,width,height,renderCallback,opt_this){var block,i,ii;for(i=0,ii=this.emptyBlocks_.length;i<ii;++i){block=this.emptyBlocks_[i];if(block.width>=width+this.space_&&block.height>=height+this.space_){var entry={offsetX:block.x+this.space_,offsetY:block.y+this.space_,image:this.canvas_};this.entries_[id]=entry;renderCallback.call(opt_this,this.context_,block.x+this.space_,block.y+this.space_);this.split_(i,block,width+this.space_,height+this.space_);return entry}}return null};
ol.style.Atlas.prototype.split_=function(index,block,width,height){var deltaWidth=block.width-width;var deltaHeight=block.height-height;var newBlock1;var newBlock2;if(deltaWidth>deltaHeight){newBlock1={x:block.x+width,y:block.y,width:block.width-width,height:block.height};newBlock2={x:block.x,y:block.y+height,width:width,height:block.height-height};this.updateBlocks_(index,newBlock1,newBlock2)}else{newBlock1={x:block.x+width,y:block.y,width:block.width-width,height:height};newBlock2={x:block.x,y:block.y+
height,width:block.width,height:block.height-height};this.updateBlocks_(index,newBlock1,newBlock2)}};ol.style.Atlas.prototype.updateBlocks_=function(index,newBlock1,newBlock2){var args=[index,1];if(newBlock1.width>0&&newBlock1.height>0)args.push(newBlock1);if(newBlock2.width>0&&newBlock2.height>0)args.push(newBlock2);this.emptyBlocks_.splice.apply(this.emptyBlocks_,args)};goog.provide("ol.style.AtlasManager");goog.require("ol");goog.require("ol.style.Atlas");
ol.style.AtlasManager=function(opt_options){var options=opt_options||{};this.currentSize_=options.initialSize!==undefined?options.initialSize:ol.INITIAL_ATLAS_SIZE;this.maxSize_=options.maxSize!==undefined?options.maxSize:ol.MAX_ATLAS_SIZE!=-1?ol.MAX_ATLAS_SIZE:ol.WEBGL_MAX_TEXTURE_SIZE!==undefined?ol.WEBGL_MAX_TEXTURE_SIZE:2048;this.space_=options.space!==undefined?options.space:1;this.atlases_=[new ol.style.Atlas(this.currentSize_,this.space_)];this.currentHitSize_=this.currentSize_;this.hitAtlases_=
[new ol.style.Atlas(this.currentHitSize_,this.space_)]};ol.style.AtlasManager.prototype.getInfo=function(id){var info=this.getInfo_(this.atlases_,id);if(!info)return null;var hitInfo=this.getInfo_(this.hitAtlases_,id);return this.mergeInfos_(info,hitInfo)};ol.style.AtlasManager.prototype.getInfo_=function(atlases,id){var atlas,info,i,ii;for(i=0,ii=atlases.length;i<ii;++i){atlas=atlases[i];info=atlas.get(id);if(info)return info}return null};
ol.style.AtlasManager.prototype.mergeInfos_=function(info,hitInfo){return{offsetX:info.offsetX,offsetY:info.offsetY,image:info.image,hitImage:hitInfo.image}};
ol.style.AtlasManager.prototype.add=function(id,width,height,renderCallback,opt_renderHitCallback,opt_this){if(width+this.space_>this.maxSize_||height+this.space_>this.maxSize_)return null;var info=this.add_(false,id,width,height,renderCallback,opt_this);if(!info)return null;var renderHitCallback=opt_renderHitCallback!==undefined?opt_renderHitCallback:ol.nullFunction;var hitInfo=this.add_(true,id,width,height,renderHitCallback,opt_this);return this.mergeInfos_(info,hitInfo)};
ol.style.AtlasManager.prototype.add_=function(isHitAtlas,id,width,height,renderCallback,opt_this){var atlases=isHitAtlas?this.hitAtlases_:this.atlases_;var atlas,info,i,ii;for(i=0,ii=atlases.length;i<ii;++i){atlas=atlases[i];info=atlas.add(id,width,height,renderCallback,opt_this);if(info)return info;else if(!info&&i===ii-1){var size;if(isHitAtlas){size=Math.min(this.currentHitSize_*2,this.maxSize_);this.currentHitSize_=size}else{size=Math.min(this.currentSize_*2,this.maxSize_);this.currentSize_=size}atlas=
new ol.style.Atlas(size,this.space_);atlases.push(atlas);++ii}}return null};goog.provide("ol.render.webgl.TextReplay");goog.require("ol");goog.require("ol.colorlike");goog.require("ol.dom");goog.require("ol.geom.GeometryType");goog.require("ol.has");goog.require("ol.render.replay");goog.require("ol.render.webgl");goog.require("ol.render.webgl.TextureReplay");goog.require("ol.style.AtlasManager");goog.require("ol.webgl.Buffer");
ol.render.webgl.TextReplay=function(tolerance,maxExtent){ol.render.webgl.TextureReplay.call(this,tolerance,maxExtent);this.images_=[];this.textures_=[];this.measureCanvas_=ol.dom.createCanvasContext2D(0,0).canvas;this.state_={strokeColor:null,lineCap:undefined,lineDash:null,lineDashOffset:undefined,lineJoin:undefined,lineWidth:0,miterLimit:undefined,fillColor:null,font:undefined,scale:undefined};this.text_="";this.textAlign_=undefined;this.textBaseline_=undefined;this.offsetX_=undefined;this.offsetY_=
undefined;this.atlases_={};this.currAtlas_=undefined;this.scale=1;this.opacity=1};ol.inherits(ol.render.webgl.TextReplay,ol.render.webgl.TextureReplay);
ol.render.webgl.TextReplay.prototype.drawText=function(geometry,feature){if(this.text_){var flatCoordinates=null;var offset=0;var end=2;var stride=2;switch(geometry.getType()){case ol.geom.GeometryType.POINT:case ol.geom.GeometryType.MULTI_POINT:flatCoordinates=geometry.getFlatCoordinates();end=flatCoordinates.length;stride=geometry.getStride();break;case ol.geom.GeometryType.CIRCLE:flatCoordinates=geometry.getCenter();break;case ol.geom.GeometryType.LINE_STRING:flatCoordinates=geometry.getFlatMidpoint();
break;case ol.geom.GeometryType.MULTI_LINE_STRING:flatCoordinates=geometry.getFlatMidpoints();end=flatCoordinates.length;break;case ol.geom.GeometryType.POLYGON:flatCoordinates=geometry.getFlatInteriorPoint();break;case ol.geom.GeometryType.MULTI_POLYGON:flatCoordinates=geometry.getFlatInteriorPoints();end=flatCoordinates.length;break;default:}this.startIndices.push(this.indices.length);this.startIndicesFeature.push(feature);var glyphAtlas=this.currAtlas_;var lines=this.text_.split("\n");var textSize=
this.getTextSize_(lines);var i,ii,j,jj,currX,currY,charArr,charInfo;var anchorX=Math.round(textSize[0]*this.textAlign_-this.offsetX_);var anchorY=Math.round(textSize[1]*this.textBaseline_-this.offsetY_);var lineWidth=this.state_.lineWidth/2*this.state_.scale;for(i=0,ii=lines.length;i<ii;++i){currX=0;currY=glyphAtlas.height*i;charArr=lines[i].split("");for(j=0,jj=charArr.length;j<jj;++j){charInfo=glyphAtlas.atlas.getInfo(charArr[j]);if(charInfo){var image=charInfo.image;this.anchorX=anchorX-currX;
this.anchorY=anchorY-currY;this.originX=j===0?charInfo.offsetX-lineWidth:charInfo.offsetX;this.originY=charInfo.offsetY;this.height=glyphAtlas.height;this.width=j===0||j===charArr.length-1?glyphAtlas.width[charArr[j]]+lineWidth:glyphAtlas.width[charArr[j]];this.imageHeight=image.height;this.imageWidth=image.width;var currentImage;if(this.images_.length===0)this.images_.push(image);else{currentImage=this.images_[this.images_.length-1];if(ol.getUid(currentImage)!=ol.getUid(image)){this.groupIndices.push(this.indices.length);
this.images_.push(image)}}this.drawText_(flatCoordinates,offset,end,stride)}currX+=this.width}}}};
ol.render.webgl.TextReplay.prototype.getTextSize_=function(lines){var self=this;var glyphAtlas=this.currAtlas_;var textHeight=lines.length*glyphAtlas.height;var textWidth=lines.map(function(str){var sum=0;var i,ii;for(i=0,ii=str.length;i<ii;++i){var curr=str[i];if(!glyphAtlas.width[curr])self.addCharToAtlas_(curr);sum+=glyphAtlas.width[curr]?glyphAtlas.width[curr]:0}return sum}).reduce(function(max,curr){return Math.max(max,curr)});return[textWidth,textHeight]};
ol.render.webgl.TextReplay.prototype.drawText_=function(flatCoordinates,offset,end,stride){var i,ii;for(i=offset,ii=end;i<ii;i+=stride)this.drawCoordinates(flatCoordinates,offset,end,stride)};
ol.render.webgl.TextReplay.prototype.addCharToAtlas_=function(char){if(char.length===1){var glyphAtlas=this.currAtlas_;var state=this.state_;var mCtx=this.measureCanvas_.getContext("2d");mCtx.font=state.font;var width=Math.ceil(mCtx.measureText(char).width*state.scale);var info=glyphAtlas.atlas.add(char,width,glyphAtlas.height,function(ctx,x,y){ctx.font=state.font;ctx.fillStyle=state.fillColor;ctx.strokeStyle=state.strokeColor;ctx.lineWidth=state.lineWidth;ctx.lineCap=state.lineCap;ctx.lineJoin=state.lineJoin;
ctx.miterLimit=state.miterLimit;ctx.textAlign="left";ctx.textBaseline="top";if(ol.has.CANVAS_LINE_DASH&&state.lineDash){ctx.setLineDash(state.lineDash);ctx.lineDashOffset=state.lineDashOffset}if(state.scale!==1)ctx.setTransform(state.scale,0,0,state.scale,0,0);if(state.strokeColor)ctx.strokeText(char,x,y);if(state.fillColor)ctx.fillText(char,x,y)});if(info)glyphAtlas.width[char]=width}};
ol.render.webgl.TextReplay.prototype.finish=function(context){var gl=context.getGL();this.groupIndices.push(this.indices.length);this.hitDetectionGroupIndices=this.groupIndices;this.verticesBuffer=new ol.webgl.Buffer(this.vertices);this.indicesBuffer=new ol.webgl.Buffer(this.indices);var texturePerImage={};this.createTextures(this.textures_,this.images_,texturePerImage,gl);this.state_={strokeColor:null,lineCap:undefined,lineDash:null,lineDashOffset:undefined,lineJoin:undefined,lineWidth:0,miterLimit:undefined,
fillColor:null,font:undefined,scale:undefined};this.text_="";this.textAlign_=undefined;this.textBaseline_=undefined;this.offsetX_=undefined;this.offsetY_=undefined;this.images_=null;this.atlases_={};this.currAtlas_=undefined;ol.render.webgl.TextureReplay.prototype.finish.call(this,context)};
ol.render.webgl.TextReplay.prototype.setTextStyle=function(textStyle){var state=this.state_;var textFillStyle=textStyle.getFill();var textStrokeStyle=textStyle.getStroke();if(!textStyle||!textStyle.getText()||!textFillStyle&&!textStrokeStyle)this.text_="";else{if(!textFillStyle)state.fillColor=null;else{var textFillStyleColor=textFillStyle.getColor();state.fillColor=ol.colorlike.asColorLike(textFillStyleColor?textFillStyleColor:ol.render.webgl.defaultFillStyle)}if(!textStrokeStyle){state.strokeColor=
null;state.lineWidth=0}else{var textStrokeStyleColor=textStrokeStyle.getColor();state.strokeColor=ol.colorlike.asColorLike(textStrokeStyleColor?textStrokeStyleColor:ol.render.webgl.defaultStrokeStyle);state.lineWidth=textStrokeStyle.getWidth()||ol.render.webgl.defaultLineWidth;state.lineCap=textStrokeStyle.getLineCap()||ol.render.webgl.defaultLineCap;state.lineDashOffset=textStrokeStyle.getLineDashOffset()||ol.render.webgl.defaultLineDashOffset;state.lineJoin=textStrokeStyle.getLineJoin()||ol.render.webgl.defaultLineJoin;
state.miterLimit=textStrokeStyle.getMiterLimit()||ol.render.webgl.defaultMiterLimit;var lineDash=textStrokeStyle.getLineDash();state.lineDash=lineDash?lineDash.slice():ol.render.webgl.defaultLineDash}state.font=textStyle.getFont()||ol.render.webgl.defaultFont;state.scale=textStyle.getScale()||1;this.text_=textStyle.getText();var textAlign=ol.render.replay.TEXT_ALIGN[textStyle.getTextAlign()];var textBaseline=ol.render.replay.TEXT_ALIGN[textStyle.getTextBaseline()];this.textAlign_=textAlign===undefined?
ol.render.webgl.defaultTextAlign:textAlign;this.textBaseline_=textBaseline===undefined?ol.render.webgl.defaultTextBaseline:textBaseline;this.offsetX_=textStyle.getOffsetX()||0;this.offsetY_=textStyle.getOffsetY()||0;this.rotateWithView=!!textStyle.getRotateWithView();this.rotation=textStyle.getRotation()||0;this.currAtlas_=this.getAtlas_(state)}};
ol.render.webgl.TextReplay.prototype.getAtlas_=function(state){var params=[];var i;for(i in state)if(state[i]||state[i]===0)if(Array.isArray(state[i]))params=params.concat(state[i]);else params.push(state[i]);var hash=this.calculateHash_(params);if(!this.atlases_[hash]){var mCtx=this.measureCanvas_.getContext("2d");mCtx.font=state.font;var height=Math.ceil((mCtx.measureText("M").width*1.5+state.lineWidth/2)*state.scale);this.atlases_[hash]={atlas:new ol.style.AtlasManager({space:state.lineWidth+1}),
width:{},height:height}}return this.atlases_[hash]};ol.render.webgl.TextReplay.prototype.calculateHash_=function(params){var i,ii;var hash="";for(i=0,ii=params.length;i<ii;++i)hash+=params[i];return hash};ol.render.webgl.TextReplay.prototype.getTextures=function(opt_all){return this.textures_};ol.render.webgl.TextReplay.prototype.getHitDetectionTextures=function(){return this.textures_};goog.provide("ol.render.webgl.ReplayGroup");goog.require("ol");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.obj");goog.require("ol.render.replay");goog.require("ol.render.ReplayGroup");goog.require("ol.render.webgl.CircleReplay");goog.require("ol.render.webgl.ImageReplay");goog.require("ol.render.webgl.LineStringReplay");goog.require("ol.render.webgl.PolygonReplay");goog.require("ol.render.webgl.TextReplay");
ol.render.webgl.ReplayGroup=function(tolerance,maxExtent,opt_renderBuffer){ol.render.ReplayGroup.call(this);this.maxExtent_=maxExtent;this.tolerance_=tolerance;this.renderBuffer_=opt_renderBuffer;this.replaysByZIndex_={}};ol.inherits(ol.render.webgl.ReplayGroup,ol.render.ReplayGroup);ol.render.webgl.ReplayGroup.prototype.addDeclutter=function(style,group){};
ol.render.webgl.ReplayGroup.prototype.getDeleteResourcesFunction=function(context){var functions=[];var zKey;for(zKey in this.replaysByZIndex_){var replays=this.replaysByZIndex_[zKey];var replayKey;for(replayKey in replays)functions.push(replays[replayKey].getDeleteResourcesFunction(context))}return function(){var length=functions.length;var result;for(var i=0;i<length;i++)result=functions[i].apply(this,arguments);return result}};
ol.render.webgl.ReplayGroup.prototype.finish=function(context){var zKey;for(zKey in this.replaysByZIndex_){var replays=this.replaysByZIndex_[zKey];var replayKey;for(replayKey in replays)replays[replayKey].finish(context)}};
ol.render.webgl.ReplayGroup.prototype.getReplay=function(zIndex,replayType){var zIndexKey=zIndex!==undefined?zIndex.toString():"0";var replays=this.replaysByZIndex_[zIndexKey];if(replays===undefined){replays={};this.replaysByZIndex_[zIndexKey]=replays}var replay=replays[replayType];if(replay===undefined){var Constructor=ol.render.webgl.ReplayGroup.BATCH_CONSTRUCTORS_[replayType];replay=new Constructor(this.tolerance_,this.maxExtent_);replays[replayType]=replay}return replay};
ol.render.webgl.ReplayGroup.prototype.isEmpty=function(){return ol.obj.isEmpty(this.replaysByZIndex_)};
ol.render.webgl.ReplayGroup.prototype.replay=function(context,center,resolution,rotation,size,pixelRatio,opacity,skippedFeaturesHash){var zs=Object.keys(this.replaysByZIndex_).map(Number);zs.sort(ol.array.numberSafeCompareFunction);var i,ii,j,jj,replays,replay;for(i=0,ii=zs.length;i<ii;++i){replays=this.replaysByZIndex_[zs[i].toString()];for(j=0,jj=ol.render.replay.ORDER.length;j<jj;++j){replay=replays[ol.render.replay.ORDER[j]];if(replay!==undefined)replay.replay(context,center,resolution,rotation,
size,pixelRatio,opacity,skippedFeaturesHash,undefined,false)}}};
ol.render.webgl.ReplayGroup.prototype.replayHitDetection_=function(context,center,resolution,rotation,size,pixelRatio,opacity,skippedFeaturesHash,featureCallback,oneByOne,opt_hitExtent){var zs=Object.keys(this.replaysByZIndex_).map(Number);zs.sort(function(a,b){return b-a});var i,ii,j,replays,replay,result;for(i=0,ii=zs.length;i<ii;++i){replays=this.replaysByZIndex_[zs[i].toString()];for(j=ol.render.replay.ORDER.length-1;j>=0;--j){replay=replays[ol.render.replay.ORDER[j]];if(replay!==undefined){result=
replay.replay(context,center,resolution,rotation,size,pixelRatio,opacity,skippedFeaturesHash,featureCallback,oneByOne,opt_hitExtent);if(result)return result}}}return undefined};
ol.render.webgl.ReplayGroup.prototype.forEachFeatureAtCoordinate=function(coordinate,context,center,resolution,rotation,size,pixelRatio,opacity,skippedFeaturesHash,callback){var gl=context.getGL();gl.bindFramebuffer(gl.FRAMEBUFFER,context.getHitDetectionFramebuffer());var hitExtent;if(this.renderBuffer_!==undefined)hitExtent=ol.extent.buffer(ol.extent.createOrUpdateFromCoordinate(coordinate),resolution*this.renderBuffer_);return this.replayHitDetection_(context,coordinate,resolution,rotation,ol.render.webgl.ReplayGroup.HIT_DETECTION_SIZE_,
pixelRatio,opacity,skippedFeaturesHash,function(feature){var imageData=new Uint8Array(4);gl.readPixels(0,0,1,1,gl.RGBA,gl.UNSIGNED_BYTE,imageData);if(imageData[3]>0){var result=callback(feature);if(result)return result}},true,hitExtent)};
ol.render.webgl.ReplayGroup.prototype.hasFeatureAtCoordinate=function(coordinate,context,center,resolution,rotation,size,pixelRatio,opacity,skippedFeaturesHash){var gl=context.getGL();gl.bindFramebuffer(gl.FRAMEBUFFER,context.getHitDetectionFramebuffer());var hasFeature=this.replayHitDetection_(context,coordinate,resolution,rotation,ol.render.webgl.ReplayGroup.HIT_DETECTION_SIZE_,pixelRatio,opacity,skippedFeaturesHash,function(feature){var imageData=new Uint8Array(4);gl.readPixels(0,0,1,1,gl.RGBA,
gl.UNSIGNED_BYTE,imageData);return imageData[3]>0},false);return hasFeature!==undefined};ol.render.webgl.ReplayGroup.HIT_DETECTION_SIZE_=[1,1];ol.render.webgl.ReplayGroup.BATCH_CONSTRUCTORS_={"Circle":ol.render.webgl.CircleReplay,"Image":ol.render.webgl.ImageReplay,"LineString":ol.render.webgl.LineStringReplay,"Polygon":ol.render.webgl.PolygonReplay,"Text":ol.render.webgl.TextReplay};goog.provide("ol.render.webgl.Immediate");goog.require("ol");goog.require("ol.extent");goog.require("ol.geom.GeometryType");goog.require("ol.render.ReplayType");goog.require("ol.render.VectorContext");goog.require("ol.render.webgl.ReplayGroup");
ol.render.webgl.Immediate=function(context,center,resolution,rotation,size,extent,pixelRatio){ol.render.VectorContext.call(this);this.context_=context;this.center_=center;this.extent_=extent;this.pixelRatio_=pixelRatio;this.size_=size;this.rotation_=rotation;this.resolution_=resolution;this.imageStyle_=null;this.fillStyle_=null;this.strokeStyle_=null;this.textStyle_=null};ol.inherits(ol.render.webgl.Immediate,ol.render.VectorContext);
ol.render.webgl.Immediate.prototype.drawText_=function(replayGroup,geometry){var context=this.context_;var replay=replayGroup.getReplay(0,ol.render.ReplayType.TEXT);replay.setTextStyle(this.textStyle_);replay.drawText(geometry,null);replay.finish(context);var opacity=1;var skippedFeatures={};var featureCallback;var oneByOne=false;replay.replay(this.context_,this.center_,this.resolution_,this.rotation_,this.size_,this.pixelRatio_,opacity,skippedFeatures,featureCallback,oneByOne);replay.getDeleteResourcesFunction(context)()};
ol.render.webgl.Immediate.prototype.setStyle=function(style){this.setFillStrokeStyle(style.getFill(),style.getStroke());this.setImageStyle(style.getImage());this.setTextStyle(style.getText())};
ol.render.webgl.Immediate.prototype.drawGeometry=function(geometry){var type=geometry.getType();switch(type){case ol.geom.GeometryType.POINT:this.drawPoint(geometry,null);break;case ol.geom.GeometryType.LINE_STRING:this.drawLineString(geometry,null);break;case ol.geom.GeometryType.POLYGON:this.drawPolygon(geometry,null);break;case ol.geom.GeometryType.MULTI_POINT:this.drawMultiPoint(geometry,null);break;case ol.geom.GeometryType.MULTI_LINE_STRING:this.drawMultiLineString(geometry,null);break;case ol.geom.GeometryType.MULTI_POLYGON:this.drawMultiPolygon(geometry,
null);break;case ol.geom.GeometryType.GEOMETRY_COLLECTION:this.drawGeometryCollection(geometry,null);break;case ol.geom.GeometryType.CIRCLE:this.drawCircle(geometry,null);break;default:}};ol.render.webgl.Immediate.prototype.drawFeature=function(feature,style){var geometry=style.getGeometryFunction()(feature);if(!geometry||!ol.extent.intersects(this.extent_,geometry.getExtent()))return;this.setStyle(style);this.drawGeometry(geometry)};
ol.render.webgl.Immediate.prototype.drawGeometryCollection=function(geometry,data){var geometries=geometry.getGeometriesArray();var i,ii;for(i=0,ii=geometries.length;i<ii;++i)this.drawGeometry(geometries[i])};
ol.render.webgl.Immediate.prototype.drawPoint=function(geometry,data){var context=this.context_;var replayGroup=new ol.render.webgl.ReplayGroup(1,this.extent_);var replay=replayGroup.getReplay(0,ol.render.ReplayType.IMAGE);replay.setImageStyle(this.imageStyle_);replay.drawPoint(geometry,data);replay.finish(context);var opacity=1;var skippedFeatures={};var featureCallback;var oneByOne=false;replay.replay(this.context_,this.center_,this.resolution_,this.rotation_,this.size_,this.pixelRatio_,opacity,
skippedFeatures,featureCallback,oneByOne);replay.getDeleteResourcesFunction(context)();if(this.textStyle_)this.drawText_(replayGroup,geometry)};
ol.render.webgl.Immediate.prototype.drawMultiPoint=function(geometry,data){var context=this.context_;var replayGroup=new ol.render.webgl.ReplayGroup(1,this.extent_);var replay=replayGroup.getReplay(0,ol.render.ReplayType.IMAGE);replay.setImageStyle(this.imageStyle_);replay.drawMultiPoint(geometry,data);replay.finish(context);var opacity=1;var skippedFeatures={};var featureCallback;var oneByOne=false;replay.replay(this.context_,this.center_,this.resolution_,this.rotation_,this.size_,this.pixelRatio_,
opacity,skippedFeatures,featureCallback,oneByOne);replay.getDeleteResourcesFunction(context)();if(this.textStyle_)this.drawText_(replayGroup,geometry)};
ol.render.webgl.Immediate.prototype.drawLineString=function(geometry,data){var context=this.context_;var replayGroup=new ol.render.webgl.ReplayGroup(1,this.extent_);var replay=replayGroup.getReplay(0,ol.render.ReplayType.LINE_STRING);replay.setFillStrokeStyle(null,this.strokeStyle_);replay.drawLineString(geometry,data);replay.finish(context);var opacity=1;var skippedFeatures={};var featureCallback;var oneByOne=false;replay.replay(this.context_,this.center_,this.resolution_,this.rotation_,this.size_,
this.pixelRatio_,opacity,skippedFeatures,featureCallback,oneByOne);replay.getDeleteResourcesFunction(context)();if(this.textStyle_)this.drawText_(replayGroup,geometry)};
ol.render.webgl.Immediate.prototype.drawMultiLineString=function(geometry,data){var context=this.context_;var replayGroup=new ol.render.webgl.ReplayGroup(1,this.extent_);var replay=replayGroup.getReplay(0,ol.render.ReplayType.LINE_STRING);replay.setFillStrokeStyle(null,this.strokeStyle_);replay.drawMultiLineString(geometry,data);replay.finish(context);var opacity=1;var skippedFeatures={};var featureCallback;var oneByOne=false;replay.replay(this.context_,this.center_,this.resolution_,this.rotation_,
this.size_,this.pixelRatio_,opacity,skippedFeatures,featureCallback,oneByOne);replay.getDeleteResourcesFunction(context)();if(this.textStyle_)this.drawText_(replayGroup,geometry)};
ol.render.webgl.Immediate.prototype.drawPolygon=function(geometry,data){var context=this.context_;var replayGroup=new ol.render.webgl.ReplayGroup(1,this.extent_);var replay=replayGroup.getReplay(0,ol.render.ReplayType.POLYGON);replay.setFillStrokeStyle(this.fillStyle_,this.strokeStyle_);replay.drawPolygon(geometry,data);replay.finish(context);var opacity=1;var skippedFeatures={};var featureCallback;var oneByOne=false;replay.replay(this.context_,this.center_,this.resolution_,this.rotation_,this.size_,
this.pixelRatio_,opacity,skippedFeatures,featureCallback,oneByOne);replay.getDeleteResourcesFunction(context)();if(this.textStyle_)this.drawText_(replayGroup,geometry)};
ol.render.webgl.Immediate.prototype.drawMultiPolygon=function(geometry,data){var context=this.context_;var replayGroup=new ol.render.webgl.ReplayGroup(1,this.extent_);var replay=replayGroup.getReplay(0,ol.render.ReplayType.POLYGON);replay.setFillStrokeStyle(this.fillStyle_,this.strokeStyle_);replay.drawMultiPolygon(geometry,data);replay.finish(context);var opacity=1;var skippedFeatures={};var featureCallback;var oneByOne=false;replay.replay(this.context_,this.center_,this.resolution_,this.rotation_,
this.size_,this.pixelRatio_,opacity,skippedFeatures,featureCallback,oneByOne);replay.getDeleteResourcesFunction(context)();if(this.textStyle_)this.drawText_(replayGroup,geometry)};
ol.render.webgl.Immediate.prototype.drawCircle=function(geometry,data){var context=this.context_;var replayGroup=new ol.render.webgl.ReplayGroup(1,this.extent_);var replay=replayGroup.getReplay(0,ol.render.ReplayType.CIRCLE);replay.setFillStrokeStyle(this.fillStyle_,this.strokeStyle_);replay.drawCircle(geometry,data);replay.finish(context);var opacity=1;var skippedFeatures={};var featureCallback;var oneByOne=false;replay.replay(this.context_,this.center_,this.resolution_,this.rotation_,this.size_,
this.pixelRatio_,opacity,skippedFeatures,featureCallback,oneByOne);replay.getDeleteResourcesFunction(context)();if(this.textStyle_)this.drawText_(replayGroup,geometry)};ol.render.webgl.Immediate.prototype.setImageStyle=function(imageStyle){this.imageStyle_=imageStyle};ol.render.webgl.Immediate.prototype.setFillStrokeStyle=function(fillStyle,strokeStyle){this.fillStyle_=fillStyle;this.strokeStyle_=strokeStyle};ol.render.webgl.Immediate.prototype.setTextStyle=function(textStyle){this.textStyle_=textStyle};goog.provide("ol.renderer.webgl.defaultmapshader");goog.require("ol");goog.require("ol.webgl.Fragment");goog.require("ol.webgl.Vertex");ol.renderer.webgl.defaultmapshader.fragment=new ol.webgl.Fragment(ol.DEBUG_WEBGL?"precision mediump float;\nvarying vec2 v_texCoord;\n\n\nuniform float u_opacity;\nuniform sampler2D u_texture;\n\nvoid main(void) {\n  vec4 texColor = texture2D(u_texture, v_texCoord);\n  gl_FragColor.rgb = texColor.rgb;\n  gl_FragColor.a = texColor.a * u_opacity;\n}\n":"precision mediump float;varying vec2 a;uniform float f;uniform sampler2D g;void main(void){vec4 texColor=texture2D(g,a);gl_FragColor.rgb=texColor.rgb;gl_FragColor.a=texColor.a*f;}");
ol.renderer.webgl.defaultmapshader.vertex=new ol.webgl.Vertex(ol.DEBUG_WEBGL?"varying vec2 v_texCoord;\n\n\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat4 u_texCoordMatrix;\nuniform mat4 u_projectionMatrix;\n\nvoid main(void) {\n  gl_Position = u_projectionMatrix * vec4(a_position, 0., 1.);\n  v_texCoord = (u_texCoordMatrix * vec4(a_texCoord, 0., 1.)).st;\n}\n\n\n":"varying vec2 a;attribute vec2 b;attribute vec2 c;uniform mat4 d;uniform mat4 e;void main(void){gl_Position=e*vec4(b,0.,1.);a=(d*vec4(c,0.,1.)).st;}");goog.provide("ol.renderer.webgl.defaultmapshader.Locations");goog.require("ol");
ol.renderer.webgl.defaultmapshader.Locations=function(gl,program){this.u_texCoordMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_texCoordMatrix":"d");this.u_projectionMatrix=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_projectionMatrix":"e");this.u_opacity=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_opacity":"f");this.u_texture=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_texture":"g");this.a_position=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_position":"b");this.a_texCoord=gl.getAttribLocation(program,
ol.DEBUG_WEBGL?"a_texCoord":"c")};goog.provide("ol.renderer.webgl.Layer");goog.require("ol");goog.require("ol.render.Event");goog.require("ol.render.EventType");goog.require("ol.render.webgl.Immediate");goog.require("ol.renderer.Layer");goog.require("ol.renderer.webgl.defaultmapshader");goog.require("ol.renderer.webgl.defaultmapshader.Locations");goog.require("ol.transform");goog.require("ol.vec.Mat4");goog.require("ol.webgl");goog.require("ol.webgl.Buffer");goog.require("ol.webgl.Context");
ol.renderer.webgl.Layer=function(mapRenderer,layer){ol.renderer.Layer.call(this,layer);this.mapRenderer=mapRenderer;this.arrayBuffer_=new ol.webgl.Buffer([-1,-1,0,0,1,-1,1,0,-1,1,0,1,1,1,1,1]);this.texture=null;this.framebuffer=null;this.framebufferDimension=undefined;this.texCoordMatrix=ol.transform.create();this.projectionMatrix=ol.transform.create();this.tmpMat4_=ol.vec.Mat4.create();this.defaultLocations_=null};ol.inherits(ol.renderer.webgl.Layer,ol.renderer.Layer);
ol.renderer.webgl.Layer.prototype.bindFramebuffer=function(frameState,framebufferDimension){var gl=this.mapRenderer.getGL();if(this.framebufferDimension===undefined||this.framebufferDimension!=framebufferDimension){var postRenderFunction=function(gl,framebuffer,texture){if(!gl.isContextLost()){gl.deleteFramebuffer(framebuffer);gl.deleteTexture(texture)}}.bind(null,gl,this.framebuffer,this.texture);frameState.postRenderFunctions.push(postRenderFunction);var texture=ol.webgl.Context.createEmptyTexture(gl,
framebufferDimension,framebufferDimension);var framebuffer=gl.createFramebuffer();gl.bindFramebuffer(ol.webgl.FRAMEBUFFER,framebuffer);gl.framebufferTexture2D(ol.webgl.FRAMEBUFFER,ol.webgl.COLOR_ATTACHMENT0,ol.webgl.TEXTURE_2D,texture,0);this.texture=texture;this.framebuffer=framebuffer;this.framebufferDimension=framebufferDimension}else gl.bindFramebuffer(ol.webgl.FRAMEBUFFER,this.framebuffer)};
ol.renderer.webgl.Layer.prototype.composeFrame=function(frameState,layerState,context){this.dispatchComposeEvent_(ol.render.EventType.PRECOMPOSE,context,frameState);context.bindBuffer(ol.webgl.ARRAY_BUFFER,this.arrayBuffer_);var gl=context.getGL();var fragmentShader=ol.renderer.webgl.defaultmapshader.fragment;var vertexShader=ol.renderer.webgl.defaultmapshader.vertex;var program=context.getProgram(fragmentShader,vertexShader);var locations;if(!this.defaultLocations_){locations=new ol.renderer.webgl.defaultmapshader.Locations(gl,
program);this.defaultLocations_=locations}else locations=this.defaultLocations_;if(context.useProgram(program)){gl.enableVertexAttribArray(locations.a_position);gl.vertexAttribPointer(locations.a_position,2,ol.webgl.FLOAT,false,16,0);gl.enableVertexAttribArray(locations.a_texCoord);gl.vertexAttribPointer(locations.a_texCoord,2,ol.webgl.FLOAT,false,16,8);gl.uniform1i(locations.u_texture,0)}gl.uniformMatrix4fv(locations.u_texCoordMatrix,false,ol.vec.Mat4.fromTransform(this.tmpMat4_,this.getTexCoordMatrix()));
gl.uniformMatrix4fv(locations.u_projectionMatrix,false,ol.vec.Mat4.fromTransform(this.tmpMat4_,this.getProjectionMatrix()));gl.uniform1f(locations.u_opacity,layerState.opacity);gl.bindTexture(ol.webgl.TEXTURE_2D,this.getTexture());gl.drawArrays(ol.webgl.TRIANGLE_STRIP,0,4);this.dispatchComposeEvent_(ol.render.EventType.POSTCOMPOSE,context,frameState)};
ol.renderer.webgl.Layer.prototype.dispatchComposeEvent_=function(type,context,frameState){var layer=this.getLayer();if(layer.hasListener(type)){var viewState=frameState.viewState;var resolution=viewState.resolution;var pixelRatio=frameState.pixelRatio;var extent=frameState.extent;var center=viewState.center;var rotation=viewState.rotation;var size=frameState.size;var render=new ol.render.webgl.Immediate(context,center,resolution,rotation,size,extent,pixelRatio);var composeEvent=new ol.render.Event(type,
render,frameState,null,context);layer.dispatchEvent(composeEvent)}};ol.renderer.webgl.Layer.prototype.getTexCoordMatrix=function(){return this.texCoordMatrix};ol.renderer.webgl.Layer.prototype.getTexture=function(){return this.texture};ol.renderer.webgl.Layer.prototype.getProjectionMatrix=function(){return this.projectionMatrix};ol.renderer.webgl.Layer.prototype.handleWebGLContextLost=function(){this.texture=null;this.framebuffer=null;this.framebufferDimension=undefined};
ol.renderer.webgl.Layer.prototype.prepareFrame=function(frameState,layerState,context){};ol.renderer.webgl.Layer.prototype.forEachLayerAtPixel=function(pixel,frameState,callback,thisArg){};goog.provide("ol.renderer.webgl.ImageLayer");goog.require("ol");goog.require("ol.LayerType");goog.require("ol.ViewHint");goog.require("ol.dom");goog.require("ol.extent");goog.require("ol.functions");goog.require("ol.renderer.Type");goog.require("ol.renderer.webgl.Layer");goog.require("ol.transform");goog.require("ol.webgl");goog.require("ol.webgl.Context");
ol.renderer.webgl.ImageLayer=function(mapRenderer,imageLayer){ol.renderer.webgl.Layer.call(this,mapRenderer,imageLayer);this.image_=null;this.hitCanvasContext_=null;this.hitTransformationMatrix_=null};ol.inherits(ol.renderer.webgl.ImageLayer,ol.renderer.webgl.Layer);ol.renderer.webgl.ImageLayer["handles"]=function(type,layer){return type===ol.renderer.Type.WEBGL&&layer.getType()===ol.LayerType.IMAGE};
ol.renderer.webgl.ImageLayer["create"]=function(mapRenderer,layer){return new ol.renderer.webgl.ImageLayer(mapRenderer,layer)};ol.renderer.webgl.ImageLayer.prototype.createTexture_=function(image){var imageElement=image.getImage();var gl=this.mapRenderer.getGL();return ol.webgl.Context.createTexture(gl,imageElement,ol.webgl.CLAMP_TO_EDGE,ol.webgl.CLAMP_TO_EDGE)};
ol.renderer.webgl.ImageLayer.prototype.forEachFeatureAtCoordinate=function(coordinate,frameState,hitTolerance,callback,thisArg){var layer=this.getLayer();var source=layer.getSource();var resolution=frameState.viewState.resolution;var rotation=frameState.viewState.rotation;var skippedFeatureUids=frameState.skippedFeatureUids;return source.forEachFeatureAtCoordinate(coordinate,resolution,rotation,hitTolerance,skippedFeatureUids,function(feature){return callback.call(thisArg,feature,layer)})};
ol.renderer.webgl.ImageLayer.prototype.prepareFrame=function(frameState,layerState,context){var gl=this.mapRenderer.getGL();var pixelRatio=frameState.pixelRatio;var viewState=frameState.viewState;var viewCenter=viewState.center;var viewResolution=viewState.resolution;var viewRotation=viewState.rotation;var image=this.image_;var texture=this.texture;var imageLayer=this.getLayer();var imageSource=imageLayer.getSource();var hints=frameState.viewHints;var renderedExtent=frameState.extent;if(layerState.extent!==
undefined)renderedExtent=ol.extent.getIntersection(renderedExtent,layerState.extent);if(!hints[ol.ViewHint.ANIMATING]&&!hints[ol.ViewHint.INTERACTING]&&!ol.extent.isEmpty(renderedExtent)){var projection=viewState.projection;if(!ol.ENABLE_RASTER_REPROJECTION){var sourceProjection=imageSource.getProjection();if(sourceProjection)projection=sourceProjection}var image_=imageSource.getImage(renderedExtent,viewResolution,pixelRatio,projection);if(image_){var loaded=this.loadImage(image_);if(loaded){image=
image_;texture=this.createTexture_(image_);if(this.texture){var postRenderFunction=function(gl,texture){if(!gl.isContextLost())gl.deleteTexture(texture)}.bind(null,gl,this.texture);frameState.postRenderFunctions.push(postRenderFunction)}}}}if(image){var canvas=this.mapRenderer.getContext().getCanvas();this.updateProjectionMatrix_(canvas.width,canvas.height,pixelRatio,viewCenter,viewResolution,viewRotation,image.getExtent());this.hitTransformationMatrix_=null;var texCoordMatrix=this.texCoordMatrix;
ol.transform.reset(texCoordMatrix);ol.transform.scale(texCoordMatrix,1,-1);ol.transform.translate(texCoordMatrix,0,-1);this.image_=image;this.texture=texture;this.updateLogos(frameState,imageSource)}return!!image};
ol.renderer.webgl.ImageLayer.prototype.updateProjectionMatrix_=function(canvasWidth,canvasHeight,pixelRatio,viewCenter,viewResolution,viewRotation,imageExtent){var canvasExtentWidth=canvasWidth*viewResolution;var canvasExtentHeight=canvasHeight*viewResolution;var projectionMatrix=this.projectionMatrix;ol.transform.reset(projectionMatrix);ol.transform.scale(projectionMatrix,pixelRatio*2/canvasExtentWidth,pixelRatio*2/canvasExtentHeight);ol.transform.rotate(projectionMatrix,-viewRotation);ol.transform.translate(projectionMatrix,
imageExtent[0]-viewCenter[0],imageExtent[1]-viewCenter[1]);ol.transform.scale(projectionMatrix,(imageExtent[2]-imageExtent[0])/2,(imageExtent[3]-imageExtent[1])/2);ol.transform.translate(projectionMatrix,1,1)};ol.renderer.webgl.ImageLayer.prototype.hasFeatureAtCoordinate=function(coordinate,frameState){var hasFeature=this.forEachFeatureAtCoordinate(coordinate,frameState,0,ol.functions.TRUE,this);return hasFeature!==undefined};
ol.renderer.webgl.ImageLayer.prototype.forEachLayerAtPixel=function(pixel,frameState,callback,thisArg){if(!this.image_||!this.image_.getImage())return undefined;if(this.getLayer().getSource().forEachFeatureAtCoordinate!==ol.nullFunction){var coordinate=ol.transform.apply(frameState.pixelToCoordinateTransform,pixel.slice());var hasFeature=this.forEachFeatureAtCoordinate(coordinate,frameState,0,ol.functions.TRUE,this);if(hasFeature)return callback.call(thisArg,this.getLayer(),null);else return undefined}else{var imageSize=
[this.image_.getImage().width,this.image_.getImage().height];if(!this.hitTransformationMatrix_)this.hitTransformationMatrix_=this.getHitTransformationMatrix_(frameState.size,imageSize);var pixelOnFrameBuffer=ol.transform.apply(this.hitTransformationMatrix_,pixel.slice());if(pixelOnFrameBuffer[0]<0||pixelOnFrameBuffer[0]>imageSize[0]||pixelOnFrameBuffer[1]<0||pixelOnFrameBuffer[1]>imageSize[1])return undefined;if(!this.hitCanvasContext_)this.hitCanvasContext_=ol.dom.createCanvasContext2D(1,1);this.hitCanvasContext_.clearRect(0,
0,1,1);this.hitCanvasContext_.drawImage(this.image_.getImage(),pixelOnFrameBuffer[0],pixelOnFrameBuffer[1],1,1,0,0,1,1);var imageData=this.hitCanvasContext_.getImageData(0,0,1,1).data;if(imageData[3]>0)return callback.call(thisArg,this.getLayer(),imageData);else return undefined}};
ol.renderer.webgl.ImageLayer.prototype.getHitTransformationMatrix_=function(mapSize,imageSize){var mapCoordTransform=ol.transform.create();ol.transform.translate(mapCoordTransform,-1,-1);ol.transform.scale(mapCoordTransform,2/mapSize[0],2/mapSize[1]);ol.transform.translate(mapCoordTransform,0,mapSize[1]);ol.transform.scale(mapCoordTransform,1,-1);var projectionMatrixInv=ol.transform.invert(this.projectionMatrix.slice());var transform=ol.transform.create();ol.transform.translate(transform,0,imageSize[1]);
ol.transform.scale(transform,1,-1);ol.transform.scale(transform,imageSize[0]/2,imageSize[1]/2);ol.transform.translate(transform,1,1);ol.transform.multiply(transform,projectionMatrixInv);ol.transform.multiply(transform,mapCoordTransform);return transform};goog.provide("ol.renderer.webgl.Map");goog.require("ol");goog.require("ol.array");goog.require("ol.css");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.has");goog.require("ol.layer.Layer");goog.require("ol.render.Event");goog.require("ol.render.EventType");goog.require("ol.render.webgl.Immediate");goog.require("ol.renderer.Map");goog.require("ol.renderer.Type");goog.require("ol.source.State");goog.require("ol.structs.LRUCache");goog.require("ol.structs.PriorityQueue");goog.require("ol.webgl");
goog.require("ol.webgl.Context");goog.require("ol.webgl.ContextEventType");
ol.renderer.webgl.Map=function(container,map){ol.renderer.Map.call(this,container,map);this.canvas_=document.createElement("CANVAS");this.canvas_.style.width="100%";this.canvas_.style.height="100%";this.canvas_.style.display="block";this.canvas_.className=ol.css.CLASS_UNSELECTABLE;container.insertBefore(this.canvas_,container.childNodes[0]||null);this.clipTileCanvasWidth_=0;this.clipTileCanvasHeight_=0;this.clipTileContext_=ol.dom.createCanvasContext2D();this.renderedVisible_=true;this.gl_=ol.webgl.getContext(this.canvas_,
{antialias:true,depth:true,failIfMajorPerformanceCaveat:true,preserveDrawingBuffer:false,stencil:true});this.context_=new ol.webgl.Context(this.canvas_,this.gl_);ol.events.listen(this.canvas_,ol.webgl.ContextEventType.LOST,this.handleWebGLContextLost,this);ol.events.listen(this.canvas_,ol.webgl.ContextEventType.RESTORED,this.handleWebGLContextRestored,this);this.textureCache_=new ol.structs.LRUCache;this.focus_=null;this.tileTextureQueue_=new ol.structs.PriorityQueue(function(element){var tileCenter=
element[1];var tileResolution=element[2];var deltaX=tileCenter[0]-this.focus_[0];var deltaY=tileCenter[1]-this.focus_[1];return 65536*Math.log(tileResolution)+Math.sqrt(deltaX*deltaX+deltaY*deltaY)/tileResolution}.bind(this),function(element){return element[0].getKey()});this.loadNextTileTexture_=function(map,frameState){if(!this.tileTextureQueue_.isEmpty()){this.tileTextureQueue_.reprioritize();var element=this.tileTextureQueue_.dequeue();var tile=element[0];var tileSize=element[3];var tileGutter=
element[4];this.bindTileTexture(tile,tileSize,tileGutter,ol.webgl.LINEAR,ol.webgl.LINEAR)}return false}.bind(this);this.textureCacheFrameMarkerCount_=0;this.initializeGL_()};ol.inherits(ol.renderer.webgl.Map,ol.renderer.Map);ol.renderer.webgl.Map["handles"]=function(type){return ol.has.WEBGL&&type===ol.renderer.Type.WEBGL};ol.renderer.webgl.Map["create"]=function(container,map){return new ol.renderer.webgl.Map(container,map)};
ol.renderer.webgl.Map.prototype.bindTileTexture=function(tile,tileSize,tileGutter,magFilter,minFilter){var gl=this.getGL();var tileKey=tile.getKey();if(this.textureCache_.containsKey(tileKey)){var textureCacheEntry=this.textureCache_.get(tileKey);gl.bindTexture(ol.webgl.TEXTURE_2D,textureCacheEntry.texture);if(textureCacheEntry.magFilter!=magFilter){gl.texParameteri(ol.webgl.TEXTURE_2D,ol.webgl.TEXTURE_MAG_FILTER,magFilter);textureCacheEntry.magFilter=magFilter}if(textureCacheEntry.minFilter!=minFilter){gl.texParameteri(ol.webgl.TEXTURE_2D,
ol.webgl.TEXTURE_MIN_FILTER,minFilter);textureCacheEntry.minFilter=minFilter}}else{var texture=gl.createTexture();gl.bindTexture(ol.webgl.TEXTURE_2D,texture);if(tileGutter>0){var clipTileCanvas=this.clipTileContext_.canvas;var clipTileContext=this.clipTileContext_;if(this.clipTileCanvasWidth_!==tileSize[0]||this.clipTileCanvasHeight_!==tileSize[1]){clipTileCanvas.width=tileSize[0];clipTileCanvas.height=tileSize[1];this.clipTileCanvasWidth_=tileSize[0];this.clipTileCanvasHeight_=tileSize[1]}else clipTileContext.clearRect(0,
0,tileSize[0],tileSize[1]);clipTileContext.drawImage(tile.getImage(),tileGutter,tileGutter,tileSize[0],tileSize[1],0,0,tileSize[0],tileSize[1]);gl.texImage2D(ol.webgl.TEXTURE_2D,0,ol.webgl.RGBA,ol.webgl.RGBA,ol.webgl.UNSIGNED_BYTE,clipTileCanvas)}else gl.texImage2D(ol.webgl.TEXTURE_2D,0,ol.webgl.RGBA,ol.webgl.RGBA,ol.webgl.UNSIGNED_BYTE,tile.getImage());gl.texParameteri(ol.webgl.TEXTURE_2D,ol.webgl.TEXTURE_MAG_FILTER,magFilter);gl.texParameteri(ol.webgl.TEXTURE_2D,ol.webgl.TEXTURE_MIN_FILTER,minFilter);
gl.texParameteri(ol.webgl.TEXTURE_2D,ol.webgl.TEXTURE_WRAP_S,ol.webgl.CLAMP_TO_EDGE);gl.texParameteri(ol.webgl.TEXTURE_2D,ol.webgl.TEXTURE_WRAP_T,ol.webgl.CLAMP_TO_EDGE);this.textureCache_.set(tileKey,{texture:texture,magFilter:magFilter,minFilter:minFilter})}};
ol.renderer.webgl.Map.prototype.dispatchComposeEvent_=function(type,frameState){var map=this.getMap();if(map.hasListener(type)){var context=this.context_;var extent=frameState.extent;var size=frameState.size;var viewState=frameState.viewState;var pixelRatio=frameState.pixelRatio;var resolution=viewState.resolution;var center=viewState.center;var rotation=viewState.rotation;var vectorContext=new ol.render.webgl.Immediate(context,center,resolution,rotation,size,extent,pixelRatio);var composeEvent=new ol.render.Event(type,
vectorContext,frameState,null,context);map.dispatchEvent(composeEvent)}};ol.renderer.webgl.Map.prototype.disposeInternal=function(){var gl=this.getGL();if(!gl.isContextLost())this.textureCache_.forEach(function(textureCacheEntry){if(textureCacheEntry)gl.deleteTexture(textureCacheEntry.texture)});this.context_.dispose();ol.renderer.Map.prototype.disposeInternal.call(this)};
ol.renderer.webgl.Map.prototype.expireCache_=function(map,frameState){var gl=this.getGL();var textureCacheEntry;while(this.textureCache_.getCount()-this.textureCacheFrameMarkerCount_>ol.WEBGL_TEXTURE_CACHE_HIGH_WATER_MARK){textureCacheEntry=this.textureCache_.peekLast();if(!textureCacheEntry)if(+this.textureCache_.peekLastKey()==frameState.index)break;else--this.textureCacheFrameMarkerCount_;else gl.deleteTexture(textureCacheEntry.texture);this.textureCache_.pop()}};
ol.renderer.webgl.Map.prototype.getContext=function(){return this.context_};ol.renderer.webgl.Map.prototype.getGL=function(){return this.gl_};ol.renderer.webgl.Map.prototype.getTileTextureQueue=function(){return this.tileTextureQueue_};ol.renderer.webgl.Map.prototype.getType=function(){return ol.renderer.Type.WEBGL};
ol.renderer.webgl.Map.prototype.handleWebGLContextLost=function(event){event.preventDefault();this.textureCache_.clear();this.textureCacheFrameMarkerCount_=0;var renderers=this.getLayerRenderers();for(var id in renderers){var renderer=renderers[id];renderer.handleWebGLContextLost()}};ol.renderer.webgl.Map.prototype.handleWebGLContextRestored=function(){this.initializeGL_();this.getMap().render()};
ol.renderer.webgl.Map.prototype.initializeGL_=function(){var gl=this.gl_;gl.activeTexture(ol.webgl.TEXTURE0);gl.blendFuncSeparate(ol.webgl.SRC_ALPHA,ol.webgl.ONE_MINUS_SRC_ALPHA,ol.webgl.ONE,ol.webgl.ONE_MINUS_SRC_ALPHA);gl.disable(ol.webgl.CULL_FACE);gl.disable(ol.webgl.DEPTH_TEST);gl.disable(ol.webgl.SCISSOR_TEST);gl.disable(ol.webgl.STENCIL_TEST)};ol.renderer.webgl.Map.prototype.isTileTextureLoaded=function(tile){return this.textureCache_.containsKey(tile.getKey())};
ol.renderer.webgl.Map.prototype.renderFrame=function(frameState){var context=this.getContext();var gl=this.getGL();if(gl.isContextLost())return false;if(!frameState){if(this.renderedVisible_){this.canvas_.style.display="none";this.renderedVisible_=false}return false}this.focus_=frameState.focus;this.textureCache_.set((-frameState.index).toString(),null);++this.textureCacheFrameMarkerCount_;this.dispatchComposeEvent_(ol.render.EventType.PRECOMPOSE,frameState);var layerStatesToDraw=[];var layerStatesArray=
frameState.layerStatesArray;ol.array.stableSort(layerStatesArray,ol.renderer.Map.sortByZIndex);var viewResolution=frameState.viewState.resolution;var i,ii,layerRenderer,layerState;for(i=0,ii=layerStatesArray.length;i<ii;++i){layerState=layerStatesArray[i];if(ol.layer.Layer.visibleAtResolution(layerState,viewResolution)&&layerState.sourceState==ol.source.State.READY){layerRenderer=this.getLayerRenderer(layerState.layer);if(layerRenderer.prepareFrame(frameState,layerState,context))layerStatesToDraw.push(layerState)}}var width=
frameState.size[0]*frameState.pixelRatio;var height=frameState.size[1]*frameState.pixelRatio;if(this.canvas_.width!=width||this.canvas_.height!=height){this.canvas_.width=width;this.canvas_.height=height}gl.bindFramebuffer(ol.webgl.FRAMEBUFFER,null);gl.clearColor(0,0,0,0);gl.clear(ol.webgl.COLOR_BUFFER_BIT);gl.enable(ol.webgl.BLEND);gl.viewport(0,0,this.canvas_.width,this.canvas_.height);for(i=0,ii=layerStatesToDraw.length;i<ii;++i){layerState=layerStatesToDraw[i];layerRenderer=this.getLayerRenderer(layerState.layer);
layerRenderer.composeFrame(frameState,layerState,context)}if(!this.renderedVisible_){this.canvas_.style.display="";this.renderedVisible_=true}this.calculateMatrices2D(frameState);if(this.textureCache_.getCount()-this.textureCacheFrameMarkerCount_>ol.WEBGL_TEXTURE_CACHE_HIGH_WATER_MARK)frameState.postRenderFunctions.push(this.expireCache_.bind(this));if(!this.tileTextureQueue_.isEmpty()){frameState.postRenderFunctions.push(this.loadNextTileTexture_);frameState.animate=true}this.dispatchComposeEvent_(ol.render.EventType.POSTCOMPOSE,
frameState);this.scheduleRemoveUnusedLayerRenderers(frameState);this.scheduleExpireIconCache(frameState)};
ol.renderer.webgl.Map.prototype.forEachFeatureAtCoordinate=function(coordinate,frameState,hitTolerance,callback,thisArg,layerFilter,thisArg2){var result;if(this.getGL().isContextLost())return false;var viewState=frameState.viewState;var layerStates=frameState.layerStatesArray;var numLayers=layerStates.length;var i;for(i=numLayers-1;i>=0;--i){var layerState=layerStates[i];var layer=layerState.layer;if(ol.layer.Layer.visibleAtResolution(layerState,viewState.resolution)&&layerFilter.call(thisArg2,layer)){var layerRenderer=
this.getLayerRenderer(layer);result=layerRenderer.forEachFeatureAtCoordinate(coordinate,frameState,hitTolerance,callback,thisArg);if(result)return result}}return undefined};
ol.renderer.webgl.Map.prototype.hasFeatureAtCoordinate=function(coordinate,frameState,hitTolerance,layerFilter,thisArg){var hasFeature=false;if(this.getGL().isContextLost())return false;var viewState=frameState.viewState;var layerStates=frameState.layerStatesArray;var numLayers=layerStates.length;var i;for(i=numLayers-1;i>=0;--i){var layerState=layerStates[i];var layer=layerState.layer;if(ol.layer.Layer.visibleAtResolution(layerState,viewState.resolution)&&layerFilter.call(thisArg,layer)){var layerRenderer=
this.getLayerRenderer(layer);hasFeature=layerRenderer.hasFeatureAtCoordinate(coordinate,frameState);if(hasFeature)return true}}return hasFeature};
ol.renderer.webgl.Map.prototype.forEachLayerAtPixel=function(pixel,frameState,callback,thisArg,layerFilter,thisArg2){if(this.getGL().isContextLost())return false;var viewState=frameState.viewState;var result;var layerStates=frameState.layerStatesArray;var numLayers=layerStates.length;var i;for(i=numLayers-1;i>=0;--i){var layerState=layerStates[i];var layer=layerState.layer;if(ol.layer.Layer.visibleAtResolution(layerState,viewState.resolution)&&layerFilter.call(thisArg,layer)){var layerRenderer=this.getLayerRenderer(layer);
result=layerRenderer.forEachLayerAtPixel(pixel,frameState,callback,thisArg);if(result)return result}}return undefined};goog.provide("ol.renderer.webgl.tilelayershader");goog.require("ol");goog.require("ol.webgl.Fragment");goog.require("ol.webgl.Vertex");ol.renderer.webgl.tilelayershader.fragment=new ol.webgl.Fragment(ol.DEBUG_WEBGL?"precision mediump float;\nvarying vec2 v_texCoord;\n\n\nuniform sampler2D u_texture;\n\nvoid main(void) {\n  gl_FragColor = texture2D(u_texture, v_texCoord);\n}\n":"precision mediump float;varying vec2 a;uniform sampler2D e;void main(void){gl_FragColor=texture2D(e,a);}");
ol.renderer.webgl.tilelayershader.vertex=new ol.webgl.Vertex(ol.DEBUG_WEBGL?"varying vec2 v_texCoord;\n\n\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nuniform vec4 u_tileOffset;\n\nvoid main(void) {\n  gl_Position = vec4(a_position * u_tileOffset.xy + u_tileOffset.zw, 0., 1.);\n  v_texCoord = a_texCoord;\n}\n\n\n":"varying vec2 a;attribute vec2 b;attribute vec2 c;uniform vec4 d;void main(void){gl_Position=vec4(b*d.xy+d.zw,0.,1.);a=c;}");goog.provide("ol.renderer.webgl.tilelayershader.Locations");goog.require("ol");ol.renderer.webgl.tilelayershader.Locations=function(gl,program){this.u_tileOffset=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_tileOffset":"d");this.u_texture=gl.getUniformLocation(program,ol.DEBUG_WEBGL?"u_texture":"e");this.a_position=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_position":"b");this.a_texCoord=gl.getAttribLocation(program,ol.DEBUG_WEBGL?"a_texCoord":"c")};goog.provide("ol.renderer.webgl.TileLayer");goog.require("ol");goog.require("ol.LayerType");goog.require("ol.TileRange");goog.require("ol.TileState");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.math");goog.require("ol.renderer.Type");goog.require("ol.renderer.webgl.Layer");goog.require("ol.renderer.webgl.tilelayershader");goog.require("ol.renderer.webgl.tilelayershader.Locations");goog.require("ol.size");goog.require("ol.transform");goog.require("ol.webgl");goog.require("ol.webgl.Buffer");
ol.renderer.webgl.TileLayer=function(mapRenderer,tileLayer){ol.renderer.webgl.Layer.call(this,mapRenderer,tileLayer);this.fragmentShader_=ol.renderer.webgl.tilelayershader.fragment;this.vertexShader_=ol.renderer.webgl.tilelayershader.vertex;this.locations_=null;this.renderArrayBuffer_=new ol.webgl.Buffer([0,0,0,1,1,0,1,1,0,1,0,0,1,1,1,0]);this.renderedTileRange_=null;this.renderedFramebufferExtent_=null;this.renderedRevision_=-1;this.tmpSize_=[0,0]};ol.inherits(ol.renderer.webgl.TileLayer,ol.renderer.webgl.Layer);
ol.renderer.webgl.TileLayer["handles"]=function(type,layer){return type===ol.renderer.Type.WEBGL&&layer.getType()===ol.LayerType.TILE};ol.renderer.webgl.TileLayer["create"]=function(mapRenderer,layer){return new ol.renderer.webgl.TileLayer(mapRenderer,layer)};ol.renderer.webgl.TileLayer.prototype.disposeInternal=function(){var context=this.mapRenderer.getContext();context.deleteBuffer(this.renderArrayBuffer_);ol.renderer.webgl.Layer.prototype.disposeInternal.call(this)};
ol.renderer.webgl.TileLayer.prototype.createLoadedTileFinder=function(source,projection,tiles){var mapRenderer=this.mapRenderer;return function(zoom,tileRange){function callback(tile){var loaded=mapRenderer.isTileTextureLoaded(tile);if(loaded){if(!tiles[zoom])tiles[zoom]={};tiles[zoom][tile.tileCoord.toString()]=tile}return loaded}return source.forEachLoadedTile(projection,zoom,tileRange,callback)}};
ol.renderer.webgl.TileLayer.prototype.handleWebGLContextLost=function(){ol.renderer.webgl.Layer.prototype.handleWebGLContextLost.call(this);this.locations_=null};
ol.renderer.webgl.TileLayer.prototype.prepareFrame=function(frameState,layerState,context){var mapRenderer=this.mapRenderer;var gl=context.getGL();var viewState=frameState.viewState;var projection=viewState.projection;var tileLayer=this.getLayer();var tileSource=tileLayer.getSource();var tileGrid=tileSource.getTileGridForProjection(projection);var z=tileGrid.getZForResolution(viewState.resolution);var tileResolution=tileGrid.getResolution(z);var tilePixelSize=tileSource.getTilePixelSize(z,frameState.pixelRatio,
projection);var pixelRatio=tilePixelSize[0]/ol.size.toSize(tileGrid.getTileSize(z),this.tmpSize_)[0];var tilePixelResolution=tileResolution/pixelRatio;var tileGutter=tileSource.getTilePixelRatio(pixelRatio)*tileSource.getGutter(projection);var center=viewState.center;var extent=frameState.extent;var tileRange=tileGrid.getTileRangeForExtentAndZ(extent,z);var framebufferExtent;if(this.renderedTileRange_&&this.renderedTileRange_.equals(tileRange)&&this.renderedRevision_==tileSource.getRevision())framebufferExtent=
this.renderedFramebufferExtent_;else{var tileRangeSize=tileRange.getSize();var maxDimension=Math.max(tileRangeSize[0]*tilePixelSize[0],tileRangeSize[1]*tilePixelSize[1]);var framebufferDimension=ol.math.roundUpToPowerOfTwo(maxDimension);var framebufferExtentDimension=tilePixelResolution*framebufferDimension;var origin=tileGrid.getOrigin(z);var minX=origin[0]+tileRange.minX*tilePixelSize[0]*tilePixelResolution;var minY=origin[1]+tileRange.minY*tilePixelSize[1]*tilePixelResolution;framebufferExtent=
[minX,minY,minX+framebufferExtentDimension,minY+framebufferExtentDimension];this.bindFramebuffer(frameState,framebufferDimension);gl.viewport(0,0,framebufferDimension,framebufferDimension);gl.clearColor(0,0,0,0);gl.clear(ol.webgl.COLOR_BUFFER_BIT);gl.disable(ol.webgl.BLEND);var program=context.getProgram(this.fragmentShader_,this.vertexShader_);context.useProgram(program);if(!this.locations_)this.locations_=new ol.renderer.webgl.tilelayershader.Locations(gl,program);context.bindBuffer(ol.webgl.ARRAY_BUFFER,
this.renderArrayBuffer_);gl.enableVertexAttribArray(this.locations_.a_position);gl.vertexAttribPointer(this.locations_.a_position,2,ol.webgl.FLOAT,false,16,0);gl.enableVertexAttribArray(this.locations_.a_texCoord);gl.vertexAttribPointer(this.locations_.a_texCoord,2,ol.webgl.FLOAT,false,16,8);gl.uniform1i(this.locations_.u_texture,0);var tilesToDrawByZ={};tilesToDrawByZ[z]={};var findLoadedTiles=this.createLoadedTileFinder(tileSource,projection,tilesToDrawByZ);var useInterimTilesOnError=tileLayer.getUseInterimTilesOnError();
var allTilesLoaded=true;var tmpExtent=ol.extent.createEmpty();var tmpTileRange=new ol.TileRange(0,0,0,0);var childTileRange,drawable,fullyLoaded,tile,tileState;var x,y,tileExtent;for(x=tileRange.minX;x<=tileRange.maxX;++x)for(y=tileRange.minY;y<=tileRange.maxY;++y){tile=tileSource.getTile(z,x,y,pixelRatio,projection);if(layerState.extent!==undefined){tileExtent=tileGrid.getTileCoordExtent(tile.tileCoord,tmpExtent);if(!ol.extent.intersects(tileExtent,layerState.extent))continue}tileState=tile.getState();
drawable=tileState==ol.TileState.LOADED||tileState==ol.TileState.EMPTY||tileState==ol.TileState.ERROR&&!useInterimTilesOnError;if(!drawable)tile=tile.getInterimTile();tileState=tile.getState();if(tileState==ol.TileState.LOADED){if(mapRenderer.isTileTextureLoaded(tile)){tilesToDrawByZ[z][tile.tileCoord.toString()]=tile;continue}}else if(tileState==ol.TileState.EMPTY||tileState==ol.TileState.ERROR&&!useInterimTilesOnError)continue;allTilesLoaded=false;fullyLoaded=tileGrid.forEachTileCoordParentTileRange(tile.tileCoord,
findLoadedTiles,null,tmpTileRange,tmpExtent);if(!fullyLoaded){childTileRange=tileGrid.getTileCoordChildTileRange(tile.tileCoord,tmpTileRange,tmpExtent);if(childTileRange)findLoadedTiles(z+1,childTileRange)}}var zs=Object.keys(tilesToDrawByZ).map(Number);zs.sort(ol.array.numberSafeCompareFunction);var u_tileOffset=new Float32Array(4);var i,ii,tileKey,tilesToDraw;for(i=0,ii=zs.length;i<ii;++i){tilesToDraw=tilesToDrawByZ[zs[i]];for(tileKey in tilesToDraw){tile=tilesToDraw[tileKey];tileExtent=tileGrid.getTileCoordExtent(tile.tileCoord,
tmpExtent);u_tileOffset[0]=2*(tileExtent[2]-tileExtent[0])/framebufferExtentDimension;u_tileOffset[1]=2*(tileExtent[3]-tileExtent[1])/framebufferExtentDimension;u_tileOffset[2]=2*(tileExtent[0]-framebufferExtent[0])/framebufferExtentDimension-1;u_tileOffset[3]=2*(tileExtent[1]-framebufferExtent[1])/framebufferExtentDimension-1;gl.uniform4fv(this.locations_.u_tileOffset,u_tileOffset);mapRenderer.bindTileTexture(tile,tilePixelSize,tileGutter*pixelRatio,ol.webgl.LINEAR,ol.webgl.LINEAR);gl.drawArrays(ol.webgl.TRIANGLE_STRIP,
0,4)}}if(allTilesLoaded){this.renderedTileRange_=tileRange;this.renderedFramebufferExtent_=framebufferExtent;this.renderedRevision_=tileSource.getRevision()}else{this.renderedTileRange_=null;this.renderedFramebufferExtent_=null;this.renderedRevision_=-1;frameState.animate=true}}this.updateUsedTiles(frameState.usedTiles,tileSource,z,tileRange);var tileTextureQueue=mapRenderer.getTileTextureQueue();this.manageTilePyramid(frameState,tileSource,tileGrid,pixelRatio,projection,extent,z,tileLayer.getPreload(),
function(tile){if(tile.getState()==ol.TileState.LOADED&&!mapRenderer.isTileTextureLoaded(tile)&&!tileTextureQueue.isKeyQueued(tile.getKey()))tileTextureQueue.enqueue([tile,tileGrid.getTileCoordCenter(tile.tileCoord),tileGrid.getResolution(tile.tileCoord[0]),tilePixelSize,tileGutter*pixelRatio])},this);this.scheduleExpireCache(frameState,tileSource);this.updateLogos(frameState,tileSource);var texCoordMatrix=this.texCoordMatrix;ol.transform.reset(texCoordMatrix);ol.transform.translate(texCoordMatrix,
(Math.round(center[0]/tileResolution)*tileResolution-framebufferExtent[0])/(framebufferExtent[2]-framebufferExtent[0]),(Math.round(center[1]/tileResolution)*tileResolution-framebufferExtent[1])/(framebufferExtent[3]-framebufferExtent[1]));if(viewState.rotation!==0)ol.transform.rotate(texCoordMatrix,viewState.rotation);ol.transform.scale(texCoordMatrix,frameState.size[0]*viewState.resolution/(framebufferExtent[2]-framebufferExtent[0]),frameState.size[1]*viewState.resolution/(framebufferExtent[3]-framebufferExtent[1]));
ol.transform.translate(texCoordMatrix,-.5,-.5);return true};
ol.renderer.webgl.TileLayer.prototype.forEachLayerAtPixel=function(pixel,frameState,callback,thisArg){if(!this.framebuffer)return undefined;var pixelOnMapScaled=[pixel[0]/frameState.size[0],(frameState.size[1]-pixel[1])/frameState.size[1]];var pixelOnFrameBufferScaled=ol.transform.apply(this.texCoordMatrix,pixelOnMapScaled.slice());var pixelOnFrameBuffer=[pixelOnFrameBufferScaled[0]*this.framebufferDimension,pixelOnFrameBufferScaled[1]*this.framebufferDimension];var gl=this.mapRenderer.getContext().getGL();
gl.bindFramebuffer(gl.FRAMEBUFFER,this.framebuffer);var imageData=new Uint8Array(4);gl.readPixels(pixelOnFrameBuffer[0],pixelOnFrameBuffer[1],1,1,gl.RGBA,gl.UNSIGNED_BYTE,imageData);if(imageData[3]>0)return callback.call(thisArg,this.getLayer(),imageData);else return undefined};goog.provide("ol.renderer.webgl.VectorLayer");goog.require("ol");goog.require("ol.LayerType");goog.require("ol.ViewHint");goog.require("ol.extent");goog.require("ol.render.webgl.ReplayGroup");goog.require("ol.renderer.Type");goog.require("ol.renderer.vector");goog.require("ol.renderer.webgl.Layer");goog.require("ol.transform");
ol.renderer.webgl.VectorLayer=function(mapRenderer,vectorLayer){ol.renderer.webgl.Layer.call(this,mapRenderer,vectorLayer);this.dirty_=false;this.renderedRevision_=-1;this.renderedResolution_=NaN;this.renderedExtent_=ol.extent.createEmpty();this.renderedRenderOrder_=null;this.replayGroup_=null;this.layerState_=null};ol.inherits(ol.renderer.webgl.VectorLayer,ol.renderer.webgl.Layer);
ol.renderer.webgl.VectorLayer["handles"]=function(type,layer){return type===ol.renderer.Type.WEBGL&&layer.getType()===ol.LayerType.VECTOR};ol.renderer.webgl.VectorLayer["create"]=function(mapRenderer,layer){return new ol.renderer.webgl.VectorLayer(mapRenderer,layer)};
ol.renderer.webgl.VectorLayer.prototype.composeFrame=function(frameState,layerState,context){this.layerState_=layerState;var viewState=frameState.viewState;var replayGroup=this.replayGroup_;var size=frameState.size;var pixelRatio=frameState.pixelRatio;var gl=this.mapRenderer.getGL();if(replayGroup&&!replayGroup.isEmpty()){gl.enable(gl.SCISSOR_TEST);gl.scissor(0,0,size[0]*pixelRatio,size[1]*pixelRatio);replayGroup.replay(context,viewState.center,viewState.resolution,viewState.rotation,size,pixelRatio,
layerState.opacity,layerState.managed?frameState.skippedFeatureUids:{});gl.disable(gl.SCISSOR_TEST)}};ol.renderer.webgl.VectorLayer.prototype.disposeInternal=function(){var replayGroup=this.replayGroup_;if(replayGroup){var context=this.mapRenderer.getContext();replayGroup.getDeleteResourcesFunction(context)();this.replayGroup_=null}ol.renderer.webgl.Layer.prototype.disposeInternal.call(this)};
ol.renderer.webgl.VectorLayer.prototype.forEachFeatureAtCoordinate=function(coordinate,frameState,hitTolerance,callback,thisArg){if(!this.replayGroup_||!this.layerState_)return undefined;else{var context=this.mapRenderer.getContext();var viewState=frameState.viewState;var layer=this.getLayer();var layerState=this.layerState_;var features={};return this.replayGroup_.forEachFeatureAtCoordinate(coordinate,context,viewState.center,viewState.resolution,viewState.rotation,frameState.size,frameState.pixelRatio,
layerState.opacity,{},function(feature){var key=ol.getUid(feature).toString();if(!(key in features)){features[key]=true;return callback.call(thisArg,feature,layer)}})}};
ol.renderer.webgl.VectorLayer.prototype.hasFeatureAtCoordinate=function(coordinate,frameState){if(!this.replayGroup_||!this.layerState_)return false;else{var context=this.mapRenderer.getContext();var viewState=frameState.viewState;var layerState=this.layerState_;return this.replayGroup_.hasFeatureAtCoordinate(coordinate,context,viewState.center,viewState.resolution,viewState.rotation,frameState.size,frameState.pixelRatio,layerState.opacity,frameState.skippedFeatureUids)}};
ol.renderer.webgl.VectorLayer.prototype.forEachLayerAtPixel=function(pixel,frameState,callback,thisArg){var coordinate=ol.transform.apply(frameState.pixelToCoordinateTransform,pixel.slice());var hasFeature=this.hasFeatureAtCoordinate(coordinate,frameState);if(hasFeature)return callback.call(thisArg,this.getLayer(),null);else return undefined};ol.renderer.webgl.VectorLayer.prototype.handleStyleImageChange_=function(event){this.renderIfReadyAndVisible()};
ol.renderer.webgl.VectorLayer.prototype.prepareFrame=function(frameState,layerState,context){var vectorLayer=this.getLayer();var vectorSource=vectorLayer.getSource();this.updateLogos(frameState,vectorSource);var animating=frameState.viewHints[ol.ViewHint.ANIMATING];var interacting=frameState.viewHints[ol.ViewHint.INTERACTING];var updateWhileAnimating=vectorLayer.getUpdateWhileAnimating();var updateWhileInteracting=vectorLayer.getUpdateWhileInteracting();if(!this.dirty_&&(!updateWhileAnimating&&animating)||
!updateWhileInteracting&&interacting)return true;var frameStateExtent=frameState.extent;var viewState=frameState.viewState;var projection=viewState.projection;var resolution=viewState.resolution;var pixelRatio=frameState.pixelRatio;var vectorLayerRevision=vectorLayer.getRevision();var vectorLayerRenderBuffer=vectorLayer.getRenderBuffer();var vectorLayerRenderOrder=vectorLayer.getRenderOrder();if(vectorLayerRenderOrder===undefined)vectorLayerRenderOrder=ol.renderer.vector.defaultOrder;var extent=ol.extent.buffer(frameStateExtent,
vectorLayerRenderBuffer*resolution);if(!this.dirty_&&this.renderedResolution_==resolution&&this.renderedRevision_==vectorLayerRevision&&this.renderedRenderOrder_==vectorLayerRenderOrder&&ol.extent.containsExtent(this.renderedExtent_,extent))return true;if(this.replayGroup_)frameState.postRenderFunctions.push(this.replayGroup_.getDeleteResourcesFunction(context));this.dirty_=false;var replayGroup=new ol.render.webgl.ReplayGroup(ol.renderer.vector.getTolerance(resolution,pixelRatio),extent,vectorLayer.getRenderBuffer());
vectorSource.loadFeatures(extent,resolution,projection);var renderFeature=function(feature){var styles;var styleFunction=feature.getStyleFunction();if(styleFunction)styles=styleFunction.call(feature,resolution);else{styleFunction=vectorLayer.getStyleFunction();if(styleFunction)styles=styleFunction(feature,resolution)}if(styles){var dirty=this.renderFeature(feature,resolution,pixelRatio,styles,replayGroup);this.dirty_=this.dirty_||dirty}};if(vectorLayerRenderOrder){var features=[];vectorSource.forEachFeatureInExtent(extent,
function(feature){features.push(feature)},this);features.sort(vectorLayerRenderOrder);features.forEach(renderFeature,this)}else vectorSource.forEachFeatureInExtent(extent,renderFeature,this);replayGroup.finish(context);this.renderedResolution_=resolution;this.renderedRevision_=vectorLayerRevision;this.renderedRenderOrder_=vectorLayerRenderOrder;this.renderedExtent_=extent;this.replayGroup_=replayGroup;return true};
ol.renderer.webgl.VectorLayer.prototype.renderFeature=function(feature,resolution,pixelRatio,styles,replayGroup){if(!styles)return false;var loading=false;if(Array.isArray(styles))for(var i=styles.length-1,ii=0;i>=ii;--i)loading=ol.renderer.vector.renderFeature(replayGroup,feature,styles[i],ol.renderer.vector.getSquaredTolerance(resolution,pixelRatio),this.handleStyleImageChange_,this)||loading;else loading=ol.renderer.vector.renderFeature(replayGroup,feature,styles,ol.renderer.vector.getSquaredTolerance(resolution,
pixelRatio),this.handleStyleImageChange_,this)||loading;return loading};goog.provide("ol.Map");goog.require("ol");goog.require("ol.PluggableMap");goog.require("ol.PluginType");goog.require("ol.control");goog.require("ol.interaction");goog.require("ol.obj");goog.require("ol.plugins");goog.require("ol.renderer.canvas.ImageLayer");goog.require("ol.renderer.canvas.Map");goog.require("ol.renderer.canvas.TileLayer");goog.require("ol.renderer.canvas.VectorLayer");goog.require("ol.renderer.canvas.VectorTileLayer");goog.require("ol.renderer.webgl.ImageLayer");goog.require("ol.renderer.webgl.Map");
goog.require("ol.renderer.webgl.TileLayer");goog.require("ol.renderer.webgl.VectorLayer");if(ol.ENABLE_CANVAS){ol.plugins.register(ol.PluginType.MAP_RENDERER,ol.renderer.canvas.Map);ol.plugins.registerMultiple(ol.PluginType.LAYER_RENDERER,[ol.renderer.canvas.ImageLayer,ol.renderer.canvas.TileLayer,ol.renderer.canvas.VectorLayer,ol.renderer.canvas.VectorTileLayer])}
if(ol.ENABLE_WEBGL){ol.plugins.register(ol.PluginType.MAP_RENDERER,ol.renderer.webgl.Map);ol.plugins.registerMultiple(ol.PluginType.LAYER_RENDERER,[ol.renderer.webgl.ImageLayer,ol.renderer.webgl.TileLayer,ol.renderer.webgl.VectorLayer])}ol.Map=function(options){options=ol.obj.assign({},options);if(!options.controls)options.controls=ol.control.defaults();if(!options.interactions)options.interactions=ol.interaction.defaults();ol.PluggableMap.call(this,options)};ol.inherits(ol.Map,ol.PluggableMap);goog.provide("ol.net");goog.require("ol");
ol.net.jsonp=function(url,callback,opt_errback,opt_callbackParam){var script=document.createElement("script");var key="olc_"+ol.getUid(callback);function cleanup(){delete window[key];script.parentNode.removeChild(script)}script.async=true;script.src=url+(url.indexOf("?")==-1?"?":"&")+(opt_callbackParam||"callback")+"="+key;var timer=setTimeout(function(){cleanup();if(opt_errback)opt_errback()},1E4);window[key]=function(data){clearTimeout(timer);cleanup();callback(data)};document.getElementsByTagName("head")[0].appendChild(script)};goog.provide("ol.proj.common");goog.require("ol.proj");ol.proj.common.add=ol.proj.addCommon;goog.provide("ol.render");goog.require("ol.has");goog.require("ol.transform");goog.require("ol.render.canvas.Immediate");
ol.render.toContext=function(context,opt_options){var canvas=context.canvas;var options=opt_options?opt_options:{};var pixelRatio=options.pixelRatio||ol.has.DEVICE_PIXEL_RATIO;var size=options.size;if(size){canvas.width=size[0]*pixelRatio;canvas.height=size[1]*pixelRatio;canvas.style.width=size[0]+"px";canvas.style.height=size[1]+"px"}var extent=[0,0,canvas.width,canvas.height];var transform=ol.transform.scale(ol.transform.create(),pixelRatio,pixelRatio);return new ol.render.canvas.Immediate(context,
pixelRatio,extent,transform,0)};goog.provide("ol.reproj");goog.require("ol.dom");goog.require("ol.extent");goog.require("ol.math");goog.require("ol.proj");
ol.reproj.calculateSourceResolution=function(sourceProj,targetProj,targetCenter,targetResolution){var sourceCenter=ol.proj.transform(targetCenter,targetProj,sourceProj);var sourceResolution=ol.proj.getPointResolution(targetProj,targetResolution,targetCenter);var targetMetersPerUnit=targetProj.getMetersPerUnit();if(targetMetersPerUnit!==undefined)sourceResolution*=targetMetersPerUnit;var sourceMetersPerUnit=sourceProj.getMetersPerUnit();if(sourceMetersPerUnit!==undefined)sourceResolution/=sourceMetersPerUnit;
var sourceExtent=sourceProj.getExtent();if(!sourceExtent||ol.extent.containsCoordinate(sourceExtent,sourceCenter)){var compensationFactor=ol.proj.getPointResolution(sourceProj,sourceResolution,sourceCenter)/sourceResolution;if(isFinite(compensationFactor)&&compensationFactor>0)sourceResolution/=compensationFactor}return sourceResolution};
ol.reproj.enlargeClipPoint_=function(centroidX,centroidY,x,y){var dX=x-centroidX,dY=y-centroidY;var distance=Math.sqrt(dX*dX+dY*dY);return[Math.round(x+dX/distance),Math.round(y+dY/distance)]};
ol.reproj.render=function(width,height,pixelRatio,sourceResolution,sourceExtent,targetResolution,targetExtent,triangulation,sources,gutter,opt_renderEdges){var context=ol.dom.createCanvasContext2D(Math.round(pixelRatio*width),Math.round(pixelRatio*height));if(sources.length===0)return context.canvas;context.scale(pixelRatio,pixelRatio);var sourceDataExtent=ol.extent.createEmpty();sources.forEach(function(src,i,arr){ol.extent.extend(sourceDataExtent,src.extent)});var canvasWidthInUnits=ol.extent.getWidth(sourceDataExtent);
var canvasHeightInUnits=ol.extent.getHeight(sourceDataExtent);var stitchContext=ol.dom.createCanvasContext2D(Math.round(pixelRatio*canvasWidthInUnits/sourceResolution),Math.round(pixelRatio*canvasHeightInUnits/sourceResolution));var stitchScale=pixelRatio/sourceResolution;sources.forEach(function(src,i,arr){var xPos=src.extent[0]-sourceDataExtent[0];var yPos=-(src.extent[3]-sourceDataExtent[3]);var srcWidth=ol.extent.getWidth(src.extent);var srcHeight=ol.extent.getHeight(src.extent);stitchContext.drawImage(src.image,
gutter,gutter,src.image.width-2*gutter,src.image.height-2*gutter,xPos*stitchScale,yPos*stitchScale,srcWidth*stitchScale,srcHeight*stitchScale)});var targetTopLeft=ol.extent.getTopLeft(targetExtent);triangulation.getTriangles().forEach(function(triangle,i,arr){var source=triangle.source,target=triangle.target;var x0=source[0][0],y0=source[0][1],x1=source[1][0],y1=source[1][1],x2=source[2][0],y2=source[2][1];var u0=(target[0][0]-targetTopLeft[0])/targetResolution,v0=-(target[0][1]-targetTopLeft[1])/
targetResolution;var u1=(target[1][0]-targetTopLeft[0])/targetResolution,v1=-(target[1][1]-targetTopLeft[1])/targetResolution;var u2=(target[2][0]-targetTopLeft[0])/targetResolution,v2=-(target[2][1]-targetTopLeft[1])/targetResolution;var sourceNumericalShiftX=x0,sourceNumericalShiftY=y0;x0=0;y0=0;x1-=sourceNumericalShiftX;y1-=sourceNumericalShiftY;x2-=sourceNumericalShiftX;y2-=sourceNumericalShiftY;var augmentedMatrix=[[x1,y1,0,0,u1-u0],[x2,y2,0,0,u2-u0],[0,0,x1,y1,v1-v0],[0,0,x2,y2,v2-v0]];var affineCoefs=
ol.math.solveLinearSystem(augmentedMatrix);if(!affineCoefs)return;context.save();context.beginPath();var centroidX=(u0+u1+u2)/3,centroidY=(v0+v1+v2)/3;var p0=ol.reproj.enlargeClipPoint_(centroidX,centroidY,u0,v0);var p1=ol.reproj.enlargeClipPoint_(centroidX,centroidY,u1,v1);var p2=ol.reproj.enlargeClipPoint_(centroidX,centroidY,u2,v2);context.moveTo(p1[0],p1[1]);context.lineTo(p0[0],p0[1]);context.lineTo(p2[0],p2[1]);context.clip();context.transform(affineCoefs[0],affineCoefs[2],affineCoefs[1],affineCoefs[3],
u0,v0);context.translate(sourceDataExtent[0]-sourceNumericalShiftX,sourceDataExtent[3]-sourceNumericalShiftY);context.scale(sourceResolution/pixelRatio,-sourceResolution/pixelRatio);context.drawImage(stitchContext.canvas,0,0);context.restore()});if(opt_renderEdges){context.save();context.strokeStyle="black";context.lineWidth=1;triangulation.getTriangles().forEach(function(triangle,i,arr){var target=triangle.target;var u0=(target[0][0]-targetTopLeft[0])/targetResolution,v0=-(target[0][1]-targetTopLeft[1])/
targetResolution;var u1=(target[1][0]-targetTopLeft[0])/targetResolution,v1=-(target[1][1]-targetTopLeft[1])/targetResolution;var u2=(target[2][0]-targetTopLeft[0])/targetResolution,v2=-(target[2][1]-targetTopLeft[1])/targetResolution;context.beginPath();context.moveTo(u1,v1);context.lineTo(u0,v0);context.lineTo(u2,v2);context.closePath();context.stroke()});context.restore()}return context.canvas};goog.provide("ol.reproj.Triangulation");goog.require("ol");goog.require("ol.extent");goog.require("ol.math");goog.require("ol.proj");
ol.reproj.Triangulation=function(sourceProj,targetProj,targetExtent,maxSourceExtent,errorThreshold){this.sourceProj_=sourceProj;this.targetProj_=targetProj;var transformInvCache={};var transformInv=ol.proj.getTransform(this.targetProj_,this.sourceProj_);this.transformInv_=function(c){var key=c[0]+"/"+c[1];if(!transformInvCache[key])transformInvCache[key]=transformInv(c);return transformInvCache[key]};this.maxSourceExtent_=maxSourceExtent;this.errorThresholdSquared_=errorThreshold*errorThreshold;this.triangles_=
[];this.wrapsXInSource_=false;this.canWrapXInSource_=this.sourceProj_.canWrapX()&&!!maxSourceExtent&&!!this.sourceProj_.getExtent()&&ol.extent.getWidth(maxSourceExtent)==ol.extent.getWidth(this.sourceProj_.getExtent());this.sourceWorldWidth_=this.sourceProj_.getExtent()?ol.extent.getWidth(this.sourceProj_.getExtent()):null;this.targetWorldWidth_=this.targetProj_.getExtent()?ol.extent.getWidth(this.targetProj_.getExtent()):null;var destinationTopLeft=ol.extent.getTopLeft(targetExtent);var destinationTopRight=
ol.extent.getTopRight(targetExtent);var destinationBottomRight=ol.extent.getBottomRight(targetExtent);var destinationBottomLeft=ol.extent.getBottomLeft(targetExtent);var sourceTopLeft=this.transformInv_(destinationTopLeft);var sourceTopRight=this.transformInv_(destinationTopRight);var sourceBottomRight=this.transformInv_(destinationBottomRight);var sourceBottomLeft=this.transformInv_(destinationBottomLeft);this.addQuad_(destinationTopLeft,destinationTopRight,destinationBottomRight,destinationBottomLeft,
sourceTopLeft,sourceTopRight,sourceBottomRight,sourceBottomLeft,ol.RASTER_REPROJECTION_MAX_SUBDIVISION);if(this.wrapsXInSource_){var leftBound=Infinity;this.triangles_.forEach(function(triangle,i,arr){leftBound=Math.min(leftBound,triangle.source[0][0],triangle.source[1][0],triangle.source[2][0])});this.triangles_.forEach(function(triangle){if(Math.max(triangle.source[0][0],triangle.source[1][0],triangle.source[2][0])-leftBound>this.sourceWorldWidth_/2){var newTriangle=[[triangle.source[0][0],triangle.source[0][1]],
[triangle.source[1][0],triangle.source[1][1]],[triangle.source[2][0],triangle.source[2][1]]];if(newTriangle[0][0]-leftBound>this.sourceWorldWidth_/2)newTriangle[0][0]-=this.sourceWorldWidth_;if(newTriangle[1][0]-leftBound>this.sourceWorldWidth_/2)newTriangle[1][0]-=this.sourceWorldWidth_;if(newTriangle[2][0]-leftBound>this.sourceWorldWidth_/2)newTriangle[2][0]-=this.sourceWorldWidth_;var minX=Math.min(newTriangle[0][0],newTriangle[1][0],newTriangle[2][0]);var maxX=Math.max(newTriangle[0][0],newTriangle[1][0],
newTriangle[2][0]);if(maxX-minX<this.sourceWorldWidth_/2)triangle.source=newTriangle}},this)}transformInvCache={}};ol.reproj.Triangulation.prototype.addTriangle_=function(a,b,c,aSrc,bSrc,cSrc){this.triangles_.push({source:[aSrc,bSrc,cSrc],target:[a,b,c]})};
ol.reproj.Triangulation.prototype.addQuad_=function(a,b,c,d,aSrc,bSrc,cSrc,dSrc,maxSubdivision){var sourceQuadExtent=ol.extent.boundingExtent([aSrc,bSrc,cSrc,dSrc]);var sourceCoverageX=this.sourceWorldWidth_?ol.extent.getWidth(sourceQuadExtent)/this.sourceWorldWidth_:null;var sourceWorldWidth=this.sourceWorldWidth_;var wrapsX=this.sourceProj_.canWrapX()&&sourceCoverageX>.5&&sourceCoverageX<1;var needsSubdivision=false;if(maxSubdivision>0){if(this.targetProj_.isGlobal()&&this.targetWorldWidth_){var targetQuadExtent=
ol.extent.boundingExtent([a,b,c,d]);var targetCoverageX=ol.extent.getWidth(targetQuadExtent)/this.targetWorldWidth_;needsSubdivision|=targetCoverageX>ol.RASTER_REPROJECTION_MAX_TRIANGLE_WIDTH}if(!wrapsX&&this.sourceProj_.isGlobal()&&sourceCoverageX)needsSubdivision|=sourceCoverageX>ol.RASTER_REPROJECTION_MAX_TRIANGLE_WIDTH}if(!needsSubdivision&&this.maxSourceExtent_)if(!ol.extent.intersects(sourceQuadExtent,this.maxSourceExtent_))return;if(!needsSubdivision)if(!isFinite(aSrc[0])||!isFinite(aSrc[1])||
!isFinite(bSrc[0])||!isFinite(bSrc[1])||!isFinite(cSrc[0])||!isFinite(cSrc[1])||!isFinite(dSrc[0])||!isFinite(dSrc[1]))if(maxSubdivision>0)needsSubdivision=true;else return;if(maxSubdivision>0){if(!needsSubdivision){var center=[(a[0]+c[0])/2,(a[1]+c[1])/2];var centerSrc=this.transformInv_(center);var dx;if(wrapsX){var centerSrcEstimX=(ol.math.modulo(aSrc[0],sourceWorldWidth)+ol.math.modulo(cSrc[0],sourceWorldWidth))/2;dx=centerSrcEstimX-ol.math.modulo(centerSrc[0],sourceWorldWidth)}else dx=(aSrc[0]+
cSrc[0])/2-centerSrc[0];var dy=(aSrc[1]+cSrc[1])/2-centerSrc[1];var centerSrcErrorSquared=dx*dx+dy*dy;needsSubdivision=centerSrcErrorSquared>this.errorThresholdSquared_}if(needsSubdivision){if(Math.abs(a[0]-c[0])<=Math.abs(a[1]-c[1])){var bc=[(b[0]+c[0])/2,(b[1]+c[1])/2];var bcSrc=this.transformInv_(bc);var da=[(d[0]+a[0])/2,(d[1]+a[1])/2];var daSrc=this.transformInv_(da);this.addQuad_(a,b,bc,da,aSrc,bSrc,bcSrc,daSrc,maxSubdivision-1);this.addQuad_(da,bc,c,d,daSrc,bcSrc,cSrc,dSrc,maxSubdivision-1)}else{var ab=
[(a[0]+b[0])/2,(a[1]+b[1])/2];var abSrc=this.transformInv_(ab);var cd=[(c[0]+d[0])/2,(c[1]+d[1])/2];var cdSrc=this.transformInv_(cd);this.addQuad_(a,ab,cd,d,aSrc,abSrc,cdSrc,dSrc,maxSubdivision-1);this.addQuad_(ab,b,c,cd,abSrc,bSrc,cSrc,cdSrc,maxSubdivision-1)}return}}if(wrapsX){if(!this.canWrapXInSource_)return;this.wrapsXInSource_=true}this.addTriangle_(a,c,d,aSrc,cSrc,dSrc);this.addTriangle_(a,b,c,aSrc,bSrc,cSrc)};
ol.reproj.Triangulation.prototype.calculateSourceExtent=function(){var extent=ol.extent.createEmpty();this.triangles_.forEach(function(triangle,i,arr){var src=triangle.source;ol.extent.extendCoordinate(extent,src[0]);ol.extent.extendCoordinate(extent,src[1]);ol.extent.extendCoordinate(extent,src[2])});return extent};ol.reproj.Triangulation.prototype.getTriangles=function(){return this.triangles_};goog.provide("ol.reproj.Image");goog.require("ol");goog.require("ol.ImageBase");goog.require("ol.ImageState");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.reproj");goog.require("ol.reproj.Triangulation");
ol.reproj.Image=function(sourceProj,targetProj,targetExtent,targetResolution,pixelRatio,getImageFunction){this.targetProj_=targetProj;this.maxSourceExtent_=sourceProj.getExtent();var maxTargetExtent=targetProj.getExtent();var limitedTargetExtent=maxTargetExtent?ol.extent.getIntersection(targetExtent,maxTargetExtent):targetExtent;var targetCenter=ol.extent.getCenter(limitedTargetExtent);var sourceResolution=ol.reproj.calculateSourceResolution(sourceProj,targetProj,targetCenter,targetResolution);var errorThresholdInPixels=
ol.DEFAULT_RASTER_REPROJECTION_ERROR_THRESHOLD;this.triangulation_=new ol.reproj.Triangulation(sourceProj,targetProj,limitedTargetExtent,this.maxSourceExtent_,sourceResolution*errorThresholdInPixels);this.targetResolution_=targetResolution;this.targetExtent_=targetExtent;var sourceExtent=this.triangulation_.calculateSourceExtent();this.sourceImage_=getImageFunction(sourceExtent,sourceResolution,pixelRatio);this.sourcePixelRatio_=this.sourceImage_?this.sourceImage_.getPixelRatio():1;this.canvas_=null;
this.sourceListenerKey_=null;var state=ol.ImageState.LOADED;if(this.sourceImage_)state=ol.ImageState.IDLE;ol.ImageBase.call(this,targetExtent,targetResolution,this.sourcePixelRatio_,state)};ol.inherits(ol.reproj.Image,ol.ImageBase);ol.reproj.Image.prototype.disposeInternal=function(){if(this.state==ol.ImageState.LOADING)this.unlistenSource_();ol.ImageBase.prototype.disposeInternal.call(this)};ol.reproj.Image.prototype.getImage=function(){return this.canvas_};
ol.reproj.Image.prototype.getProjection=function(){return this.targetProj_};
ol.reproj.Image.prototype.reproject_=function(){var sourceState=this.sourceImage_.getState();if(sourceState==ol.ImageState.LOADED){var width=ol.extent.getWidth(this.targetExtent_)/this.targetResolution_;var height=ol.extent.getHeight(this.targetExtent_)/this.targetResolution_;this.canvas_=ol.reproj.render(width,height,this.sourcePixelRatio_,this.sourceImage_.getResolution(),this.maxSourceExtent_,this.targetResolution_,this.targetExtent_,this.triangulation_,[{extent:this.sourceImage_.getExtent(),image:this.sourceImage_.getImage()}],
0)}this.state=sourceState;this.changed()};
ol.reproj.Image.prototype.load=function(){if(this.state==ol.ImageState.IDLE){this.state=ol.ImageState.LOADING;this.changed();var sourceState=this.sourceImage_.getState();if(sourceState==ol.ImageState.LOADED||sourceState==ol.ImageState.ERROR)this.reproject_();else{this.sourceListenerKey_=ol.events.listen(this.sourceImage_,ol.events.EventType.CHANGE,function(e){var sourceState=this.sourceImage_.getState();if(sourceState==ol.ImageState.LOADED||sourceState==ol.ImageState.ERROR){this.unlistenSource_();this.reproject_()}},
this);this.sourceImage_.load()}}};ol.reproj.Image.prototype.unlistenSource_=function(){ol.events.unlistenByKey(this.sourceListenerKey_);this.sourceListenerKey_=null};goog.provide("ol.reproj.Tile");goog.require("ol");goog.require("ol.Tile");goog.require("ol.TileState");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.math");goog.require("ol.reproj");goog.require("ol.reproj.Triangulation");
ol.reproj.Tile=function(sourceProj,sourceTileGrid,targetProj,targetTileGrid,tileCoord,wrappedTileCoord,pixelRatio,gutter,getTileFunction,opt_errorThreshold,opt_renderEdges){ol.Tile.call(this,tileCoord,ol.TileState.IDLE);this.renderEdges_=opt_renderEdges!==undefined?opt_renderEdges:false;this.pixelRatio_=pixelRatio;this.gutter_=gutter;this.canvas_=null;this.sourceTileGrid_=sourceTileGrid;this.targetTileGrid_=targetTileGrid;this.wrappedTileCoord_=wrappedTileCoord?wrappedTileCoord:tileCoord;this.sourceTiles_=
[];this.sourcesListenerKeys_=null;this.sourceZ_=0;var targetExtent=targetTileGrid.getTileCoordExtent(this.wrappedTileCoord_);var maxTargetExtent=this.targetTileGrid_.getExtent();var maxSourceExtent=this.sourceTileGrid_.getExtent();var limitedTargetExtent=maxTargetExtent?ol.extent.getIntersection(targetExtent,maxTargetExtent):targetExtent;if(ol.extent.getArea(limitedTargetExtent)===0){this.state=ol.TileState.EMPTY;return}var sourceProjExtent=sourceProj.getExtent();if(sourceProjExtent)if(!maxSourceExtent)maxSourceExtent=
sourceProjExtent;else maxSourceExtent=ol.extent.getIntersection(maxSourceExtent,sourceProjExtent);var targetResolution=targetTileGrid.getResolution(this.wrappedTileCoord_[0]);var targetCenter=ol.extent.getCenter(limitedTargetExtent);var sourceResolution=ol.reproj.calculateSourceResolution(sourceProj,targetProj,targetCenter,targetResolution);if(!isFinite(sourceResolution)||sourceResolution<=0){this.state=ol.TileState.EMPTY;return}var errorThresholdInPixels=opt_errorThreshold!==undefined?opt_errorThreshold:
ol.DEFAULT_RASTER_REPROJECTION_ERROR_THRESHOLD;this.triangulation_=new ol.reproj.Triangulation(sourceProj,targetProj,limitedTargetExtent,maxSourceExtent,sourceResolution*errorThresholdInPixels);if(this.triangulation_.getTriangles().length===0){this.state=ol.TileState.EMPTY;return}this.sourceZ_=sourceTileGrid.getZForResolution(sourceResolution);var sourceExtent=this.triangulation_.calculateSourceExtent();if(maxSourceExtent)if(sourceProj.canWrapX()){sourceExtent[1]=ol.math.clamp(sourceExtent[1],maxSourceExtent[1],
maxSourceExtent[3]);sourceExtent[3]=ol.math.clamp(sourceExtent[3],maxSourceExtent[1],maxSourceExtent[3])}else sourceExtent=ol.extent.getIntersection(sourceExtent,maxSourceExtent);if(!ol.extent.getArea(sourceExtent))this.state=ol.TileState.EMPTY;else{var sourceRange=sourceTileGrid.getTileRangeForExtentAndZ(sourceExtent,this.sourceZ_);for(var srcX=sourceRange.minX;srcX<=sourceRange.maxX;srcX++)for(var srcY=sourceRange.minY;srcY<=sourceRange.maxY;srcY++){var tile=getTileFunction(this.sourceZ_,srcX,srcY,
pixelRatio);if(tile)this.sourceTiles_.push(tile)}if(this.sourceTiles_.length===0)this.state=ol.TileState.EMPTY}};ol.inherits(ol.reproj.Tile,ol.Tile);ol.reproj.Tile.prototype.disposeInternal=function(){if(this.state==ol.TileState.LOADING)this.unlistenSources_();ol.Tile.prototype.disposeInternal.call(this)};ol.reproj.Tile.prototype.getImage=function(){return this.canvas_};
ol.reproj.Tile.prototype.reproject_=function(){var sources=[];this.sourceTiles_.forEach(function(tile,i,arr){if(tile&&tile.getState()==ol.TileState.LOADED)sources.push({extent:this.sourceTileGrid_.getTileCoordExtent(tile.tileCoord),image:tile.getImage()})},this);this.sourceTiles_.length=0;if(sources.length===0)this.state=ol.TileState.ERROR;else{var z=this.wrappedTileCoord_[0];var size=this.targetTileGrid_.getTileSize(z);var width=typeof size==="number"?size:size[0];var height=typeof size==="number"?
size:size[1];var targetResolution=this.targetTileGrid_.getResolution(z);var sourceResolution=this.sourceTileGrid_.getResolution(this.sourceZ_);var targetExtent=this.targetTileGrid_.getTileCoordExtent(this.wrappedTileCoord_);this.canvas_=ol.reproj.render(width,height,this.pixelRatio_,sourceResolution,this.sourceTileGrid_.getExtent(),targetResolution,targetExtent,this.triangulation_,sources,this.gutter_,this.renderEdges_);this.state=ol.TileState.LOADED}this.changed()};
ol.reproj.Tile.prototype.load=function(){if(this.state==ol.TileState.IDLE){this.state=ol.TileState.LOADING;this.changed();var leftToLoad=0;this.sourcesListenerKeys_=[];this.sourceTiles_.forEach(function(tile,i,arr){var state=tile.getState();if(state==ol.TileState.IDLE||state==ol.TileState.LOADING){leftToLoad++;var sourceListenKey;sourceListenKey=ol.events.listen(tile,ol.events.EventType.CHANGE,function(e){var state=tile.getState();if(state==ol.TileState.LOADED||state==ol.TileState.ERROR||state==ol.TileState.EMPTY){ol.events.unlistenByKey(sourceListenKey);
leftToLoad--;if(leftToLoad===0){this.unlistenSources_();this.reproject_()}}},this);this.sourcesListenerKeys_.push(sourceListenKey)}},this);this.sourceTiles_.forEach(function(tile,i,arr){var state=tile.getState();if(state==ol.TileState.IDLE)tile.load()});if(leftToLoad===0)setTimeout(this.reproject_.bind(this),0)}};ol.reproj.Tile.prototype.unlistenSources_=function(){this.sourcesListenerKeys_.forEach(ol.events.unlistenByKey);this.sourcesListenerKeys_=null};goog.provide("ol.TileUrlFunction");goog.require("ol.asserts");goog.require("ol.math");goog.require("ol.tilecoord");
ol.TileUrlFunction.createFromTemplate=function(template,tileGrid){var zRegEx=/\{z\}/g;var xRegEx=/\{x\}/g;var yRegEx=/\{y\}/g;var dashYRegEx=/\{-y\}/g;return function(tileCoord,pixelRatio,projection){if(!tileCoord)return undefined;else return template.replace(zRegEx,tileCoord[0].toString()).replace(xRegEx,tileCoord[1].toString()).replace(yRegEx,function(){var y=-tileCoord[2]-1;return y.toString()}).replace(dashYRegEx,function(){var z=tileCoord[0];var range=tileGrid.getFullTileRange(z);ol.asserts.assert(range,
55);var y=range.getHeight()+tileCoord[2];return y.toString()})}};ol.TileUrlFunction.createFromTemplates=function(templates,tileGrid){var len=templates.length;var tileUrlFunctions=new Array(len);for(var i=0;i<len;++i)tileUrlFunctions[i]=ol.TileUrlFunction.createFromTemplate(templates[i],tileGrid);return ol.TileUrlFunction.createFromTileUrlFunctions(tileUrlFunctions)};
ol.TileUrlFunction.createFromTileUrlFunctions=function(tileUrlFunctions){if(tileUrlFunctions.length===1)return tileUrlFunctions[0];return function(tileCoord,pixelRatio,projection){if(!tileCoord)return undefined;else{var h=ol.tilecoord.hash(tileCoord);var index=ol.math.modulo(h,tileUrlFunctions.length);return tileUrlFunctions[index](tileCoord,pixelRatio,projection)}}};ol.TileUrlFunction.nullTileUrlFunction=function(tileCoord,pixelRatio,projection){return undefined};
ol.TileUrlFunction.expandUrl=function(url){var urls=[];var match=/\{([a-z])-([a-z])\}/.exec(url);if(match){var startCharCode=match[1].charCodeAt(0);var stopCharCode=match[2].charCodeAt(0);var charCode;for(charCode=startCharCode;charCode<=stopCharCode;++charCode)urls.push(url.replace(match[0],String.fromCharCode(charCode)));return urls}match=match=/\{(\d+)-(\d+)\}/.exec(url);if(match){var stop=parseInt(match[2],10);for(var i=parseInt(match[1],10);i<=stop;i++)urls.push(url.replace(match[0],i.toString()));
return urls}urls.push(url);return urls};goog.provide("ol.TileCache");goog.require("ol");goog.require("ol.structs.LRUCache");goog.require("ol.tilecoord");ol.TileCache=function(opt_highWaterMark){ol.structs.LRUCache.call(this,opt_highWaterMark)};ol.inherits(ol.TileCache,ol.structs.LRUCache);ol.TileCache.prototype.expireCache=function(usedTiles){var tile,zKey;while(this.canExpireCache()){tile=this.peekLast();zKey=tile.tileCoord[0].toString();if(zKey in usedTiles&&usedTiles[zKey].contains(tile.tileCoord))break;else this.pop().dispose()}};
ol.TileCache.prototype.pruneExceptNewestZ=function(){if(this.getCount()===0)return;var key=this.peekFirstKey();var tileCoord=ol.tilecoord.fromKey(key);var z=tileCoord[0];this.forEach(function(tile){if(tile.tileCoord[0]!==z){this.remove(ol.tilecoord.getKey(tile.tileCoord));tile.dispose()}},this)};goog.provide("ol.source.Tile");goog.require("ol");goog.require("ol.TileCache");goog.require("ol.TileState");goog.require("ol.events.Event");goog.require("ol.proj");goog.require("ol.size");goog.require("ol.source.Source");goog.require("ol.tilecoord");goog.require("ol.tilegrid");
ol.source.Tile=function(options){ol.source.Source.call(this,{attributions:options.attributions,extent:options.extent,logo:options.logo,projection:options.projection,state:options.state,wrapX:options.wrapX});this.opaque_=options.opaque!==undefined?options.opaque:false;this.tilePixelRatio_=options.tilePixelRatio!==undefined?options.tilePixelRatio:1;this.tileGrid=options.tileGrid!==undefined?options.tileGrid:null;this.tileCache=new ol.TileCache(options.cacheSize);this.tmpSize=[0,0];this.key_="";this.tileOptions=
{transition:options.transition}};ol.inherits(ol.source.Tile,ol.source.Source);ol.source.Tile.prototype.canExpireCache=function(){return this.tileCache.canExpireCache()};ol.source.Tile.prototype.expireCache=function(projection,usedTiles){var tileCache=this.getTileCacheForProjection(projection);if(tileCache)tileCache.expireCache(usedTiles)};
ol.source.Tile.prototype.forEachLoadedTile=function(projection,z,tileRange,callback){var tileCache=this.getTileCacheForProjection(projection);if(!tileCache)return false;var covered=true;var tile,tileCoordKey,loaded;for(var x=tileRange.minX;x<=tileRange.maxX;++x)for(var y=tileRange.minY;y<=tileRange.maxY;++y){tileCoordKey=ol.tilecoord.getKeyZXY(z,x,y);loaded=false;if(tileCache.containsKey(tileCoordKey)){tile=tileCache.get(tileCoordKey);loaded=tile.getState()===ol.TileState.LOADED;if(loaded)loaded=
callback(tile)!==false}if(!loaded)covered=false}return covered};ol.source.Tile.prototype.getGutter=function(projection){return 0};ol.source.Tile.prototype.getKey=function(){return this.key_};ol.source.Tile.prototype.setKey=function(key){if(this.key_!==key){this.key_=key;this.changed()}};ol.source.Tile.prototype.getOpaque=function(projection){return this.opaque_};ol.source.Tile.prototype.getResolutions=function(){return this.tileGrid.getResolutions()};
ol.source.Tile.prototype.getTile=function(z,x,y,pixelRatio,projection){};ol.source.Tile.prototype.getTileGrid=function(){return this.tileGrid};ol.source.Tile.prototype.getTileGridForProjection=function(projection){if(!this.tileGrid)return ol.tilegrid.getForProjection(projection);else return this.tileGrid};ol.source.Tile.prototype.getTileCacheForProjection=function(projection){var thisProj=this.getProjection();if(thisProj&&!ol.proj.equivalent(thisProj,projection))return null;else return this.tileCache};
ol.source.Tile.prototype.getTilePixelRatio=function(pixelRatio){return this.tilePixelRatio_};ol.source.Tile.prototype.getTilePixelSize=function(z,pixelRatio,projection){var tileGrid=this.getTileGridForProjection(projection);var tilePixelRatio=this.getTilePixelRatio(pixelRatio);var tileSize=ol.size.toSize(tileGrid.getTileSize(z),this.tmpSize);if(tilePixelRatio==1)return tileSize;else return ol.size.scale(tileSize,tilePixelRatio,this.tmpSize)};
ol.source.Tile.prototype.getTileCoordForTileUrlFunction=function(tileCoord,opt_projection){var projection=opt_projection!==undefined?opt_projection:this.getProjection();var tileGrid=this.getTileGridForProjection(projection);if(this.getWrapX()&&projection.isGlobal())tileCoord=ol.tilegrid.wrapX(tileGrid,tileCoord,projection);return ol.tilecoord.withinExtentAndZ(tileCoord,tileGrid)?tileCoord:null};ol.source.Tile.prototype.refresh=function(){this.tileCache.clear();this.changed()};
ol.source.Tile.prototype.useTile=ol.nullFunction;ol.source.Tile.Event=function(type,tile){ol.events.Event.call(this,type);this.tile=tile};ol.inherits(ol.source.Tile.Event,ol.events.Event);goog.provide("ol.source.TileEventType");ol.source.TileEventType={TILELOADSTART:"tileloadstart",TILELOADEND:"tileloadend",TILELOADERROR:"tileloaderror"};goog.provide("ol.source.UrlTile");goog.require("ol");goog.require("ol.TileState");goog.require("ol.TileUrlFunction");goog.require("ol.source.Tile");goog.require("ol.source.TileEventType");goog.require("ol.tilecoord");
ol.source.UrlTile=function(options){ol.source.Tile.call(this,{attributions:options.attributions,cacheSize:options.cacheSize,extent:options.extent,logo:options.logo,opaque:options.opaque,projection:options.projection,state:options.state,tileGrid:options.tileGrid,tilePixelRatio:options.tilePixelRatio,wrapX:options.wrapX,transition:options.transition});this.tileLoadFunction=options.tileLoadFunction;this.tileUrlFunction=this.fixedTileUrlFunction?this.fixedTileUrlFunction.bind(this):ol.TileUrlFunction.nullTileUrlFunction;
this.urls=null;if(options.urls)this.setUrls(options.urls);else if(options.url)this.setUrl(options.url);if(options.tileUrlFunction)this.setTileUrlFunction(options.tileUrlFunction);this.tileLoadingKeys_={}};ol.inherits(ol.source.UrlTile,ol.source.Tile);ol.source.UrlTile.prototype.fixedTileUrlFunction;ol.source.UrlTile.prototype.getTileLoadFunction=function(){return this.tileLoadFunction};ol.source.UrlTile.prototype.getTileUrlFunction=function(){return this.tileUrlFunction};
ol.source.UrlTile.prototype.getUrls=function(){return this.urls};
ol.source.UrlTile.prototype.handleTileChange=function(event){var tile=event.target;var uid=ol.getUid(tile);var tileState=tile.getState();var type;if(tileState==ol.TileState.LOADING){this.tileLoadingKeys_[uid]=true;type=ol.source.TileEventType.TILELOADSTART}else if(uid in this.tileLoadingKeys_){delete this.tileLoadingKeys_[uid];type=tileState==ol.TileState.ERROR?ol.source.TileEventType.TILELOADERROR:tileState==ol.TileState.LOADED||tileState==ol.TileState.ABORT?ol.source.TileEventType.TILELOADEND:undefined}if(type!=
undefined)this.dispatchEvent(new ol.source.Tile.Event(type,tile))};ol.source.UrlTile.prototype.setTileLoadFunction=function(tileLoadFunction){this.tileCache.clear();this.tileLoadFunction=tileLoadFunction;this.changed()};ol.source.UrlTile.prototype.setTileUrlFunction=function(tileUrlFunction,opt_key){this.tileUrlFunction=tileUrlFunction;this.tileCache.pruneExceptNewestZ();if(typeof opt_key!=="undefined")this.setKey(opt_key);else this.changed()};
ol.source.UrlTile.prototype.setUrl=function(url){var urls=this.urls=ol.TileUrlFunction.expandUrl(url);this.setTileUrlFunction(this.fixedTileUrlFunction?this.fixedTileUrlFunction.bind(this):ol.TileUrlFunction.createFromTemplates(urls,this.tileGrid),url)};ol.source.UrlTile.prototype.setUrls=function(urls){this.urls=urls;var key=urls.join("\n");this.setTileUrlFunction(this.fixedTileUrlFunction?this.fixedTileUrlFunction.bind(this):ol.TileUrlFunction.createFromTemplates(urls,this.tileGrid),key)};
ol.source.UrlTile.prototype.useTile=function(z,x,y){var tileCoordKey=ol.tilecoord.getKeyZXY(z,x,y);if(this.tileCache.containsKey(tileCoordKey))this.tileCache.get(tileCoordKey)};goog.provide("ol.source.TileImage");goog.require("ol");goog.require("ol.ImageTile");goog.require("ol.TileCache");goog.require("ol.TileState");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.proj");goog.require("ol.reproj.Tile");goog.require("ol.source.UrlTile");goog.require("ol.tilecoord");goog.require("ol.tilegrid");
ol.source.TileImage=function(options){ol.source.UrlTile.call(this,{attributions:options.attributions,cacheSize:options.cacheSize,extent:options.extent,logo:options.logo,opaque:options.opaque,projection:options.projection,state:options.state,tileGrid:options.tileGrid,tileLoadFunction:options.tileLoadFunction?options.tileLoadFunction:ol.source.TileImage.defaultTileLoadFunction,tilePixelRatio:options.tilePixelRatio,tileUrlFunction:options.tileUrlFunction,url:options.url,urls:options.urls,wrapX:options.wrapX,
transition:options.transition});this.crossOrigin=options.crossOrigin!==undefined?options.crossOrigin:null;this.tileClass=options.tileClass!==undefined?options.tileClass:ol.ImageTile;this.tileCacheForProjection={};this.tileGridForProjection={};this.reprojectionErrorThreshold_=options.reprojectionErrorThreshold;this.renderReprojectionEdges_=false};ol.inherits(ol.source.TileImage,ol.source.UrlTile);
ol.source.TileImage.prototype.canExpireCache=function(){if(!ol.ENABLE_RASTER_REPROJECTION)return ol.source.UrlTile.prototype.canExpireCache.call(this);if(this.tileCache.canExpireCache())return true;else for(var key in this.tileCacheForProjection)if(this.tileCacheForProjection[key].canExpireCache())return true;return false};
ol.source.TileImage.prototype.expireCache=function(projection,usedTiles){if(!ol.ENABLE_RASTER_REPROJECTION){ol.source.UrlTile.prototype.expireCache.call(this,projection,usedTiles);return}var usedTileCache=this.getTileCacheForProjection(projection);this.tileCache.expireCache(this.tileCache==usedTileCache?usedTiles:{});for(var id in this.tileCacheForProjection){var tileCache=this.tileCacheForProjection[id];tileCache.expireCache(tileCache==usedTileCache?usedTiles:{})}};
ol.source.TileImage.prototype.getGutter=function(projection){if(ol.ENABLE_RASTER_REPROJECTION&&this.getProjection()&&projection&&!ol.proj.equivalent(this.getProjection(),projection))return 0;else return this.getGutterInternal()};ol.source.TileImage.prototype.getGutterInternal=function(){return 0};
ol.source.TileImage.prototype.getOpaque=function(projection){if(ol.ENABLE_RASTER_REPROJECTION&&this.getProjection()&&projection&&!ol.proj.equivalent(this.getProjection(),projection))return false;else return ol.source.UrlTile.prototype.getOpaque.call(this,projection)};
ol.source.TileImage.prototype.getTileGridForProjection=function(projection){if(!ol.ENABLE_RASTER_REPROJECTION)return ol.source.UrlTile.prototype.getTileGridForProjection.call(this,projection);var thisProj=this.getProjection();if(this.tileGrid&&(!thisProj||ol.proj.equivalent(thisProj,projection)))return this.tileGrid;else{var projKey=ol.getUid(projection).toString();if(!(projKey in this.tileGridForProjection))this.tileGridForProjection[projKey]=ol.tilegrid.getForProjection(projection);return this.tileGridForProjection[projKey]}};
ol.source.TileImage.prototype.getTileCacheForProjection=function(projection){if(!ol.ENABLE_RASTER_REPROJECTION)return ol.source.UrlTile.prototype.getTileCacheForProjection.call(this,projection);var thisProj=this.getProjection();if(!thisProj||ol.proj.equivalent(thisProj,projection))return this.tileCache;else{var projKey=ol.getUid(projection).toString();if(!(projKey in this.tileCacheForProjection))this.tileCacheForProjection[projKey]=new ol.TileCache(this.tileCache.highWaterMark);return this.tileCacheForProjection[projKey]}};
ol.source.TileImage.prototype.createTile_=function(z,x,y,pixelRatio,projection,key){var tileCoord=[z,x,y];var urlTileCoord=this.getTileCoordForTileUrlFunction(tileCoord,projection);var tileUrl=urlTileCoord?this.tileUrlFunction(urlTileCoord,pixelRatio,projection):undefined;var tile=new this.tileClass(tileCoord,tileUrl!==undefined?ol.TileState.IDLE:ol.TileState.EMPTY,tileUrl!==undefined?tileUrl:"",this.crossOrigin,this.tileLoadFunction,this.tileOptions);tile.key=key;ol.events.listen(tile,ol.events.EventType.CHANGE,
this.handleTileChange,this);return tile};
ol.source.TileImage.prototype.getTile=function(z,x,y,pixelRatio,projection){var sourceProjection=this.getProjection();if(!ol.ENABLE_RASTER_REPROJECTION||!sourceProjection||!projection||ol.proj.equivalent(sourceProjection,projection))return this.getTileInternal(z,x,y,pixelRatio,sourceProjection||projection);else{var cache=this.getTileCacheForProjection(projection);var tileCoord=[z,x,y];var tile;var tileCoordKey=ol.tilecoord.getKey(tileCoord);if(cache.containsKey(tileCoordKey))tile=cache.get(tileCoordKey);
var key=this.getKey();if(tile&&tile.key==key)return tile;else{var sourceTileGrid=this.getTileGridForProjection(sourceProjection);var targetTileGrid=this.getTileGridForProjection(projection);var wrappedTileCoord=this.getTileCoordForTileUrlFunction(tileCoord,projection);var newTile=new ol.reproj.Tile(sourceProjection,sourceTileGrid,projection,targetTileGrid,tileCoord,wrappedTileCoord,this.getTilePixelRatio(pixelRatio),this.getGutterInternal(),function(z,x,y,pixelRatio){return this.getTileInternal(z,
x,y,pixelRatio,sourceProjection)}.bind(this),this.reprojectionErrorThreshold_,this.renderReprojectionEdges_);newTile.key=key;if(tile){newTile.interimTile=tile;newTile.refreshInterimChain();cache.replace(tileCoordKey,newTile)}else cache.set(tileCoordKey,newTile);return newTile}}};
ol.source.TileImage.prototype.getTileInternal=function(z,x,y,pixelRatio,projection){var tile=null;var tileCoordKey=ol.tilecoord.getKeyZXY(z,x,y);var key=this.getKey();if(!this.tileCache.containsKey(tileCoordKey)){tile=this.createTile_(z,x,y,pixelRatio,projection,key);this.tileCache.set(tileCoordKey,tile)}else{tile=this.tileCache.get(tileCoordKey);if(tile.key!=key){var interimTile=tile;tile=this.createTile_(z,x,y,pixelRatio,projection,key);if(interimTile.getState()==ol.TileState.IDLE)tile.interimTile=
interimTile.interimTile;else tile.interimTile=interimTile;tile.refreshInterimChain();this.tileCache.replace(tileCoordKey,tile)}}return tile};ol.source.TileImage.prototype.setRenderReprojectionEdges=function(render){if(!ol.ENABLE_RASTER_REPROJECTION||this.renderReprojectionEdges_==render)return;this.renderReprojectionEdges_=render;for(var id in this.tileCacheForProjection)this.tileCacheForProjection[id].clear();this.changed()};
ol.source.TileImage.prototype.setTileGridForProjection=function(projection,tilegrid){if(ol.ENABLE_RASTER_REPROJECTION){var proj=ol.proj.get(projection);if(proj){var projKey=ol.getUid(proj).toString();if(!(projKey in this.tileGridForProjection))this.tileGridForProjection[projKey]=tilegrid}}};ol.source.TileImage.defaultTileLoadFunction=function(imageTile,src){imageTile.getImage().src=src};goog.provide("ol.source.BingMaps");goog.require("ol");goog.require("ol.TileUrlFunction");goog.require("ol.extent");goog.require("ol.net");goog.require("ol.proj");goog.require("ol.source.State");goog.require("ol.source.TileImage");goog.require("ol.tilecoord");goog.require("ol.tilegrid");
ol.source.BingMaps=function(options){this.hidpi_=options.hidpi!==undefined?options.hidpi:false;ol.source.TileImage.call(this,{cacheSize:options.cacheSize,crossOrigin:"anonymous",opaque:true,projection:ol.proj.get("EPSG:3857"),reprojectionErrorThreshold:options.reprojectionErrorThreshold,state:ol.source.State.LOADING,tileLoadFunction:options.tileLoadFunction,tilePixelRatio:this.hidpi_?2:1,wrapX:options.wrapX!==undefined?options.wrapX:true,transition:options.transition});this.culture_=options.culture!==
undefined?options.culture:"en-us";this.maxZoom_=options.maxZoom!==undefined?options.maxZoom:-1;this.apiKey_=options.key;this.imagerySet_=options.imagerySet;var url="https://dev.virtualearth.net/REST/v1/Imagery/Metadata/"+this.imagerySet_+"?uriScheme=https&include=ImageryProviders&key="+this.apiKey_+"&c="+this.culture_;ol.net.jsonp(url,this.handleImageryMetadataResponse.bind(this),undefined,"jsonp")};ol.inherits(ol.source.BingMaps,ol.source.TileImage);
ol.source.BingMaps.TOS_ATTRIBUTION='<a class="ol-attribution-bing-tos" '+'href="https://www.microsoft.com/maps/product/terms.html">'+"Terms of Use</a>";ol.source.BingMaps.prototype.getApiKey=function(){return this.apiKey_};ol.source.BingMaps.prototype.getImagerySet=function(){return this.imagerySet_};
ol.source.BingMaps.prototype.handleImageryMetadataResponse=function(response){if(response.statusCode!=200||response.statusDescription!="OK"||response.authenticationResultCode!="ValidCredentials"||response.resourceSets.length!=1||response.resourceSets[0].resources.length!=1){this.setState(ol.source.State.ERROR);return}var brandLogoUri=response.brandLogoUri;if(brandLogoUri.indexOf("https")==-1)brandLogoUri=brandLogoUri.replace("http","https");var resource=response.resourceSets[0].resources[0];var maxZoom=
this.maxZoom_==-1?resource.zoomMax:this.maxZoom_;var sourceProjection=this.getProjection();var extent=ol.tilegrid.extentFromProjection(sourceProjection);var tileSize=resource.imageWidth==resource.imageHeight?resource.imageWidth:[resource.imageWidth,resource.imageHeight];var tileGrid=ol.tilegrid.createXYZ({extent:extent,minZoom:resource.zoomMin,maxZoom:maxZoom,tileSize:tileSize/(this.hidpi_?2:1)});this.tileGrid=tileGrid;var culture=this.culture_;var hidpi=this.hidpi_;this.tileUrlFunction=ol.TileUrlFunction.createFromTileUrlFunctions(resource.imageUrlSubdomains.map(function(subdomain){var quadKeyTileCoord=
[0,0,0];var imageUrl=resource.imageUrl.replace("{subdomain}",subdomain).replace("{culture}",culture);return function(tileCoord,pixelRatio,projection){if(!tileCoord)return undefined;else{ol.tilecoord.createOrUpdate(tileCoord[0],tileCoord[1],-tileCoord[2]-1,quadKeyTileCoord);var url=imageUrl;if(hidpi)url+="&dpi=d1&device=mobile";return url.replace("{quadkey}",ol.tilecoord.quadKey(quadKeyTileCoord))}}}));if(resource.imageryProviders){var transform=ol.proj.getTransformFromProjections(ol.proj.get("EPSG:4326"),
this.getProjection());this.setAttributions(function(frameState){var attributions=[];var zoom=frameState.viewState.zoom;resource.imageryProviders.map(function(imageryProvider){var intersects=false;var coverageAreas=imageryProvider.coverageAreas;for(var i=0,ii=coverageAreas.length;i<ii;++i){var coverageArea=coverageAreas[i];if(zoom>=coverageArea.zoomMin&&zoom<=coverageArea.zoomMax){var bbox=coverageArea.bbox;var epsg4326Extent=[bbox[1],bbox[0],bbox[3],bbox[2]];var extent=ol.extent.applyTransform(epsg4326Extent,
transform);if(ol.extent.intersects(extent,frameState.extent)){intersects=true;break}}}if(intersects)attributions.push(imageryProvider.attribution)});attributions.push(ol.source.BingMaps.TOS_ATTRIBUTION);return attributions})}this.setLogo(brandLogoUri);this.setState(ol.source.State.READY)};goog.provide("ol.source.XYZ");goog.require("ol");goog.require("ol.source.TileImage");goog.require("ol.tilegrid");
ol.source.XYZ=function(opt_options){var options=opt_options||{};var projection=options.projection!==undefined?options.projection:"EPSG:3857";var tileGrid=options.tileGrid!==undefined?options.tileGrid:ol.tilegrid.createXYZ({extent:ol.tilegrid.extentFromProjection(projection),maxZoom:options.maxZoom,minZoom:options.minZoom,tileSize:options.tileSize});ol.source.TileImage.call(this,{attributions:options.attributions,cacheSize:options.cacheSize,crossOrigin:options.crossOrigin,logo:options.logo,opaque:options.opaque,
projection:projection,reprojectionErrorThreshold:options.reprojectionErrorThreshold,tileGrid:tileGrid,tileLoadFunction:options.tileLoadFunction,tilePixelRatio:options.tilePixelRatio,tileUrlFunction:options.tileUrlFunction,url:options.url,urls:options.urls,wrapX:options.wrapX!==undefined?options.wrapX:true,transition:options.transition})};ol.inherits(ol.source.XYZ,ol.source.TileImage);goog.provide("ol.source.CartoDB");goog.require("ol");goog.require("ol.obj");goog.require("ol.source.State");goog.require("ol.source.XYZ");
ol.source.CartoDB=function(options){this.account_=options.account;this.mapId_=options.map||"";this.config_=options.config||{};this.templateCache_={};ol.source.XYZ.call(this,{attributions:options.attributions,cacheSize:options.cacheSize,crossOrigin:options.crossOrigin,logo:options.logo,maxZoom:options.maxZoom!==undefined?options.maxZoom:18,minZoom:options.minZoom,projection:options.projection,state:ol.source.State.LOADING,wrapX:options.wrapX});this.initializeMap_()};ol.inherits(ol.source.CartoDB,ol.source.XYZ);
ol.source.CartoDB.prototype.getConfig=function(){return this.config_};ol.source.CartoDB.prototype.updateConfig=function(config){ol.obj.assign(this.config_,config);this.initializeMap_()};ol.source.CartoDB.prototype.setConfig=function(config){this.config_=config||{};this.initializeMap_()};
ol.source.CartoDB.prototype.initializeMap_=function(){var paramHash=JSON.stringify(this.config_);if(this.templateCache_[paramHash]){this.applyTemplate_(this.templateCache_[paramHash]);return}var mapUrl="https://"+this.account_+".carto.com/api/v1/map";if(this.mapId_)mapUrl+="/named/"+this.mapId_;var client=new XMLHttpRequest;client.addEventListener("load",this.handleInitResponse_.bind(this,paramHash));client.addEventListener("error",this.handleInitError_.bind(this));client.open("POST",mapUrl);client.setRequestHeader("Content-type",
"application/json");client.send(JSON.stringify(this.config_))};ol.source.CartoDB.prototype.handleInitResponse_=function(paramHash,event){var client=event.target;if(!client.status||client.status>=200&&client.status<300){var response;try{response=JSON.parse(client.responseText)}catch(err){this.setState(ol.source.State.ERROR);return}this.applyTemplate_(response);this.templateCache_[paramHash]=response;this.setState(ol.source.State.READY)}else this.setState(ol.source.State.ERROR)};
ol.source.CartoDB.prototype.handleInitError_=function(event){this.setState(ol.source.State.ERROR)};ol.source.CartoDB.prototype.applyTemplate_=function(data){var tilesUrl="https://"+data.cdn_url.https+"/"+this.account_+"/api/v1/map/"+data.layergroupid+"/{z}/{x}/{y}.png";this.setUrl(tilesUrl)};goog.provide("ol.source.Cluster");goog.require("ol");goog.require("ol.asserts");goog.require("ol.Feature");goog.require("ol.coordinate");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.geom.Point");goog.require("ol.source.Vector");
ol.source.Cluster=function(options){ol.source.Vector.call(this,{attributions:options.attributions,extent:options.extent,logo:options.logo,projection:options.projection,wrapX:options.wrapX});this.resolution=undefined;this.distance=options.distance!==undefined?options.distance:20;this.features=[];this.geometryFunction=options.geometryFunction||function(feature){var geometry=feature.getGeometry();ol.asserts.assert(geometry instanceof ol.geom.Point,10);return geometry};this.source=options.source;this.source.on(ol.events.EventType.CHANGE,
ol.source.Cluster.prototype.refresh,this)};ol.inherits(ol.source.Cluster,ol.source.Vector);ol.source.Cluster.prototype.getDistance=function(){return this.distance};ol.source.Cluster.prototype.getSource=function(){return this.source};ol.source.Cluster.prototype.loadFeatures=function(extent,resolution,projection){this.source.loadFeatures(extent,resolution,projection);if(resolution!==this.resolution){this.clear();this.resolution=resolution;this.cluster();this.addFeatures(this.features)}};
ol.source.Cluster.prototype.setDistance=function(distance){this.distance=distance;this.refresh()};ol.source.Cluster.prototype.refresh=function(){this.clear();this.cluster();this.addFeatures(this.features);ol.source.Vector.prototype.refresh.call(this)};
ol.source.Cluster.prototype.cluster=function(){if(this.resolution===undefined)return;this.features.length=0;var extent=ol.extent.createEmpty();var mapDistance=this.distance*this.resolution;var features=this.source.getFeatures();var clustered={};for(var i=0,ii=features.length;i<ii;i++){var feature=features[i];if(!(ol.getUid(feature).toString()in clustered)){var geometry=this.geometryFunction(feature);if(geometry){var coordinates=geometry.getCoordinates();ol.extent.createOrUpdateFromCoordinate(coordinates,
extent);ol.extent.buffer(extent,mapDistance,extent);var neighbors=this.source.getFeaturesInExtent(extent);neighbors=neighbors.filter(function(neighbor){var uid=ol.getUid(neighbor).toString();if(!(uid in clustered)){clustered[uid]=true;return true}else return false});this.features.push(this.createCluster(neighbors))}}}};
ol.source.Cluster.prototype.createCluster=function(features){var centroid=[0,0];for(var i=features.length-1;i>=0;--i){var geometry=this.geometryFunction(features[i]);if(geometry)ol.coordinate.add(centroid,geometry.getCoordinates());else features.splice(i,1)}ol.coordinate.scale(centroid,1/features.length);var cluster=new ol.Feature(new ol.geom.Point(centroid));cluster.set("features",features);return cluster};goog.provide("ol.source.Image");goog.require("ol");goog.require("ol.ImageState");goog.require("ol.array");goog.require("ol.events.Event");goog.require("ol.extent");goog.require("ol.proj");goog.require("ol.reproj.Image");goog.require("ol.source.Source");
ol.source.Image=function(options){ol.source.Source.call(this,{attributions:options.attributions,extent:options.extent,logo:options.logo,projection:options.projection,state:options.state});this.resolutions_=options.resolutions!==undefined?options.resolutions:null;this.reprojectedImage_=null;this.reprojectedRevision_=0};ol.inherits(ol.source.Image,ol.source.Source);ol.source.Image.prototype.getResolutions=function(){return this.resolutions_};
ol.source.Image.prototype.findNearestResolution=function(resolution){if(this.resolutions_){var idx=ol.array.linearFindNearest(this.resolutions_,resolution,0);resolution=this.resolutions_[idx]}return resolution};
ol.source.Image.prototype.getImage=function(extent,resolution,pixelRatio,projection){var sourceProjection=this.getProjection();if(!ol.ENABLE_RASTER_REPROJECTION||!sourceProjection||!projection||ol.proj.equivalent(sourceProjection,projection)){if(sourceProjection)projection=sourceProjection;return this.getImageInternal(extent,resolution,pixelRatio,projection)}else{if(this.reprojectedImage_){if(this.reprojectedRevision_==this.getRevision()&&ol.proj.equivalent(this.reprojectedImage_.getProjection(),
projection)&&this.reprojectedImage_.getResolution()==resolution&&ol.extent.equals(this.reprojectedImage_.getExtent(),extent))return this.reprojectedImage_;this.reprojectedImage_.dispose();this.reprojectedImage_=null}this.reprojectedImage_=new ol.reproj.Image(sourceProjection,projection,extent,resolution,pixelRatio,function(extent,resolution,pixelRatio){return this.getImageInternal(extent,resolution,pixelRatio,sourceProjection)}.bind(this));this.reprojectedRevision_=this.getRevision();return this.reprojectedImage_}};
ol.source.Image.prototype.getImageInternal=function(extent,resolution,pixelRatio,projection){};
ol.source.Image.prototype.handleImageChange=function(event){var image=event.target;switch(image.getState()){case ol.ImageState.LOADING:this.dispatchEvent(new ol.source.Image.Event(ol.source.Image.EventType_.IMAGELOADSTART,image));break;case ol.ImageState.LOADED:this.dispatchEvent(new ol.source.Image.Event(ol.source.Image.EventType_.IMAGELOADEND,image));break;case ol.ImageState.ERROR:this.dispatchEvent(new ol.source.Image.Event(ol.source.Image.EventType_.IMAGELOADERROR,image));break;default:}};
ol.source.Image.defaultImageLoadFunction=function(image,src){image.getImage().src=src};ol.source.Image.Event=function(type,image){ol.events.Event.call(this,type);this.image=image};ol.inherits(ol.source.Image.Event,ol.events.Event);ol.source.Image.EventType_={IMAGELOADSTART:"imageloadstart",IMAGELOADEND:"imageloadend",IMAGELOADERROR:"imageloaderror"};goog.provide("ol.uri");ol.uri.appendParams=function(uri,params){var keyParams=[];Object.keys(params).forEach(function(k){if(params[k]!==null&&params[k]!==undefined)keyParams.push(k+"="+encodeURIComponent(params[k]))});var qs=keyParams.join("&");uri=uri.replace(/[?&]$/,"");uri=uri.indexOf("?")===-1?uri+"?":uri+"&";return uri+qs};goog.provide("ol.source.ImageArcGISRest");goog.require("ol");goog.require("ol.Image");goog.require("ol.asserts");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.obj");goog.require("ol.source.Image");goog.require("ol.uri");
ol.source.ImageArcGISRest=function(opt_options){var options=opt_options||{};ol.source.Image.call(this,{attributions:options.attributions,logo:options.logo,projection:options.projection,resolutions:options.resolutions});this.crossOrigin_=options.crossOrigin!==undefined?options.crossOrigin:null;this.hidpi_=options.hidpi!==undefined?options.hidpi:true;this.url_=options.url;this.imageLoadFunction_=options.imageLoadFunction!==undefined?options.imageLoadFunction:ol.source.Image.defaultImageLoadFunction;
this.params_=options.params||{};this.image_=null;this.imageSize_=[0,0];this.renderedRevision_=0;this.ratio_=options.ratio!==undefined?options.ratio:1.5};ol.inherits(ol.source.ImageArcGISRest,ol.source.Image);ol.source.ImageArcGISRest.prototype.getParams=function(){return this.params_};
ol.source.ImageArcGISRest.prototype.getImageInternal=function(extent,resolution,pixelRatio,projection){if(this.url_===undefined)return null;resolution=this.findNearestResolution(resolution);pixelRatio=this.hidpi_?pixelRatio:1;var image=this.image_;if(image&&this.renderedRevision_==this.getRevision()&&image.getResolution()==resolution&&image.getPixelRatio()==pixelRatio&&ol.extent.containsExtent(image.getExtent(),extent))return image;var params={"F":"image","FORMAT":"PNG32","TRANSPARENT":true};ol.obj.assign(params,
this.params_);extent=extent.slice();var centerX=(extent[0]+extent[2])/2;var centerY=(extent[1]+extent[3])/2;if(this.ratio_!=1){var halfWidth=this.ratio_*ol.extent.getWidth(extent)/2;var halfHeight=this.ratio_*ol.extent.getHeight(extent)/2;extent[0]=centerX-halfWidth;extent[1]=centerY-halfHeight;extent[2]=centerX+halfWidth;extent[3]=centerY+halfHeight}var imageResolution=resolution/pixelRatio;var width=Math.ceil(ol.extent.getWidth(extent)/imageResolution);var height=Math.ceil(ol.extent.getHeight(extent)/
imageResolution);extent[0]=centerX-imageResolution*width/2;extent[2]=centerX+imageResolution*width/2;extent[1]=centerY-imageResolution*height/2;extent[3]=centerY+imageResolution*height/2;this.imageSize_[0]=width;this.imageSize_[1]=height;var url=this.getRequestUrl_(extent,this.imageSize_,pixelRatio,projection,params);this.image_=new ol.Image(extent,resolution,pixelRatio,url,this.crossOrigin_,this.imageLoadFunction_);this.renderedRevision_=this.getRevision();ol.events.listen(this.image_,ol.events.EventType.CHANGE,
this.handleImageChange,this);return this.image_};ol.source.ImageArcGISRest.prototype.getImageLoadFunction=function(){return this.imageLoadFunction_};
ol.source.ImageArcGISRest.prototype.getRequestUrl_=function(extent,size,pixelRatio,projection,params){var srid=projection.getCode().split(":").pop();params["SIZE"]=size[0]+","+size[1];params["BBOX"]=extent.join(",");params["BBOXSR"]=srid;params["IMAGESR"]=srid;params["DPI"]=Math.round(90*pixelRatio);var url=this.url_;var modifiedUrl=url.replace(/MapServer\/?$/,"MapServer/export").replace(/ImageServer\/?$/,"ImageServer/exportImage");if(modifiedUrl==url)ol.asserts.assert(false,50);return ol.uri.appendParams(modifiedUrl,
params)};ol.source.ImageArcGISRest.prototype.getUrl=function(){return this.url_};ol.source.ImageArcGISRest.prototype.setImageLoadFunction=function(imageLoadFunction){this.image_=null;this.imageLoadFunction_=imageLoadFunction;this.changed()};ol.source.ImageArcGISRest.prototype.setUrl=function(url){if(url!=this.url_){this.url_=url;this.image_=null;this.changed()}};ol.source.ImageArcGISRest.prototype.updateParams=function(params){ol.obj.assign(this.params_,params);this.image_=null;this.changed()};goog.provide("ol.source.ImageCanvas");goog.require("ol");goog.require("ol.ImageCanvas");goog.require("ol.extent");goog.require("ol.source.Image");ol.source.ImageCanvas=function(options){ol.source.Image.call(this,{attributions:options.attributions,logo:options.logo,projection:options.projection,resolutions:options.resolutions,state:options.state});this.canvasFunction_=options.canvasFunction;this.canvas_=null;this.renderedRevision_=0;this.ratio_=options.ratio!==undefined?options.ratio:1.5};
ol.inherits(ol.source.ImageCanvas,ol.source.Image);
ol.source.ImageCanvas.prototype.getImageInternal=function(extent,resolution,pixelRatio,projection){resolution=this.findNearestResolution(resolution);var canvas=this.canvas_;if(canvas&&this.renderedRevision_==this.getRevision()&&canvas.getResolution()==resolution&&canvas.getPixelRatio()==pixelRatio&&ol.extent.containsExtent(canvas.getExtent(),extent))return canvas;extent=extent.slice();ol.extent.scaleFromCenter(extent,this.ratio_);var width=ol.extent.getWidth(extent)/resolution;var height=ol.extent.getHeight(extent)/
resolution;var size=[width*pixelRatio,height*pixelRatio];var canvasElement=this.canvasFunction_(extent,resolution,pixelRatio,size,projection);if(canvasElement)canvas=new ol.ImageCanvas(extent,resolution,pixelRatio,canvasElement);this.canvas_=canvas;this.renderedRevision_=this.getRevision();return canvas};goog.provide("ol.source.ImageMapGuide");goog.require("ol");goog.require("ol.Image");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.obj");goog.require("ol.source.Image");goog.require("ol.uri");
ol.source.ImageMapGuide=function(options){ol.source.Image.call(this,{projection:options.projection,resolutions:options.resolutions});this.crossOrigin_=options.crossOrigin!==undefined?options.crossOrigin:null;this.displayDpi_=options.displayDpi!==undefined?options.displayDpi:96;this.params_=options.params||{};this.url_=options.url;this.imageLoadFunction_=options.imageLoadFunction!==undefined?options.imageLoadFunction:ol.source.Image.defaultImageLoadFunction;this.hidpi_=options.hidpi!==undefined?options.hidpi:
true;this.metersPerUnit_=options.metersPerUnit!==undefined?options.metersPerUnit:1;this.ratio_=options.ratio!==undefined?options.ratio:1;this.useOverlay_=options.useOverlay!==undefined?options.useOverlay:false;this.image_=null;this.renderedRevision_=0};ol.inherits(ol.source.ImageMapGuide,ol.source.Image);ol.source.ImageMapGuide.prototype.getParams=function(){return this.params_};
ol.source.ImageMapGuide.prototype.getImageInternal=function(extent,resolution,pixelRatio,projection){resolution=this.findNearestResolution(resolution);pixelRatio=this.hidpi_?pixelRatio:1;var image=this.image_;if(image&&this.renderedRevision_==this.getRevision()&&image.getResolution()==resolution&&image.getPixelRatio()==pixelRatio&&ol.extent.containsExtent(image.getExtent(),extent))return image;if(this.ratio_!=1){extent=extent.slice();ol.extent.scaleFromCenter(extent,this.ratio_)}var width=ol.extent.getWidth(extent)/
resolution;var height=ol.extent.getHeight(extent)/resolution;var size=[width*pixelRatio,height*pixelRatio];if(this.url_!==undefined){var imageUrl=this.getUrl(this.url_,this.params_,extent,size,projection);image=new ol.Image(extent,resolution,pixelRatio,imageUrl,this.crossOrigin_,this.imageLoadFunction_);ol.events.listen(image,ol.events.EventType.CHANGE,this.handleImageChange,this)}else image=null;this.image_=image;this.renderedRevision_=this.getRevision();return image};
ol.source.ImageMapGuide.prototype.getImageLoadFunction=function(){return this.imageLoadFunction_};ol.source.ImageMapGuide.getScale=function(extent,size,metersPerUnit,dpi){var mcsW=ol.extent.getWidth(extent);var mcsH=ol.extent.getHeight(extent);var devW=size[0];var devH=size[1];var mpp=.0254/dpi;if(devH*mcsW>devW*mcsH)return mcsW*metersPerUnit/(devW*mpp);else return mcsH*metersPerUnit/(devH*mpp)};ol.source.ImageMapGuide.prototype.updateParams=function(params){ol.obj.assign(this.params_,params);this.changed()};
ol.source.ImageMapGuide.prototype.getUrl=function(baseUrl,params,extent,size,projection){var scale=ol.source.ImageMapGuide.getScale(extent,size,this.metersPerUnit_,this.displayDpi_);var center=ol.extent.getCenter(extent);var baseParams={"OPERATION":this.useOverlay_?"GETDYNAMICMAPOVERLAYIMAGE":"GETMAPIMAGE","VERSION":"2.0.0","LOCALE":"en","CLIENTAGENT":"ol.source.ImageMapGuide source","CLIP":"1","SETDISPLAYDPI":this.displayDpi_,"SETDISPLAYWIDTH":Math.round(size[0]),"SETDISPLAYHEIGHT":Math.round(size[1]),
"SETVIEWSCALE":scale,"SETVIEWCENTERX":center[0],"SETVIEWCENTERY":center[1]};ol.obj.assign(baseParams,params);return ol.uri.appendParams(baseUrl,baseParams)};ol.source.ImageMapGuide.prototype.setImageLoadFunction=function(imageLoadFunction){this.image_=null;this.imageLoadFunction_=imageLoadFunction;this.changed()};goog.provide("ol.source.ImageStatic");goog.require("ol");goog.require("ol.Image");goog.require("ol.ImageState");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.proj");goog.require("ol.source.Image");
ol.source.ImageStatic=function(options){var imageExtent=options.imageExtent;var crossOrigin=options.crossOrigin!==undefined?options.crossOrigin:null;var imageLoadFunction=options.imageLoadFunction!==undefined?options.imageLoadFunction:ol.source.Image.defaultImageLoadFunction;ol.source.Image.call(this,{attributions:options.attributions,logo:options.logo,projection:ol.proj.get(options.projection)});this.image_=new ol.Image(imageExtent,undefined,1,options.url,crossOrigin,imageLoadFunction);this.imageSize_=
options.imageSize?options.imageSize:null;ol.events.listen(this.image_,ol.events.EventType.CHANGE,this.handleImageChange,this)};ol.inherits(ol.source.ImageStatic,ol.source.Image);ol.source.ImageStatic.prototype.getImageInternal=function(extent,resolution,pixelRatio,projection){if(ol.extent.intersects(extent,this.image_.getExtent()))return this.image_;return null};
ol.source.ImageStatic.prototype.handleImageChange=function(evt){if(this.image_.getState()==ol.ImageState.LOADED){var imageExtent=this.image_.getExtent();var image=this.image_.getImage();var imageWidth,imageHeight;if(this.imageSize_){imageWidth=this.imageSize_[0];imageHeight=this.imageSize_[1]}else{imageWidth=image.width;imageHeight=image.height}var resolution=ol.extent.getHeight(imageExtent)/imageHeight;var targetWidth=Math.ceil(ol.extent.getWidth(imageExtent)/resolution);if(targetWidth!=imageWidth){var context=
ol.dom.createCanvasContext2D(targetWidth,imageHeight);var canvas=context.canvas;context.drawImage(image,0,0,imageWidth,imageHeight,0,0,canvas.width,canvas.height);this.image_.setImage(canvas)}}ol.source.Image.prototype.handleImageChange.call(this,evt)};goog.provide("ol.source.ImageVector");goog.require("ol");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.ext.rbush");goog.require("ol.extent");goog.require("ol.render.canvas.ReplayGroup");goog.require("ol.renderer.vector");goog.require("ol.source.ImageCanvas");goog.require("ol.style.Style");goog.require("ol.transform");
ol.source.ImageVector=function(options){this.source_=options.source;this.transform_=ol.transform.create();this.canvasContext_=ol.dom.createCanvasContext2D();this.canvasSize_=[0,0];this.declutterTree_=ol.ext.rbush(9);this.renderBuffer_=options.renderBuffer==undefined?100:options.renderBuffer;this.replayGroup_=null;ol.source.ImageCanvas.call(this,{attributions:options.attributions,canvasFunction:this.canvasFunctionInternal_.bind(this),logo:options.logo,projection:options.projection,ratio:options.ratio,
resolutions:options.resolutions,state:this.source_.getState()});this.style_=null;this.styleFunction_=undefined;this.setStyle(options.style);ol.events.listen(this.source_,ol.events.EventType.CHANGE,this.handleSourceChange_,this)};ol.inherits(ol.source.ImageVector,ol.source.ImageCanvas);
ol.source.ImageVector.prototype.canvasFunctionInternal_=function(extent,resolution,pixelRatio,size,projection){var replayGroup=new ol.render.canvas.ReplayGroup(ol.renderer.vector.getTolerance(resolution,pixelRatio),extent,resolution,pixelRatio,this.source_.getOverlaps(),this.declutterTree_,this.renderBuffer_);this.source_.loadFeatures(extent,resolution,projection);var loading=false;this.source_.forEachFeatureInExtent(extent,function(feature){loading=loading||this.renderFeature_(feature,resolution,
pixelRatio,replayGroup)},this);replayGroup.finish();if(loading)return null;if(this.canvasSize_[0]!=size[0]||this.canvasSize_[1]!=size[1]){this.canvasContext_.canvas.width=size[0];this.canvasContext_.canvas.height=size[1];this.canvasSize_[0]=size[0];this.canvasSize_[1]=size[1]}else this.canvasContext_.clearRect(0,0,size[0],size[1]);this.declutterTree_.clear();var transform=this.getTransform_(ol.extent.getCenter(extent),resolution,pixelRatio,size);replayGroup.replay(this.canvasContext_,transform,0,
{});this.replayGroup_=replayGroup;return this.canvasContext_.canvas};
ol.source.ImageVector.prototype.forEachFeatureAtCoordinate=function(coordinate,resolution,rotation,hitTolerance,skippedFeatureUids,callback){if(!this.replayGroup_)return undefined;else{var features={};var result=this.replayGroup_.forEachFeatureAtCoordinate(coordinate,resolution,0,hitTolerance,skippedFeatureUids,function(feature){var key=ol.getUid(feature).toString();if(!(key in features)){features[key]=true;return callback(feature)}},null);return result}};
ol.source.ImageVector.prototype.getSource=function(){return this.source_};ol.source.ImageVector.prototype.getStyle=function(){return this.style_};ol.source.ImageVector.prototype.getStyleFunction=function(){return this.styleFunction_};
ol.source.ImageVector.prototype.getTransform_=function(center,resolution,pixelRatio,size){var dx1=size[0]/2;var dy1=size[1]/2;var sx=pixelRatio/resolution;var sy=-sx;var dx2=-center[0];var dy2=-center[1];return ol.transform.compose(this.transform_,dx1,dy1,sx,sy,0,dx2,dy2)};ol.source.ImageVector.prototype.handleImageChange_=function(event){this.changed()};ol.source.ImageVector.prototype.handleSourceChange_=function(){this.setState(this.source_.getState())};
ol.source.ImageVector.prototype.renderFeature_=function(feature,resolution,pixelRatio,replayGroup){var styles;var styleFunction=feature.getStyleFunction();if(styleFunction)styles=styleFunction.call(feature,resolution);else if(this.styleFunction_)styles=this.styleFunction_(feature,resolution);if(!styles)return false;var i,ii,loading=false;if(!Array.isArray(styles))styles=[styles];for(i=0,ii=styles.length;i<ii;++i)loading=ol.renderer.vector.renderFeature(replayGroup,feature,styles[i],ol.renderer.vector.getSquaredTolerance(resolution,
pixelRatio),this.handleImageChange_,this)||loading;return loading};ol.source.ImageVector.prototype.setStyle=function(style){this.style_=style!==undefined?style:ol.style.Style.defaultFunction;this.styleFunction_=!style?undefined:ol.style.Style.createFunction(this.style_);this.changed()};goog.provide("ol.source.WMSServerType");ol.source.WMSServerType={CARMENTA_SERVER:"carmentaserver",GEOSERVER:"geoserver",MAPSERVER:"mapserver",QGIS:"qgis"};goog.provide("ol.source.ImageWMS");goog.require("ol");goog.require("ol.Image");goog.require("ol.asserts");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.obj");goog.require("ol.proj");goog.require("ol.reproj");goog.require("ol.source.Image");goog.require("ol.source.WMSServerType");goog.require("ol.string");goog.require("ol.uri");
ol.source.ImageWMS=function(opt_options){var options=opt_options||{};ol.source.Image.call(this,{attributions:options.attributions,logo:options.logo,projection:options.projection,resolutions:options.resolutions});this.crossOrigin_=options.crossOrigin!==undefined?options.crossOrigin:null;this.url_=options.url;this.imageLoadFunction_=options.imageLoadFunction!==undefined?options.imageLoadFunction:ol.source.Image.defaultImageLoadFunction;this.params_=options.params||{};this.v13_=true;this.updateV13_();
this.serverType_=options.serverType;this.hidpi_=options.hidpi!==undefined?options.hidpi:true;this.image_=null;this.imageSize_=[0,0];this.renderedRevision_=0;this.ratio_=options.ratio!==undefined?options.ratio:1.5};ol.inherits(ol.source.ImageWMS,ol.source.Image);ol.source.ImageWMS.GETFEATUREINFO_IMAGE_SIZE_=[101,101];
ol.source.ImageWMS.prototype.getGetFeatureInfoUrl=function(coordinate,resolution,projection,params){if(this.url_===undefined)return undefined;var projectionObj=ol.proj.get(projection);var sourceProjectionObj=this.getProjection();if(sourceProjectionObj&&sourceProjectionObj!==projectionObj){resolution=ol.reproj.calculateSourceResolution(sourceProjectionObj,projectionObj,coordinate,resolution);coordinate=ol.proj.transform(coordinate,projectionObj,sourceProjectionObj)}var extent=ol.extent.getForViewAndSize(coordinate,
resolution,0,ol.source.ImageWMS.GETFEATUREINFO_IMAGE_SIZE_);var baseParams={"SERVICE":"WMS","VERSION":ol.DEFAULT_WMS_VERSION,"REQUEST":"GetFeatureInfo","FORMAT":"image/png","TRANSPARENT":true,"QUERY_LAYERS":this.params_["LAYERS"]};ol.obj.assign(baseParams,this.params_,params);var x=Math.floor((coordinate[0]-extent[0])/resolution);var y=Math.floor((extent[3]-coordinate[1])/resolution);baseParams[this.v13_?"I":"X"]=x;baseParams[this.v13_?"J":"Y"]=y;return this.getRequestUrl_(extent,ol.source.ImageWMS.GETFEATUREINFO_IMAGE_SIZE_,
1,sourceProjectionObj||projectionObj,baseParams)};ol.source.ImageWMS.prototype.getParams=function(){return this.params_};
ol.source.ImageWMS.prototype.getImageInternal=function(extent,resolution,pixelRatio,projection){if(this.url_===undefined)return null;resolution=this.findNearestResolution(resolution);if(pixelRatio!=1&&(!this.hidpi_||this.serverType_===undefined))pixelRatio=1;var imageResolution=resolution/pixelRatio;var center=ol.extent.getCenter(extent);var viewWidth=Math.ceil(ol.extent.getWidth(extent)/imageResolution);var viewHeight=Math.ceil(ol.extent.getHeight(extent)/imageResolution);var viewExtent=ol.extent.getForViewAndSize(center,
imageResolution,0,[viewWidth,viewHeight]);var requestWidth=Math.ceil(this.ratio_*ol.extent.getWidth(extent)/imageResolution);var requestHeight=Math.ceil(this.ratio_*ol.extent.getHeight(extent)/imageResolution);var requestExtent=ol.extent.getForViewAndSize(center,imageResolution,0,[requestWidth,requestHeight]);var image=this.image_;if(image&&this.renderedRevision_==this.getRevision()&&image.getResolution()==resolution&&image.getPixelRatio()==pixelRatio&&ol.extent.containsExtent(image.getExtent(),viewExtent))return image;
var params={"SERVICE":"WMS","VERSION":ol.DEFAULT_WMS_VERSION,"REQUEST":"GetMap","FORMAT":"image/png","TRANSPARENT":true};ol.obj.assign(params,this.params_);this.imageSize_[0]=Math.round(ol.extent.getWidth(requestExtent)/imageResolution);this.imageSize_[1]=Math.round(ol.extent.getHeight(requestExtent)/imageResolution);var url=this.getRequestUrl_(requestExtent,this.imageSize_,pixelRatio,projection,params);this.image_=new ol.Image(requestExtent,resolution,pixelRatio,url,this.crossOrigin_,this.imageLoadFunction_);
this.renderedRevision_=this.getRevision();ol.events.listen(this.image_,ol.events.EventType.CHANGE,this.handleImageChange,this);return this.image_};ol.source.ImageWMS.prototype.getImageLoadFunction=function(){return this.imageLoadFunction_};
ol.source.ImageWMS.prototype.getRequestUrl_=function(extent,size,pixelRatio,projection,params){ol.asserts.assert(this.url_!==undefined,9);params[this.v13_?"CRS":"SRS"]=projection.getCode();if(!("STYLES"in this.params_))params["STYLES"]="";if(pixelRatio!=1)switch(this.serverType_){case ol.source.WMSServerType.GEOSERVER:var dpi=90*pixelRatio+.5|0;if("FORMAT_OPTIONS"in params)params["FORMAT_OPTIONS"]+=";dpi:"+dpi;else params["FORMAT_OPTIONS"]="dpi:"+dpi;break;case ol.source.WMSServerType.MAPSERVER:params["MAP_RESOLUTION"]=
90*pixelRatio;break;case ol.source.WMSServerType.CARMENTA_SERVER:case ol.source.WMSServerType.QGIS:params["DPI"]=90*pixelRatio;break;default:ol.asserts.assert(false,8);break}params["WIDTH"]=size[0];params["HEIGHT"]=size[1];var axisOrientation=projection.getAxisOrientation();var bbox;if(this.v13_&&axisOrientation.substr(0,2)=="ne")bbox=[extent[1],extent[0],extent[3],extent[2]];else bbox=extent;params["BBOX"]=bbox.join(",");return ol.uri.appendParams(this.url_,params)};
ol.source.ImageWMS.prototype.getUrl=function(){return this.url_};ol.source.ImageWMS.prototype.setImageLoadFunction=function(imageLoadFunction){this.image_=null;this.imageLoadFunction_=imageLoadFunction;this.changed()};ol.source.ImageWMS.prototype.setUrl=function(url){if(url!=this.url_){this.url_=url;this.image_=null;this.changed()}};ol.source.ImageWMS.prototype.updateParams=function(params){ol.obj.assign(this.params_,params);this.updateV13_();this.image_=null;this.changed()};
ol.source.ImageWMS.prototype.updateV13_=function(){var version=this.params_["VERSION"]||ol.DEFAULT_WMS_VERSION;this.v13_=ol.string.compareVersions(version,"1.3")>=0};goog.provide("ol.source.OSM");goog.require("ol");goog.require("ol.source.XYZ");
ol.source.OSM=function(opt_options){var options=opt_options||{};var attributions;if(options.attributions!==undefined)attributions=options.attributions;else attributions=[ol.source.OSM.ATTRIBUTION];var crossOrigin=options.crossOrigin!==undefined?options.crossOrigin:"anonymous";var url=options.url!==undefined?options.url:"https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png";ol.source.XYZ.call(this,{attributions:attributions,cacheSize:options.cacheSize,crossOrigin:crossOrigin,opaque:options.opaque!==
undefined?options.opaque:true,maxZoom:options.maxZoom!==undefined?options.maxZoom:19,reprojectionErrorThreshold:options.reprojectionErrorThreshold,tileLoadFunction:options.tileLoadFunction,url:url,wrapX:options.wrapX})};ol.inherits(ol.source.OSM,ol.source.XYZ);ol.source.OSM.ATTRIBUTION="&copy; "+'<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> '+"contributors.";goog.provide("ol.ext.pixelworks.Processor");ol.ext.pixelworks.Processor=function(){};
(function(){(function(exports){var hasImageData=true;try{new ImageData(10,10)}catch(_){hasImageData=false}var context=document.createElement("canvas").getContext("2d");function newImageData$1(data,width,height){if(hasImageData)return new ImageData(data,width,height);else{var imageData=context.createImageData(width,height);imageData.data.set(data);return imageData}}var newImageData_1=newImageData$1;var util={newImageData:newImageData_1};var newImageData=util.newImageData;function createMinion(operation){var workerHasImageData=
true;try{new ImageData(10,10)}catch(_$1){workerHasImageData=false}function newWorkerImageData(data,width,height){if(workerHasImageData)return new ImageData(data,width,height);else return{data:data,width:width,height:height}}return function(data){var buffers=data["buffers"];var meta=data["meta"];var imageOps=data["imageOps"];var width=data["width"];var height=data["height"];var numBuffers=buffers.length;var numBytes=buffers[0].byteLength;var output,b;if(imageOps){var images=new Array(numBuffers);for(b=
0;b<numBuffers;++b)images[b]=newWorkerImageData(new Uint8ClampedArray(buffers[b]),width,height);output=operation(images,meta).data}else{output=new Uint8ClampedArray(numBytes);var arrays=new Array(numBuffers);var pixels=new Array(numBuffers);for(b=0;b<numBuffers;++b){arrays[b]=new Uint8ClampedArray(buffers[b]);pixels[b]=[0,0,0,0]}for(var i=0;i<numBytes;i+=4){for(var j=0;j<numBuffers;++j){var array=arrays[j];pixels[j][0]=array[i];pixels[j][1]=array[i+1];pixels[j][2]=array[i+2];pixels[j][3]=array[i+
3]}var pixel=operation(pixels,meta);output[i]=pixel[0];output[i+1]=pixel[1];output[i+2]=pixel[2];output[i+3]=pixel[3]}}return output.buffer}}function createWorker(config,onMessage){var lib=Object.keys(config.lib||{}).map(function(name){return"var "+name+" = "+config.lib[name].toString()+";"});var lines=lib.concat(["var __minion__ = ("+createMinion.toString()+")(",config.operation.toString(),");",'self.addEventListener("message", function(event) {',"  var buffer = __minion__(event.data);","  self.postMessage({buffer: buffer, meta: event.data.meta}, [buffer]);",
"});"]);var blob=new Blob(lines,{type:"text/javascript"});var source=URL.createObjectURL(blob);var worker=new Worker(source);worker.addEventListener("message",onMessage);return worker}function createFauxWorker(config,onMessage){var minion=createMinion(config.operation);return{postMessage:function(data){setTimeout(function(){onMessage({"data":{"buffer":minion(data),"meta":data["meta"]}})},0)}}}function Processor(config){this._imageOps=!!config.imageOps;var threads;if(config.threads===0)threads=0;else if(this._imageOps)threads=
1;else threads=config.threads||1;var workers=[];if(threads)for(var i=0;i<threads;++i)workers[i]=createWorker(config,this._onWorkerMessage.bind(this,i));else workers[0]=createFauxWorker(config,this._onWorkerMessage.bind(this,0));this._workers=workers;this._queue=[];this._maxQueueLength=config.queue||Infinity;this._running=0;this._dataLookup={};this._job=null}Processor.prototype.process=function(inputs,meta,callback){this._enqueue({inputs:inputs,meta:meta,callback:callback});this._dispatch()};Processor.prototype.destroy=
function(){for(var key in this)this[key]=null;this._destroyed=true};Processor.prototype._enqueue=function(job){this._queue.push(job);while(this._queue.length>this._maxQueueLength)this._queue.shift().callback(null,null)};Processor.prototype._dispatch=function(){if(this._running===0&&this._queue.length>0){var job=this._job=this._queue.shift();var width=job.inputs[0].width;var height=job.inputs[0].height;var buffers=job.inputs.map(function(input){return input.data.buffer});var threads=this._workers.length;
this._running=threads;if(threads===1)this._workers[0].postMessage({"buffers":buffers,"meta":job.meta,"imageOps":this._imageOps,"width":width,"height":height},buffers);else{var length=job.inputs[0].data.length;var segmentLength=4*Math.ceil(length/4/threads);for(var i=0;i<threads;++i){var offset=i*segmentLength;var slices=[];for(var j=0,jj=buffers.length;j<jj;++j)slices.push(buffers[i].slice(offset,offset+segmentLength));this._workers[i].postMessage({"buffers":slices,"meta":job.meta,"imageOps":this._imageOps,
"width":width,"height":height},slices)}}}};Processor.prototype._onWorkerMessage=function(index,event){if(this._destroyed)return;this._dataLookup[index]=event.data;--this._running;if(this._running===0)this._resolveJob()};Processor.prototype._resolveJob=function(){var job=this._job;var threads=this._workers.length;var data,meta;if(threads===1){data=new Uint8ClampedArray(this._dataLookup[0]["buffer"]);meta=this._dataLookup[0]["meta"]}else{var length=job.inputs[0].data.length;data=new Uint8ClampedArray(length);
meta=new Array(length);var segmentLength=4*Math.ceil(length/4/threads);for(var i=0;i<threads;++i){var buffer=this._dataLookup[i]["buffer"];var offset=i*segmentLength;data.set(new Uint8ClampedArray(buffer),offset);meta[i]=this._dataLookup[i]["meta"]}}this._job=null;this._dataLookup={};job.callback(null,newImageData(data,job.inputs[0].width,job.inputs[0].height),meta);this._dispatch()};var processor=Processor;var Processor_1=processor;var lib={Processor:Processor_1};exports["default"]=lib;exports.Processor=
Processor_1})(this.pixelworks=this.pixelworks||{})}).call(ol.ext);goog.provide("ol.source.RasterOperationType");ol.source.RasterOperationType={PIXEL:"pixel",IMAGE:"image"};goog.provide("ol.source.Raster");goog.require("ol");goog.require("ol.ImageCanvas");goog.require("ol.TileQueue");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.events.EventType");goog.require("ol.ext.pixelworks.Processor");goog.require("ol.extent");goog.require("ol.layer.Image");goog.require("ol.layer.Tile");goog.require("ol.obj");goog.require("ol.renderer.canvas.ImageLayer");goog.require("ol.renderer.canvas.TileLayer");goog.require("ol.source.Image");
goog.require("ol.source.RasterOperationType");goog.require("ol.source.State");goog.require("ol.source.Tile");goog.require("ol.transform");
ol.source.Raster=function(options){this.worker_=null;this.operationType_=options.operationType!==undefined?options.operationType:ol.source.RasterOperationType.PIXEL;this.threads_=options.threads!==undefined?options.threads:1;this.renderers_=ol.source.Raster.createRenderers_(options.sources);for(var r=0,rr=this.renderers_.length;r<rr;++r)ol.events.listen(this.renderers_[r],ol.events.EventType.CHANGE,this.changed,this);this.tileQueue_=new ol.TileQueue(function(){return 1},this.changed.bind(this));var layerStatesArray=
ol.source.Raster.getLayerStatesArray_(this.renderers_);var layerStates={};for(var i=0,ii=layerStatesArray.length;i<ii;++i)layerStates[ol.getUid(layerStatesArray[i].layer)]=layerStatesArray[i];this.requestedFrameState_;this.renderedImageCanvas_=null;this.renderedRevision_;this.frameState_={animate:false,coordinateToPixelTransform:ol.transform.create(),extent:null,focus:null,index:0,layerStates:layerStates,layerStatesArray:layerStatesArray,logos:{},pixelRatio:1,pixelToCoordinateTransform:ol.transform.create(),
postRenderFunctions:[],size:[0,0],skippedFeatureUids:{},tileQueue:this.tileQueue_,time:Date.now(),usedTiles:{},viewState:{rotation:0},viewHints:[],wantedTiles:{}};ol.source.Image.call(this,{});if(options.operation!==undefined)this.setOperation(options.operation,options.lib)};ol.inherits(ol.source.Raster,ol.source.Image);
ol.source.Raster.prototype.setOperation=function(operation,opt_lib){this.worker_=new ol.ext.pixelworks.Processor({operation:operation,imageOps:this.operationType_===ol.source.RasterOperationType.IMAGE,queue:1,lib:opt_lib,threads:this.threads_});this.changed()};
ol.source.Raster.prototype.updateFrameState_=function(extent,resolution,projection){var frameState=ol.obj.assign({},this.frameState_);frameState.viewState=ol.obj.assign({},frameState.viewState);var center=ol.extent.getCenter(extent);frameState.extent=extent.slice();frameState.focus=center;frameState.size[0]=Math.round(ol.extent.getWidth(extent)/resolution);frameState.size[1]=Math.round(ol.extent.getHeight(extent)/resolution);frameState.time=Date.now();frameState.animate=false;var viewState=frameState.viewState;
viewState.center=center;viewState.projection=projection;viewState.resolution=resolution;return frameState};ol.source.Raster.prototype.allSourcesReady_=function(){var ready=true;var source;for(var i=0,ii=this.renderers_.length;i<ii;++i){source=this.renderers_[i].getLayer().getSource();if(source.getState()!==ol.source.State.READY){ready=false;break}}return ready};
ol.source.Raster.prototype.getImage=function(extent,resolution,pixelRatio,projection){if(!this.allSourcesReady_())return null;var frameState=this.updateFrameState_(extent,resolution,projection);this.requestedFrameState_=frameState;if(this.renderedImageCanvas_){var renderedResolution=this.renderedImageCanvas_.getResolution();var renderedExtent=this.renderedImageCanvas_.getExtent();if(resolution!==renderedResolution||!ol.extent.equals(extent,renderedExtent))this.renderedImageCanvas_=null}if(!this.renderedImageCanvas_||
this.getRevision()!==this.renderedRevision_)this.processSources_();frameState.tileQueue.loadMoreTiles(16,16);if(frameState.animate)requestAnimationFrame(this.changed.bind(this));return this.renderedImageCanvas_};
ol.source.Raster.prototype.processSources_=function(){var frameState=this.requestedFrameState_;var len=this.renderers_.length;var imageDatas=new Array(len);for(var i=0;i<len;++i){var imageData=ol.source.Raster.getImageData_(this.renderers_[i],frameState,frameState.layerStatesArray[i]);if(imageData)imageDatas[i]=imageData;else return}var data={};this.dispatchEvent(new ol.source.Raster.Event(ol.source.Raster.EventType_.BEFOREOPERATIONS,frameState,data));this.worker_.process(imageDatas,data,this.onWorkerComplete_.bind(this,
frameState))};
ol.source.Raster.prototype.onWorkerComplete_=function(frameState,err,output,data){if(err||!output)return;var extent=frameState.extent;var resolution=frameState.viewState.resolution;if(resolution!==this.requestedFrameState_.viewState.resolution||!ol.extent.equals(extent,this.requestedFrameState_.extent))return;var context;if(this.renderedImageCanvas_)context=this.renderedImageCanvas_.getImage().getContext("2d");else{var width=Math.round(ol.extent.getWidth(extent)/resolution);var height=Math.round(ol.extent.getHeight(extent)/
resolution);context=ol.dom.createCanvasContext2D(width,height);this.renderedImageCanvas_=new ol.ImageCanvas(extent,resolution,1,context.canvas)}context.putImageData(output,0,0);this.changed();this.renderedRevision_=this.getRevision();this.dispatchEvent(new ol.source.Raster.Event(ol.source.Raster.EventType_.AFTEROPERATIONS,frameState,data))};
ol.source.Raster.getImageData_=function(renderer,frameState,layerState){if(!renderer.prepareFrame(frameState,layerState))return null;var width=frameState.size[0];var height=frameState.size[1];if(!ol.source.Raster.context_)ol.source.Raster.context_=ol.dom.createCanvasContext2D(width,height);else{var canvas=ol.source.Raster.context_.canvas;if(canvas.width!==width||canvas.height!==height)ol.source.Raster.context_=ol.dom.createCanvasContext2D(width,height);else ol.source.Raster.context_.clearRect(0,0,
width,height)}renderer.composeFrame(frameState,layerState,ol.source.Raster.context_);return ol.source.Raster.context_.getImageData(0,0,width,height)};ol.source.Raster.context_=null;ol.source.Raster.getLayerStatesArray_=function(renderers){return renderers.map(function(renderer){return renderer.getLayer().getLayerState()})};
ol.source.Raster.createRenderers_=function(sources){var len=sources.length;var renderers=new Array(len);for(var i=0;i<len;++i)renderers[i]=ol.source.Raster.createRenderer_(sources[i]);return renderers};ol.source.Raster.createRenderer_=function(source){var renderer=null;if(source instanceof ol.source.Tile)renderer=ol.source.Raster.createTileRenderer_(source);else if(source instanceof ol.source.Image)renderer=ol.source.Raster.createImageRenderer_(source);return renderer};
ol.source.Raster.createImageRenderer_=function(source){var layer=new ol.layer.Image({source:source});return new ol.renderer.canvas.ImageLayer(layer)};ol.source.Raster.createTileRenderer_=function(source){var layer=new ol.layer.Tile({source:source});return new ol.renderer.canvas.TileLayer(layer)};ol.source.Raster.Event=function(type,frameState,data){ol.events.Event.call(this,type);this.extent=frameState.extent;this.resolution=frameState.viewState.resolution/frameState.pixelRatio;this.data=data};
ol.inherits(ol.source.Raster.Event,ol.events.Event);ol.source.Raster.prototype.getImageInternal=function(){return null};ol.source.Raster.EventType_={BEFOREOPERATIONS:"beforeoperations",AFTEROPERATIONS:"afteroperations"};goog.provide("ol.source.Stamen");goog.require("ol");goog.require("ol.source.OSM");goog.require("ol.source.XYZ");
ol.source.Stamen=function(options){var i=options.layer.indexOf("-");var provider=i==-1?options.layer:options.layer.slice(0,i);var providerConfig=ol.source.Stamen.ProviderConfig[provider];var layerConfig=ol.source.Stamen.LayerConfig[options.layer];var url=options.url!==undefined?options.url:"https://stamen-tiles-{a-d}.a.ssl.fastly.net/"+options.layer+"/{z}/{x}/{y}."+layerConfig.extension;ol.source.XYZ.call(this,{attributions:ol.source.Stamen.ATTRIBUTIONS,cacheSize:options.cacheSize,crossOrigin:"anonymous",
maxZoom:options.maxZoom!=undefined?options.maxZoom:providerConfig.maxZoom,minZoom:options.minZoom!=undefined?options.minZoom:providerConfig.minZoom,opaque:layerConfig.opaque,reprojectionErrorThreshold:options.reprojectionErrorThreshold,tileLoadFunction:options.tileLoadFunction,url:url,wrapX:options.wrapX})};ol.inherits(ol.source.Stamen,ol.source.XYZ);
ol.source.Stamen.ATTRIBUTIONS=['Map tiles by <a href="https://stamen.com/">Stamen Design</a>, '+'under <a href="https://creativecommons.org/licenses/by/3.0/">CC BY'+" 3.0</a>.",ol.source.OSM.ATTRIBUTION];
ol.source.Stamen.LayerConfig={"terrain":{extension:"jpg",opaque:true},"terrain-background":{extension:"jpg",opaque:true},"terrain-labels":{extension:"png",opaque:false},"terrain-lines":{extension:"png",opaque:false},"toner-background":{extension:"png",opaque:true},"toner":{extension:"png",opaque:true},"toner-hybrid":{extension:"png",opaque:false},"toner-labels":{extension:"png",opaque:false},"toner-lines":{extension:"png",opaque:false},"toner-lite":{extension:"png",opaque:true},"watercolor":{extension:"jpg",
opaque:true}};ol.source.Stamen.ProviderConfig={"terrain":{minZoom:4,maxZoom:18},"toner":{minZoom:0,maxZoom:20},"watercolor":{minZoom:1,maxZoom:16}};goog.provide("ol.source.TileArcGISRest");goog.require("ol");goog.require("ol.extent");goog.require("ol.math");goog.require("ol.obj");goog.require("ol.size");goog.require("ol.source.TileImage");goog.require("ol.tilecoord");goog.require("ol.uri");
ol.source.TileArcGISRest=function(opt_options){var options=opt_options||{};ol.source.TileImage.call(this,{attributions:options.attributions,cacheSize:options.cacheSize,crossOrigin:options.crossOrigin,logo:options.logo,projection:options.projection,reprojectionErrorThreshold:options.reprojectionErrorThreshold,tileGrid:options.tileGrid,tileLoadFunction:options.tileLoadFunction,url:options.url,urls:options.urls,wrapX:options.wrapX!==undefined?options.wrapX:true,transition:options.transition});this.params_=
options.params||{};this.tmpExtent_=ol.extent.createEmpty();this.setKey(this.getKeyForParams_())};ol.inherits(ol.source.TileArcGISRest,ol.source.TileImage);ol.source.TileArcGISRest.prototype.getKeyForParams_=function(){var i=0;var res=[];for(var key in this.params_)res[i++]=key+"-"+this.params_[key];return res.join("/")};ol.source.TileArcGISRest.prototype.getParams=function(){return this.params_};
ol.source.TileArcGISRest.prototype.getRequestUrl_=function(tileCoord,tileSize,tileExtent,pixelRatio,projection,params){var urls=this.urls;if(!urls)return undefined;var srid=projection.getCode().split(":").pop();params["SIZE"]=tileSize[0]+","+tileSize[1];params["BBOX"]=tileExtent.join(",");params["BBOXSR"]=srid;params["IMAGESR"]=srid;params["DPI"]=Math.round(params["DPI"]?params["DPI"]*pixelRatio:90*pixelRatio);var url;if(urls.length==1)url=urls[0];else{var index=ol.math.modulo(ol.tilecoord.hash(tileCoord),
urls.length);url=urls[index]}var modifiedUrl=url.replace(/MapServer\/?$/,"MapServer/export").replace(/ImageServer\/?$/,"ImageServer/exportImage");return ol.uri.appendParams(modifiedUrl,params)};ol.source.TileArcGISRest.prototype.getTilePixelRatio=function(pixelRatio){return pixelRatio};
ol.source.TileArcGISRest.prototype.fixedTileUrlFunction=function(tileCoord,pixelRatio,projection){var tileGrid=this.getTileGrid();if(!tileGrid)tileGrid=this.getTileGridForProjection(projection);if(tileGrid.getResolutions().length<=tileCoord[0])return undefined;var tileExtent=tileGrid.getTileCoordExtent(tileCoord,this.tmpExtent_);var tileSize=ol.size.toSize(tileGrid.getTileSize(tileCoord[0]),this.tmpSize);if(pixelRatio!=1)tileSize=ol.size.scale(tileSize,pixelRatio,this.tmpSize);var baseParams={"F":"image",
"FORMAT":"PNG32","TRANSPARENT":true};ol.obj.assign(baseParams,this.params_);return this.getRequestUrl_(tileCoord,tileSize,tileExtent,pixelRatio,projection,baseParams)};ol.source.TileArcGISRest.prototype.updateParams=function(params){ol.obj.assign(this.params_,params);this.setKey(this.getKeyForParams_())};goog.provide("ol.source.TileDebug");goog.require("ol");goog.require("ol.Tile");goog.require("ol.TileState");goog.require("ol.dom");goog.require("ol.size");goog.require("ol.source.Tile");goog.require("ol.tilecoord");ol.source.TileDebug=function(options){ol.source.Tile.call(this,{opaque:false,projection:options.projection,tileGrid:options.tileGrid,wrapX:options.wrapX!==undefined?options.wrapX:true})};ol.inherits(ol.source.TileDebug,ol.source.Tile);
ol.source.TileDebug.prototype.getTile=function(z,x,y){var tileCoordKey=ol.tilecoord.getKeyZXY(z,x,y);if(this.tileCache.containsKey(tileCoordKey))return this.tileCache.get(tileCoordKey);else{var tileSize=ol.size.toSize(this.tileGrid.getTileSize(z));var tileCoord=[z,x,y];var textTileCoord=this.getTileCoordForTileUrlFunction(tileCoord);var text=!textTileCoord?"":this.getTileCoordForTileUrlFunction(textTileCoord).toString();var tile=new ol.source.TileDebug.Tile_(tileCoord,tileSize,text);this.tileCache.set(tileCoordKey,
tile);return tile}};ol.source.TileDebug.Tile_=function(tileCoord,tileSize,text){ol.Tile.call(this,tileCoord,ol.TileState.LOADED);this.tileSize_=tileSize;this.text_=text;this.canvas_=null};ol.inherits(ol.source.TileDebug.Tile_,ol.Tile);
ol.source.TileDebug.Tile_.prototype.getImage=function(){if(this.canvas_)return this.canvas_;else{var tileSize=this.tileSize_;var context=ol.dom.createCanvasContext2D(tileSize[0],tileSize[1]);context.strokeStyle="black";context.strokeRect(.5,.5,tileSize[0]+.5,tileSize[1]+.5);context.fillStyle="black";context.textAlign="center";context.textBaseline="middle";context.font="24px sans-serif";context.fillText(this.text_,tileSize[0]/2,tileSize[1]/2);this.canvas_=context.canvas;return context.canvas}};
ol.source.TileDebug.Tile_.prototype.load=function(){};goog.provide("ol.source.TileJSON");goog.require("ol");goog.require("ol.TileUrlFunction");goog.require("ol.asserts");goog.require("ol.extent");goog.require("ol.net");goog.require("ol.proj");goog.require("ol.source.State");goog.require("ol.source.TileImage");goog.require("ol.tilegrid");
ol.source.TileJSON=function(options){this.tileJSON_=null;ol.source.TileImage.call(this,{attributions:options.attributions,cacheSize:options.cacheSize,crossOrigin:options.crossOrigin,projection:ol.proj.get("EPSG:3857"),reprojectionErrorThreshold:options.reprojectionErrorThreshold,state:ol.source.State.LOADING,tileLoadFunction:options.tileLoadFunction,wrapX:options.wrapX!==undefined?options.wrapX:true,transition:options.transition});if(options.url)if(options.jsonp)ol.net.jsonp(options.url,this.handleTileJSONResponse.bind(this),
this.handleTileJSONError.bind(this));else{var client=new XMLHttpRequest;client.addEventListener("load",this.onXHRLoad_.bind(this));client.addEventListener("error",this.onXHRError_.bind(this));client.open("GET",options.url);client.send()}else if(options.tileJSON)this.handleTileJSONResponse(options.tileJSON);else ol.asserts.assert(false,51)};ol.inherits(ol.source.TileJSON,ol.source.TileImage);
ol.source.TileJSON.prototype.onXHRLoad_=function(event){var client=event.target;if(!client.status||client.status>=200&&client.status<300){var response;try{response=JSON.parse(client.responseText)}catch(err){this.handleTileJSONError();return}this.handleTileJSONResponse(response)}else this.handleTileJSONError()};ol.source.TileJSON.prototype.onXHRError_=function(event){this.handleTileJSONError()};ol.source.TileJSON.prototype.getTileJSON=function(){return this.tileJSON_};
ol.source.TileJSON.prototype.handleTileJSONResponse=function(tileJSON){var epsg4326Projection=ol.proj.get("EPSG:4326");var sourceProjection=this.getProjection();var extent;if(tileJSON.bounds!==undefined){var transform=ol.proj.getTransformFromProjections(epsg4326Projection,sourceProjection);extent=ol.extent.applyTransform(tileJSON.bounds,transform)}var minZoom=tileJSON.minzoom||0;var maxZoom=tileJSON.maxzoom||22;var tileGrid=ol.tilegrid.createXYZ({extent:ol.tilegrid.extentFromProjection(sourceProjection),
maxZoom:maxZoom,minZoom:minZoom});this.tileGrid=tileGrid;this.tileUrlFunction=ol.TileUrlFunction.createFromTemplates(tileJSON.tiles,tileGrid);if(tileJSON.attribution!==undefined&&!this.getAttributions2()){var attributionExtent=extent!==undefined?extent:epsg4326Projection.getExtent();this.setAttributions(function(frameState){if(ol.extent.intersects(attributionExtent,frameState.extent))return[tileJSON.attribution];return null})}this.tileJSON_=tileJSON;this.setState(ol.source.State.READY)};
ol.source.TileJSON.prototype.handleTileJSONError=function(){this.setState(ol.source.State.ERROR)};goog.provide("ol.source.TileUTFGrid");goog.require("ol");goog.require("ol.Tile");goog.require("ol.TileState");goog.require("ol.TileUrlFunction");goog.require("ol.asserts");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.extent");goog.require("ol.net");goog.require("ol.proj");goog.require("ol.source.State");goog.require("ol.source.Tile");goog.require("ol.tilecoord");goog.require("ol.tilegrid");
ol.source.TileUTFGrid=function(options){ol.source.Tile.call(this,{projection:ol.proj.get("EPSG:3857"),state:ol.source.State.LOADING});this.preemptive_=options.preemptive!==undefined?options.preemptive:true;this.tileUrlFunction_=ol.TileUrlFunction.nullTileUrlFunction;this.template_=undefined;this.jsonp_=options.jsonp||false;if(options.url)if(this.jsonp_)ol.net.jsonp(options.url,this.handleTileJSONResponse.bind(this),this.handleTileJSONError.bind(this));else{var client=new XMLHttpRequest;client.addEventListener("load",
this.onXHRLoad_.bind(this));client.addEventListener("error",this.onXHRError_.bind(this));client.open("GET",options.url);client.send()}else if(options.tileJSON)this.handleTileJSONResponse(options.tileJSON);else ol.asserts.assert(false,51)};ol.inherits(ol.source.TileUTFGrid,ol.source.Tile);
ol.source.TileUTFGrid.prototype.onXHRLoad_=function(event){var client=event.target;if(!client.status||client.status>=200&&client.status<300){var response;try{response=JSON.parse(client.responseText)}catch(err){this.handleTileJSONError();return}this.handleTileJSONResponse(response)}else this.handleTileJSONError()};ol.source.TileUTFGrid.prototype.onXHRError_=function(event){this.handleTileJSONError()};ol.source.TileUTFGrid.prototype.getTemplate=function(){return this.template_};
ol.source.TileUTFGrid.prototype.forDataAtCoordinateAndResolution=function(coordinate,resolution,callback,opt_this,opt_request){if(this.tileGrid){var tileCoord=this.tileGrid.getTileCoordForCoordAndResolution(coordinate,resolution);var tile=this.getTile(tileCoord[0],tileCoord[1],tileCoord[2],1,this.getProjection());tile.forDataAtCoordinate(coordinate,callback,opt_this,opt_request)}else if(opt_request===true)setTimeout(function(){callback.call(opt_this,null)},0);else callback.call(opt_this,null)};
ol.source.TileUTFGrid.prototype.handleTileJSONError=function(){this.setState(ol.source.State.ERROR)};
ol.source.TileUTFGrid.prototype.handleTileJSONResponse=function(tileJSON){var epsg4326Projection=ol.proj.get("EPSG:4326");var sourceProjection=this.getProjection();var extent;if(tileJSON.bounds!==undefined){var transform=ol.proj.getTransformFromProjections(epsg4326Projection,sourceProjection);extent=ol.extent.applyTransform(tileJSON.bounds,transform)}var minZoom=tileJSON.minzoom||0;var maxZoom=tileJSON.maxzoom||22;var tileGrid=ol.tilegrid.createXYZ({extent:ol.tilegrid.extentFromProjection(sourceProjection),
maxZoom:maxZoom,minZoom:minZoom});this.tileGrid=tileGrid;this.template_=tileJSON.template;var grids=tileJSON.grids;if(!grids){this.setState(ol.source.State.ERROR);return}this.tileUrlFunction_=ol.TileUrlFunction.createFromTemplates(grids,tileGrid);if(tileJSON.attribution!==undefined){var attributionExtent=extent!==undefined?extent:epsg4326Projection.getExtent();this.setAttributions(function(frameState){if(ol.extent.intersects(attributionExtent,frameState.extent))return[tileJSON.attribution];return null})}this.setState(ol.source.State.READY)};
ol.source.TileUTFGrid.prototype.getTile=function(z,x,y,pixelRatio,projection){var tileCoordKey=ol.tilecoord.getKeyZXY(z,x,y);if(this.tileCache.containsKey(tileCoordKey))return this.tileCache.get(tileCoordKey);else{var tileCoord=[z,x,y];var urlTileCoord=this.getTileCoordForTileUrlFunction(tileCoord,projection);var tileUrl=this.tileUrlFunction_(urlTileCoord,pixelRatio,projection);var tile=new ol.source.TileUTFGrid.Tile_(tileCoord,tileUrl!==undefined?ol.TileState.IDLE:ol.TileState.EMPTY,tileUrl!==undefined?
tileUrl:"",this.tileGrid.getTileCoordExtent(tileCoord),this.preemptive_,this.jsonp_);this.tileCache.set(tileCoordKey,tile);return tile}};ol.source.TileUTFGrid.prototype.useTile=function(z,x,y){var tileCoordKey=ol.tilecoord.getKeyZXY(z,x,y);if(this.tileCache.containsKey(tileCoordKey))this.tileCache.get(tileCoordKey)};
ol.source.TileUTFGrid.Tile_=function(tileCoord,state,src,extent,preemptive,jsonp){ol.Tile.call(this,tileCoord,state);this.src_=src;this.extent_=extent;this.preemptive_=preemptive;this.grid_=null;this.keys_=null;this.data_=null;this.jsonp_=jsonp};ol.inherits(ol.source.TileUTFGrid.Tile_,ol.Tile);ol.source.TileUTFGrid.Tile_.prototype.getImage=function(){return null};
ol.source.TileUTFGrid.Tile_.prototype.getData=function(coordinate){if(!this.grid_||!this.keys_)return null;var xRelative=(coordinate[0]-this.extent_[0])/(this.extent_[2]-this.extent_[0]);var yRelative=(coordinate[1]-this.extent_[1])/(this.extent_[3]-this.extent_[1]);var row=this.grid_[Math.floor((1-yRelative)*this.grid_.length)];if(typeof row!=="string")return null;var code=row.charCodeAt(Math.floor(xRelative*row.length));if(code>=93)code--;if(code>=35)code--;code-=32;var data=null;if(code in this.keys_){var id=
this.keys_[code];if(this.data_&&id in this.data_)data=this.data_[id];else data=id}return data};
ol.source.TileUTFGrid.Tile_.prototype.forDataAtCoordinate=function(coordinate,callback,opt_this,opt_request){if(this.state==ol.TileState.IDLE&&opt_request===true){ol.events.listenOnce(this,ol.events.EventType.CHANGE,function(e){callback.call(opt_this,this.getData(coordinate))},this);this.loadInternal_()}else if(opt_request===true)setTimeout(function(){callback.call(opt_this,this.getData(coordinate))}.bind(this),0);else callback.call(opt_this,this.getData(coordinate))};
ol.source.TileUTFGrid.Tile_.prototype.getKey=function(){return this.src_};ol.source.TileUTFGrid.Tile_.prototype.handleError_=function(){this.state=ol.TileState.ERROR;this.changed()};ol.source.TileUTFGrid.Tile_.prototype.handleLoad_=function(json){this.grid_=json.grid;this.keys_=json.keys;this.data_=json.data;this.state=ol.TileState.EMPTY;this.changed()};
ol.source.TileUTFGrid.Tile_.prototype.loadInternal_=function(){if(this.state==ol.TileState.IDLE){this.state=ol.TileState.LOADING;if(this.jsonp_)ol.net.jsonp(this.src_,this.handleLoad_.bind(this),this.handleError_.bind(this));else{var client=new XMLHttpRequest;client.addEventListener("load",this.onXHRLoad_.bind(this));client.addEventListener("error",this.onXHRError_.bind(this));client.open("GET",this.src_);client.send()}}};
ol.source.TileUTFGrid.Tile_.prototype.onXHRLoad_=function(event){var client=event.target;if(!client.status||client.status>=200&&client.status<300){var response;try{response=JSON.parse(client.responseText)}catch(err){this.handleError_();return}this.handleLoad_(response)}else this.handleError_()};ol.source.TileUTFGrid.Tile_.prototype.onXHRError_=function(event){this.handleError_()};ol.source.TileUTFGrid.Tile_.prototype.load=function(){if(this.preemptive_)this.loadInternal_()};goog.provide("ol.source.TileWMS");goog.require("ol");goog.require("ol.asserts");goog.require("ol.extent");goog.require("ol.obj");goog.require("ol.math");goog.require("ol.proj");goog.require("ol.reproj");goog.require("ol.size");goog.require("ol.source.TileImage");goog.require("ol.source.WMSServerType");goog.require("ol.tilecoord");goog.require("ol.string");goog.require("ol.uri");
ol.source.TileWMS=function(opt_options){var options=opt_options||{};var params=options.params||{};var transparent="TRANSPARENT"in params?params["TRANSPARENT"]:true;ol.source.TileImage.call(this,{attributions:options.attributions,cacheSize:options.cacheSize,crossOrigin:options.crossOrigin,logo:options.logo,opaque:!transparent,projection:options.projection,reprojectionErrorThreshold:options.reprojectionErrorThreshold,tileClass:options.tileClass,tileGrid:options.tileGrid,tileLoadFunction:options.tileLoadFunction,
url:options.url,urls:options.urls,wrapX:options.wrapX!==undefined?options.wrapX:true,transition:options.transition});this.gutter_=options.gutter!==undefined?options.gutter:0;this.params_=params;this.v13_=true;this.serverType_=options.serverType;this.hidpi_=options.hidpi!==undefined?options.hidpi:true;this.tmpExtent_=ol.extent.createEmpty();this.updateV13_();this.setKey(this.getKeyForParams_())};ol.inherits(ol.source.TileWMS,ol.source.TileImage);
ol.source.TileWMS.prototype.getGetFeatureInfoUrl=function(coordinate,resolution,projection,params){var projectionObj=ol.proj.get(projection);var sourceProjectionObj=this.getProjection();var tileGrid=this.getTileGrid();if(!tileGrid)tileGrid=this.getTileGridForProjection(projectionObj);var tileCoord=tileGrid.getTileCoordForCoordAndResolution(coordinate,resolution);if(tileGrid.getResolutions().length<=tileCoord[0])return undefined;var tileResolution=tileGrid.getResolution(tileCoord[0]);var tileExtent=
tileGrid.getTileCoordExtent(tileCoord,this.tmpExtent_);var tileSize=ol.size.toSize(tileGrid.getTileSize(tileCoord[0]),this.tmpSize);var gutter=this.gutter_;if(gutter!==0){tileSize=ol.size.buffer(tileSize,gutter,this.tmpSize);tileExtent=ol.extent.buffer(tileExtent,tileResolution*gutter,tileExtent)}if(sourceProjectionObj&&sourceProjectionObj!==projectionObj){tileResolution=ol.reproj.calculateSourceResolution(sourceProjectionObj,projectionObj,coordinate,tileResolution);tileExtent=ol.proj.transformExtent(tileExtent,
projectionObj,sourceProjectionObj);coordinate=ol.proj.transform(coordinate,projectionObj,sourceProjectionObj)}var baseParams={"SERVICE":"WMS","VERSION":ol.DEFAULT_WMS_VERSION,"REQUEST":"GetFeatureInfo","FORMAT":"image/png","TRANSPARENT":true,"QUERY_LAYERS":this.params_["LAYERS"]};ol.obj.assign(baseParams,this.params_,params);var x=Math.floor((coordinate[0]-tileExtent[0])/tileResolution);var y=Math.floor((tileExtent[3]-coordinate[1])/tileResolution);baseParams[this.v13_?"I":"X"]=x;baseParams[this.v13_?
"J":"Y"]=y;return this.getRequestUrl_(tileCoord,tileSize,tileExtent,1,sourceProjectionObj||projectionObj,baseParams)};ol.source.TileWMS.prototype.getGutterInternal=function(){return this.gutter_};ol.source.TileWMS.prototype.getParams=function(){return this.params_};
ol.source.TileWMS.prototype.getRequestUrl_=function(tileCoord,tileSize,tileExtent,pixelRatio,projection,params){var urls=this.urls;if(!urls)return undefined;params["WIDTH"]=tileSize[0];params["HEIGHT"]=tileSize[1];params[this.v13_?"CRS":"SRS"]=projection.getCode();if(!("STYLES"in this.params_))params["STYLES"]="";if(pixelRatio!=1)switch(this.serverType_){case ol.source.WMSServerType.GEOSERVER:var dpi=90*pixelRatio+.5|0;if("FORMAT_OPTIONS"in params)params["FORMAT_OPTIONS"]+=";dpi:"+dpi;else params["FORMAT_OPTIONS"]=
"dpi:"+dpi;break;case ol.source.WMSServerType.MAPSERVER:params["MAP_RESOLUTION"]=90*pixelRatio;break;case ol.source.WMSServerType.CARMENTA_SERVER:case ol.source.WMSServerType.QGIS:params["DPI"]=90*pixelRatio;break;default:ol.asserts.assert(false,52);break}var axisOrientation=projection.getAxisOrientation();var bbox=tileExtent;if(this.v13_&&axisOrientation.substr(0,2)=="ne"){var tmp;tmp=tileExtent[0];bbox[0]=tileExtent[1];bbox[1]=tmp;tmp=tileExtent[2];bbox[2]=tileExtent[3];bbox[3]=tmp}params["BBOX"]=
bbox.join(",");var url;if(urls.length==1)url=urls[0];else{var index=ol.math.modulo(ol.tilecoord.hash(tileCoord),urls.length);url=urls[index]}return ol.uri.appendParams(url,params)};ol.source.TileWMS.prototype.getTilePixelRatio=function(pixelRatio){return!this.hidpi_||this.serverType_===undefined?1:pixelRatio};ol.source.TileWMS.prototype.getKeyForParams_=function(){var i=0;var res=[];for(var key in this.params_)res[i++]=key+"-"+this.params_[key];return res.join("/")};
ol.source.TileWMS.prototype.fixedTileUrlFunction=function(tileCoord,pixelRatio,projection){var tileGrid=this.getTileGrid();if(!tileGrid)tileGrid=this.getTileGridForProjection(projection);if(tileGrid.getResolutions().length<=tileCoord[0])return undefined;if(pixelRatio!=1&&(!this.hidpi_||this.serverType_===undefined))pixelRatio=1;var tileResolution=tileGrid.getResolution(tileCoord[0]);var tileExtent=tileGrid.getTileCoordExtent(tileCoord,this.tmpExtent_);var tileSize=ol.size.toSize(tileGrid.getTileSize(tileCoord[0]),
this.tmpSize);var gutter=this.gutter_;if(gutter!==0){tileSize=ol.size.buffer(tileSize,gutter,this.tmpSize);tileExtent=ol.extent.buffer(tileExtent,tileResolution*gutter,tileExtent)}if(pixelRatio!=1)tileSize=ol.size.scale(tileSize,pixelRatio,this.tmpSize);var baseParams={"SERVICE":"WMS","VERSION":ol.DEFAULT_WMS_VERSION,"REQUEST":"GetMap","FORMAT":"image/png","TRANSPARENT":true};ol.obj.assign(baseParams,this.params_);return this.getRequestUrl_(tileCoord,tileSize,tileExtent,pixelRatio,projection,baseParams)};
ol.source.TileWMS.prototype.updateParams=function(params){ol.obj.assign(this.params_,params);this.updateV13_();this.setKey(this.getKeyForParams_())};ol.source.TileWMS.prototype.updateV13_=function(){var version=this.params_["VERSION"]||ol.DEFAULT_WMS_VERSION;this.v13_=ol.string.compareVersions(version,"1.3")>=0};goog.provide("ol.VectorImageTile");goog.require("ol");goog.require("ol.Tile");goog.require("ol.TileState");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.extent");goog.require("ol.events.EventType");goog.require("ol.featureloader");
ol.VectorImageTile=function(tileCoord,state,sourceRevision,format,tileLoadFunction,urlTileCoord,tileUrlFunction,sourceTileGrid,tileGrid,sourceTiles,pixelRatio,projection,tileClass,handleTileChange,opt_options){ol.Tile.call(this,tileCoord,state,opt_options);this.context_={};this.loader_;this.replayState_={};this.sourceTiles_=sourceTiles;this.tileKeys=[];this.sourceRevision_=sourceRevision;this.wrappedTileCoord=urlTileCoord;this.loadListenerKeys_=[];this.sourceTileListenerKeys_=[];if(urlTileCoord){var extent=
tileGrid.getTileCoordExtent(urlTileCoord);var resolution=tileGrid.getResolution(tileCoord[0]);var sourceZ=sourceTileGrid.getZForResolution(resolution);sourceTileGrid.forEachTileCoord(extent,sourceZ,function(sourceTileCoord){var sharedExtent=ol.extent.getIntersection(extent,sourceTileGrid.getTileCoordExtent(sourceTileCoord));var sourceExtent=sourceTileGrid.getExtent();if(sourceExtent)sharedExtent=ol.extent.getIntersection(sharedExtent,sourceExtent);if(ol.extent.getWidth(sharedExtent)/resolution>=.5&&
ol.extent.getHeight(sharedExtent)/resolution>=.5){var sourceTileKey=sourceTileCoord.toString();var sourceTile=sourceTiles[sourceTileKey];if(!sourceTile){var tileUrl=tileUrlFunction(sourceTileCoord,pixelRatio,projection);sourceTile=sourceTiles[sourceTileKey]=new tileClass(sourceTileCoord,tileUrl==undefined?ol.TileState.EMPTY:ol.TileState.IDLE,tileUrl==undefined?"":tileUrl,format,tileLoadFunction);this.sourceTileListenerKeys_.push(ol.events.listen(sourceTile,ol.events.EventType.CHANGE,handleTileChange))}sourceTile.consumers++;
this.tileKeys.push(sourceTileKey)}}.bind(this))}};ol.inherits(ol.VectorImageTile,ol.Tile);
ol.VectorImageTile.prototype.disposeInternal=function(){for(var i=0,ii=this.tileKeys.length;i<ii;++i){var sourceTileKey=this.tileKeys[i];var sourceTile=this.getTile(sourceTileKey);sourceTile.consumers--;if(sourceTile.consumers==0){delete this.sourceTiles_[sourceTileKey];sourceTile.dispose()}}this.tileKeys.length=0;this.sourceTiles_=null;this.loadListenerKeys_.forEach(ol.events.unlistenByKey);this.loadListenerKeys_.length=0;if(this.interimTile)this.interimTile.dispose();this.state=ol.TileState.ABORT;
this.changed();this.sourceTileListenerKeys_.forEach(ol.events.unlistenByKey);this.sourceTileListenerKeys_.length=0;ol.Tile.prototype.disposeInternal.call(this)};ol.VectorImageTile.prototype.getContext=function(layer){var key=ol.getUid(layer).toString();if(!(key in this.context_))this.context_[key]=ol.dom.createCanvasContext2D();return this.context_[key]};ol.VectorImageTile.prototype.getImage=function(layer){return this.getReplayState(layer).renderedTileRevision==-1?null:this.getContext(layer).canvas};
ol.VectorImageTile.prototype.getReplayState=function(layer){var key=ol.getUid(layer).toString();if(!(key in this.replayState_))this.replayState_[key]={dirty:false,renderedRenderOrder:null,renderedRevision:-1,renderedTileRevision:-1};return this.replayState_[key]};ol.VectorImageTile.prototype.getKey=function(){return this.tileKeys.join("/")+"-"+this.sourceRevision_};ol.VectorImageTile.prototype.getTile=function(tileKey){return this.sourceTiles_[tileKey]};
ol.VectorImageTile.prototype.load=function(){var leftToLoad=0;var errorSourceTiles={};if(this.state==ol.TileState.IDLE)this.setState(ol.TileState.LOADING);if(this.state==ol.TileState.LOADING)this.tileKeys.forEach(function(sourceTileKey){var sourceTile=this.getTile(sourceTileKey);if(sourceTile.state==ol.TileState.IDLE){sourceTile.setLoader(this.loader_);sourceTile.load()}if(sourceTile.state==ol.TileState.LOADING){var key=ol.events.listen(sourceTile,ol.events.EventType.CHANGE,function(e){var state=
sourceTile.getState();if(state==ol.TileState.LOADED||state==ol.TileState.ERROR){var uid=ol.getUid(sourceTile);if(state==ol.TileState.ERROR)errorSourceTiles[uid]=true;else{--leftToLoad;delete errorSourceTiles[uid]}if(leftToLoad-Object.keys(errorSourceTiles).length==0)this.finishLoading_()}}.bind(this));this.loadListenerKeys_.push(key);++leftToLoad}}.bind(this));if(leftToLoad-Object.keys(errorSourceTiles).length==0)setTimeout(this.finishLoading_.bind(this),0)};
ol.VectorImageTile.prototype.finishLoading_=function(){var loaded=this.tileKeys.length;var empty=0;for(var i=loaded-1;i>=0;--i){var state=this.getTile(this.tileKeys[i]).getState();if(state!=ol.TileState.LOADED)--loaded;if(state==ol.TileState.EMPTY)++empty}if(loaded==this.tileKeys.length){this.loadListenerKeys_.forEach(ol.events.unlistenByKey);this.loadListenerKeys_.length=0;this.setState(ol.TileState.LOADED)}else this.setState(empty==this.tileKeys.length?ol.TileState.EMPTY:ol.TileState.ERROR)};
ol.VectorImageTile.defaultLoadFunction=function(tile,url){var loader=ol.featureloader.loadFeaturesXhr(url,tile.getFormat(),tile.onLoad.bind(tile),tile.onError.bind(tile));tile.setLoader(loader)};goog.provide("ol.VectorTile");goog.require("ol");goog.require("ol.Tile");goog.require("ol.TileState");ol.VectorTile=function(tileCoord,state,src,format,tileLoadFunction,opt_options){ol.Tile.call(this,tileCoord,state,opt_options);this.consumers=0;this.extent_=null;this.format_=format;this.features_=null;this.loader_;this.projection_;this.replayGroups_={};this.tileLoadFunction_=tileLoadFunction;this.url_=src};ol.inherits(ol.VectorTile,ol.Tile);
ol.VectorTile.prototype.disposeInternal=function(){this.features_=null;this.replayGroups_={};this.state=ol.TileState.ABORT;this.changed();ol.Tile.prototype.disposeInternal.call(this)};ol.VectorTile.prototype.getExtent=function(){return this.extent_||ol.VectorTile.DEFAULT_EXTENT};ol.VectorTile.prototype.getFormat=function(){return this.format_};ol.VectorTile.prototype.getFeatures=function(){return this.features_};ol.VectorTile.prototype.getKey=function(){return this.url_};
ol.VectorTile.prototype.getProjection=function(){return this.projection_};ol.VectorTile.prototype.getReplayGroup=function(layer,key){return this.replayGroups_[ol.getUid(layer)+","+key]};ol.VectorTile.prototype.load=function(){if(this.state==ol.TileState.IDLE){this.setState(ol.TileState.LOADING);this.tileLoadFunction_(this,this.url_);this.loader_(null,NaN,null)}};ol.VectorTile.prototype.onLoad=function(features,dataProjection,extent){this.setProjection(dataProjection);this.setFeatures(features);this.setExtent(extent)};
ol.VectorTile.prototype.onError=function(){this.setState(ol.TileState.ERROR)};ol.VectorTile.prototype.setExtent=function(extent){this.extent_=extent};ol.VectorTile.prototype.setFeatures=function(features){this.features_=features;this.setState(ol.TileState.LOADED)};ol.VectorTile.prototype.setProjection=function(projection){this.projection_=projection};ol.VectorTile.prototype.setReplayGroup=function(layer,key,replayGroup){this.replayGroups_[ol.getUid(layer)+","+key]=replayGroup};
ol.VectorTile.prototype.setLoader=function(loader){this.loader_=loader};ol.VectorTile.DEFAULT_EXTENT=[0,0,4096,4096];goog.provide("ol.source.VectorTile");goog.require("ol");goog.require("ol.TileState");goog.require("ol.VectorImageTile");goog.require("ol.VectorTile");goog.require("ol.size");goog.require("ol.source.UrlTile");goog.require("ol.tilecoord");goog.require("ol.tilegrid");
ol.source.VectorTile=function(options){var projection=options.projection||"EPSG:3857";var extent=options.extent||ol.tilegrid.extentFromProjection(projection);var tileGrid=options.tileGrid||ol.tilegrid.createXYZ({extent:extent,maxZoom:options.maxZoom||22,minZoom:options.minZoom,tileSize:options.tileSize||512});ol.source.UrlTile.call(this,{attributions:options.attributions,cacheSize:options.cacheSize!==undefined?options.cacheSize:128,extent:extent,logo:options.logo,opaque:false,projection:projection,
state:options.state,tileGrid:tileGrid,tileLoadFunction:options.tileLoadFunction?options.tileLoadFunction:ol.VectorImageTile.defaultLoadFunction,tileUrlFunction:options.tileUrlFunction,url:options.url,urls:options.urls,wrapX:options.wrapX===undefined?true:options.wrapX,transition:options.transition});this.format_=options.format?options.format:null;this.sourceTiles_={};this.overlaps_=options.overlaps==undefined?true:options.overlaps;this.tileClass=options.tileClass?options.tileClass:ol.VectorTile;this.tileGrids_=
{}};ol.inherits(ol.source.VectorTile,ol.source.UrlTile);ol.source.VectorTile.prototype.getOverlaps=function(){return this.overlaps_};ol.source.VectorTile.prototype.clear=function(){this.tileCache.clear();this.sourceTiles_={}};
ol.source.VectorTile.prototype.getTile=function(z,x,y,pixelRatio,projection){var tileCoordKey=ol.tilecoord.getKeyZXY(z,x,y);if(this.tileCache.containsKey(tileCoordKey))return this.tileCache.get(tileCoordKey);else{var tileCoord=[z,x,y];var urlTileCoord=this.getTileCoordForTileUrlFunction(tileCoord,projection);var tile=new ol.VectorImageTile(tileCoord,urlTileCoord!==null?ol.TileState.IDLE:ol.TileState.EMPTY,this.getRevision(),this.format_,this.tileLoadFunction,urlTileCoord,this.tileUrlFunction,this.tileGrid,
this.getTileGridForProjection(projection),this.sourceTiles_,pixelRatio,projection,this.tileClass,this.handleTileChange.bind(this),this.tileOptions);this.tileCache.set(tileCoordKey,tile);return tile}};
ol.source.VectorTile.prototype.getTileGridForProjection=function(projection){var code=projection.getCode();var tileGrid=this.tileGrids_[code];if(!tileGrid){var sourceTileGrid=this.tileGrid;tileGrid=this.tileGrids_[code]=ol.tilegrid.createForProjection(projection,undefined,sourceTileGrid?sourceTileGrid.getTileSize(sourceTileGrid.getMinZoom()):undefined)}return tileGrid};ol.source.VectorTile.prototype.getTilePixelRatio=function(pixelRatio){return pixelRatio};
ol.source.VectorTile.prototype.getTilePixelSize=function(z,pixelRatio,projection){var tileSize=ol.size.toSize(this.getTileGridForProjection(projection).getTileSize(z));return[Math.round(tileSize[0]*pixelRatio),Math.round(tileSize[1]*pixelRatio)]};goog.provide("ol.source.WMTSRequestEncoding");ol.source.WMTSRequestEncoding={KVP:"KVP",REST:"REST"};goog.provide("ol.tilegrid.WMTS");goog.require("ol");goog.require("ol.array");goog.require("ol.proj");goog.require("ol.tilegrid.TileGrid");ol.tilegrid.WMTS=function(options){this.matrixIds_=options.matrixIds;ol.tilegrid.TileGrid.call(this,{extent:options.extent,origin:options.origin,origins:options.origins,resolutions:options.resolutions,tileSize:options.tileSize,tileSizes:options.tileSizes,sizes:options.sizes})};ol.inherits(ol.tilegrid.WMTS,ol.tilegrid.TileGrid);
ol.tilegrid.WMTS.prototype.getMatrixId=function(z){return this.matrixIds_[z]};ol.tilegrid.WMTS.prototype.getMatrixIds=function(){return this.matrixIds_};
ol.tilegrid.WMTS.createFromCapabilitiesMatrixSet=function(matrixSet,opt_extent,opt_matrixLimits){var resolutions=[];var matrixIds=[];var origins=[];var tileSizes=[];var sizes=[];var matrixLimits=opt_matrixLimits!==undefined?opt_matrixLimits:[];var supportedCRSPropName="SupportedCRS";var matrixIdsPropName="TileMatrix";var identifierPropName="Identifier";var scaleDenominatorPropName="ScaleDenominator";var topLeftCornerPropName="TopLeftCorner";var tileWidthPropName="TileWidth";var tileHeightPropName=
"TileHeight";var code=matrixSet[supportedCRSPropName];var projection=ol.proj.get(code.replace(/urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/,"$1:$3"))||ol.proj.get(code);var metersPerUnit=projection.getMetersPerUnit();var switchOriginXY=projection.getAxisOrientation().substr(0,2)=="ne";matrixSet[matrixIdsPropName].sort(function(a,b){return b[scaleDenominatorPropName]-a[scaleDenominatorPropName]});matrixSet[matrixIdsPropName].forEach(function(elt,index,array){var matrixAvailable;if(matrixLimits.length>0)matrixAvailable=
ol.array.find(matrixLimits,function(elt_ml,index_ml,array_ml){return elt[identifierPropName]==elt_ml[matrixIdsPropName]});else matrixAvailable=true;if(matrixAvailable){matrixIds.push(elt[identifierPropName]);var resolution=elt[scaleDenominatorPropName]*2.8E-4/metersPerUnit;var tileWidth=elt[tileWidthPropName];var tileHeight=elt[tileHeightPropName];if(switchOriginXY)origins.push([elt[topLeftCornerPropName][1],elt[topLeftCornerPropName][0]]);else origins.push(elt[topLeftCornerPropName]);resolutions.push(resolution);
tileSizes.push(tileWidth==tileHeight?tileWidth:[tileWidth,tileHeight]);sizes.push([elt["MatrixWidth"],-elt["MatrixHeight"]])}});return new ol.tilegrid.WMTS({extent:opt_extent,origins:origins,resolutions:resolutions,matrixIds:matrixIds,tileSizes:tileSizes,sizes:sizes})};goog.provide("ol.source.WMTS");goog.require("ol");goog.require("ol.TileUrlFunction");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.obj");goog.require("ol.proj");goog.require("ol.source.TileImage");goog.require("ol.source.WMTSRequestEncoding");goog.require("ol.tilegrid.WMTS");goog.require("ol.uri");
ol.source.WMTS=function(options){this.version_=options.version!==undefined?options.version:"1.0.0";this.format_=options.format!==undefined?options.format:"image/jpeg";this.dimensions_=options.dimensions!==undefined?options.dimensions:{};this.layer_=options.layer;this.matrixSet_=options.matrixSet;this.style_=options.style;var urls=options.urls;if(urls===undefined&&options.url!==undefined)urls=ol.TileUrlFunction.expandUrl(options.url);this.requestEncoding_=options.requestEncoding!==undefined?options.requestEncoding:
ol.source.WMTSRequestEncoding.KVP;var requestEncoding=this.requestEncoding_;var tileGrid=options.tileGrid;var context={"layer":this.layer_,"style":this.style_,"tilematrixset":this.matrixSet_};if(requestEncoding==ol.source.WMTSRequestEncoding.KVP)ol.obj.assign(context,{"Service":"WMTS","Request":"GetTile","Version":this.version_,"Format":this.format_});var dimensions=this.dimensions_;this.createFromWMTSTemplate_=function(template){template=requestEncoding==ol.source.WMTSRequestEncoding.KVP?ol.uri.appendParams(template,
context):template.replace(/\{(\w+?)\}/g,function(m,p){return p.toLowerCase()in context?context[p.toLowerCase()]:m});return function(tileCoord,pixelRatio,projection){if(!tileCoord)return undefined;else{var localContext={"TileMatrix":tileGrid.getMatrixId(tileCoord[0]),"TileCol":tileCoord[1],"TileRow":-tileCoord[2]-1};ol.obj.assign(localContext,dimensions);var url=template;if(requestEncoding==ol.source.WMTSRequestEncoding.KVP)url=ol.uri.appendParams(url,localContext);else url=url.replace(/\{(\w+?)\}/g,
function(m,p){return localContext[p]});return url}}};var tileUrlFunction=urls&&urls.length>0?ol.TileUrlFunction.createFromTileUrlFunctions(urls.map(this.createFromWMTSTemplate_)):ol.TileUrlFunction.nullTileUrlFunction;ol.source.TileImage.call(this,{attributions:options.attributions,cacheSize:options.cacheSize,crossOrigin:options.crossOrigin,logo:options.logo,projection:options.projection,reprojectionErrorThreshold:options.reprojectionErrorThreshold,tileClass:options.tileClass,tileGrid:tileGrid,tileLoadFunction:options.tileLoadFunction,
tilePixelRatio:options.tilePixelRatio,tileUrlFunction:tileUrlFunction,urls:urls,wrapX:options.wrapX!==undefined?options.wrapX:false,transition:options.transition});this.setKey(this.getKeyForDimensions_())};ol.inherits(ol.source.WMTS,ol.source.TileImage);
ol.source.WMTS.prototype.setUrls=function(urls){this.urls=urls;var key=urls.join("\n");this.setTileUrlFunction(this.fixedTileUrlFunction?this.fixedTileUrlFunction.bind(this):ol.TileUrlFunction.createFromTileUrlFunctions(urls.map(this.createFromWMTSTemplate_.bind(this))),key)};ol.source.WMTS.prototype.getDimensions=function(){return this.dimensions_};ol.source.WMTS.prototype.getFormat=function(){return this.format_};ol.source.WMTS.prototype.getLayer=function(){return this.layer_};
ol.source.WMTS.prototype.getMatrixSet=function(){return this.matrixSet_};ol.source.WMTS.prototype.getRequestEncoding=function(){return this.requestEncoding_};ol.source.WMTS.prototype.getStyle=function(){return this.style_};ol.source.WMTS.prototype.getVersion=function(){return this.version_};ol.source.WMTS.prototype.getKeyForDimensions_=function(){var i=0;var res=[];for(var key in this.dimensions_)res[i++]=key+"-"+this.dimensions_[key];return res.join("/")};
ol.source.WMTS.prototype.updateDimensions=function(dimensions){ol.obj.assign(this.dimensions_,dimensions);this.setKey(this.getKeyForDimensions_())};
ol.source.WMTS.optionsFromCapabilities=function(wmtsCap,config){var layers=wmtsCap["Contents"]["Layer"];var l=ol.array.find(layers,function(elt,index,array){return elt["Identifier"]==config["layer"]});if(l===null)return null;var tileMatrixSets=wmtsCap["Contents"]["TileMatrixSet"];var idx,matrixSet,matrixLimits;if(l["TileMatrixSetLink"].length>1)if("projection"in config)idx=ol.array.findIndex(l["TileMatrixSetLink"],function(elt,index,array){var tileMatrixSet=ol.array.find(tileMatrixSets,function(el){return el["Identifier"]==
elt["TileMatrixSet"]});var supportedCRS=tileMatrixSet["SupportedCRS"];var proj1=ol.proj.get(supportedCRS.replace(/urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/,"$1:$3"))||ol.proj.get(supportedCRS);var proj2=ol.proj.get(config["projection"]);if(proj1&&proj2)return ol.proj.equivalent(proj1,proj2);else return supportedCRS==config["projection"]});else idx=ol.array.findIndex(l["TileMatrixSetLink"],function(elt,index,array){return elt["TileMatrixSet"]==config["matrixSet"]});else idx=0;if(idx<0)idx=0;matrixSet=l["TileMatrixSetLink"][idx]["TileMatrixSet"];
matrixLimits=l["TileMatrixSetLink"][idx]["TileMatrixSetLimits"];var format=l["Format"][0];if("format"in config)format=config["format"];idx=ol.array.findIndex(l["Style"],function(elt,index,array){if("style"in config)return elt["Title"]==config["style"];else return elt["isDefault"]});if(idx<0)idx=0;var style=l["Style"][idx]["Identifier"];var dimensions={};if("Dimension"in l)l["Dimension"].forEach(function(elt,index,array){var key=elt["Identifier"];var value=elt["Default"];if(value===undefined)value=
elt["Value"][0];dimensions[key]=value});var matrixSets=wmtsCap["Contents"]["TileMatrixSet"];var matrixSetObj=ol.array.find(matrixSets,function(elt,index,array){return elt["Identifier"]==matrixSet});var projection;var code=matrixSetObj["SupportedCRS"];if(code)projection=ol.proj.get(code.replace(/urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/,"$1:$3"))||ol.proj.get(code);if("projection"in config){var projConfig=ol.proj.get(config["projection"]);if(projConfig)if(!projection||ol.proj.equivalent(projConfig,projection))projection=
projConfig}var wgs84BoundingBox=l["WGS84BoundingBox"];var extent,wrapX;if(wgs84BoundingBox!==undefined){var wgs84ProjectionExtent=ol.proj.get("EPSG:4326").getExtent();wrapX=wgs84BoundingBox[0]==wgs84ProjectionExtent[0]&&wgs84BoundingBox[2]==wgs84ProjectionExtent[2];extent=ol.proj.transformExtent(wgs84BoundingBox,"EPSG:4326",projection);var projectionExtent=projection.getExtent();if(projectionExtent)if(!ol.extent.containsExtent(projectionExtent,extent))extent=undefined}var tileGrid=ol.tilegrid.WMTS.createFromCapabilitiesMatrixSet(matrixSetObj,
extent,matrixLimits);var urls=[];var requestEncoding=config["requestEncoding"];requestEncoding=requestEncoding!==undefined?requestEncoding:"";if("OperationsMetadata"in wmtsCap&&"GetTile"in wmtsCap["OperationsMetadata"]){var gets=wmtsCap["OperationsMetadata"]["GetTile"]["DCP"]["HTTP"]["Get"];for(var i=0,ii=gets.length;i<ii;++i)if(gets[i]["Constraint"]){var constraint=ol.array.find(gets[i]["Constraint"],function(element){return element["name"]=="GetEncoding"});var encodings=constraint["AllowedValues"]["Value"];
if(requestEncoding==="")requestEncoding=encodings[0];if(requestEncoding===ol.source.WMTSRequestEncoding.KVP){if(ol.array.includes(encodings,ol.source.WMTSRequestEncoding.KVP))urls.push(gets[i]["href"])}else break}else if(gets[i]["href"]){requestEncoding=ol.source.WMTSRequestEncoding.KVP;urls.push(gets[i]["href"])}}if(urls.length===0){requestEncoding=ol.source.WMTSRequestEncoding.REST;l["ResourceURL"].forEach(function(element){if(element["resourceType"]==="tile"){format=element["format"];urls.push(element["template"])}})}return{urls:urls,
layer:config["layer"],matrixSet:matrixSet,format:format,projection:projection,requestEncoding:requestEncoding,tileGrid:tileGrid,style:style,dimensions:dimensions,wrapX:wrapX,crossOrigin:config["crossOrigin"]}};goog.provide("ol.source.Zoomify");goog.require("ol");goog.require("ol.ImageTile");goog.require("ol.TileState");goog.require("ol.TileUrlFunction");goog.require("ol.asserts");goog.require("ol.dom");goog.require("ol.extent");goog.require("ol.size");goog.require("ol.source.TileImage");goog.require("ol.tilegrid.TileGrid");
ol.source.Zoomify=function(opt_options){var options=opt_options||{};var size=options.size;var tierSizeCalculation=options.tierSizeCalculation!==undefined?options.tierSizeCalculation:ol.source.Zoomify.TierSizeCalculation_.DEFAULT;var imageWidth=size[0];var imageHeight=size[1];var extent=options.extent||[0,-size[1],size[0],0];var tierSizeInTiles=[];var tileSize=options.tileSize||ol.DEFAULT_TILE_SIZE;var tileSizeForTierSizeCalculation=tileSize;switch(tierSizeCalculation){case ol.source.Zoomify.TierSizeCalculation_.DEFAULT:while(imageWidth>
tileSizeForTierSizeCalculation||imageHeight>tileSizeForTierSizeCalculation){tierSizeInTiles.push([Math.ceil(imageWidth/tileSizeForTierSizeCalculation),Math.ceil(imageHeight/tileSizeForTierSizeCalculation)]);tileSizeForTierSizeCalculation+=tileSizeForTierSizeCalculation}break;case ol.source.Zoomify.TierSizeCalculation_.TRUNCATED:var width=imageWidth;var height=imageHeight;while(width>tileSizeForTierSizeCalculation||height>tileSizeForTierSizeCalculation){tierSizeInTiles.push([Math.ceil(width/tileSizeForTierSizeCalculation),
Math.ceil(height/tileSizeForTierSizeCalculation)]);width>>=1;height>>=1}break;default:ol.asserts.assert(false,53);break}tierSizeInTiles.push([1,1]);tierSizeInTiles.reverse();var resolutions=[1];var tileCountUpToTier=[0];var i,ii;for(i=1,ii=tierSizeInTiles.length;i<ii;i++){resolutions.push(1<<i);tileCountUpToTier.push(tierSizeInTiles[i-1][0]*tierSizeInTiles[i-1][1]+tileCountUpToTier[i-1])}resolutions.reverse();var tileGrid=new ol.tilegrid.TileGrid({tileSize:tileSize,extent:extent,origin:ol.extent.getTopLeft(extent),
resolutions:resolutions});var url=options.url;if(url&&url.indexOf("{TileGroup}")==-1&&url.indexOf("{tileIndex}")==-1)url+="{TileGroup}/{z}-{x}-{y}.jpg";var urls=ol.TileUrlFunction.expandUrl(url);function createFromTemplate(template){return function(tileCoord,pixelRatio,projection){if(!tileCoord)return undefined;else{var tileCoordZ=tileCoord[0];var tileCoordX=tileCoord[1];var tileCoordY=-tileCoord[2]-1;var tileIndex=tileCoordX+tileCoordY*tierSizeInTiles[tileCoordZ][0];var tileSize=tileGrid.getTileSize(tileCoordZ);
var tileGroup=(tileIndex+tileCountUpToTier[tileCoordZ])/tileSize|0;var localContext={"z":tileCoordZ,"x":tileCoordX,"y":tileCoordY,"tileIndex":tileIndex,"TileGroup":"TileGroup"+tileGroup};return template.replace(/\{(\w+?)\}/g,function(m,p){return localContext[p]})}}}var tileUrlFunction=ol.TileUrlFunction.createFromTileUrlFunctions(urls.map(createFromTemplate));var ZoomifyTileClass=ol.source.Zoomify.Tile_.bind(null,tileGrid);ol.source.TileImage.call(this,{attributions:options.attributions,cacheSize:options.cacheSize,
crossOrigin:options.crossOrigin,logo:options.logo,projection:options.projection,reprojectionErrorThreshold:options.reprojectionErrorThreshold,tileClass:ZoomifyTileClass,tileGrid:tileGrid,tileUrlFunction:tileUrlFunction,transition:options.transition})};ol.inherits(ol.source.Zoomify,ol.source.TileImage);
ol.source.Zoomify.Tile_=function(tileGrid,tileCoord,state,src,crossOrigin,tileLoadFunction,opt_options){ol.ImageTile.call(this,tileCoord,state,src,crossOrigin,tileLoadFunction,opt_options);this.zoomifyImage_=null;this.tileSize_=ol.size.toSize(tileGrid.getTileSize(tileCoord[0]))};ol.inherits(ol.source.Zoomify.Tile_,ol.ImageTile);
ol.source.Zoomify.Tile_.prototype.getImage=function(){if(this.zoomifyImage_)return this.zoomifyImage_;var image=ol.ImageTile.prototype.getImage.call(this);if(this.state==ol.TileState.LOADED){var tileSize=this.tileSize_;if(image.width==tileSize[0]&&image.height==tileSize[1]){this.zoomifyImage_=image;return image}else{var context=ol.dom.createCanvasContext2D(tileSize[0],tileSize[1]);context.drawImage(image,0,0);this.zoomifyImage_=context.canvas;return context.canvas}}else return image};
ol.source.Zoomify.TierSizeCalculation_={DEFAULT:"default",TRUNCATED:"truncated"};goog.provide("de.novasib.ol.format.TTSIB");goog.require("ol");goog.require("ol.format.GML2");goog.require("ol.format.GMLBase");goog.require("ol.xml");de.novasib.ol.format.TTSIB=function(opt_options){var options=opt_options?opt_options:{};ol.format.GML2.call(this,options);var featureFilter;if(options.filter&&typeof options.filter=="function")featureFilter=options.filter;this.featureFilter_=featureFilter};ol.inherits(de.novasib.ol.format.TTSIB,ol.format.GML2);
de.novasib.ol.format.TTSIB.prototype.readFeaturesInternal=function(node,objectStack){var localName=node.localName;var features=[];if(localName=="Objektmenge")for(var i=0;i<node.childNodes.length;++i){var child=node.childNodes[i];if(child.localName=="Objekt")features.push(this.readFeatureElement(child.firstChild,objectStack))}else if(localName==="FeatureCollection")if(node.namespaceURI==="http://www.opengis.net/wfs")features=ol.xml.pushParseAndPop([],this.FEATURE_COLLECTION_PARSERS,node,objectStack,
this);else features=ol.xml.pushParseAndPop(null,this.FEATURE_COLLECTION_PARSERS,node,objectStack,this);return features};de.novasib.ol.format.TTSIB.ONLY_WHITESPACE_RE_=/^[\s\xa0]*$/;
de.novasib.ol.format.TTSIB.prototype.readFeatureElement=function(node,objectStack){var n;var fid=node.getAttribute("fid")||ol.xml.getAttributeNS(node,ol.format.GMLBase.GMLNS,"id");var featureTypeName=node.localName;var values={},geometryName;for(n=node.firstElementChild;n;n=n.nextElementSibling){var localName=n.localName;if(n.childNodes.length===0||n.childNodes.length===1&&(n.firstChild.nodeType===3||n.firstChild.nodeType===4)){var value=ol.xml.getAllTextContent(n,false);if(de.novasib.ol.format.TTSIB.ONLY_WHITESPACE_RE_.test(value))if(n.attributes&&
n.attributes.length>0){value=null;for(var i=0;i<n.attributes.length;++i){var attr=n.attributes[i];if(attr&&attr.name)values[localName+"/@"+attr.name]=attr.value}}else value=undefined;values[localName]=value}else{if(localName!=="boundedBy")geometryName=localName;values[localName]=this.readGeometryElement(n,objectStack)}}var feature=new ol.Feature(values);if(geometryName)feature.setGeometryName(geometryName);if(fid)feature.setId(fid);if(featureTypeName)feature.set(de.novasib.ol.FeatureProperties.FEATURE_TYPE,
featureTypeName);if(this.featureFilter_)feature=this.featureFilter_(feature);return feature};
de.novasib.ol.format.TTSIB.prototype.readFlatCoordinates_=function(node,objectStack){var s=ol.xml.getAllTextContent(node,false).replace(/^\s*|\s*$/g,"");var coordsGroups=s.trim().split(/\s+/);var x,y,z;var flatCoordinates=[];for(var i=0,ii=coordsGroups.length;i<ii;i++){var coords=coordsGroups[i].split(/,+/);x=parseFloat(coords[0]);y=parseFloat(coords[1]);z=coords.length===3?parseFloat(coords[2]):0;flatCoordinates.push(x,y,z)}return flatCoordinates};
de.novasib.ol.format.TTSIB.prototype.GEOMETRY_FLAT_COORDINATES_PARSERS_={"http://www.opengis.net/gml":{"coordinates":ol.xml.makeReplacer(de.novasib.ol.format.TTSIB.prototype.readFlatCoordinates_)}};goog.provide("de.novasib.ol");goog.require("de.novasib.ol.format.TTSIB");goog.require("ol.extent");goog.require("ol.format.EsriJSON");goog.require("ol.format.GeoJSON");goog.require("ol.format.GML2");goog.require("ol.format.Polyline");goog.require("ol.format.WFS");goog.require("ol.proj");goog.require("ol.proj.proj4");goog.require("ol.proj.Projection");
de.novasib.ol.baseLogger=function(o){var log=o;if(typeof o==="object"){var cache=[];log=JSON.stringify(o,function(key,value){if(typeof value==="object"&&value!==null){if(cache.indexOf(value)!==-1)return;cache.push(value)}return value});cache=null}console.log(log)};de.novasib.ol.ATTRIBUTION="&copy; "+(new Date).getFullYear()+' <a href="https://www.novasib.de">NOVASIB GmbH</a>';de.novasib.ol.LayerType={WFS:"wfs",VECTOR:"vector",TMS:"tms",WMS:"wms",WMTS:"wmts"};
de.novasib.ol.FeatureProperties={FEATURE_TYPE:"featureType",VST:"VST",BST:"BST",KMVON:"KM_VON",KMBIS:"KM_BIS",SELECTED:"selected",TOOLTIP_PATTERN:"tooltipPattern",STROKE_COLOR:"strokeColor",STYLE_NAME:"stylename",WITH_ORIENTATION:"withOrientation",LAYER_NAME:"layername",LAYER_STYLE_NAME:"layerStyleName",ALEN:"ALEN"};
de.novasib.ol.LayerProperties={NAME:"name",TITLE:"title",TOOLTIP_PATTERN:"tooltipPattern",STYLE_CHANGE_PROPERTIES:"styleChangeProperties",FILTER_PARAM:"filter",STYLE_NAME:"stylename",GROUP_SELECT:"groupSelect"};de.novasib.ol.htmlElementType={LABEL:"label",HR:"hr",LI:"li",INPUT:"input"};de.novasib.ol.htmlInputType={BUTTON:"button",CHECKBOX:"checkbox",FILE:"file",IMAGE:"image",RADIO:"radio",TEXT:"text"};de.novasib.ol.KNOWN_APP_NAMES={NOVAMAP:"Novamap",SPERRINFOSYS:"Sperrinfosys",TTSIB:"TT-SIB",MBDE:"MBDE"};
de.novasib.ol.KNOWN_PROJECTIONS={"EPSG:2398":"+proj=tmerc +lat_0=0 +lon_0=12 +k=1 +x_0=4500000 +y_0=0 +ellps=krass +towgs84=26,-121,-78,0,0,0,0 +units=m +no_defs +axis=ned ","EPSG:2399":"+proj=tmerc +lat_0=0 +lon_0=15 +k=1 +x_0=5500000 +y_0=0 +ellps=krass +towgs84=26,-121,-78,0,0,0,0 +units=m +no_defs +axis=ned ","EPSG:25832":"+proj=utm +zone=32 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs","EPSG:25833":"+proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs","EPSG:31466":"+proj=tmerc +lat_0=0 +lon_0=6 +k=1 +x_0=2500000 +y_0=0 +ellps=bessel +towgs84=598.1,73.7,418.2,0.202,0.045,-2.455,6.7 +units=m +no_defs +axis=ned ",
"EPSG:31467":"+proj=tmerc +lat_0=0 +lon_0=9 +k=1 +x_0=3500000 +y_0=0 +ellps=bessel +towgs84=598.1,73.7,418.2,0.202,0.045,-2.455,6.7 +units=m +no_defs +axis=ned ","EPSG:31468":"+proj=tmerc +lat_0=0 +lon_0=12 +k=1 +x_0=4500000 +y_0=0 +ellps=bessel +towgs84=598.1,73.7,418.2,0.202,0.045,-2.455,6.7 +units=m +no_defs +axis=ned ","EPSG:31469":"+proj=tmerc +lat_0=0 +lon_0=15 +k=1 +x_0=5500000 +y_0=0 +ellps=bessel +towgs84=598.1,73.7,418.2,0.202,0.045,-2.455,6.7 +units=m +no_defs +axis=ned "};
de.novasib.ol.KNOWN_PROJECTIONS["urn:ogc:def:crs:EPSG::2398"]=de.novasib.ol.KNOWN_PROJECTIONS["urn:x-ogc:def:crs:EPSG:2398"]=de.novasib.ol.KNOWN_PROJECTIONS["EPSG:2398"];de.novasib.ol.KNOWN_PROJECTIONS["urn:ogc:def:crs:EPSG::2399"]=de.novasib.ol.KNOWN_PROJECTIONS["urn:x-ogc:def:crs:EPSG:2399"]=de.novasib.ol.KNOWN_PROJECTIONS["EPSG:2399"];de.novasib.ol.KNOWN_PROJECTIONS["urn:ogc:def:crs:EPSG::25832"]=de.novasib.ol.KNOWN_PROJECTIONS["urn:x-ogc:def:crs:EPSG:25832"]=de.novasib.ol.KNOWN_PROJECTIONS["EPSG:25832"];
de.novasib.ol.KNOWN_PROJECTIONS["urn:ogc:def:crs:EPSG::25833"]=de.novasib.ol.KNOWN_PROJECTIONS["urn:x-ogc:def:crs:EPSG:25833"]=de.novasib.ol.KNOWN_PROJECTIONS["EPSG:25833"];de.novasib.ol.KNOWN_PROJECTIONS["urn:ogc:def:crs:EPSG::31466"]=de.novasib.ol.KNOWN_PROJECTIONS["urn:x-ogc:def:crs:EPSG:31466"]=de.novasib.ol.KNOWN_PROJECTIONS["EPSG:31466"];de.novasib.ol.KNOWN_PROJECTIONS["urn:ogc:def:crs:EPSG::31467"]=de.novasib.ol.KNOWN_PROJECTIONS["urn:x-ogc:def:crs:EPSG:31467"]=de.novasib.ol.KNOWN_PROJECTIONS["EPSG:31467"];
de.novasib.ol.KNOWN_PROJECTIONS["urn:ogc:def:crs:EPSG::31468"]=de.novasib.ol.KNOWN_PROJECTIONS["urn:x-ogc:def:crs:EPSG:31468"]=de.novasib.ol.KNOWN_PROJECTIONS["EPSG:31468"];de.novasib.ol.KNOWN_PROJECTIONS["urn:ogc:def:crs:EPSG::31469"]=de.novasib.ol.KNOWN_PROJECTIONS["urn:x-ogc:def:crs:EPSG:31469"]=de.novasib.ol.KNOWN_PROJECTIONS["EPSG:31469"];
de.novasib.ol.KNOWN_FORMATS=["EsriJSON","GeoJSON","TopoJSON","MVT","IGC","PolyLine","WKT","GML","GML2","GML3","GPX","KML","OSMXML","WFS","WMSGetFeatureInfo","TTSIB"];de.novasib.ol.getEPSGCode=function(srid){var ret=srid;if(typeof srid==="number"||typeof srid==="string"&&srid.indexOf("EPSG")==-1&&!isNaN(parseInt(srid,10)))ret="EPSG:"+srid;return ret};de.novasib.ol.normalizeSrid=function(srid){var ret;if(srid)ret=srid.replace(/urn:(?:x-|)ogc:def:crs:(\w+):(.*:)?(\w+)$/,"$1:$3");return ret||false};
de.novasib.ol.normalizeProjection=function(proj_){var ret;if(proj_)if(proj_ instanceof ol.proj.EPSG4326.Projection_)ret=new ol.proj.Projection({code:"EPSG:4326"});else if(proj_ instanceof ol.proj.EPSG3857.Projection_)ret=new ol.proj.Projection({code:"EPSG:3857"});else ret=proj_;return ret};de.novasib.ol.loadKnownProjections=function(){for(var srid in de.novasib.ol.KNOWN_PROJECTIONS)de.novasib.ol.loadProjection(srid)};
de.novasib.ol.loadProjection=function(srid){var ret=null;if(srid){srid=de.novasib.ol.getEPSGCode(srid);ret=ol.proj.get(srid);if(!ret){var p=de.novasib.ol.KNOWN_PROJECTIONS[srid];if(p){var proj4js=ol.proj.proj4.get();proj4js.defs(srid,p);ret=ol.proj.get(srid)}}}return ret};
de.novasib.ol.loadFormat=function(formatId,ws,wsLayer){if(de.novasib.ol.KNOWN_FORMATS.includes(formatId)){var opt=de.novasib.ol.getFormatOptions(formatId,ws,wsLayer);var olFormat=null;switch(formatId){case "EsriJSON":{olFormat=new ol.format.EsriJSON(opt);break}case "GeoJSON":{olFormat=new ol.format.GeoJSON(opt);break}case "TopoJSON":{break}case "MVT":{break}case "IGC":{break}case "Polyline":{olFormat=new ol.format.Polyline;break}case "WKT":{break}case "GML":{break}case "GML2":{olFormat=new ol.format.GML2(opt);
break}case "TTSIB":{olFormat=new de.novasib.ol.format.TTSIB(opt);break}case "GML3":{break}case "GPX":{break}case "KML":{break}case "OSMXML":{break}case "WFS":{olFormat=new ol.format.WFS(opt);break}case "WMSGetFeatureInfo":{break}}return olFormat}else if(formatId)console.log("Format nicht unterst\u00fctzt: "+formatId)};
de.novasib.ol.getFormatOptions=function(formatId,ws,wsLayer){var opt=null;var geomName=wsLayer.geometryName;switch(formatId){case "EsriJSON":{opt={geometryName:geomName};break}case "GeoJSON":{var proj=de.novasib.ol.loadProjection(wsLayer.epsgSRID)||ws.projection;opt={geometryName:geomName,defaultDataProjection:proj,featureProjection:proj};break}case "TopoJSON":{break}case "MVT":{break}case "IGC":{break}case "Polyline":{break}case "WKT":{break}case "GML":{break}case "TTSIB":case "GML2":{opt={featureNS:wsLayer.featureNS,
featureType:wsLayer.featureType,schemaLocation:wsLayer.schemaLocation,filter:wsLayer.featureFilter};break}case "GML3":{break}case "GPX":{break}case "KML":{break}case "OSMXML":{break}case "WFS":{var featureType=wsLayer.featureType;opt={featureNS:wsLayer.featureNS,featureType:featureType,schemaLocation:wsLayer.schemaLocation};break}case "WMSGetFeatureInfo":{break}}return opt};
de.novasib.ol.getWfsUrlFunction=function(url,featureType,version,name,map){return function(extent,resolution,projection){if(url.indexOf("?")==-1)url=url+"?";else if(url.indexOf("?")!=url.length-1&&url.lastIndexOf("&")!=url.length-1)url=url+"&";if(!version)version="1.0.0";var ret=url+"service=WFS&version="+version+"&request=GetFeature&typename="+featureType+"&srsname="+projection.getCode()+"&bbox="+extent.join(",")+"&mpp="+resolution;var layers=de.novasib.ol.getLayersByName(map,name,ol.layer.Vector);
if(layers.length>0){var layer=layers[0];var filter=layer.get(de.novasib.ol.LayerProperties.FILTER_PARAM);if(filter)ret+="&filter="+escape(filter)}return ret}};de.novasib.ol.getScaleFromResolution=function(resolution){var scale=resolution*de.novasib.ol.DOTS_PER_METER;return scale};de.novasib.ol.getZoomForExtent=function(extent,map){var zoom;if(extent&&map){var viewSize=map.getSize();var idealResolution=Math.max(ol.extent.getWidth(extent)/viewSize[0],ol.extent.getHeight(extent)/viewSize[1]);zoom=Math.round(map.getView().getZoomForResolution(idealResolution))}return zoom};
de.novasib.ol.DOTS_PER_INCH=91;de.novasib.ol.METERS_PER_INCH=100/3937;de.novasib.ol.INCHES_PER_METER=1/de.novasib.ol.METERS_PER_INCH;de.novasib.ol.DOTS_PER_METER=de.novasib.ol.DOTS_PER_INCH*de.novasib.ol.INCHES_PER_METER;
de.novasib.ol.getTextWidth=function(text,font){var width=0;if(text.indexOf("\n")!==-1){var split=text.split("\n");for(var i=0;i<split.length;++i){var s=split[i];var w=de.novasib.ol.getTextWidth(s,font);if(w>width)width=w}}else{var span=document.createElement("SPAN");span.innerHTML=text;span.setAttribute("style","font: "+font+"; display:none");span.setAttribute("id","text_width_span");document.body.appendChild(span);var el=window["$"].call(null,"#text_width_span");width=el["width"].call(el);document.body.removeChild(span)}return width};
de.novasib.ol.round=function(val,fracDig){if(fracDig===0)return Math.round(val);var pow=Math.pow(10,fracDig);return Math.floor(val*pow)/pow};de.novasib.ol.roundFloatToTwo=function(val){if(!val)return false;var ret=Math.sign(val)*(Math.round((Math.abs(val)+Number.EPSILON)*100)/100);return ret};de.novasib.ol.radToDeg=function(rad){if(rad)return rad*(180/Math.PI);return 0};de.novasib.ol.degToRad=function(deg){if(deg)return deg*(Math.PI/180);return 0};
de.novasib.ol.getRandomInt=function(max){return Math.floor(Math.random()*Math.floor(max))};de.novasib.ol.getRandomInt2=function(min,max){return Math.floor(Math.random()*(max-min+1))+min};
de.novasib.ol.getLayersByName=function(map,name,clazz){var layers=map.getLayers();var ret=[];if(layers&&layers.getLength()>0)for(var i=0;i<layers.getLength();++i){var l=layers.item(i);var t=l.get(de.novasib.ol.LayerProperties.TITLE);var n=l.get(de.novasib.ol.LayerProperties.NAME);if((name===t||name===n)&&(clazz==undefined||l instanceof clazz))ret.push(l)}return ret};
de.novasib.ol.parseDate=function(datestring){if(datestring&&typeof datestring==="string"){var timecode=Date.parse(datestring);if(isNaN(timecode)){timecode=Date.parse(datestring.replace(" ","T"));if(isNaN(timecode)){datestring=datestring.replace(" ","T");datestring+="Z";timecode=Date.parse(datestring);if(isNaN(timecode))return null}}return timecode}return null};
de.novasib.ol.isSameLayerType_=function(type1,type2){if(type1&&type2){if(type1==type2)return true;switch(type1){case "wfs":case "vector":{return type2=="wfs"||type2=="vector"}case "wmts":case "tile":case "tms":{return type2=="wmts"||type2=="tile"||type2=="tms"}case "wms":{return type2=="wms"}}}return false};
de.novasib.ol.formatDate=function(strDate,strFormat){if(strFormat===""||strFormat===" ")strFormat="standard";var strYear=(new Date(strDate)).toLocaleDateString("de-de",{year:"numeric"});var strMonth=(new Date(strDate)).toLocaleDateString("de-de",{month:"2-digit"});var strMonthName=(new Date(strDate)).toLocaleDateString("de-de",{month:"long"});var strDay=(new Date(strDate)).toLocaleDateString("de-de",{day:"2-digit"});var strWeekdayName=(new Date(strDate)).toLocaleDateString("de-de",{weekday:"long"});
var strTime=(new Date(strDate)).toLocaleTimeString("de-de");var strOut;switch(strFormat){case "full":strOut=strWeekdayName+", "+strDay+". "+strMonthName+" "+strYear;break;case "standard":strOut=strDay+"."+strMonth+"."+strYear+" "+strTime;break;case "long":strOut=strDay+". "+strMonthName+" "+strYear;break;case "medium":strOut=strDay+"."+strMonth+"."+strYear;break}return strOut};
de.novasib.ol.getDatePlaceholder=function(strSearch,strPattern){var posRight=strPattern.indexOf(strSearch);var posLeft=strPattern.lastIndexOf("{",posRight)+1;var strPlatzhalter=strPattern.substring(posLeft,posRight);return strPlatzhalter};
de.novasib.ol.getDateContextFullExtent=function(strSearch,strPattern){var posCurlyBracketFirst=strPattern.indexOf("{");var posLeft=strPattern.indexOf(strSearch,posCurlyBracketFirst);var posRight=strPattern.indexOf("}",posLeft);var strContext=strPattern.substring(posLeft,posRight);return strContext};
de.novasib.ol.getDateFormatOption=function(strSearch,strPattern){var posLeft=strPattern.indexOf(strSearch)+strSearch.length;var posRight=strPattern.indexOf("}",posLeft);var strOption=strPattern.substring(posLeft,posRight);return strOption};de.novasib.ol.toFixedIfNumber=function(number,fractionDigits){if(typeof number=="number"&&typeof fractionDigits=="number")return number.toFixed(fractionDigits);return number};
de.novasib.ol.isNumberOrStringOfNumber=function(anyThing){return parseFloat(anyThing)==anyThing};de.novasib.ol.getTypeOfString=function(strValue){var ret;if(strValue===undefined||strValue==="")return;if(typeof strValue==="string")if(Number(strValue))if(Number.parseInt(strValue)==strValue&&!strValue.includes("."))ret="integer";else{if(Number.parseFloat(strValue)==strValue)ret="float"}else if(Date.parse(strValue)&&!strValue.includes(","))ret="dateTime";else ret="string";return ret};
de.novasib.ol.getNovaMap=function(){var ret;switch(de.novasib.ol.PARENT_APP_NAME){case de.novasib.ol.KNOWN_APP_NAMES.TTSIB:ret=olmap.map;break;case de.novasib.ol.KNOWN_APP_NAMES.SPERRINFOSYS:ret=olwrapper.map;break;case de.novasib.ol.KNOWN_APP_NAMES.MBDE:ret=olwrapper.currentMap;break;case de.novasib.ol.KNOWN_APP_NAMES.NOVAMAP:ret=map;break;default:break}return ret||null};de.novasib.ol.getOlMap=function(this_){var ret;if(this_)ret=this_.getMap();return ret||null};
de.novasib.ol.getBaseMapVectorTileStyleFunction=function(){return function(feature,resolution){var art_=feature.get("art");var klasse_=feature.get("klasse");var layerName_=feature.get("layer");var featureName_=feature.get("name");var einwohnerzahl_=feature.get("einwohnerzahl");var klasseGehoelz=["Laubholz","Nadelholz","Wald","Laub- und Nadelholz"];var klasseEisenbahn=["Eisenbahn","G\u00fcterverkehr"];var klasseGrenzeDeutschland="Grenze der Bundesrepublik Deutschland";var klasseGrenzeBundesland="Grenze des Bundeslandes";
var klasseGrenzeBezirkKreis=["Grenze des Regierungsbezirks","Grenze des Kreises/Region"];var artHauptStadt=["Hauptstadt","Landeshauptstadt"];var tilestyle=new ol.style.Style;var getFill=function(color_){var ret;ret=new ol.style.Fill({color:color_});return ret};var getStroke=function(color_,width_){var ret;ret=new ol.style.Stroke({color:color_,width:width_});return ret};var getText=function(font_,fill_,stroke_){var ret;ret=new ol.style.Text({font:font_,fill:fill_,stroke:stroke_});return ret};if(layerName_===
"Vegetationsflaeche"&&klasseGehoelz.includes(klasse_))tilestyle.setFill(getFill("#e8fae1"));if(layerName_==="Siedlungsflaeche")tilestyle.setFill(getFill("#eee"));if(layerName_==="Gewaesserflaeche")tilestyle.setFill(getFill("#c9d7ef"));else if(layerName_==="Verkehrslinie"&&klasseEisenbahn.includes(klasse_)&&resolution<200)tilestyle.setStroke(getStroke("#aaaaaa"));else if(layerName_==="Grenze_Linie")if(klasse_===klasseGrenzeDeutschland)tilestyle.setStroke(getStroke("#eba8f7",3));else if(klasse_===klasseGrenzeBundesland)tilestyle.setStroke(getStroke("#eba8f7",
2));else{if(klasseGrenzeBezirkKreis.includes(klasse_)&&resolution<400)tilestyle.setStroke(getStroke("#eba8f7",1))}else if(layerName_==="Name_Punkt"&&klasse_==="Ort")if(artHauptStadt.includes(art_)||art_==="Stadt"&&einwohnerzahl_>1E5){tilestyle.setText(getText("16px Calibri,sans-serif",getFill("#000"),getStroke("#fff",4)));tilestyle.getText().setText(featureName_)}else if(art_==="Stadt"){if(resolution<200){tilestyle.setText(getText("13px Calibri,sans-serif",getFill("#000"),getStroke("#fff",3)));tilestyle.getText().setText(featureName_)}}else if(resolution<
30){tilestyle.setText(getText("11px Calibri,sans-serif",getFill("#000")));tilestyle.getText().setText(featureName_)}return tilestyle}};goog.provide("de.novasib.ol.condition");de.novasib.ol.condition.ctrlKeyOnly=function(event){var originalEvent=event.originalEvent;return originalEvent.ctrlKey&&!originalEvent.metaKey&&!originalEvent.shiftKey&&!originalEvent.altKey};goog.provide("de.novasib.ol.control.Attribution");goog.require("ol");goog.require("ol.array");goog.require("ol.control.Control");goog.require("ol.css");goog.require("ol.dom");goog.require("ol.events");goog.require("ol.events.EventType");goog.require("ol.layer.Layer");goog.require("ol.obj");
de.novasib.ol.control.Attribution=function(opt_options){var options=opt_options?opt_options:{};this.globalMode=options.globalMode||false;this.globalAttribution=options.globalAttribution||null;this.ulElement_=document.createElement("UL");this.logoLi_=document.createElement("LI");this.ulElement_.appendChild(this.logoLi_);this.logoLi_.style.display="none";this.collapsed_=options.collapsed!==undefined?options.collapsed:true;this.collapsible_=options.collapsible!==undefined?options.collapsible:true;if(!this.collapsible_)this.collapsed_=
false;var className=options.className!==undefined?options.className:"de-novasib-ol-attribution";var tipLabel=options.tipLabel!==undefined?options.tipLabel:"Attributions";var collapseLabel=options.collapseLabel!==undefined?options.collapseLabel:"\u00bb";if(typeof collapseLabel==="string"){this.collapseLabel_=document.createElement("span");this.collapseLabel_.textContent=collapseLabel}else this.collapseLabel_=collapseLabel;var label=options.label!==undefined?options.label:"i";if(typeof label==="string"){this.label_=
document.createElement("span");this.label_.textContent=label}else this.label_=label;var activeLabel=this.collapsible_&&!this.collapsed_?this.collapseLabel_:this.label_;var button=document.createElement("button");button.setAttribute("type","button");button.title=tipLabel;button.appendChild(activeLabel);ol.events.listen(button,ol.events.EventType.CLICK,this.handleClick_,this);var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+(this.collapsed_&&this.collapsible_?" ol-collapsed":
"")+(this.collapsible_?"":" ol-uncollapsible");var element=document.createElement("div");element.className=cssClasses;element.appendChild(this.ulElement_);element.appendChild(button);var render=options.render?options.render:de.novasib.ol.control.Attribution.render;ol.control.Control.call(this,{element:element,render:render,target:options.target});this.renderedAttributions_=[];this.renderedVisible_=true;this.logoElements_={}};ol.inherits(de.novasib.ol.control.Attribution,ol.control.Control);
de.novasib.ol.control.Attribution.prototype.getSourceAttributions_=function(frameState){var lookup={};var visibleAttributions=[];var layerStatesArray=frameState.layerStatesArray;var resolution=frameState.viewState.resolution;for(var i=0,ii=layerStatesArray.length;i<ii;++i){var layerState=layerStatesArray[i];if(!ol.layer.Layer.visibleAtResolution(layerState,resolution))continue;var source=layerState.layer.getSource();if(!source)continue;var attributionGetter=source.getAttributions2();if(!attributionGetter)continue;
var attributions=attributionGetter(frameState);if(!attributions)continue;if(Array.isArray(attributions))for(var j=0,jj=attributions.length;j<jj;++j){if(!(attributions[j]in lookup)){visibleAttributions.push(attributions[j]);lookup[attributions[j]]=true}}else if(!(attributions in lookup)){visibleAttributions.push(attributions);lookup[attributions]=true}}return visibleAttributions};de.novasib.ol.control.Attribution.render=function(mapEvent){this.updateElement_(mapEvent.frameState)};
de.novasib.ol.control.Attribution.prototype.updateElement_=function(frameState){if(!frameState){if(this.renderedVisible_){this.element.style.display="none";this.renderedVisible_=false}return}var attributions;if(this.globalMode)if(this.globalAttribution)attributions=[this.globalAttribution];else attributions=[""];else attributions=this.getSourceAttributions_(frameState);if(ol.array.equals(attributions,this.renderedAttributions_))return;while(this.ulElement_.lastChild!==this.logoLi_)this.ulElement_.removeChild(this.ulElement_.lastChild);
for(var i=0,ii=attributions.length;i<ii;++i){var element=document.createElement("LI");element.innerHTML=attributions[i];this.ulElement_.appendChild(element)}if(attributions.length===0&&this.renderedAttributions_.length>0)this.element.classList.add("ol-logo-only");else if(this.renderedAttributions_.length===0&&attributions.length>0)this.element.classList.remove("ol-logo-only");var visible=attributions.length>0||!ol.obj.isEmpty(frameState.logos);if(this.renderedVisible_!=visible){this.element.style.display=
visible?"":"none";this.renderedVisible_=visible}this.renderedAttributions_=attributions;this.insertLogos_(frameState)};
de.novasib.ol.control.Attribution.prototype.insertLogos_=function(frameState){var logo;var logos=frameState.logos;var logoElements=this.logoElements_;for(logo in logoElements)if(!(logo in logos)){ol.dom.removeNode(logoElements[logo]);delete logoElements[logo]}var image,logoElement,logoKey;for(logoKey in logos){var logoValue=logos[logoKey];if(logoValue instanceof HTMLElement){this.logoLi_.appendChild(logoValue);logoElements[logoKey]=logoValue}if(!(logoKey in logoElements)){image=new Image;image.src=
logoKey;if(logoValue==="")logoElement=image;else{logoElement=document.createElement("a");logoElement.href=logoValue;logoElement.appendChild(image)}this.logoLi_.appendChild(logoElement);logoElements[logoKey]=logoElement}}this.logoLi_.style.display=!ol.obj.isEmpty(logos)?"":"none"};de.novasib.ol.control.Attribution.prototype.handleClick_=function(event){event.preventDefault();this.handleToggle_()};
de.novasib.ol.control.Attribution.prototype.handleToggle_=function(){this.element.classList.toggle("ol-collapsed");if(this.collapsed_)ol.dom.replaceNode(this.collapseLabel_,this.label_);else ol.dom.replaceNode(this.label_,this.collapseLabel_);this.collapsed_=!this.collapsed_};de.novasib.ol.control.Attribution.prototype.getCollapsible=function(){return this.collapsible_};
de.novasib.ol.control.Attribution.prototype.setCollapsible=function(collapsible){if(this.collapsible_===collapsible)return;this.collapsible_=collapsible;this.element.classList.toggle("ol-uncollapsible");if(!collapsible&&this.collapsed_)this.handleToggle_()};de.novasib.ol.control.Attribution.prototype.setCollapsed=function(collapsed){if(!this.collapsible_||this.collapsed_===collapsed)return;this.handleToggle_()};de.novasib.ol.control.Attribution.prototype.getCollapsed=function(){return this.collapsed_};goog.provide("de.novasib.ol.control.Button");goog.require("ol");goog.require("ol.events");goog.require("ol.control.Control");goog.require("ol.css");
de.novasib.ol.control.Button=function(options){var className=options.className!==undefined?options.className:"de-novasib-ol-button";var label=options.label!==undefined?options.label:"B";var tipLabel=options.tipLabel!==undefined?options.tipLabel:"Simple Button Control";var idDiv=options.idDiv||undefined;var button=document.createElement("BUTTON");button.setAttribute("type","button");button.title=tipLabel;button.appendChild(typeof label==="string"?document.createTextNode(label):label);var handleClick=
options.handleClick;if(!handleClick||typeof handleClick!=="function")throw new Error("Button Control needs a click handler.");ol.events.listen(button,ol.events.EventType.CLICK,handleClick,this);var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL;var element=document.createElement("div");element.className=cssClasses;idDiv!==undefined?element.id=idDiv:null;element.appendChild(button);ol.control.Control.call(this,{element:element,target:options.target})};
ol.inherits(de.novasib.ol.control.Button,ol.control.Control);goog.provide("de.novasib.ol.control.ImportPanel");goog.require("ol");goog.require("ol.control.Control");goog.require("ol.dom");goog.require("ol.events");
de.novasib.ol.control.ImportPanel=function(options,empty){var render,element,target;if(empty){this.ulElement_=document.createElement("UL");this.collapsed_=options.collapsed!==undefined?options.collapsed:true;this.collapsible_=options.collapsible!==undefined?options.collapsible:true;if(!this.collapsible_)this.collapsed_=false;var className=options.className||"de-novasib-ol-importpanel";this.id=options.idDiv;render=options.render||de.novasib.ol.control.ImportPanel.render;var cssClasses=className+" "+
ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+(this.collapsed_&&this.collapsible_?" ol-collapsed":"")+(this.collapsible_?"":" ol-uncollapsible");element=document.createElement("DIV");element.className=cssClasses;element.appendChild(this.ulElement_);this.elements_=[]}else{this.ulElement_=document.createElement("UL");this.collapsed_=options.collapsed!==undefined?options.collapsed:true;this.collapsible_=options.collapsible!==undefined?options.collapsible:true;if(!this.collapsible_)this.collapsed_=
false;var className$2=options.className||"de-novasib-ol-importpanel";var tipLabel=options.tipLabel||"Import Panel";var collapseLabel=options.collapseLabel||"\u00bb";if(typeof collapseLabel==="string"){this.collapseLabel_=document.createElement("SPAN");this.collapseLabel_.textContent=collapseLabel}else this.collapseLabel_=collapseLabel;var label=options.label||"\u00ab";if(typeof label==="string"){this.label_=document.createElement("SPAN");this.label_.textContent=label}else this.label_=label;this.idDiv=
options.idDiv||undefined;target=options.target||undefined;var activeLabel=this.collapsible_&&!this.collapsed_?this.collapseLabel_:this.label_;var button=document.createElement("BUTTON");button.setAttribute("type","button");button.setAttribute("id","btnUnfold");button.title=tipLabel;button.appendChild(activeLabel);ol.events.listen(button,ol.events.EventType.CLICK,this.handleClick_,this);var cssClasses$3=className$2+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+(this.collapsed_&&this.collapsible_?
" ol-collapsed":"")+(this.collapsible_?"":" ol-uncollapsible");element=document.createElement("DIV");element.className=cssClasses$3;element.appendChild(button);element.appendChild(this.ulElement_);render=options.render||de.novasib.ol.control.ImportPanel.render;var elementsArray=[];this.elements_=elementsArray;this.sortElements_()}ol.control.Control.call(this,{element:element,render:render,target:target});this.renderedVisible_=true};ol.inherits(de.novasib.ol.control.ImportPanel,ol.control.Control);
de.novasib.ol.control.ImportPanel.render=function(mapEvent){this.updateElement_(mapEvent.frameState)};de.novasib.ol.control.ImportPanel.Event=function(type,element_,mouseEvent_){ol.events.Event.call(this,type);this.element=element_;this.mouseEvent=mouseEvent_};ol.inherits(de.novasib.ol.control.ImportPanel.Event,ol.events.Event);de.novasib.ol.control.ImportPanel.EventType_={CLICK:"click"};
de.novasib.ol.control.ImportPanel.prototype.addElement=function(options){var element;if(Object.keys(options).length>0){element=new de.novasib.ol.control.ImportPanel.Element_(options);this.elements_.push(element);this.getMap().render()}return element};de.novasib.ol.control.ImportPanel.prototype.removeElement=function(id){if(id){var node=document.getElementById(id);if(node.parentNode)node.parentNode.removeChild(node)}};
de.novasib.ol.control.ImportPanel.prototype.removeContent=function(){var node=this.element.lastChild;if(node&&node.nodeName==="UL")while(node.firstChild)node.removeChild(node.firstChild);var elementsArray=this.elements_;if(elementsArray.length>0)this.elements_=[]};
de.novasib.ol.control.ImportPanel.prototype.sortElements_=function(){var sortByType=function(a,b){var aType=a.getType();var bType=b.getType();if(aType===bType)return 0;else if(aType===de.novasib.ol.htmlInputType.RADIO)return-1;return 1};var sortAlph=function(a,b){var aLabel=a.getLabel();var bLabel=b.getLabel();return aLabel.localeCompare(bLabel)};var sortByZindex=function(a,b,ascending){var ret;var aZindex=a.getLayer().getZIndex();var bZindex=b.getLayer().getZIndex();if(ascending)ret=aZindex-bZindex;
else ret=bZindex-aZindex;return ret};var _=de.novasib.ol;var sort=function(a,b){var ret=sortByType(a,b);if(_.PARENT_APP_NAME===_.KNOWN_APP_NAMES.MBDE)if(ret===0)ret=sortAlph(a,b);if(ret===0)ret=sortByZindex(a,b);return ret};this.elements_.sort(sort)};
de.novasib.ol.control.ImportPanel.prototype.updateElement_=function(frameState){if(!frameState){if(this.renderedVisible_){this.element.style.visibility="hidden";this.renderedVisible_=false}return}if(!this.elements_||this.elements_.length===0)return;while(this.ulElement_.lastChild)this.ulElement_.removeChild(this.ulElement_.lastChild);this.elements_.map(function(element){this.ulElement_.appendChild(element.getElement())}.bind(this))};
de.novasib.ol.control.ImportPanel.prototype.handleClick_=function(event){event.preventDefault();this.handleToggle_()};de.novasib.ol.control.ImportPanel.prototype.handleToggle_=function(){this.element.classList.toggle("ol-collapsed");if(this.collapsed_)ol.dom.replaceNode(this.collapseLabel_,this.label_);else ol.dom.replaceNode(this.label_,this.collapseLabel_);this.collapsed_=!this.collapsed_};
de.novasib.ol.control.ImportPanel.prototype.setCollapsible=function(collapsible){if(this.collapsible_=collapsible)return;this.collapsible_=collapsible;this.element.classList.toggle("ol-uncollapsible");if(!collapsible&&this.collapsed_)this.handleToggle_()};de.novasib.ol.control.ImportPanel.prototype.setCollapsed=function(collapsed){if(!this.collapsible_||this.collapsed_==collapsed)return;this.handleToggle_()};de.novasib.ol.control.ImportPanel.prototype.getCollapsed=function(){return this.collapsed_};
de.novasib.ol.control.ImportPanel.prototype.setElementsActive=function(active){if(active)this.getMap().render()};de.novasib.ol.control.ImportPanel.Element_=function(options){if(Object.keys(options).length===0)return false;this.elementType_=options.elementType;this.inputType_=options.inputType||null;this.label_=options.label;this.value_=options.value;this.id_=options.id;this.class_=options.class;this.domElement_=this.buildHtml_();this.active_=true};
de.novasib.ol.control.ImportPanel.Element_.ID_PREFIX="id_";
de.novasib.ol.control.ImportPanel.Element_.getInputType_=function(element){var type;var input=element.querySelector("INPUT");var domType=input.getAttribute("type");var inputType=de.novasib.ol.htmlInputType;switch(domType){case "button":type=inputType.BUTTON;break;case "checkbox":type=inputType.CHECKBOX;break;case "file":type=inputType.FILE;break;case "image":type=inputType.IMAGE;break;case "radio":type=inputType.RADIO;break;case "text":type=inputType.TEXT;break;default:break}return type};
de.novasib.ol.control.ImportPanel.Element_.prototype.getElement=function(){return this.domElement_};de.novasib.ol.control.ImportPanel.Element_.prototype.setActive=function(active){this.active_=active};de.novasib.ol.control.ImportPanel.Element_.prototype.updateElement=function(){this.domElement_=this.buildHtml_()};
de.novasib.ol.control.ImportPanel.Element_.prototype.buildHtml_=function(){var el,label,textContent;var elementType=this.elementType_;if(elementType===de.novasib.ol.htmlElementType.LABEL){el=document.createElement(de.novasib.ol.htmlElementType.LI);label=document.createElement(de.novasib.ol.htmlElementType.LABEL);label.setAttribute("class",this.class_||"k-label");label.setAttribute("value",this.value_);label.setAttribute("type",de.novasib.ol.htmlElementType.LABEL);label.setAttribute("id",de.novasib.ol.control.ImportPanel.Element_.ID_PREFIX+
this.id_);textContent=document.createTextNode(this.label_);label.appendChild(textContent);el.appendChild(label)}else if(elementType===de.novasib.ol.htmlElementType.HR){el=document.createElement(de.novasib.ol.htmlElementType.HR);el.setAttribute("class","k-horizontalRule");el.setAttribute("id",de.novasib.ol.control.ImportPanel.Element_.ID_PREFIX+this.id_)}else if(elementType===de.novasib.ol.htmlElementType.INPUT)if(this.inputType_===de.novasib.ol.htmlInputType.FILE){el=document.createElement(de.novasib.ol.htmlElementType.LI);
el.setAttribute("id","li_"+this.id_);var btnImportLayer=document.createElement(this.elementType_);btnImportLayer.setAttribute("type",this.inputType_);btnImportLayer.setAttribute("id",this.id_);btnImportLayer.setAttribute("style","display: none");var btnImportLayerOverlay=document.createElement(this.elementType_);btnImportLayerOverlay.setAttribute("type",de.novasib.ol.htmlInputType.BUTTON);btnImportLayerOverlay.setAttribute("class","k-button");btnImportLayerOverlay.setAttribute("id",this.id_+"Overlay");
btnImportLayerOverlay.setAttribute("title",this.label_);label=document.createElement(de.novasib.ol.htmlElementType.LABEL);label.setAttribute("for",""+this.id_);label.setAttribute("id","label_"+this.id_);textContent=document.createTextNode(this.label_);label.appendChild(textContent);el.appendChild(btnImportLayer);el.appendChild(btnImportLayerOverlay);el.appendChild(label);var handleBtnImportLayer_change=function(event){var novaMap_=de.novasib.ol.getNovaMap();if(novaMap_){var panel_=novaMap_.getControlByClass(de.novasib.ol.control.ImportPanel);
if(panel_)panel_.dispatchEvent(new de.novasib.ol.control.ImportPanel.Event("import-layer",btnImportLayer,event))}btnImportLayer.value=""};ol.events.listen(btnImportLayerOverlay,ol.events.EventType.CLICK,function(){btnImportLayer.click()},this);ol.events.listen(btnImportLayer,ol.events.EventType.CHANGE,handleBtnImportLayer_change,this)}return el};de.novasib.ol.control.ImportPanel.Element_.prototype.getLabel=function(){return this.label_};
de.novasib.ol.control.ImportPanel.Element_.prototype.handleClick_=function(event){return null;if(event&&event.target){var el=event.target;var labelClicked=false;if(el.nodeName==="LABEL"){labelClicked=true;el=el.firstChild;if(el.disabled)return;if(el.type==="radio"&&!el.checked)el.checked=!el.checked}if(el.type==="radio"){var fireChangeEvent=function(element){if("createEvent"in document){var evt=document.createEvent("HTMLEvents");evt.initEvent("change",true,true);element.dispatchEvent(evt)}else element.fireEvent("onchange")};
var radios=document.querySelectorAll("INPUT[name="+this.radioGroupName_+"]");for(var i=0;i<radios.length;++i){var radio=radios[i];if(radio!=el)fireChangeEvent.call(this,radio)}fireChangeEvent.call(this,el)}if(el.type==="checkbox"){if(labelClicked)el.checked=!el.checked;var fireChangeEvent$4=function(element){if("createEvent"in document){var evt=document.createEvent("HTMLEvents");evt.initEvent("change",true,true);element.dispatchEvent(evt)}else element.fireEvent("onchange")};fireChangeEvent$4.call(this,
el)}var novaMap_=de.novasib.ol.getNovaMap();if(novaMap_){var panel_=novaMap_.getControlByClass(de.novasib.ol.control.ImportPanel);if(panel_)panel_.dispatchEvent(new de.novasib.ol.control.ImportPanel.Event(de.novasib.ol.control.ImportPanel.EventType_.CLICK,this))}}};de.novasib.ol.control.ImportPanel.Element_.prototype.handleChange_=function(event){if(event&&event.target);};de.novasib.ol.control.ImportPanel.Element_.prototype.isChecked=function(){};
de.novasib.ol.control.ImportPanel.Element_.prototype.getType=function(){return this.type_};de.novasib.ol.control.ImportPanel.prototype.getElements=function(){return this.elements_};de.novasib.ol.control.ImportPanel.prototype.isEmpty=function(){return ol.obj.isEmpty(this)};goog.provide("de.novasib.ol.control.InfoBox");goog.require("ol");goog.require("ol.control.Control");goog.require("ol.dom");goog.require("ol.events");
de.novasib.ol.control.InfoBox=function(opt_options){var options=opt_options?opt_options:{};this.ulElement_=document.createElement("UL");this.collapsed_=options.collapsed!==undefined?options.collapsed:true;this.collapsible_=options.collapsible!==undefined?options.collapsible:true;if(!this.collapsible_)this.collapsed_=false;var className=options.className||"de-novasib-ol-infobox";var tipLabel=options.tipLabel||"Info";var collapseLabel=options.collapseLabel||"\u00bb";if(typeof collapseLabel==="string"){this.collapseLabel_=
document.createElement("SPAN");this.collapseLabel_.textContent=collapseLabel}else this.collapseLabel_=collapseLabel;var label=options.label||"i";if(typeof label==="string"){this.label_=document.createElement("SPAN");this.label_.textContent=label}else this.label_=label;var activeLabel=this.collapsible_&&!this.collapsed_?this.collapseLabel_:this.label_;var button=document.createElement("BUTTON");button.setAttribute("type","button");button.title=tipLabel;button.appendChild(activeLabel);ol.events.listen(button,
ol.events.EventType.CLICK,this.handleClick_,this);var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+(this.collapsed_&&this.collapsible_?" ol-collapsed":"")+(this.collapsible_?"":" ol-uncollapsible");var element=document.createElement("DIV");element.className=cssClasses;element.appendChild(button);element.appendChild(this.ulElement_);var render=options.render||de.novasib.ol.control.InfoBox.render;ol.control.Control.call(this,{element:element,render:render,target:options.target});
this.renderedVisible_=true;this.elements_=[];this.setElements(options.elements,true)};ol.inherits(de.novasib.ol.control.InfoBox,ol.control.Control);de.novasib.ol.control.InfoBox.render=function(mapEvent){this.updateElement_(mapEvent.frameState)};de.novasib.ol.control.InfoBox.prototype.setElements=function(arr,clear){if(Array.isArray(arr)&&arr.length>0){if(clear)this.elements_=[];arr.forEach(function(el){this.elements_.push(new de.novasib.ol.control.InfoBox.Element_(el))},this);this.getMap().render()}};
de.novasib.ol.control.InfoBox.prototype.updateElement_=function(frameState){if(!frameState){if(this.renderedVisible_){this.element.style.display="none";this.renderedVisible_=false}return}if(!this.elements_||this.elements_.length===0)return;while(this.ulElement_.lastChild)this.ulElement_.removeChild(this.ulElement_.lastChild);var len=this.elements_.length;for(var i=0;i<len;++i){var element=this.elements_[i];this.ulElement_.appendChild(element.getHTML())}};
de.novasib.ol.control.InfoBox.prototype.handleClick_=function(event){event.preventDefault();this.handleToggle_()};de.novasib.ol.control.InfoBox.prototype.handleToggle_=function(){this.element.classList.toggle("ol-collapsed");if(this.collapsed_)ol.dom.replaceNode(this.collapseLabel_,this.label_);else ol.dom.replaceNode(this.label_,this.collapseLabel_);this.collapsed_=!this.collapsed_};de.novasib.ol.control.InfoBox.prototype.getCollapsible=function(){return this.collapsible_};
de.novasib.ol.control.InfoBox.prototype.setCollapsible=function(collapsible){if(this.collapsible_===collapsible)return;this.collapsible_=collapsible;this.element.classList.toggle("ol-uncollapsible");if(!collapsible&&this.collapsed_)this.handleToggle_()};de.novasib.ol.control.InfoBox.prototype.setCollapsed=function(collapsed){if(!this.collapsible_||this.collapsed_===collapsed)return;this.handleToggle_()};de.novasib.ol.control.InfoBox.prototype.getCollapsed=function(){return this.collapsed_};
de.novasib.ol.control.InfoBox.Element_=function(obj){this.key_=obj.key;this.keyStyle_=obj["keyStyle"];this.value_=obj.value;this.valueStyle_=obj["valueStyle"]};
de.novasib.ol.control.InfoBox.Element_.prototype.getHTML=function(){var el=document.createElement("LI");var keyStyle=this.getStyle_(this.keyStyle_);var valueStyle=this.getStyle_(this.valueStyle_);var keySpan=document.createElement("SPAN");keySpan.textContent=this.key_;var valueSpan=document.createElement("SPAN");valueSpan.textContent=this.value_;valueSpan.className="de-novasib-ol-infobox-colr";if(keyStyle&&keyStyle===valueStyle)el.setAttribute("style",keyStyle);else{if(keyStyle)keySpan.setAttribute("style",
keyStyle);if(valueStyle)valueSpan.setAttribute("style",valueStyle)}el.appendChild(keySpan);el.appendChild(valueSpan);return el};de.novasib.ol.control.InfoBox.Element_.prototype.getStyle_=function(styleObj){var ret="";if(styleObj){if(styleObj.color)ret+="color: "+styleObj.color+";text-shadow: none;";if(styleObj.backgroundColor)ret+="background-color: "+styleObj.backgroundColor+";"}return ret};goog.provide("de.novasib.ol.control.Input");goog.require("ol");goog.require("ol.events");goog.require("ol.control.Control");goog.require("ol.css");
de.novasib.ol.control.Input=function(options){var className=options.className!==undefined?options.className:"de-novasib-ol-input";var label=options.label!==undefined?options.label:"I";var tipLabel=options.tipLabel!==undefined?options.tipLabel:"Simple Input Control";var input=document.createElement("INPUT");input.setAttribute("type","input");input.title=tipLabel;input.appendChild(typeof label==="string"?document.createTextNode(label):label);var handleClick=options.handleClick;if(!handleClick||typeof handleClick!==
"function")throw new Error("Input Control needs a click handler.");ol.events.listen(input,ol.events.EventType.CLICK,handleClick,this);var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL;var element=document.createElement("div");element.className=cssClasses;element.appendChild(input);ol.control.Control.call(this,{element:element,target:options.target})};ol.inherits(de.novasib.ol.control.Input,ol.control.Control);goog.provide("de.novasib.ol.control.LayerSwitcher");goog.require("ol");goog.require("ol.control.Control");goog.require("ol.dom");goog.require("ol.events");
de.novasib.ol.control.LayerSwitcher=function(options){this.ulElement_=document.createElement("UL");this.collapsed_=options.collapsed!==undefined?options.collapsed:true;this.collapsible_=options.collapsible!==undefined?options.collapsible:true;if(!this.collapsible_)this.collapsed_=false;var className=options.className||"de-novasib-ol-layerswitcher";var tipLabel=options.tipLabel||"Layer Switcher";var collapseLabel=options.collapseLabel||"\u00bb";if(typeof collapseLabel==="string"){this.collapseLabel_=
document.createElement("SPAN");this.collapseLabel_.textContent=collapseLabel}else this.collapseLabel_=collapseLabel;var label=options.label||"\u00ab";if(typeof label==="string"){this.label_=document.createElement("SPAN");this.label_.textContent=label}else this.label_=label;var activeLabel=this.collapsible_&&!this.collapsed_?this.collapseLabel_:this.label_;var button=document.createElement("BUTTON");button.setAttribute("type","button");button.title=tipLabel;button.appendChild(activeLabel);ol.events.listen(button,
ol.events.EventType.CLICK,this.handleClick_,this);var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+(this.collapsed_&&this.collapsible_?" ol-collapsed":"")+(this.collapsible_?"":" ol-uncollapsible");var element=document.createElement("DIV");element.className=cssClasses;element.appendChild(button);element.appendChild(this.ulElement_);var render=options.render||de.novasib.ol.control.LayerSwitcher.render;ol.control.Control.call(this,{element:element,render:render,target:options.target});
this.renderedVisible_=true;this.radioGroupName_="ls_radio_grp_"+Date.now();var elementsArray=[];var layers=options.layers;layers.forEach(function(lyr){elementsArray.push(new de.novasib.ol.control.LayerSwitcher.Element_(lyr,this.radioGroupName_))},this);this.elements_=elementsArray;this.sortElements_()};ol.inherits(de.novasib.ol.control.LayerSwitcher,ol.control.Control);de.novasib.ol.control.LayerSwitcher.render=function(mapEvent){this.updateElement_(mapEvent.frameState)};
de.novasib.ol.control.LayerSwitcher.Event=function(type,element_,mouseEvent_){ol.events.Event.call(this,type);this.element=element_;this.mouseEvent=mouseEvent_};ol.inherits(de.novasib.ol.control.LayerSwitcher.Event,ol.events.Event);de.novasib.ol.control.LayerSwitcher.EventType_={CLICK:"click"};
de.novasib.ol.control.LayerSwitcher.prototype.addElement=function(object_){if(object_ instanceof ol.layer.Layer){var existingElement=this.getElementForLayer_(object_);if(!existingElement){var element=new de.novasib.ol.control.LayerSwitcher.Element_(object_,this.radioGroupName_);this.elements_.push(element);this.sortElements_();this.getMap().render()}}else{var existingElement$5=this.getElement_(object_);if(!existingElement$5){var element$6=new de.novasib.ol.control.LayerSwitcher.Element_(object_);
this.elements_.push(element$6);this.sortElements_();this.getMap().render()}}};de.novasib.ol.control.LayerSwitcher.prototype.removeElement=function(layer){if(layer){var element=this.getElementForLayer_(layer);var index=this.elements_.indexOf(element);if(element&&index!=-1)this.elements_.splice(index,1)}};
de.novasib.ol.control.LayerSwitcher.prototype.sortElements_=function(){var sortByType=function(a,b){var aType=a.getType();var bType=b.getType();if(aType===bType)return 0;else if(aType===de.novasib.ol.control.LayerSwitcher.Element_.Type_.RADIO)return-1;return 1};var sortAlph=function(a,b){var aLabel=a.getLabel();var bLabel=b.getLabel();return aLabel.localeCompare(bLabel)};var sortByZindex=function(a,b,ascending){var ret;var aZindex=a.getLayer().getZIndex();var bZindex=b.getLayer().getZIndex();if(ascending)ret=
aZindex-bZindex;else ret=bZindex-aZindex;return ret};var _=de.novasib.ol;var sort=function(a,b){var ret=sortByType(a,b);if(_.PARENT_APP_NAME===_.KNOWN_APP_NAMES.MBDE)if(ret===0)ret=sortAlph(a,b);if(ret===0)ret=sortByZindex(a,b);return ret};this.elements_.sort(sort)};
de.novasib.ol.control.LayerSwitcher.prototype.updateElement_=function(frameState){if(!frameState){if(this.renderedVisible_){this.element.style.display="none";this.renderedVisible_=false}return}if(!this.elements_)return;while(this.ulElement_.lastChild)this.ulElement_.removeChild(this.ulElement_.lastChild);var len=this.elements_.length;var overlayBarDrawn=false;for(var i=0;i<len;++i){var element=this.elements_[i];element.updateElement();var _=de.novasib.ol;var controlType_=undefined;if(_.PARENT_APP_NAME===
_.KNOWN_APP_NAMES.NOVAMAP||_.PARENT_APP_NAME===_.KNOWN_APP_NAMES.SPERRINFOSYS)controlType_=de.novasib.ol.control.LayerSwitcher.Element_.Type_.RADIO;else controlType_=de.novasib.ol.control.LayerSwitcher.Element_.Type_.CHECK;if(!overlayBarDrawn&&element.getType()===controlType_){var hr=document.createElement("HR");this.ulElement_.appendChild(hr);overlayBarDrawn=true}this.ulElement_.appendChild(element.getElement())}};
de.novasib.ol.control.LayerSwitcher.prototype.handleClick_=function(event){event.preventDefault();this.handleToggle_()};
de.novasib.ol.control.LayerSwitcher.prototype.handleToggle_=function(){this.element.classList.toggle("ol-collapsed");if(this.collapsed_){var olmap_=de.novasib.ol.getOlMap(this);olmap_.once(ol.events.EventType.CLICK,function(evt){var novaMap_=de.novasib.ol.getNovaMap();var layerSwitcher=novaMap_.getControlByClass(de.novasib.ol.control.LayerSwitcher);if(layerSwitcher){var layerSwitcherUnCollapsed=!layerSwitcher.collapsed_;layerSwitcherUnCollapsed?layerSwitcher.setCollapsed(true):null}}.bind(this));
ol.dom.replaceNode(this.collapseLabel_,this.label_)}else ol.dom.replaceNode(this.label_,this.collapseLabel_);this.collapsed_=!this.collapsed_};de.novasib.ol.control.LayerSwitcher.prototype.setCollapsible=function(collapsible){if(this.collapsible_=collapsible)return;this.collapsible_=collapsible;this.element.classList.toggle("ol-uncollapsible");if(!collapsible&&this.collapsed_)this.handleToggle_()};
de.novasib.ol.control.LayerSwitcher.prototype.setCollapsed=function(collapsed){if(!this.collapsible_||this.collapsed_==collapsed)return;this.handleToggle_()};de.novasib.ol.control.LayerSwitcher.prototype.getCollapsed=function(){return this.collapsed_};
de.novasib.ol.control.LayerSwitcher.prototype.setElementsActive=function(layers,active){if(layers){if(!Array.isArray(layers))layers=[layers];layers.forEach(function(layer){var element=this.getElementForLayer_(layer);if(element)element.setActive(active)},this);this.getMap().render()}};
de.novasib.ol.control.LayerSwitcher.prototype.getElementForLayer_=function(layer){if(layer){var ret=null;for(var i=0;i<this.elements_.length;++i){var element=this.elements_[i];var elLayer=element.getLayer();if(elLayer==layer){ret=element;break}}return ret}return null};de.novasib.ol.control.LayerSwitcher.prototype.getElement_=function(el){if(el){var ret=null;for(var i=0;i<this.elements_.length;++i){var element=this.elements_[i];if(element.id_&&element.id_===el.id){ret=element;break}}return ret}return null};
de.novasib.ol.control.LayerSwitcher.Element_=function(object_,radioGroupName){if(!object_)throw Error("LayerSwitcher-Element needs a layer object for initialization!");if(object_ instanceof ol.layer.Layer){this.layer_=object_;if(this.layer_.get("title")==="Knoten-Import"||this.layer_.get("title")==="Kanten-Import")this.label_=this.layer_.get("title");else this.label_=this.layer_.get("title")||this.layer_.get("name");this.domElement_=this.buildHtml_();this.type_=de.novasib.ol.control.LayerSwitcher.Element_.getType_(this.domElement_);
this.active_=true;this.radioGroupName_=radioGroupName}else{this.id_=object_.id;this.label_=object_.label;this.elementType_=object_.elementType;this.domElement_=this.buildHtml_();if(this.elementType_===de.novasib.ol.htmlElementType.INPUT){this.inputType_=this.getInputType_(this.domElement_);this.type_=de.novasib.ol.control.LayerSwitcher.Element_.getType_(this.domElement_);this.active_=true;this.radioGroupName_=radioGroupName}}};de.novasib.ol.control.LayerSwitcher.Element_.ID_PREFIX="id_";
de.novasib.ol.control.LayerSwitcher.Element_.prototype.getElementType_=function(element){var elementType=element.localName;return elementType};de.novasib.ol.control.LayerSwitcher.Element_.prototype.getInputType_=function(element){var inputType=de.novasib.ol.control.LayerSwitcher.Element_.Type_.RADIO;var input=element.querySelector("INPUT");var domType=input.getAttribute("type");if(domType==="checkbox")inputType=de.novasib.ol.control.LayerSwitcher.Element_.Type_.CHECK;return inputType};
de.novasib.ol.control.LayerSwitcher.Element_.getType_=function(element){var type=de.novasib.ol.control.LayerSwitcher.Element_.Type_.RADIO;var input=element.querySelector("INPUT");var domType=input.getAttribute("type");if(domType==="checkbox")type=de.novasib.ol.control.LayerSwitcher.Element_.Type_.CHECK;return type};de.novasib.ol.control.LayerSwitcher.Element_.prototype.getElement=function(){return this.domElement_};
de.novasib.ol.control.LayerSwitcher.Element_.prototype.setActive=function(active){this.active_=active};de.novasib.ol.control.LayerSwitcher.Element_.prototype.updateElement=function(){this.domElement_=this.buildHtml_()};
de.novasib.ol.control.LayerSwitcher.Element_.prototype.buildHtml_=function(){var elementType=this.elementType_;if(elementType===de.novasib.ol.htmlElementType.HR){el=document.createElement(de.novasib.ol.htmlElementType.HR);el.setAttribute("class","k-horizontalRule");el.setAttribute("id",de.novasib.ol.control.ImportPanel.Element_.ID_PREFIX+this.id_);return el}var el=document.createElement("LI");var input=document.createElement("INPUT");var type="";if(this.layer_.get("backgroundLayer")){type="radio";
input.setAttribute("name",this.radioGroupName_);input.setAttribute("class","k-radio");ol.events.listen(input,ol.events.EventType.CHANGE,this.handleChange_,this)}else{type="checkbox";input.setAttribute("class","k-checkbox")}input.setAttribute("type",type);input.setAttribute("value",this.label_);input.setAttribute("id",de.novasib.ol.control.LayerSwitcher.Element_.ID_PREFIX+this.label_);if(this.layer_.getVisible())input.setAttribute("checked","checked");var label=document.createElement("LABEL");label.setAttribute("for",
"layer_"+this.label_);ol.events.listen(label,ol.events.EventType.CLICK,this.handleClick_,this);var textContent=document.createTextNode(this.label_);label.appendChild(input);label.appendChild(textContent);if(!this.active_){input.setAttribute("disabled","disabled");label.setAttribute("style","color: gray; text-shadow: none !important;")}el.appendChild(label);return el};de.novasib.ol.control.LayerSwitcher.Element_.prototype.getLabel=function(){return this.label_};
de.novasib.ol.control.LayerSwitcher.Element_.prototype.getLayer=function(){return this.layer_};
de.novasib.ol.control.LayerSwitcher.Element_.prototype.handleClick_=function(event){if(event&&event.target){var el=event.target;var labelClicked=false;if(el.nodeName==="LABEL"){labelClicked=true;el=el.firstChild;if(el.disabled)return;if(el.type==="radio"&&!el.checked)el.checked=!el.checked}if(el.type==="radio"){var fireChangeEvent=function(element){if("createEvent"in document){var evt=document.createEvent("HTMLEvents");evt.initEvent("change",true,true);element.dispatchEvent(evt)}else element.fireEvent("onchange")};
var radios=document.querySelectorAll("INPUT[name="+this.radioGroupName_+"]");for(var i=0;i<radios.length;++i){var radio=radios[i];if(radio!=el)fireChangeEvent.call(this,radio)}fireChangeEvent.call(this,el)}else{if(labelClicked)el.checked=!el.checked;this.layer_.setVisible(el.checked)}var novaMap_=de.novasib.ol.getNovaMap();if(novaMap_){var layerSwitcher_=novaMap_.getControlByClass(de.novasib.ol.control.LayerSwitcher);if(layerSwitcher_)layerSwitcher_.dispatchEvent(new de.novasib.ol.control.LayerSwitcher.Event(de.novasib.ol.control.LayerSwitcher.EventType_.CLICK,
this,event))}}};de.novasib.ol.control.LayerSwitcher.Element_.prototype.handleChange_=function(event){if(event&&event.target){var visible=event.target.checked;if(this.layer_.getVisible()!=visible)this.layer_.setVisible(visible)}};de.novasib.ol.control.LayerSwitcher.Element_.prototype.isChecked=function(){return this.layer_.getVisible()};de.novasib.ol.control.LayerSwitcher.Element_.prototype.getType=function(){return this.type_};de.novasib.ol.control.LayerSwitcher.Element_.Type_={RADIO:"radio",CHECK:"check"};
de.novasib.ol.control.LayerSwitcher.prototype.setZIndex=function(zIndex){var style_=this.element.style;if(!style_)return false;style_.zIndex=zIndex;return true};de.novasib.ol.control.LayerSwitcher.prototype.getZIndex=function(){var style_=this.element.style;if(!style_)return false;return style_};de.novasib.ol.control.LayerSwitcher.prototype.getElements=function(){return this.elements_};de.novasib.ol.control.LayerSwitcher.prototype.isEmpty=function(){return ol.obj.isEmpty(this)};goog.provide("de.novasib.ol.control.Radio");goog.require("ol");goog.require("ol.control.Control");goog.require("ol.dom");goog.require("ol.events");
de.novasib.ol.control.Radio=function(opt_options){var options=opt_options||{};this.ulElement_=document.createElement("UL");this.collapsed_=options.collapsed!==undefined?options.collapsed:true;this.collapsible_=options.collapsible!==undefined?options.collapsible:true;if(!this.collapsible_)this.collapsed_=false;var className=options.className||"de-novasib-ol-radio";var tipLabel=options.tipLabel||"Simple Radio Control";var collapseLabel=options.collapseLabel||"\u00ab";if(typeof collapseLabel==="string"){this.collapseLabel_=
document.createElement("SPAN");this.collapseLabel_.textContent=collapseLabel}else this.collapseLabel_=collapseLabel;var label=options.label||"\u00bb";if(typeof label==="string"){this.label_=document.createElement("SPAN");this.label_.textContent=label}else this.label_=label;var activeLabel=this.collapsible_&&!this.collapsed_?this.collapseLabel_:this.label_;var button=document.createElement("BUTTON");button.setAttribute("type","button");button.title=tipLabel;button.appendChild(activeLabel);ol.events.listen(button,
ol.events.EventType.CLICK,this.handleClick_,this);var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+(this.collapsed_&&this.collapsible_?" ol-collapsed":"")+(this.collapsible_?"":" ol-uncollapsible");var element=document.createElement("DIV");element.className=cssClasses;element.appendChild(button);element.appendChild(this.ulElement_);var render=options.render||de.novasib.ol.control.Radio.render;ol.control.Control.call(this,{element:element,render:render,target:options.target});
this.renderedVisible_=true;var elementsArray=[];var elements=options.elements;elements.forEach(function(el){elementsArray.push(new de.novasib.ol.control.Radio.Element_(el))});this.elements_=elementsArray;if(this.elements_.length>0){this.elements_[0].setActive(true);this.elements_.forEach(function(element){element.on("radiochange",function(event){this.dispatchEvent(event)}.bind(this))},this)}};ol.inherits(de.novasib.ol.control.Radio,ol.control.Control);de.novasib.ol.control.Radio.render=function(mapEvent){this.updateElement_(mapEvent.frameState)};
de.novasib.ol.control.Radio.prototype.updateElement_=function(frameState){if(!frameState){if(this.renderedVisible_){this.element.style.display="none";this.renderedVisible_=false}return}if(!this.elements_)return;while(this.ulElement_.lastChild)this.ulElement_.removeChild(this.ulElement_.lastChild);var len=this.elements_.length;for(var i=0;i<len;++i){var element=this.elements_[i];this.ulElement_.appendChild(element.getHTML())}};
de.novasib.ol.control.Radio.prototype.handleClick_=function(event){event.preventDefault();this.handleToggle_()};de.novasib.ol.control.Radio.prototype.handleToggle_=function(){this.element.classList.toggle("ol-collapsed");if(this.collapsed_)ol.dom.replaceNode(this.collapseLabel_,this.label_);else ol.dom.replaceNode(this.label_,this.collapseLabel_);this.collapsed_=!this.collapsed_};
de.novasib.ol.control.Radio.prototype.setCollapsible=function(collapsible){if(this.collapsible_=collapsible)return;this.collapsible_=collapsible;this.element.classList.toggle("ol-uncollapsible");if(!collapsible&&this.collapsed_)this.handleToggle_()};de.novasib.ol.control.Radio.prototype.setCollapsed=function(collapsed){if(!this.collapsible_||this.collapsed_==collapsed)return;this.handleToggle_()};de.novasib.ol.control.Radio.prototype.getCollapsed=function(){return this.collapsed_};
de.novasib.ol.control.Radio.Element_=function(options){ol.Object.call(this);this.label_=options.label;this.active_=false};ol.inherits(de.novasib.ol.control.Radio.Element_,ol.Object);de.novasib.ol.control.Radio.Element_.ID_PREFIX="id_";de.novasib.ol.control.Radio.Element_.prototype.setActive=function(active){this.active_=active};
de.novasib.ol.control.Radio.Element_.prototype.getHTML=function(){var el=document.createElement("LI");var input=document.createElement("INPUT");input.setAttribute("name","rc_radio_grp");ol.events.listen(input,ol.events.EventType.CHANGE,this.handleChange_,this);input.setAttribute("type","radio");input.setAttribute("value",this.label_);input.setAttribute("id",de.novasib.ol.control.Radio.Element_.ID_PREFIX+this.label_);if(this.active_)input.setAttribute("checked","checked");var label=document.createElement("LABEL");
label.setAttribute("for","label_"+this.label_);ol.events.listen(label,ol.events.EventType.CLICK,this.handleClick_,this);var textContent=document.createTextNode(this.label_);label.appendChild(input);label.appendChild(textContent);el.appendChild(label);return el};
de.novasib.ol.control.Radio.Element_.prototype.handleClick_=function(event){if(event&&event.target){var el=event.target;if(el.nodeName==="LABEL"){el=el.firstChild;if(!el.checked)el.checked=!el.checked}var fireChangeEvent=function(element){if("createEvent"in document){var evt=document.createEvent("HTMLEvents");evt.initEvent("change",true,true);element.dispatchEvent(evt)}else element.fireEvent("onchange")};var radios=document.querySelectorAll("INPUT[name=rc_radio_grp]");for(var i=0;i<radios.length;++i){var radio=
radios[i];if(radio!=el)fireChangeEvent.call(this,radio)}fireChangeEvent.call(this,el)}};de.novasib.ol.control.Radio.Element_.prototype.handleChange_=function(event){if(event&&event.target){var checked=event.target.checked;this.active_=checked;if(checked)this.dispatchEvent(new de.novasib.ol.control.Radio.Event(this.label_))}};de.novasib.ol.control.Radio.Event=function(label){ol.events.Event.call(this,"radiochange");this.label=label};ol.inherits(de.novasib.ol.control.Radio.Event,ol.events.Event);goog.provide("de.novasib.ol.control.ToolboxPanel");goog.require("ol");goog.require("ol.control.Control");goog.require("ol.dom");goog.require("ol.events");
de.novasib.ol.control.ToolboxPanel=function(options,empty){var render,element,target;if(empty){this.ulElement_=document.createElement("UL");this.collapsed_=options.collapsed!==undefined?options.collapsed:true;this.collapsible_=options.collapsible!==undefined?options.collapsible:true;if(!this.collapsible_)this.collapsed_=false;var className=options.className||"de-novasib-ol-toolboxpanel";this.id=options.idDiv;render=options.render||de.novasib.ol.control.ToolboxPanel.render;var cssClasses=className+
" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+(this.collapsed_&&this.collapsible_?" ol-collapsed":"")+(this.collapsible_?"":" ol-uncollapsible");element=document.createElement("DIV");element.className=cssClasses;element.appendChild(this.ulElement_);this.elements_=[]}else{this.ulElement_=document.createElement("UL");this.collapsed_=options.collapsed!==undefined?options.collapsed:true;this.collapsible_=options.collapsible!==undefined?options.collapsible:true;if(!this.collapsible_)this.collapsed_=
false;var className$7=options.className||"de-novasib-ol-toolboxpanel";var tipLabel=options.tipLabel||"Toolbox Panel";var collapseLabel=options.collapseLabel||"\u00bb";if(typeof collapseLabel==="string"){this.collapseLabel_=document.createElement("SPAN");this.collapseLabel_.textContent=collapseLabel}else this.collapseLabel_=collapseLabel;var label=options.label||"\u00ab";if(typeof label==="string"){this.label_=document.createElement("SPAN");this.label_.textContent=label}else this.label_=label;this.idDiv=
options.idDiv||undefined;target=options.target||undefined;var activeLabel=this.collapsible_&&!this.collapsed_?this.collapseLabel_:this.label_;var button=document.createElement("BUTTON");button.setAttribute("type","button");button.setAttribute("id","btnUnfold");button.title=tipLabel;button.appendChild(activeLabel);ol.events.listen(button,ol.events.EventType.CLICK,this.handleClick_,this);var cssClasses$8=className$7+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+(this.collapsed_&&this.collapsible_?
" ol-collapsed":"")+(this.collapsible_?"":" ol-uncollapsible");element=document.createElement("DIV");element.className=cssClasses$8;element.appendChild(button);element.appendChild(this.ulElement_);render=options.render||de.novasib.ol.control.ToolboxPanel.render;var elementsArray=[];this.elements_=elementsArray;this.sortElements_()}ol.control.Control.call(this,{element:element,render:render,target:target});this.renderedVisible_=true};ol.inherits(de.novasib.ol.control.ToolboxPanel,ol.control.Control);
de.novasib.ol.control.ToolboxPanel.render=function(mapEvent){this.updateElement_(mapEvent.frameState)};de.novasib.ol.control.ToolboxPanel.Event=function(type,element_,mouseEvent_){ol.events.Event.call(this,type);this.element=element_;this.mouseEvent=mouseEvent_};ol.inherits(de.novasib.ol.control.ToolboxPanel.Event,ol.events.Event);de.novasib.ol.control.ToolboxPanel.EventType_={CLICK:"click"};
de.novasib.ol.control.ToolboxPanel.prototype.addElement=function(type,label,id,active,checked){var element;if(type){element=new de.novasib.ol.control.ToolboxPanel.Element_(type,label,id,active,checked);this.elements_.push(element);this.getMap().render()}return element};de.novasib.ol.control.ToolboxPanel.prototype.removeElement=function(id){if(id){var node=document.getElementById(id);if(node.parentNode)node.parentNode.removeChild(node)}};
de.novasib.ol.control.ToolboxPanel.prototype.removeContent=function(){var node=this.element.lastChild;if(node&&node.nodeName==="UL")while(node.firstChild)node.removeChild(node.firstChild);var elementsArray=this.elements_;if(elementsArray.length>0)this.elements_=[]};
de.novasib.ol.control.ToolboxPanel.prototype.sortElements_=function(){var sortByType=function(a,b){var aType=a.getType();var bType=b.getType();if(aType===bType)return 0;else if(aType===de.novasib.ol.control.ToolboxPanel.Element_.Type_.RADIO)return-1;return 1};var sortAlph=function(a,b){var aLabel=a.getLabel();var bLabel=b.getLabel();return aLabel.localeCompare(bLabel)};var sortByZindex=function(a,b,ascending){var ret;var aZindex=a.getLayer().getZIndex();var bZindex=b.getLayer().getZIndex();if(ascending)ret=
aZindex-bZindex;else ret=bZindex-aZindex;return ret};var _=de.novasib.ol;var sort=function(a,b){var ret=sortByType(a,b);if(_.PARENT_APP_NAME===_.KNOWN_APP_NAMES.MBDE)if(ret===0)ret=sortAlph(a,b);if(ret===0)ret=sortByZindex(a,b);return ret};this.elements_.sort(sort)};
de.novasib.ol.control.ToolboxPanel.prototype.updateElement_=function(frameState){if(!frameState){if(this.renderedVisible_){this.element.style.visibility="hidden";this.renderedVisible_=false}return}if(!this.elements_||this.elements_.length===0)return;while(this.ulElement_.lastChild)this.ulElement_.removeChild(this.ulElement_.lastChild);this.elements_.map(function(element){this.ulElement_.appendChild(element.getElement())}.bind(this))};
de.novasib.ol.control.ToolboxPanel.prototype.handleClick_=function(event){event.preventDefault();this.handleToggle_()};de.novasib.ol.control.ToolboxPanel.prototype.handleToggle_=function(){this.element.classList.toggle("ol-collapsed");if(this.collapsed_)ol.dom.replaceNode(this.collapseLabel_,this.label_);else ol.dom.replaceNode(this.label_,this.collapseLabel_);this.collapsed_=!this.collapsed_};
de.novasib.ol.control.ToolboxPanel.prototype.setCollapsible=function(collapsible){if(this.collapsible_=collapsible)return;this.collapsible_=collapsible;this.element.classList.toggle("ol-uncollapsible");if(!collapsible&&this.collapsed_)this.handleToggle_()};de.novasib.ol.control.ToolboxPanel.prototype.setCollapsed=function(collapsed){if(!this.collapsible_||this.collapsed_==collapsed)return;this.handleToggle_()};de.novasib.ol.control.ToolboxPanel.prototype.getCollapsed=function(){return this.collapsed_};
de.novasib.ol.control.ToolboxPanel.prototype.setElementsActive=function(active){if(active)this.getMap().render()};de.novasib.ol.control.ToolboxPanel.Element_=function(type,label,id,active,checked){this.type_=type;this.label_=label;this.id_=id;if(type==="BUTTON")if(active===undefined)this.active_=true;else this.active_=active;if(type==="CHECKBOX")this.checked_=checked;this.domElement_=this.buildHtml_();this.active_=true};de.novasib.ol.control.ToolboxPanel.Element_.ID_PREFIX="id_";
de.novasib.ol.control.ToolboxPanel.Element_.getType_=function(element){var type;var input=element.querySelector("INPUT");var domType=input.getAttribute("type");var elementType=de.novasib.ol.control.ToolboxPanel.Element_.Type_;switch(domType){case "radio":type=elementType.RADIO;break;case "check":type=elementType.CHECK;break;case "button":type=elementType.BUTTON;break;case "text":type=elementType.TEXT;break;case "br":type=elementType.BR;break;default:break}return type};
de.novasib.ol.control.ToolboxPanel.Element_.prototype.getElement=function(){return this.domElement_};de.novasib.ol.control.ToolboxPanel.Element_.prototype.setActive=function(active){this.active_=active};de.novasib.ol.control.ToolboxPanel.Element_.prototype.updateElement=function(){this.domElement_=this.buildHtml_()};
de.novasib.ol.control.ToolboxPanel.Element_.prototype.buildHtml_=function(){var label,el,textContent;var type=this.type_;if(type==="HR"){el=document.createElement("HR");el.setAttribute("class","k-horizontalRule");el.setAttribute("id",de.novasib.ol.control.ToolboxPanel.Element_.ID_PREFIX+this.id_);return el}if(type==="BUTTON"){el=document.createElement("LI");el.setAttribute("id","li_"+this.id_);input=document.createElement("INPUT");input.setAttribute("class","k-button");input.setAttribute("title",
this.label_);input.setAttribute("type","button");input.setAttribute("id",this.id_);if(this.active_===true)input.setAttribute("enabled","");else if(this.active_===false)input.setAttribute("disabled","");label=document.createElement("LABEL");label.setAttribute("id","label_"+this.id_);textContent=document.createTextNode(this.label_);label.appendChild(textContent);el.appendChild(input);el.appendChild(label);ol.events.listen(input,ol.events.EventType.CLICK,this.handleClick_,this);return el}if(type==="TEXT"){el=
document.createElement("LI");el.setAttribute("id","li_"+this.id_);input=document.createElement("INPUT");input.setAttribute("type","text");input.setAttribute("id",this.id_);input.setAttribute("class","k-text");input.setAttribute("disabled","disabled");label=document.createElement("LABEL");label.setAttribute("id","label_"+this.id_);textContent=document.createTextNode(this.label_);label.appendChild(textContent);el.appendChild(label);el.appendChild(input);ol.events.listen(input,ol.events.EventType.CLICK,
this.handleClick_,this);return el}if(type==="FILE"){el=document.createElement("LI");el.setAttribute("id","li_"+this.id_);var btnPolylineImport=document.createElement("INPUT");btnPolylineImport.setAttribute("type","FILE");btnPolylineImport.setAttribute("class","btnPolylineImport");btnPolylineImport.setAttribute("id","btnPolylineImport");btnPolylineImport.setAttribute("style","display: none");var btnPolylineImportOverlay=document.createElement("INPUT");btnPolylineImportOverlay.setAttribute("type","BUTTON");
btnPolylineImportOverlay.setAttribute("class","k-button");btnPolylineImportOverlay.setAttribute("id","btnPolylineImportOverlay");btnPolylineImportOverlay.setAttribute("title",this.label_);label=document.createElement("LABEL");label.setAttribute("for",""+this.id_);label.setAttribute("id","label_"+this.id_);textContent=document.createTextNode(this.label_);label.appendChild(textContent);el.appendChild(btnPolylineImport);el.appendChild(btnPolylineImportOverlay);el.appendChild(label);var handleBtnPolylineImport_change=
function(event){var novaMap_=de.novasib.ol.getNovaMap();if(novaMap_){var toolboxPanel_=novaMap_.getControlByClass(de.novasib.ol.control.ToolboxPanel);if(toolboxPanel_)toolboxPanel_.dispatchEvent(new de.novasib.ol.control.ToolboxPanel.Event("btnPolylineImport_change",btnPolylineImport,event))}btnPolylineImport.value=""};ol.events.listen(btnPolylineImportOverlay,ol.events.EventType.CLICK,function(){btnPolylineImport.click()},this);ol.events.listen(btnPolylineImport,ol.events.EventType.CHANGE,handleBtnPolylineImport_change,
this);return el}if(type==="TEXTAREA"){var toolboxPanel_;el=document.createElement("LI");el.setAttribute("id","li_"+this.id_);input=document.createElement("textarea");input.setAttribute("class","k-textarea");input.setAttribute("rows","5");input.setAttribute("cols","30");input.setAttribute("wrap","soft");input.setAttribute("id",de.novasib.ol.control.ToolboxPanel.Element_.ID_PREFIX+this.id_);var div=document.createElement("DIV");div.setAttribute("id","field_"+this.id_);div.setAttribute("class","field_"+
this.id_);var btnPolylinePasteApply=document.createElement("INPUT");btnPolylinePasteApply.setAttribute("type","BUTTON");btnPolylinePasteApply.setAttribute("class","btnPolylinePasteApply");btnPolylinePasteApply.setAttribute("id","btnPolylinePasteApply");btnPolylinePasteApply.setAttribute("value","Anwenden");var btnPolylinePasteDiscard=document.createElement("INPUT");btnPolylinePasteDiscard.setAttribute("type","BUTTON");btnPolylinePasteDiscard.setAttribute("class","btnPolylinePasteDiscard");btnPolylinePasteDiscard.setAttribute("id",
"btnPolylinePasteDiscard");btnPolylinePasteDiscard.setAttribute("value","Abbrechen");var btnPolylineUpload=document.createElement("INPUT");btnPolylineUpload.setAttribute("type","FILE");btnPolylineUpload.setAttribute("class","btnPolylineUpload");btnPolylineUpload.setAttribute("id","btnPolylineUpload");btnPolylineUpload.setAttribute("style","display: none");var btnPolylineUploadOverlay=document.createElement("INPUT");btnPolylineUploadOverlay.setAttribute("type","BUTTON");btnPolylineUploadOverlay.setAttribute("class",
"btnPolylineUploadOverlay");btnPolylineUploadOverlay.setAttribute("id","btnPolylineUploadOverlay");btnPolylineUploadOverlay.setAttribute("value","Laden von Datei...");div.appendChild(btnPolylinePasteApply);div.appendChild(btnPolylinePasteDiscard);div.appendChild(btnPolylineUpload);div.appendChild(btnPolylineUploadOverlay);el.appendChild(div);var handleBtnPolylinePasteDiscardClick_=function(event){toolboxPanel_=event.view.control;if(toolboxPanel_)toolboxPanel_.dispatchEvent(new de.novasib.ol.control.ToolboxPanel.Event("btnPolylinePasteDiscard_click",
btnPolylinePasteDiscard,event))};var handleBtnUploadOverlayClick_=function(event){btnPolylineUpload.click();toolboxPanel_=event.view.control};var handleBtnUploadChange_=function(event){var novaMap_=de.novasib.ol.getNovaMap();if(novaMap_){var toolboxPanel_$9=novaMap_.getControlByClass(de.novasib.ol.control.ToolboxPanel);if(toolboxPanel_$9)toolboxPanel_$9.dispatchEvent(new de.novasib.ol.control.ToolboxPanel.Event("btnPolylineUpload_change",btnPolylineUpload,event))}btnPolylineUpload.value=""};ol.events.listen(btnPolylinePasteDiscard,
ol.events.EventType.CLICK,handleBtnPolylinePasteDiscardClick_,this);ol.events.listen(btnPolylineUploadOverlay,ol.events.EventType.CLICK,handleBtnUploadOverlayClick_,this);ol.events.listen(btnPolylineUpload,ol.events.EventType.CHANGE,handleBtnUploadChange_,this);return el}el=document.createElement("LI");var input=document.createElement("INPUT");if(type==="LABEL"){type="label";label=document.createElement("LABEL");label.setAttribute("class","k-label");label.setAttribute("value",this.label_);label.setAttribute("type",
type);label.setAttribute("id",de.novasib.ol.control.ToolboxPanel.Element_.ID_PREFIX+this.id_)}else{if(type==="RADIO"){type="radio";input.setAttribute("class","k-radio")}else if(type==="CHECKBOX"){type="checkbox";input.setAttribute("class","k-checkbox");input.checked=this.checked_}input.setAttribute("type",type);input.setAttribute("id",de.novasib.ol.control.ToolboxPanel.Element_.ID_PREFIX+this.id_);label=document.createElement("LABEL");label.setAttribute("for",""+this.id_);label.appendChild(input)}textContent=
document.createTextNode(this.label_);label.appendChild(textContent);if(!this.active_)el.appendChild(label);ol.events.listen(label,ol.events.EventType.CLICK,this.handleClick_,this);return el};de.novasib.ol.control.ToolboxPanel.Element_.prototype.getLabel=function(){return this.label_};
de.novasib.ol.control.ToolboxPanel.Element_.prototype.handleClick_=function(event){if(event&&event.target){var el=event.target;var labelClicked=false;if(el.nodeName==="LABEL"){labelClicked=true;el=el.firstChild;if(el.disabled)return;if(el.type==="radio"&&!el.checked)el.checked=!el.checked}if(el.type==="radio"){var fireChangeEvent=function(element){if("createEvent"in document){var evt=document.createEvent("HTMLEvents");evt.initEvent("change",true,true);element.dispatchEvent(evt)}else element.fireEvent("onchange")};
var radios=document.querySelectorAll("INPUT[name="+this.radioGroupName_+"]");for(var i=0;i<radios.length;++i){var radio=radios[i];if(radio!=el)fireChangeEvent.call(this,radio)}fireChangeEvent.call(this,el)}if(el.type==="checkbox"){if(labelClicked)el.checked=!el.checked;var fireChangeEvent$10=function(element){if("createEvent"in document){var evt=document.createEvent("HTMLEvents");evt.initEvent("change",true,true);element.dispatchEvent(evt)}else element.fireEvent("onchange")};fireChangeEvent$10.call(this,
el)}var novaMap_=de.novasib.ol.getNovaMap();if(novaMap_){var toolboxPanel_=novaMap_.getControlByClass(de.novasib.ol.control.ToolboxPanel);if(toolboxPanel_)toolboxPanel_.dispatchEvent(new de.novasib.ol.control.ToolboxPanel.Event(de.novasib.ol.control.ToolboxPanel.EventType_.CLICK,this))}}};de.novasib.ol.control.ToolboxPanel.Element_.prototype.handleChange_=function(event){if(event&&event.target);};de.novasib.ol.control.ToolboxPanel.Element_.prototype.isChecked=function(){};
de.novasib.ol.control.ToolboxPanel.Element_.prototype.getType=function(){return this.type_};de.novasib.ol.control.ToolboxPanel.Element_.Type_={RADIO:"radio",CHECK:"check",BUTTON:"button",TEXT:"text",SUBMIT:"submit",LABEL:"label",HR:"hr"};de.novasib.ol.control.ToolboxPanel.prototype.getElements=function(){return this.elements_};de.novasib.ol.control.ToolboxPanel.prototype.isEmpty=function(){return ol.obj.isEmpty(this)};goog.provide("de.novasib.ol.control.Visibility");goog.require("ol");goog.require("ol.control.Control");goog.require("ol.dom");goog.require("ol.events");
de.novasib.ol.control.Visibility=function(opt_options){var options=opt_options||{};this.ulElement_=document.createElement("UL");this.collapsed_=options.collapsed!==undefined?options.collapsed:true;this.collapsible_=options.collapsible!==undefined?options.collapsible:true;if(!this.collapsible_)this.collapsed_=false;var className=options.className||"de-novasib-ol-visibility";var tipLabel=options.tipLabel||"Visibility";var collapseLabel=options.collapseLabel||"\u00bb";if(typeof collapseLabel==="string"){this.collapseLabel_=
document.createElement("SPAN");this.collapseLabel_.textContent=collapseLabel}else this.collapseLabel_=collapseLabel;var label=options.label||"V";if(typeof label==="string"){this.label_=document.createElement("SPAN");this.label_.textContent=label}else this.label_=label;var activeLabel=this.collapsible_&&!this.collapsed_?this.collapseLabel_:this.label_;var button=document.createElement("BUTTON");button.setAttribute("type","button");button.title=tipLabel;button.appendChild(activeLabel);ol.events.listen(button,
ol.events.EventType.CLICK,this.handleClick_,this);var cssClasses=className+" "+ol.css.CLASS_UNSELECTABLE+" "+ol.css.CLASS_CONTROL+(this.collapsed_&&this.collapsible_?" ol-collapsed":"")+(this.collapsible_?"":" ol-uncollapsible");var element=document.createElement("DIV");element.className=cssClasses;element.appendChild(this.ulElement_);element.appendChild(button);var render=options.render||de.novasib.ol.control.Visibility.render;ol.control.Control.call(this,{element:element,render:render,target:options.target});
this.renderedVisible_=true;var elementArray=[];var elements=options.elements;elements.forEach(function(el){elementArray.push(new de.novasib.ol.control.Visibility.Element_(el))});this.elements_=elementArray};ol.inherits(de.novasib.ol.control.Visibility,ol.control.Control);de.novasib.ol.control.Visibility.render=function(mapEvent){this.updateElement_(mapEvent.frameState)};
de.novasib.ol.control.Visibility.prototype.updateElement_=function(frameState){if(!frameState){if(this.renderedVisible_){this.element.style.display="none";this.renderedVisible_=false}return}if(!this.elements_)return;while(this.ulElement_.lastChild)this.ulElement_.removeChild(this.ulElement_.lastChild);var fireChangeEvent=false;var len=this.elements_.length;for(var i=0;i<len;++i){var element=this.elements_[i];var wasVisible=element.visible;this.ulElement_.appendChild(element.getHTML(frameState));if(!fireChangeEvent)fireChangeEvent=
wasVisible!==element.visible;if(i<len-1)this.ulElement_.appendChild(this.getSeparator())}if(fireChangeEvent)this.dispatchEvent(new de.novasib.ol.control.Visibility.Event)};de.novasib.ol.control.Visibility.prototype.handleClick_=function(event){event.preventDefault();this.handleToggle_()};
de.novasib.ol.control.Visibility.prototype.handleToggle_=function(){this.element.classList.toggle("ol-collapsed");if(this.collapsed_)ol.dom.replaceNode(this.collapseLabel_,this.label_);else ol.dom.replaceNode(this.label_,this.collapseLabel_);this.collapsed_=!this.collapsed_};de.novasib.ol.control.Visibility.prototype.getSeparator=function(){var span=document.createElement("SPAN");span.innerHTML=" | ";return span};de.novasib.ol.control.Visibility.prototype.getCollapsible=function(){return this.collapsible_};
de.novasib.ol.control.Visibility.prototype.setCollapsible=function(collapsible){if(this.collapsible_===collapsible)return;this.collapsible_=collapsible;this.element.classList.toggle("ol-uncollapsible");if(!collapsible&&this.collapsed_)this.handleToggle_()};de.novasib.ol.control.Visibility.prototype.setCollapsed=function(collapsed){if(!this.collapsible_||this.collapsed_===collapsed)return;this.handleToggle_()};de.novasib.ol.control.Visibility.prototype.getCollapsed=function(){return this.collapsed_};
de.novasib.ol.control.Visibility.Element_=function(options){this.label_=options.label;this.zoom_=options.zoom||0;this.visible=false};
de.novasib.ol.control.Visibility.Element_.prototype.getHTML=function(frameState){var el=document.createElement("LI");var label=document.createElement("SPAN");if(frameState&&frameState.viewState){var viewState=frameState.viewState;this.visible=de.novasib.ol.control.Visibility.Element_.isVisible_(viewState.zoom,this.zoom_)}if(this.visible)label.innerHTML="\u2713 - ";else label.innerHTML="\u274c - ";label.innerHTML+=this.label_;el.appendChild(label);return el};
de.novasib.ol.control.Visibility.Element_.isVisible_=function(currentZoom,expectedZoom){return currentZoom>=expectedZoom};de.novasib.ol.control.Visibility.Event=function(){ol.events.Event.call(this,"visibilitychanged")};ol.inherits(de.novasib.ol.control.Visibility.Event,ol.events.Event);goog.provide("de.novasib.ol.control.ZoomStep");goog.require("ol");goog.require("ol.control.Control");
de.novasib.ol.control.ZoomStep=function(options){var className=options.className!==undefined?options.className:"de-novasib-ol-zoom-step";var element=document.createElement("DIV");element.className=className+" "+ol.css.CLASS_UNSELECTABLE;var render=options.render?options.render:de.novasib.ol.control.ZoomStep.render;ol.control.Control.call(this,{element:element,render:render,target:options.target});if(options.zoomFormat)this.setZoomFormat(options.zoomFormat);this.zoom_=0;this.undefinedHTML_=options.undefinedHTML!==
undefined?options.undefinedHTML:"";this.renderedHTML_=element.innerHTML};ol.inherits(de.novasib.ol.control.ZoomStep,ol.control.Control);de.novasib.ol.control.ZoomStep.render=function(mapEvent){var frameState=mapEvent.frameState;if(!frameState)this.zoom_=-1;else if(this.zoom_!=Math.round(frameState.viewState.zoom))this.zoom_=Math.round(frameState.viewState.zoom);this.updateHTML_()};
de.novasib.ol.control.ZoomStep.prototype.updateHTML_=function(){var html=this.undefinedHTML_;var zoomFormat=this.getZoomFormat();if(zoomFormat)html=zoomFormat(this.zoom_);else html=this.zoom_.toString();if(!this.renderedHTML_||html!=this.renderedHTML_){this.element.innerHTML=html;this.renderedHTML_=html}};de.novasib.ol.control.ZoomStep.prototype.getZoom=function(){return this.zoom_};de.novasib.ol.control.ZoomStep.prototype.getZoomFormat=function(){return this.get(de.novasib.ol.control.ZoomStep.Property_.ZOOM_FORMAT)};
de.novasib.ol.control.ZoomStep.prototype.setZoomFormat=function(format){this.set(de.novasib.ol.control.ZoomStep.Property_.ZOOM_FORMAT,format)};de.novasib.ol.control.ZoomStep.Property_={ZOOM_FORMAT:"zoomFormat"};goog.provide("de.novasib.ol.Events");
de.novasib.ol.Events={MAPINITIALIZED:"mapinitialized",FEATUREADDED:"featureadded",FEATUREROTATED:"featurerotated",FEATURESTATIONED:"featurestationed",FEATUREMOVED:"featuremoved",FEATUREDRAWN:"featuredrawn",FEATUREMODIFIED:"featuremodified",ADDICON:"addicon",SELECT:"select",HOVER:"hover",VIEWPORTCHANGED:"viewportchanged",VISIBILITYCHANGED:"visibilitychanged",FREETEXTADDED:"freetextadded",LAYERADDED:"layeradded",BEFOREFEATURETOOLTIP:"beforeFeatureTooltip",ZOOMEND:"zoomend",MAPMOVED:"mapmoved",REFRESHMAP:"refreshMap"};goog.provide("de.novasib.ol.extent");goog.require("ol.extent");de.novasib.ol.extent.getBufferedExtent=function(extent){var ret=extent;if(extent&&!ol.extent.isEmpty(extent)){var width=ol.extent.getWidth(extent);var height=ol.extent.getHeight(extent);var buffer=width/10;if(width<height)buffer=height/10;ret=ol.extent.buffer(extent,buffer)}return ret};goog.provide("de.novasib.ol.geom");goog.require("de.novasib.ol");goog.require("ol.coordinate");goog.require("ol.geom.LineString");
de.novasib.ol.geom.computeOffsetLineString=function(src,length,distanceFrom,distanceTo){var ret=[];var count=src.length;if(count<2)return src;src=de.novasib.ol.geom.normalizeLineStringCoordinates(src);ret[0]=de.novasib.ol.geom.offsetPoint(src[0],src[1],distanceFrom);ret[count-1]=de.novasib.ol.geom.offsetPoint(src[count-1],src[count-2],-distanceTo);var delta=distanceTo-distanceFrom;var run=0;for(var i=1;i<count-1;++i){var p1=src[i-1];var c=src[i];var p2=src[i+1];var x=p1[0]-c[0];var y=p1[1]-c[1];run+=
Math.sqrt(x*x+y*y);var offset=distanceFrom+delta*run/length;var p=de.novasib.ol.geom.offsetSegment(p1,c,offset);var q=de.novasib.ol.geom.offsetSegment(c,p2,offset);ret[i]=de.novasib.ol.geom.intersection(p,q)}return ret};de.novasib.ol.geom.offsetPoint=function(from,to,offset){var dx=to[0]-from[0];var dy=to[1]-from[1];var len=Math.sqrt(dx*dx+dy*dy);var ux=offset*dx/len;var uy=offset*dy/len;return[from[0]-uy,from[1]+ux]};
de.novasib.ol.geom.offsetSegment=function(from,to,offset){var dx=to[0]-from[0];var dy=to[1]-from[1];var len=Math.sqrt(dx*dx+dy*dy);var ux=offset*dx/len;var uy=offset*dy/len;var p1=[from[0]-uy,from[1]+ux];var p2=[to[0]-uy,to[1]+ux];return[p1,p2]};
de.novasib.ol.geom.intersection=function(p,q){if(de.novasib.ol.geom.areSegmentsParallel(p,q,de.novasib.ol.degToRad(.01))){var closestDistance=Infinity;var closestPoint=null;for(var i=0;i<p.length;++i){var a=p[i];for(var j=0;j<q.length;++j){var b=q[j];var distance=ol.coordinate.distance(a,b);if(distance<closestDistance){closestDistance=distance;closestPoint=a}}}return closestPoint}else{var px=p[0][1]-p[1][1];var py=p[1][0]-p[0][0];var pw=p[0][0]*p[1][1]-p[1][0]*p[0][1];var qx=q[0][1]-q[1][1];var qy=
q[1][0]-q[0][0];var qw=q[0][0]*q[1][1]-q[1][0]*q[0][1];var x=py*qw-qy*pw;var y=qx*pw-px*qw;var w=px*qy-qx*py;return[x/w,y/w]}};
de.novasib.ol.geom.getShortenedLineString=function(geometry,from,to,alen){from=from===undefined?0:from;alen=alen===undefined?-1:alen;var length;var reverseCoords=false;if(geometry&&geometry instanceof ol.geom.LineString){length=geometry.getLength();if(!to&&to!==0||to>length)to=length;if(from===0&&(to===length||to==alen))return geometry;else if(from===to)return new ol.geom.LineString([de.novasib.ol.geom.getPointOnLineString(geometry,from,alen)]);else if(from>to)if(to===0&&from===length){var coords=
geometry.getCoordinates();var reverse=coords.reverse();return new ol.geom.LineString(reverse)}else{var tmp=from;from=to;to=tmp;reverseCoords=true}if(isNaN(from)||isNaN(to))return geometry;if(typeof alen==="number"&&alen>0){var ratio=length/alen;from=from*ratio;to=to*ratio}var points=[];var curLen=0;var coordinates=geometry.getCoordinates();for(var i=0;i<coordinates.length-1;++i){var start=coordinates[i];var end=coordinates[i+1];var segmentLen=ol.coordinate.distance(start,end);if(curLen>=from&&curLen<=
to)points.push(start);else if(curLen<from&&curLen+segmentLen>from){var segment=[start,end];var abs=from-curLen;var p=de.novasib.ol.geom.pointOnSegment(segment,abs);points.push(p)}if(curLen<to&&curLen+segmentLen>to){var segment$11=[start,end];var abs$12=to-curLen;var p$13=de.novasib.ol.geom.pointOnSegment(segment$11,abs$12);points.push(p$13);break}else if(curLen+segmentLen===to){points.push(end);break}curLen+=segmentLen}if(reverseCoords)points=points.reverse();var ret=new ol.geom.LineString(points);
return ret}return geometry};de.novasib.ol.geom.pointOnSegment=function(segment,abs){var start=segment[0];var end=segment[1];var segmentLen=de.novasib.ol.geom.segmentLength(segment);var dx=end[0]-start[0];var dy=end[1]-start[1];dx/=segmentLen;dy/=segmentLen;var x=start[0]+dx*abs;var y=start[1]+dy*abs;return[x,y]};
de.novasib.ol.geom.closestOnLine=function(coordinate,geometry){var coords=geometry.getCoordinates();var closestSegment=null;var dist=Infinity;for(var i=0;i<coords.length-1;++i){var segment=coords.slice(i,i+2);var d=ol.coordinate.squaredDistanceToSegment(coordinate,segment);if(d<dist){dist=d;closestSegment=segment}}return ol.coordinate.closestOnSegment(coordinate,closestSegment)};
de.novasib.ol.geom.isOnSegment=function(coordinate,segment){var start=segment[0];var end=segment[1];var cx=coordinate[0];var cy=coordinate[1];var sx=start[0];var sy=start[1];var ex=end[0];var ey=end[1];var dx=ex-sx;var dy=ey-sy;if(dx===0)dx=1;if(dy===0)dy=1;var lambdaX=de.novasib.ol.round((cx-sx)/dx,4);var lambdaY=de.novasib.ol.round((cy-sy)/dy,4);if(lambdaX!==lambdaY)if(cx!==sx&&cy!==sy)return false;return lambdaX>=0&&lambdaX<=1&&lambdaY>=0&&lambdaY<=1};
de.novasib.ol.geom.segmentLength=function(segment){var start=segment[0];var end=segment[1];return ol.coordinate.distance(start,end)};
de.novasib.ol.geom.getPointOnLineString=function(geom,pos,alen){if(geom&&geom instanceof ol.geom.LineString){var coords=geom.getCoordinates();var length=geom.getLength();if(pos<=0)return coords[0];else if(pos>=length)return coords[coords.length-1];if(alen){var ratio=length/alen;pos*=ratio}var curLen=0;for(var i=0;i<coords.length-1;++i){var segment=coords.slice(i,i+2);var segmentLength=de.novasib.ol.geom.segmentLength(segment);if(curLen+segmentLength>=pos){var abs=Math.abs(curLen-pos);return de.novasib.ol.geom.pointOnSegment(segment,
abs)}curLen+=segmentLength}}return null};
de.novasib.ol.geom.getMedianPointCoord=function(arg){var geometry_,coord_;if(arg instanceof ol.Feature){var feature_=arg;geometry_=feature_.getGeometry()}else if(arg instanceof ol.geom.LineString)geometry_=arg;else if(arg instanceof Array)geometry_=new ol.geom.LineString(arg);var length_=geometry_.getLength();var medianLength_=length_/2;if(length_&&medianLength_)coord_=de.novasib.ol.geom.getPointOnLineString(geometry_,medianLength_,length_);return coord_||null};
de.novasib.ol.geom.setFeatureCoordinates=function(feature,coordinates){if(feature&&feature.getGeometry()){var geom=feature.getGeometry();var type=geom.getType();if(type===ol.geom.GeometryType.POINT){var coord=coordinates;if(Array.isArray(coordinates[0]))coord=coordinates[0];geom.setCoordinates(coord)}}};goog.exportSymbol("NovaMapUtils.setFeatureCoordinates",de.novasib.ol.geom.setFeatureCoordinates);
de.novasib.ol.geom.getFeatureCoordinates=function(feature){var ret=[];if(feature&&feature.getGeometry())ret=feature.getGeometry().getCoordinates();return ret};goog.exportSymbol("NovaMapUtils.getFeatureCoordinates",de.novasib.ol.geom.getFeatureCoordinates);de.novasib.ol.geom.getGeometryLength=function(coordinates){var ret=0;if(coordinates&&Array.isArray(coordinates)&&coordinates.length>=2){var geom=new ol.geom.LineString(coordinates);ret=geom.getLength()}return ret};
goog.exportSymbol("NovaMapUtils.getGeometryLength",de.novasib.ol.geom.getGeometryLength);de.novasib.ol.geom.equals=function(a,b){if(a===null||b===null)return true;var atype=a.getType();var btype=b.getType();if(atype!=btype)return false;var acoords=a.getCoordinates();var bcoords=b.getCoordinates();if(acoords.length!=bcoords.length)return false;var len=acoords.length;var equals=true;for(var i=0;i<len;++i){var pa=acoords[i];var pb=bcoords[i];equals&=ol.coordinate.equals(pa,pb);if(!equals)return false}return equals};
de.novasib.ol.geom.getPointLocation=function(_pa,_pb,_p){var ret=0;if(_pa!=null&&_pb!=null&&_p!=null){var rx=_pa[0]-_p[0];var ry=_pa[1]-_p[1];var nx=-(_pb[1]-_pa[1]);var ny=_pb[0]-_pa[0];var dot=rx*nx+ry*ny;if(dot!=0)ret=dot/Math.abs(dot)}return ret};
de.novasib.ol.geom.getPointDistance=function(_pa,_pb,_p){var rx=_pa[0]-_p[0];var ry=_pa[1]-_p[1];var nx=-(_pb[1]-_pa[1]);var ny=_pb[0]-_pa[0];var dot=rx*nx+ry*ny;var lage=1;if(dot!=0)lage=dot/Math.abs(dot);var a=ol.coordinate.distance(_pa,_pb);var b=ol.coordinate.distance(_pa,_p);var c=ol.coordinate.distance(_pb,_p);var s=(a+b+c)/2;var A=Math.sqrt(s*(s-a)*(s-b)*(s-c));var h=2*A/a;return lage*h};
de.novasib.ol.geom.calcLage=function(_pa,_pb,_p){var ret=1;var rx=_pa[0]-_p[0];var ry=_pa[1]-_p[1];var nx=-(_pb[1]-_pa[1]);var ny=_pb[0]-_pa[0];var dot=rx*nx+ry*ny;if(dot!=0)ret=dot/Math.abs(dot);return ret};
de.novasib.ol.geom.getWeightedStation=function(_point,_geom,_featureLength,_gisLength){var station=0;var closestCoord=_geom.getClosestPoint(_point);var geomLen=_geom.getLength();if(_featureLength==undefined)_featureLength=geomLen;if(_gisLength==undefined)_gisLength=geomLen;if(closestCoord){var coords=_geom.getCoordinates();var newCoords=[];for(var i=0;i<coords.length-1;++i){var segment=[coords[i],coords[i+1]];newCoords.push(segment[0]);if(de.novasib.ol.geom.isOnSegment(closestCoord,segment)){newCoords.push(closestCoord);
break}}var ls=new ol.geom.LineString(newCoords);var calcStation=ls.getLength();var ratio=_gisLength/geomLen;var dStation=ratio*calcStation;station=Math.round(dStation)}return station};de.novasib.ol.geom.segmentSlope=function(segment){var a=segment[0];var b=segment[1];return(b[1]-a[1])/(b[0]-a[0])};
de.novasib.ol.geom.getSegmentDirectionInDegrees=function(segment){if(!segment)return false;var x1=segment[0][0];var y1=segment[0][1];var x2=segment[1][0];var y2=segment[1][1];var dy=y2-y1;var dx=x2-x1;var angle=Math.atan2(dx,dy);var angleDeg=de.novasib.ol.geom.radiansToDegrees(angle);angleDeg=de.novasib.ol.geom.normalizeDegreesToFullCircle(angleDeg);return angleDeg};de.novasib.ol.geom.segmentSlopeAngle=function(segment){return Math.atan(de.novasib.ol.geom.segmentSlope(segment))};
de.novasib.ol.geom.areSegmentsParallel=function(segmentA,segmentB,threshold){var aAngle=de.novasib.ol.geom.segmentSlopeAngle(segmentA);var bAngle=de.novasib.ol.geom.segmentSlopeAngle(segmentB);var diff=Math.abs(bAngle-aAngle);if(diff>Math.PI/2)diff=Math.PI-diff;return diff<=threshold};
de.novasib.ol.geom.getAngleBetweenConnectedSegments=function(segmentA,segmentB){if(!(segmentA&&segmentB))return false;var x1=segmentA[0][0];var y1=segmentA[0][1];var x2=segmentA[1][0];var y2=segmentA[1][1];var x3=segmentB[1][0];var y3=segmentB[1][1];var dy_a=y2-y1;var dx_a=x2-x1;var dy_b=y3-y2;var dx_b=x3-x2;var angle_a=Math.atan2(dx_a,dy_a);var angle_b=Math.atan2(dx_b,dy_b);var angleDeg_a=de.novasib.ol.geom.radiansToDegrees(angle_a);var angleDeg_b=de.novasib.ol.geom.radiansToDegrees(angle_b);angleDeg_a=
de.novasib.ol.geom.normalizeDegreesToFullCircle(angleDeg_a);angleDeg_b=de.novasib.ol.geom.normalizeDegreesToFullCircle(angleDeg_b);var angleOfDivergence=angleDeg_a-angleDeg_b;angleOfDivergence=Math.abs(angleOfDivergence);var getSupplementaryAngleOfDivergence=de.novasib.ol.geom.getSupplementaryAngle(angleOfDivergence);return getSupplementaryAngleOfDivergence};de.novasib.ol.geom.radiansToDegrees=function(radians){if(typeof radians!=="number")return false;return radians*(180/Math.PI)};
de.novasib.ol.geom.degreesToRadians=function(degrees){if(typeof degrees!=="number")return false;return degrees*(Math.PI/180)};de.novasib.ol.geom.normalizeDegreesToFullCircle=function(degrees){if(typeof degrees!=="number")return false;return(degrees+360)%360};de.novasib.ol.geom.getSupplementaryAngle=function(degrees){if(typeof degrees!=="number")return false;var ret;if(degrees>180)ret=360-degrees;else ret=degrees;return ret};
de.novasib.ol.geom.pointInPolygon=function(point,polygon){var vs=Array.from(polygon);var x=point[0],y=point[1];var inside=false;var start=0;var end=vs.length;var len=(end-start)/2;for(var i=0,j=len-1;i<len;j=i++){var xi=vs[start+i*2+0],yi=vs[start+i*2+1];var xj=vs[start+j*2+0],yj=vs[start+j*2+1];var intersect=yi>y!==yj>y&&x<(xj-xi)*(y-yi)/(yj-yi)+xi;if(intersect)inside=!inside}return inside};
de.novasib.ol.geom.getPolygonCentroid=function(points){var x0=points[0].x;var y0=points[0].y;var x=0,y=0,twiceArea=0;var prev=points[points.length-1];for(var $jscomp$iter$0=$jscomp.makeIterator(points),$jscomp$key$next=$jscomp$iter$0.next();!$jscomp$key$next.done;$jscomp$key$next=$jscomp$iter$0.next()){var next=$jscomp$key$next.value;{var x1=prev.x-x0;var y1=prev.y-y0;var x2=next.x-x0;var y2=next.y-y0;var a=x1*y2-x2*y1;twiceArea+=a;x+=(x1+x2)*a;y+=(y1+y2)*a;prev=next}}var factor=3*twiceArea;x/=factor;
y/=factor;return{x:x+x0,y:y+y0}};
de.novasib.ol.geom.normalizeLineStringCoordinates=function(coordinates){var segmentA,segmentB;var roundFloatToTwo=de.novasib.ol.roundFloatToTwo;var coords=coordinates.slice();coords.map(function(coord,index,array){var amountOfCoords=array.length;if(index>amountOfCoords-3)return;segmentA=[array[index+0],array[index+1]];segmentB=[array[index+1],array[index+2]];var segmentLen=de.novasib.ol.geom.segmentLength(segmentB);if(segmentLen===0){var start=array[index+0];var end=array[index+3];var distance=ol.coordinate.distance(start,
end);var evenlyDistributedDistance=distance/(2+1);var newPointA=de.novasib.ol.geom.pointOnSegment([start,end],evenlyDistributedDistance*1);var newPointB=de.novasib.ol.geom.pointOnSegment([start,end],evenlyDistributedDistance*2);array[index+1][0]=roundFloatToTwo(newPointA[0]);array[index+1][1]=roundFloatToTwo(newPointA[1]);array[index+2][0]=roundFloatToTwo(newPointB[0]);array[index+2][1]=roundFloatToTwo(newPointB[1]);segmentA=[array[index+0],array[index+1]];segmentB=[array[index+1],array[index+2]]}var angleOfDivergence=
de.novasib.ol.geom.getAngleBetweenConnectedSegments(segmentA,segmentB);if(Math.abs(angleOfDivergence)>90){var start$14=array[index+0];var end$15=array[index+2];var segmentLen$16=ol.coordinate.distance(start$14,end$15);var midpoint=segmentLen$16/2;var newPoint=de.novasib.ol.geom.pointOnSegment([start$14,end$15],midpoint);array[index+1][0]=roundFloatToTwo(newPoint[0]);array[index+1][1]=roundFloatToTwo(newPoint[1])}});return coords};goog.provide("de.novasib.ol.feature");goog.require("de.novasib.ol.geom");goog.require("ol.Object");de.novasib.ol.feature.TOKEN_REG_EXP=/\$\{([\w.]+?)\}/g;
de.novasib.ol.feature.formatTemplate=function(template,context){if(!context)context=window;var replacer=function(str,match){var replacement;var subs=match.split(/\.+/);for(var i=0;i<subs.length;++i){if(i==0)replacement=context;if(replacement===undefined)break;replacement=replacement[subs[i]]}if(typeof replacement=="undefined")return"undefined";else if(typeof replacement==="number"){var replacement_,options_;if(match==="station"){replacement_=parseInt(replacement);options_={useGrouping:true}}else{replacement_=
parseFloat(replacement);options_={useGrouping:false,minimumFractionDigits:2,maximumFractionDigits:2}}return replacement_.toLocaleString("de-DE",options_)}else if(replacement===null)return"";else return replacement};return template.replace(de.novasib.ol.feature.TOKEN_REG_EXP,replacer)};de.novasib.ol.feature.haveEqualGeometries=function(a,b){if(!a||!b)return false;return de.novasib.ol.geom.equals(a.getGeometry(),b.getGeometry())};goog.exportSymbol("NovaMapUtils.haveEqualGeometries",de.novasib.ol.feature.haveEqualGeometries);
de.novasib.ol.feature.setFeatureStyleChangeListeners=function(feature,changeProperties,listener){if(!feature)return;if(changeProperties){if(!Array.isArray(changeProperties))changeProperties=[changeProperties];if(changeProperties.indexOf(de.novasib.ol.FeatureProperties.STYLE_NAME)==-1)changeProperties.push(de.novasib.ol.FeatureProperties.STYLE_NAME);if(changeProperties.indexOf(de.novasib.ol.FeatureProperties.LAYER_STYLE_NAME)==-1)changeProperties.push(de.novasib.ol.FeatureProperties.LAYER_STYLE_NAME)}else changeProperties=
[de.novasib.ol.FeatureProperties.STYLE_NAME,de.novasib.ol.FeatureProperties.LAYER_STYLE_NAME];changeProperties.forEach(function(prop){var evtType=ol.Object.getChangeEventType(prop);feature.on(evtType,listener)})};de.novasib.ol.feature.overwriteFeatureProperties=function(a,b){if(a&&b&&a.getId()==b.getId()){var newProps=b.getProperties();for(var prop in newProps)if(newProps.hasOwnProperty(prop)){var val=b.get(prop);a.set(prop,val)}}};goog.exportSymbol("NovaMapUtils.overwriteFeatureProperties",de.novasib.ol.feature.overwriteFeatureProperties);goog.provide("de.novasib.ol.FeatureFilter");goog.require("ol");goog.require("ol.Object");de.novasib.ol.FeatureFilter=function(options){this.layer_=options.layer;this.filter_=options.filter;this.map_=options.map};ol.inherits(de.novasib.ol.FeatureFilter,ol.Object);
de.novasib.ol.FeatureFilter.filterFeatures=function(){var $jscomp$this=this;if(this.layer_&&this.layer_.getVisible()){var features=this.layer_.getSource().getFeatures();features.forEach(function(feature){if(!$jscomp$this.filter_(feature))$jscomp$this.map_.skipFeature(feature);else $jscomp$this.map_.unskipFeature(feature)})}};goog.provide("de.novasib.ol.featureloader");goog.require("de.novasib.ol");goog.require("ol");goog.require("ol.format.FormatType");goog.require("ol.xml");
de.novasib.ol.featureloader.loadFeaturesXhr=function(url,format,username,password,success,failure){return function(extent,resolution,projection){this.resolution=resolution;var xhr=new XMLHttpRequest;xhr.open("GET",typeof url==="function"?url(extent,resolution,projection):url,true);if(format.getType()==ol.format.FormatType.ARRAY_BUFFER)xhr.responseType="arraybuffer";if(username&&password){var credentials=username+":"+password;xhr.setRequestHeader("Authorization","Basic "+btoa(credentials))}xhr.onload=
function(event){if(!xhr.status||xhr.status>=200&&xhr.status<300){var type=format.getType();var source;if(type==ol.format.FormatType.JSON||type==ol.format.FormatType.TEXT)source=xhr.responseText;else if(type==ol.format.FormatType.XML){source=xhr.responseXML;if(!source)source=ol.xml.parse(xhr.responseText)}else if(type==ol.format.FormatType.ARRAY_BUFFER)source=xhr.response;if(source)success.call(this,format.readFeatures(source,{featureProjection:projection}),format.readProjection(source),format.getLastExtent());
else failure.call(this)}else failure.call(this)}.bind(this);xhr.onerror=function(){failure.call(this)}.bind(this);xhr.send()}};
de.novasib.ol.featureloader.loadFeaturesXhrPost=function(url,format,data,username,password,success,failure,sourceExtract){return function(extent,resolution,projection){var xhr=new XMLHttpRequest;xhr.open("POST",typeof url==="function"?url(extent,resolution,projection):url,true);if(format.getType()==ol.format.FormatType.ARRAY_BUFFER)xhr.responseType="arraybuffer";if(username&&password){var credentials=username+":"+password;xhr.setRequestHeader("Authorization","Basic "+btoa(credentials))}xhr.setRequestHeader("Content-Type",
"application/json");if(de.novasib.ol.PARENT_APP_NAME===de.novasib.ol.KNOWN_APP_NAMES.SPERRINFOSYS){var map$17=de.novasib.ol.getNovaMap();map$17.once(de.novasib.ol.Events.VISIBILITYCHANGED,function abortXHR(e){xhr.abort();map$17.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.REFRESHMAP,{reason:"xhr.abort()",source:"de.novasib.ol.featureloader.loadFeaturesXhrPost",trigger:e}))})}xhr.onload=function(event){if(!xhr.status||xhr.status>=200&&xhr.status<300){var type=format.getType();
var source;if(type==ol.format.FormatType.JSON||type==ol.format.FormatType.TEXT)source=xhr.responseText;else if(type==ol.format.FormatType.XML){source=xhr.responseXML;if(!source)source=ol.xml.parse(xhr.responseText)}else if(type==ol.format.FormatType.ARRAY_BUFFER)source=xhr.response;if(source){if(sourceExtract&&typeof sourceExtract==="function")source=sourceExtract.call(this,source);if(source){var dataProjection=de.novasib.ol.loadProjection(source.projection)||projection;success.call(this,format.readFeatures(source,
{dataProjection:dataProjection,featureProjection:projection}),format.readProjection(source),format.getLastExtent())}else failure.call(this)}else failure.call(this)}else failure.call(this)}.bind(this);xhr.onerror=function(){failure.call(this)}.bind(this);xhr.send(typeof data==="function"?data(extent,resolution,projection):data)}};
de.novasib.ol.featureloader.xhr=function(url,format,user,password){return de.novasib.ol.featureloader.loadFeaturesXhr(url,format,user,password,function(features,dataProjection){this.addFeatures(features)},ol.nullFunction)};goog.provide("de.novasib.ol.format.GMLBase");goog.require("ol");goog.require("ol.array");goog.require("ol.Feature");goog.require("ol.format.Feature");goog.require("ol.format.XMLFeature");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.LineString");goog.require("ol.geom.LinearRing");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.MultiPoint");goog.require("ol.geom.MultiPolygon");goog.require("ol.geom.Point");goog.require("ol.geom.Polygon");goog.require("ol.obj");goog.require("ol.proj");
goog.require("ol.xml");
de.novasib.ol.format.GMLBase=function(opt_options){var options=opt_options?opt_options:{};this.featureType=options.featureType;this.featureNS=options.featureNS;this.srsName=options.srsName;this.schemaLocation="";this.FEATURE_COLLECTION_PARSERS={};for(var prop in this.featureNS)this.FEATURE_COLLECTION_PARSERS[this.featureNS[prop]]={"FeatureCollection":ol.xml.makeReplacer(de.novasib.ol.format.GMLBase.prototype.readFeatures),"featureMember":ol.xml.makeReplacer(de.novasib.ol.format.GMLBase.prototype.readFeatures),"featureMembers":ol.xml.makeReplacer(de.novasib.ol.format.GMLBase.prototype.readFeatures)};
ol.format.XMLFeature.call(this)};ol.inherits(de.novasib.ol.format.GMLBase,ol.format.XMLFeature);de.novasib.ol.format.GMLBase.GMLNS="http://www.opengis.net/gml";de.novasib.ol.format.GMLBase.OGRNS="http://ogr.maptools.org/";de.novasib.ol.format.GMLBase.features_=[];de.novasib.ol.format.GMLBase.ONLY_WHITESPACE_RE_=/^[\s\xa0]*$/;
de.novasib.ol.format.GMLBase.prototype.readFeaturesInternal=function(node,objectStack){var localName=node.localName;var features=null;if(localName=="FeatureCollection")if(node.namespaceURI==="http://www.opengis.net/wfs")features=ol.xml.pushParseAndPop([],this.FEATURE_COLLECTION_PARSERS,node,objectStack,this);else features=ol.xml.pushParseAndPop(null,this.FEATURE_COLLECTION_PARSERS,node,objectStack,this);else if(localName=="featureMembers"||localName=="featureMember"){var context=objectStack[0];var featureType=
context["featureType"];var featureNS=context["featureNS"];var i,ii,prefix="p",defaultPrefix="p0";if(!featureType&&node.childNodes){featureType=[],featureNS={};for(i=0,ii=node.childNodes.length;i<ii;++i){var child=node.childNodes[i];if(child.nodeType===1){var ft=child.nodeName.split(":").pop();if(featureType.indexOf(ft)===-1){var key="";var count=0;var uri=child.namespaceURI;for(var candidate in featureNS){if(featureNS[candidate]===uri){key=candidate;break}++count}if(!key){key=prefix+count;featureNS[key]=
uri}featureType.push(key+":"+ft)}}}if(localName!="featureMember"){context["featureType"]=featureType;context["featureNS"]=featureNS}}if(typeof featureNS==="string"){var ns=featureNS;featureNS={};featureNS[defaultPrefix]=ns}var parsersNS={};var featureTypes=Array.isArray(featureType)?featureType:[featureType];for(var p in featureNS){var parsers={};for(i=0,ii=featureTypes.length;i<ii;++i){var featurePrefix=featureTypes[i].indexOf(":")===-1?defaultPrefix:featureTypes[i].split(":")[0];if(featurePrefix===
p)if(localName=="featureMembers")parsers[featureTypes[i].split(":").pop()]=ol.xml.makeArrayPusher(this.readFeatureElement,this);else parsers[featureTypes[i].split(":").pop()]=ol.xml.makeReplacer(this.readFeatureElement,this)}parsersNS[featureNS[p]]=parsers}if(localName=="featureMember"){features=ol.xml.pushParseAndPop(undefined,parsersNS,node,objectStack);de.novasib.ol.format.GMLBase.features_.push(features)}else features=ol.xml.pushParseAndPop([],parsersNS,node,objectStack)}if(features===null)features=
[];if(!Array.isArray(features))return de.novasib.ol.format.GMLBase.features_;de.novasib.ol.format.GMLBase.features_=[];return features};
de.novasib.ol.format.GMLBase.prototype.readGeometryElement=function(node,objectStack){var context=objectStack[0];var srsName_,proj_;var firstElementChild_=node.firstElementChild;if(firstElementChild_){context["srsDimension"]=firstElementChild_.getAttribute("srsDimension");srsName_=firstElementChild_.getAttribute("srsName");if(srsName_){context["srsName"]=srsName_;proj_=ol.proj.get(srsName_);if(proj_)context["dataProjection"]=de.novasib.ol.normalizeProjection(proj_)}}var geometry=ol.xml.pushParseAndPop(null,
this.GEOMETRY_PARSERS_,node,objectStack,this);if(geometry)return de.novasib.ol.format.GMLBase.prototype.transformWithOptions(geometry,false,context);else return undefined};
de.novasib.ol.format.GMLBase.prototype.readFeatureElement=function(node,objectStack){var n;var fid=node.getAttribute("fid")||ol.xml.getAttributeNS(node,de.novasib.ol.format.GMLBase.GMLNS,"id");var values={},geometryName;for(n=node.firstElementChild;n;n=n.nextElementSibling){var localName=n.localName;if(n.childNodes.length===0||n.childNodes.length===1&&(n.firstChild.nodeType===3||n.firstChild.nodeType===4)){var value=ol.xml.getAllTextContent(n,false);if(de.novasib.ol.format.GMLBase.ONLY_WHITESPACE_RE_.test(value))value=
undefined;values[localName]=value}else{if(localName!=="boundedBy")geometryName=localName;values[localName]=this.readGeometryElement(n,objectStack)}}var feature=new ol.Feature(values);if(geometryName)feature.setGeometryName(geometryName);if(fid)feature.setId(fid);return feature};
de.novasib.ol.format.GMLBase.prototype.readPoint=function(node,objectStack){var flatCoordinates=this.readFlatCoordinatesFromNode_(node,objectStack);if(flatCoordinates){var point=new ol.geom.Point(null);point.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates);return point}};
de.novasib.ol.format.GMLBase.prototype.readMultiPoint=function(node,objectStack){var coordinates=ol.xml.pushParseAndPop([],this.MULTIPOINT_PARSERS_,node,objectStack,this);if(coordinates)return new ol.geom.MultiPoint(coordinates);else return undefined};
de.novasib.ol.format.GMLBase.prototype.readMultiLineString=function(node,objectStack){var lineStrings=ol.xml.pushParseAndPop([],this.MULTILINESTRING_PARSERS_,node,objectStack,this);if(lineStrings){var multiLineString=new ol.geom.MultiLineString(null);multiLineString.setLineStrings(lineStrings);return multiLineString}else return undefined};
de.novasib.ol.format.GMLBase.prototype.readMultiPolygon=function(node,objectStack){var polygons=ol.xml.pushParseAndPop([],this.MULTIPOLYGON_PARSERS_,node,objectStack,this);if(polygons){var multiPolygon=new ol.geom.MultiPolygon(null);multiPolygon.setPolygons(polygons);return multiPolygon}else return undefined};de.novasib.ol.format.GMLBase.prototype.pointMemberParser_=function(node,objectStack){ol.xml.parseNode(this.POINTMEMBER_PARSERS_,node,objectStack,this)};
de.novasib.ol.format.GMLBase.prototype.lineStringMemberParser_=function(node,objectStack){ol.xml.parseNode(this.LINESTRINGMEMBER_PARSERS_,node,objectStack,this)};de.novasib.ol.format.GMLBase.prototype.polygonMemberParser_=function(node,objectStack){ol.xml.parseNode(this.POLYGONMEMBER_PARSERS_,node,objectStack,this)};
de.novasib.ol.format.GMLBase.prototype.readLineString=function(node,objectStack){var flatCoordinates=this.readFlatCoordinatesFromNode_(node,objectStack);if(flatCoordinates){var lineString=new ol.geom.LineString(null);lineString.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates);return lineString}else return undefined};
de.novasib.ol.format.GMLBase.prototype.readFlatLinearRing_=function(node,objectStack){var ring=ol.xml.pushParseAndPop(null,this.GEOMETRY_FLAT_COORDINATES_PARSERS_,node,objectStack,this);if(ring)return ring;else return undefined};
de.novasib.ol.format.GMLBase.prototype.readLinearRing=function(node,objectStack){var flatCoordinates=this.readFlatCoordinatesFromNode_(node,objectStack);if(flatCoordinates){var ring=new ol.geom.LinearRing(null);ring.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates);return ring}else return undefined};
de.novasib.ol.format.GMLBase.prototype.readPolygon=function(node,objectStack){var flatLinearRings=ol.xml.pushParseAndPop([null],this.FLAT_LINEAR_RINGS_PARSERS_,node,objectStack,this);if(flatLinearRings&&flatLinearRings[0]){var polygon=new ol.geom.Polygon(null);var flatCoordinates=flatLinearRings[0];var ends=[flatCoordinates.length];var i,ii;for(i=1,ii=flatLinearRings.length;i<ii;++i){ol.array.extend(flatCoordinates,flatLinearRings[i]);ends.push(flatCoordinates.length)}polygon.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,
flatCoordinates,ends);return polygon}else return undefined};de.novasib.ol.format.GMLBase.prototype.readFlatCoordinatesFromNode_=function(node,objectStack){return ol.xml.pushParseAndPop(null,this.GEOMETRY_FLAT_COORDINATES_PARSERS_,node,objectStack,this)};de.novasib.ol.format.GMLBase.prototype.MULTIPOINT_PARSERS_={"http://www.opengis.net/gml":{"pointMember":ol.xml.makeArrayPusher(de.novasib.ol.format.GMLBase.prototype.pointMemberParser_),"pointMembers":ol.xml.makeArrayPusher(de.novasib.ol.format.GMLBase.prototype.pointMemberParser_)}};
de.novasib.ol.format.GMLBase.prototype.MULTILINESTRING_PARSERS_={"http://www.opengis.net/gml":{"lineStringMember":ol.xml.makeArrayPusher(de.novasib.ol.format.GMLBase.prototype.lineStringMemberParser_),"lineStringMembers":ol.xml.makeArrayPusher(de.novasib.ol.format.GMLBase.prototype.lineStringMemberParser_)}};
de.novasib.ol.format.GMLBase.prototype.MULTIPOLYGON_PARSERS_={"http://www.opengis.net/gml":{"polygonMember":ol.xml.makeArrayPusher(de.novasib.ol.format.GMLBase.prototype.polygonMemberParser_),"polygonMembers":ol.xml.makeArrayPusher(de.novasib.ol.format.GMLBase.prototype.polygonMemberParser_)}};de.novasib.ol.format.GMLBase.prototype.POINTMEMBER_PARSERS_={"http://www.opengis.net/gml":{"Point":ol.xml.makeArrayPusher(de.novasib.ol.format.GMLBase.prototype.readFlatCoordinatesFromNode_)}};
de.novasib.ol.format.GMLBase.prototype.LINESTRINGMEMBER_PARSERS_={"http://www.opengis.net/gml":{"LineString":ol.xml.makeArrayPusher(de.novasib.ol.format.GMLBase.prototype.readLineString)}};de.novasib.ol.format.GMLBase.prototype.POLYGONMEMBER_PARSERS_={"http://www.opengis.net/gml":{"Polygon":ol.xml.makeArrayPusher(de.novasib.ol.format.GMLBase.prototype.readPolygon)}};de.novasib.ol.format.GMLBase.prototype.RING_PARSERS={"http://www.opengis.net/gml":{"LinearRing":ol.xml.makeReplacer(de.novasib.ol.format.GMLBase.prototype.readFlatLinearRing_)}};
de.novasib.ol.format.GMLBase.prototype.readGeometryFromNode=function(node,opt_options){var geometry=this.readGeometryElement(node,[this.getReadOptions(node,opt_options?opt_options:{})]);return geometry?geometry:null};de.novasib.ol.format.GMLBase.prototype.readFeatures;
de.novasib.ol.format.GMLBase.prototype.readFeaturesFromNode=function(node,opt_options){var options={featureType:this.featureType,featureNS:this.featureNS};if(opt_options)ol.obj.assign(options,this.getReadOptions(node,opt_options));var features=this.readFeaturesInternal(node,[options]);return features||[]};
de.novasib.ol.format.GMLBase.prototype.getReadOptions=function(source,opt_options){var options;if(opt_options)options={dataProjection:opt_options.dataProjection?opt_options.dataProjection:this.readProjection(source),featureProjection:opt_options[0]?ol.proj.get(opt_options[0].featureProjection):ol.proj.get(opt_options.featureProjection)};return options};
de.novasib.ol.format.GMLBase.prototype.readProjectionFromNode=function(node){var ret,srsName_;if(this.srsName)ret=ol.proj.get(this.srsName);else{var child_=node.firstElementChild;if(child_){srsName_=child_.getAttribute("srsName");if(srsName_)ret=srsName_}}return ret||false};goog.provide("de.novasib.ol.format.GML3");goog.require("ol");goog.require("ol.array");goog.require("ol.extent");goog.require("ol.format.Feature");goog.require("de.novasib.ol.format.GMLBase");goog.require("ol.format.XSD");goog.require("ol.geom.Geometry");goog.require("ol.geom.GeometryLayout");goog.require("ol.geom.LineString");goog.require("ol.geom.MultiLineString");goog.require("ol.geom.MultiPolygon");goog.require("ol.geom.Polygon");goog.require("ol.obj");goog.require("ol.proj");goog.require("ol.xml");
de.novasib.ol.format.GML3=function(opt_options){var options=opt_options?opt_options:{};de.novasib.ol.format.GMLBase.call(this,options);this.surface_=options.surface!==undefined?options.surface:false;this.curve_=options.curve!==undefined?options.curve:false;this.multiCurve_=options.multiCurve!==undefined?options.multiCurve:true;this.multiSurface_=options.multiSurface!==undefined?options.multiSurface:true;this.schemaLocation=options.schemaLocation?options.schemaLocation:ol.format.GML3.schemaLocation_;
this.hasZ=options.hasZ!==undefined?options.hasZ:false};ol.inherits(de.novasib.ol.format.GML3,de.novasib.ol.format.GMLBase);de.novasib.ol.format.GML3.schemaLocation_=de.novasib.ol.format.GMLBase.GMLNS+" http://schemas.opengis.net/gml/3.1.1/profiles/gmlsfProfile/"+"1.0.0/gmlsf.xsd";
de.novasib.ol.format.GML3.prototype.readMultiCurve_=function(node,objectStack){var lineStrings=ol.xml.pushParseAndPop([],this.MULTICURVE_PARSERS_,node,objectStack,this);if(lineStrings){var multiLineString=new ol.geom.MultiLineString(null);multiLineString.setLineStrings(lineStrings);return multiLineString}else return undefined};
de.novasib.ol.format.GML3.prototype.readMultiSurface_=function(node,objectStack){var polygons=ol.xml.pushParseAndPop([],this.MULTISURFACE_PARSERS_,node,objectStack,this);if(polygons){var multiPolygon=new ol.geom.MultiPolygon(null);multiPolygon.setPolygons(polygons);return multiPolygon}else return undefined};de.novasib.ol.format.GML3.prototype.curveMemberParser_=function(node,objectStack){ol.xml.parseNode(this.CURVEMEMBER_PARSERS_,node,objectStack,this)};
de.novasib.ol.format.GML3.prototype.surfaceMemberParser_=function(node,objectStack){ol.xml.parseNode(this.SURFACEMEMBER_PARSERS_,node,objectStack,this)};de.novasib.ol.format.GML3.prototype.readPatch_=function(node,objectStack){return ol.xml.pushParseAndPop([null],this.PATCHES_PARSERS_,node,objectStack,this)};de.novasib.ol.format.GML3.prototype.readSegment_=function(node,objectStack){return ol.xml.pushParseAndPop([null],this.SEGMENTS_PARSERS_,node,objectStack,this)};
de.novasib.ol.format.GML3.prototype.readPolygonPatch_=function(node,objectStack){return ol.xml.pushParseAndPop([null],this.FLAT_LINEAR_RINGS_PARSERS_,node,objectStack,this)};de.novasib.ol.format.GML3.prototype.readLineStringSegment_=function(node,objectStack){return ol.xml.pushParseAndPop([null],this.GEOMETRY_FLAT_COORDINATES_PARSERS_,node,objectStack,this)};
de.novasib.ol.format.GML3.prototype.interiorParser_=function(node,objectStack){var flatLinearRing=ol.xml.pushParseAndPop(undefined,this.RING_PARSERS,node,objectStack,this);if(flatLinearRing){var flatLinearRings=objectStack[objectStack.length-1];flatLinearRings.push(flatLinearRing)}};
de.novasib.ol.format.GML3.prototype.exteriorParser_=function(node,objectStack){var flatLinearRing=ol.xml.pushParseAndPop(undefined,this.RING_PARSERS,node,objectStack,this);if(flatLinearRing){var flatLinearRings=objectStack[objectStack.length-1];flatLinearRings[0]=flatLinearRing}};
de.novasib.ol.format.GML3.prototype.readSurface_=function(node,objectStack){var flatLinearRings=ol.xml.pushParseAndPop([null],this.SURFACE_PARSERS_,node,objectStack,this);if(flatLinearRings&&flatLinearRings[0]){var polygon=new ol.geom.Polygon(null);var flatCoordinates=flatLinearRings[0];var ends=[flatCoordinates.length];var i,ii;for(i=1,ii=flatLinearRings.length;i<ii;++i){ol.array.extend(flatCoordinates,flatLinearRings[i]);ends.push(flatCoordinates.length)}polygon.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,
flatCoordinates,ends);return polygon}else return undefined};de.novasib.ol.format.GML3.prototype.readCurve_=function(node,objectStack){var flatCoordinates=ol.xml.pushParseAndPop([null],this.CURVE_PARSERS_,node,objectStack,this);if(flatCoordinates){var lineString=new ol.geom.LineString(null);lineString.setFlatCoordinates(ol.geom.GeometryLayout.XYZ,flatCoordinates);return lineString}else return undefined};
de.novasib.ol.format.GML3.prototype.readEnvelope_=function(node,objectStack){var flatCoordinates=ol.xml.pushParseAndPop([null],this.ENVELOPE_PARSERS_,node,objectStack,this);return ol.extent.createOrUpdate(flatCoordinates[1][0],flatCoordinates[1][1],flatCoordinates[2][0],flatCoordinates[2][1])};
de.novasib.ol.format.GML3.prototype.readFlatPos_=function(node,objectStack){var s=ol.xml.getAllTextContent(node,false);var re=/^\s*([+\-]?\d*\.?\d+(?:[eE][+\-]?\d+)?)\s*/;var flatCoordinates=[];var m;while(m=re.exec(s)){flatCoordinates.push(parseFloat(m[1]));s=s.substr(m[0].length)}if(s!=="")return undefined;var context=objectStack[0];var containerSrs=context["srsName"];var axisOrientation="enu";if(containerSrs){var proj=ol.proj.get(containerSrs);axisOrientation=proj.getAxisOrientation()}if(axisOrientation===
"neu"){var i,ii;for(i=0,ii=flatCoordinates.length;i<ii;i+=3){var y=flatCoordinates[i];var x=flatCoordinates[i+1];flatCoordinates[i]=x;flatCoordinates[i+1]=y}}var len=flatCoordinates.length;if(len==2)flatCoordinates.push(0);if(len===0)return undefined;return flatCoordinates};
de.novasib.ol.format.GML3.prototype.readFlatPosList_=function(node,objectStack){var s=ol.xml.getAllTextContent(node,false).replace(/^\s*|\s*$/g,"");var context=objectStack[0];var containerSrs=context["srsName"];var contextDimension=context["srsDimension"];var axisOrientation="enu";if(containerSrs){var proj=ol.proj.get(containerSrs);axisOrientation=proj.getAxisOrientation()}var coords=s.split(/\s+/);var dim=2;if(node.getAttribute("srsDimension"))dim=ol.format.XSD.readNonNegativeIntegerString(node.getAttribute("srsDimension"));
else if(node.getAttribute("dimension"))dim=ol.format.XSD.readNonNegativeIntegerString(node.getAttribute("dimension"));else if(node.parentNode.getAttribute("srsDimension"))dim=ol.format.XSD.readNonNegativeIntegerString(node.parentNode.getAttribute("srsDimension"));else if(contextDimension)dim=ol.format.XSD.readNonNegativeIntegerString(contextDimension);var x,y,z;var flatCoordinates=[];for(var i=0,ii=coords.length;i<ii;i+=dim){x=parseFloat(coords[i]);y=parseFloat(coords[i+1]);z=dim===3?parseFloat(coords[i+
2]):0;if(axisOrientation.substr(0,2)==="en")flatCoordinates.push(x,y,z);else flatCoordinates.push(y,x,z)}return flatCoordinates};
de.novasib.ol.format.GMLBase.prototype.transformWithOptions=function(geometry,write,opt_options){var featureProjection=opt_options?ol.proj.get(opt_options.featureProjection.code_):null;var dataProjection=opt_options?ol.proj.get(opt_options.dataProjection.code_):null;if(dataProjection.code_)dataProjection.code_=de.novasib.ol.normalizeSrid(dataProjection.code_);var transformed;if(featureProjection&&dataProjection&&!ol.proj.equivalent(featureProjection,dataProjection)){var map_=de.novasib.ol.getNovaMap();
map_.dispatchEvent(new ol.events.Event("projections-inequivalent",featureProjection,dataProjection));if(geometry instanceof ol.geom.Geometry)transformed=(write?geometry.clone():geometry).transform(write?featureProjection:dataProjection,write?dataProjection:featureProjection);else transformed=ol.proj.transformExtent(geometry,dataProjection,featureProjection)}else transformed=geometry;if(write&&opt_options&&opt_options.decimals!==undefined){var power=Math.pow(10,opt_options.decimals);var transform=
function(coordinates){for(var i=0,ii=coordinates.length;i<ii;++i)coordinates[i]=Math.round(coordinates[i]*power)/power;return coordinates};if(transformed===geometry)transformed=transformed.clone();transformed.applyTransform(transform)}return transformed};de.novasib.ol.format.GML3.prototype.GEOMETRY_FLAT_COORDINATES_PARSERS_={"http://www.opengis.net/gml":{"pos":ol.xml.makeReplacer(de.novasib.ol.format.GML3.prototype.readFlatPos_),"posList":ol.xml.makeReplacer(de.novasib.ol.format.GML3.prototype.readFlatPosList_)}};
de.novasib.ol.format.GML3.prototype.FLAT_LINEAR_RINGS_PARSERS_={"http://www.opengis.net/gml":{"interior":de.novasib.ol.format.GML3.prototype.interiorParser_,"exterior":de.novasib.ol.format.GML3.prototype.exteriorParser_}};
de.novasib.ol.format.GML3.prototype.GEOMETRY_PARSERS_={"http://www.opengis.net/gml":{"Point":ol.xml.makeReplacer(de.novasib.ol.format.GMLBase.prototype.readPoint),"MultiPoint":ol.xml.makeReplacer(de.novasib.ol.format.GMLBase.prototype.readMultiPoint),"LineString":ol.xml.makeReplacer(de.novasib.ol.format.GMLBase.prototype.readLineString),"MultiLineString":ol.xml.makeReplacer(de.novasib.ol.format.GMLBase.prototype.readMultiLineString),"LinearRing":ol.xml.makeReplacer(de.novasib.ol.format.GMLBase.prototype.readLinearRing),
"Polygon":ol.xml.makeReplacer(de.novasib.ol.format.GMLBase.prototype.readPolygon),"MultiPolygon":ol.xml.makeReplacer(de.novasib.ol.format.GMLBase.prototype.readMultiPolygon),"Surface":ol.xml.makeReplacer(de.novasib.ol.format.GML3.prototype.readSurface_),"MultiSurface":ol.xml.makeReplacer(de.novasib.ol.format.GML3.prototype.readMultiSurface_),"Curve":ol.xml.makeReplacer(de.novasib.ol.format.GML3.prototype.readCurve_),"MultiCurve":ol.xml.makeReplacer(de.novasib.ol.format.GML3.prototype.readMultiCurve_),
"Envelope":ol.xml.makeReplacer(de.novasib.ol.format.GML3.prototype.readEnvelope_)}};de.novasib.ol.format.GML3.prototype.MULTICURVE_PARSERS_={"http://www.opengis.net/gml":{"curveMember":ol.xml.makeArrayPusher(de.novasib.ol.format.GML3.prototype.curveMemberParser_),"curveMembers":ol.xml.makeArrayPusher(de.novasib.ol.format.GML3.prototype.curveMemberParser_)}};
de.novasib.ol.format.GML3.prototype.MULTISURFACE_PARSERS_={"http://www.opengis.net/gml":{"surfaceMember":ol.xml.makeArrayPusher(de.novasib.ol.format.GML3.prototype.surfaceMemberParser_),"surfaceMembers":ol.xml.makeArrayPusher(de.novasib.ol.format.GML3.prototype.surfaceMemberParser_)}};de.novasib.ol.format.GML3.prototype.CURVEMEMBER_PARSERS_={"http://www.opengis.net/gml":{"LineString":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readLineString),"Curve":ol.xml.makeArrayPusher(de.novasib.ol.format.GML3.prototype.readCurve_)}};
de.novasib.ol.format.GML3.prototype.SURFACEMEMBER_PARSERS_={"http://www.opengis.net/gml":{"Polygon":ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readPolygon),"Surface":ol.xml.makeArrayPusher(de.novasib.ol.format.GML3.prototype.readSurface_)}};de.novasib.ol.format.GML3.prototype.SURFACE_PARSERS_={"http://www.opengis.net/gml":{"patches":ol.xml.makeReplacer(de.novasib.ol.format.GML3.prototype.readPatch_)}};de.novasib.ol.format.GML3.prototype.CURVE_PARSERS_={"http://www.opengis.net/gml":{"segments":ol.xml.makeReplacer(de.novasib.ol.format.GML3.prototype.readSegment_)}};
de.novasib.ol.format.GML3.prototype.ENVELOPE_PARSERS_={"http://www.opengis.net/gml":{"lowerCorner":ol.xml.makeArrayPusher(de.novasib.ol.format.GML3.prototype.readFlatPosList_),"upperCorner":ol.xml.makeArrayPusher(de.novasib.ol.format.GML3.prototype.readFlatPosList_)}};de.novasib.ol.format.GML3.prototype.PATCHES_PARSERS_={"http://www.opengis.net/gml":{"PolygonPatch":ol.xml.makeReplacer(de.novasib.ol.format.GML3.prototype.readPolygonPatch_)}};de.novasib.ol.format.GML3.prototype.SEGMENTS_PARSERS_={"http://www.opengis.net/gml":{"LineStringSegment":ol.xml.makeReplacer(de.novasib.ol.format.GML3.prototype.readLineStringSegment_)}};
de.novasib.ol.format.GML3.prototype.writePos_=function(node,value,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsDimension=hasZ?3:2;node.setAttribute("srsDimension",srsDimension);var srsName=context["srsName"];var axisOrientation="enu";if(srsName)axisOrientation=ol.proj.get(srsName).getAxisOrientation();var point=value.getCoordinates();var coords;if(axisOrientation.substr(0,2)==="en")coords=point[0]+" "+point[1];else coords=point[1]+" "+point[0];if(hasZ){var z=
point[2]||0;coords+=" "+z}ol.format.XSD.writeStringTextNode(node,coords)};de.novasib.ol.format.GML3.prototype.getCoords_=function(point,opt_srsName,opt_hasZ){var axisOrientation="enu";if(opt_srsName)axisOrientation=ol.proj.get(opt_srsName).getAxisOrientation();var coords=axisOrientation.substr(0,2)==="en"?point[0]+" "+point[1]:point[1]+" "+point[0];if(opt_hasZ){var z=point[2]||0;coords+=" "+z}return coords};
de.novasib.ol.format.GML3.prototype.writePosList_=function(node,value,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsDimension=hasZ?3:2;node.setAttribute("srsDimension",srsDimension);var srsName=context["srsName"];var points=value.getCoordinates();var len=points.length;var parts=new Array(len);var point;for(var i=0;i<len;++i){point=points[i];parts[i]=this.getCoords_(point,srsName,hasZ)}ol.format.XSD.writeStringTextNode(node,parts.join(" "))};
de.novasib.ol.format.GML3.prototype.writePoint_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var pos=ol.xml.createElementNS(node.namespaceURI,"pos");node.appendChild(pos);this.writePos_(pos,geometry,objectStack)};de.novasib.ol.format.GML3.ENVELOPE_SERIALIZERS_={"http://www.opengis.net/gml":{"lowerCorner":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"upperCorner":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)}};
de.novasib.ol.format.GML3.prototype.writeEnvelope=function(node,extent,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var keys=["lowerCorner","upperCorner"];var values=[extent[0]+" "+extent[1],extent[2]+" "+extent[3]];ol.xml.pushSerializeAndPop({node:node},de.novasib.ol.format.GML3.ENVELOPE_SERIALIZERS_,ol.xml.OBJECT_PROPERTY_NODE_FACTORY,values,objectStack,keys,this)};
de.novasib.ol.format.GML3.prototype.writeLinearRing_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var posList=ol.xml.createElementNS(node.namespaceURI,"posList");node.appendChild(posList);this.writePosList_(posList,geometry,objectStack)};
de.novasib.ol.format.GML3.prototype.RING_NODE_FACTORY_=function(value,objectStack,opt_nodeName){var context=objectStack[objectStack.length-1];var parentNode=context.node;var exteriorWritten=context["exteriorWritten"];if(exteriorWritten===undefined)context["exteriorWritten"]=true;return ol.xml.createElementNS(parentNode.namespaceURI,exteriorWritten!==undefined?"interior":"exterior")};
de.novasib.ol.format.GML3.prototype.writeSurfaceOrPolygon_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];if(node.nodeName!=="PolygonPatch"&&srsName)node.setAttribute("srsName",srsName);if(node.nodeName==="Polygon"||node.nodeName==="PolygonPatch"){var rings=geometry.getLinearRings();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName},de.novasib.ol.format.GML3.RING_SERIALIZERS_,this.RING_NODE_FACTORY_,
rings,objectStack,undefined,this)}else if(node.nodeName==="Surface"){var patches=ol.xml.createElementNS(node.namespaceURI,"patches");node.appendChild(patches);this.writeSurfacePatches_(patches,geometry,objectStack)}};
de.novasib.ol.format.GML3.prototype.writeCurveOrLineString_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(node.nodeName!=="LineStringSegment"&&srsName)node.setAttribute("srsName",srsName);if(node.nodeName==="LineString"||node.nodeName==="LineStringSegment"){var posList=ol.xml.createElementNS(node.namespaceURI,"posList");node.appendChild(posList);this.writePosList_(posList,geometry,objectStack)}else if(node.nodeName==="Curve"){var segments=
ol.xml.createElementNS(node.namespaceURI,"segments");node.appendChild(segments);this.writeCurveSegments_(segments,geometry,objectStack)}};
de.novasib.ol.format.GML3.prototype.writeMultiSurfaceOrPolygon_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];var surface=context["surface"];if(srsName)node.setAttribute("srsName",srsName);var polygons=geometry.getPolygons();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName,surface:surface},de.novasib.ol.format.GML3.SURFACEORPOLYGONMEMBER_SERIALIZERS_,this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_,polygons,
objectStack,undefined,this)};de.novasib.ol.format.GML3.prototype.writeMultiPoint_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];var hasZ=context["hasZ"];if(srsName)node.setAttribute("srsName",srsName);var points=geometry.getPoints();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName},de.novasib.ol.format.GML3.POINTMEMBER_SERIALIZERS_,ol.xml.makeSimpleNodeFactory("pointMember"),points,objectStack,undefined,this)};
de.novasib.ol.format.GML3.prototype.writeMultiCurveOrLineString_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsName=context["srsName"];var curve=context["curve"];if(srsName)node.setAttribute("srsName",srsName);var lines=geometry.getLineStrings();ol.xml.pushSerializeAndPop({node:node,hasZ:hasZ,srsName:srsName,curve:curve},de.novasib.ol.format.GML3.LINESTRINGORCURVEMEMBER_SERIALIZERS_,this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_,lines,objectStack,
undefined,this)};de.novasib.ol.format.GML3.prototype.writeRing_=function(node,ring,objectStack){var linearRing=ol.xml.createElementNS(node.namespaceURI,"LinearRing");node.appendChild(linearRing);this.writeLinearRing_(linearRing,ring,objectStack)};de.novasib.ol.format.GML3.prototype.writeSurfaceOrPolygonMember_=function(node,polygon,objectStack){var child=this.GEOMETRY_NODE_FACTORY_(polygon,objectStack);if(child){node.appendChild(child);this.writeSurfaceOrPolygon_(child,polygon,objectStack)}};
de.novasib.ol.format.GML3.prototype.writePointMember_=function(node,point,objectStack){var child=ol.xml.createElementNS(node.namespaceURI,"Point");node.appendChild(child);this.writePoint_(child,point,objectStack)};de.novasib.ol.format.GML3.prototype.writeLineStringOrCurveMember_=function(node,line,objectStack){var child=this.GEOMETRY_NODE_FACTORY_(line,objectStack);if(child){node.appendChild(child);this.writeCurveOrLineString_(child,line,objectStack)}};
de.novasib.ol.format.GML3.prototype.writeSurfacePatches_=function(node,polygon,objectStack){var child=ol.xml.createElementNS(node.namespaceURI,"PolygonPatch");node.appendChild(child);this.writeSurfaceOrPolygon_(child,polygon,objectStack)};de.novasib.ol.format.GML3.prototype.writeCurveSegments_=function(node,line,objectStack){var child=ol.xml.createElementNS(node.namespaceURI,"LineStringSegment");node.appendChild(child);this.writeCurveOrLineString_(child,line,objectStack)};
de.novasib.ol.format.GML3.prototype.writeGeometryElement=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var item=ol.obj.assign({},context);item.node=node;var value;if(Array.isArray(geometry))if(context.dataProjection)value=ol.proj.transformExtent(geometry,context.featureProjection,context.dataProjection);else value=geometry;else value=ol.format.Feature.transformWithOptions(geometry,true,context);ol.xml.pushSerializeAndPop(item,de.novasib.ol.format.GML3.GEOMETRY_SERIALIZERS_,
this.GEOMETRY_NODE_FACTORY_,[value],objectStack,undefined,this)};
de.novasib.ol.format.GML3.prototype.writeFeatureElement=function(node,feature,objectStack){var fid=feature.getId();if(fid)node.setAttribute("fid",fid);var context=objectStack[objectStack.length-1];var featureNS=context["featureNS"];var geometryName=feature.getGeometryName();if(!context.serializers){context.serializers={};context.serializers[featureNS]={}}var properties=feature.getProperties();var keys=[],values=[];for(var key in properties){var value=properties[key];if(value!==null){keys.push(key);
values.push(value);if(key==geometryName||value instanceof ol.geom.Geometry){if(!(key in context.serializers[featureNS]))context.serializers[featureNS][key]=ol.xml.makeChildAppender(this.writeGeometryElement,this)}else if(!(key in context.serializers[featureNS]))context.serializers[featureNS][key]=ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)}}var item=ol.obj.assign({},context);item.node=node;ol.xml.pushSerializeAndPop(item,context.serializers,ol.xml.makeSimpleNodeFactory(undefined,featureNS),
values,objectStack,keys)};
de.novasib.ol.format.GML3.prototype.writeFeatureMembers_=function(node,features,objectStack){var context=objectStack[objectStack.length-1];var featureType=context["featureType"];var featureNS=context["featureNS"];var serializers={};serializers[featureNS]={};serializers[featureNS][featureType]=ol.xml.makeChildAppender(this.writeFeatureElement,this);var item=ol.obj.assign({},context);item.node=node;ol.xml.pushSerializeAndPop(item,serializers,ol.xml.makeSimpleNodeFactory(featureType,featureNS),features,
objectStack)};de.novasib.ol.format.GML3.SURFACEORPOLYGONMEMBER_SERIALIZERS_={"http://www.opengis.net/gml":{"surfaceMember":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeSurfaceOrPolygonMember_),"polygonMember":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeSurfaceOrPolygonMember_)}};de.novasib.ol.format.GML3.POINTMEMBER_SERIALIZERS_={"http://www.opengis.net/gml":{"pointMember":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writePointMember_)}};
de.novasib.ol.format.GML3.LINESTRINGORCURVEMEMBER_SERIALIZERS_={"http://www.opengis.net/gml":{"lineStringMember":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeLineStringOrCurveMember_),"curveMember":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeLineStringOrCurveMember_)}};de.novasib.ol.format.GML3.RING_SERIALIZERS_={"http://www.opengis.net/gml":{"exterior":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeRing_),"interior":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeRing_)}};
de.novasib.ol.format.GML3.GEOMETRY_SERIALIZERS_={"http://www.opengis.net/gml":{"Curve":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeCurveOrLineString_),"MultiCurve":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeMultiCurveOrLineString_),"Point":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writePoint_),"MultiPoint":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeMultiPoint_),"LineString":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeCurveOrLineString_),
"MultiLineString":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeMultiCurveOrLineString_),"LinearRing":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeLinearRing_),"Polygon":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeSurfaceOrPolygon_),"MultiPolygon":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeMultiSurfaceOrPolygon_),"Surface":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeSurfaceOrPolygon_),"MultiSurface":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeMultiSurfaceOrPolygon_),
"Envelope":ol.xml.makeChildAppender(de.novasib.ol.format.GML3.prototype.writeEnvelope)}};de.novasib.ol.format.GML3.MULTIGEOMETRY_TO_MEMBER_NODENAME_={"MultiLineString":"lineStringMember","MultiCurve":"curveMember","MultiPolygon":"polygonMember","MultiSurface":"surfaceMember"};
de.novasib.ol.format.GML3.prototype.MULTIGEOMETRY_MEMBER_NODE_FACTORY_=function(value,objectStack,opt_nodeName){var parentNode=objectStack[objectStack.length-1].node;return ol.xml.createElementNS("http://www.opengis.net/gml",de.novasib.ol.format.GML3.MULTIGEOMETRY_TO_MEMBER_NODENAME_[parentNode.nodeName])};
de.novasib.ol.format.GML3.prototype.GEOMETRY_NODE_FACTORY_=function(value,objectStack,opt_nodeName){var context=objectStack[objectStack.length-1];var multiSurface=context["multiSurface"];var surface=context["surface"];var curve=context["curve"];var multiCurve=context["multiCurve"];var nodeName;if(!Array.isArray(value)){nodeName=value.getType();if(nodeName==="MultiPolygon"&&multiSurface===true)nodeName="MultiSurface";else if(nodeName==="Polygon"&&surface===true)nodeName="Surface";else if(nodeName===
"LineString"&&curve===true)nodeName="Curve";else if(nodeName==="MultiLineString"&&multiCurve===true)nodeName="MultiCurve"}else nodeName="Envelope";return ol.xml.createElementNS("http://www.opengis.net/gml",nodeName)};
de.novasib.ol.format.GML3.prototype.writeGeometryNode=function(geometry,opt_options){opt_options=this.adaptOptions(opt_options);var geom=ol.xml.createElementNS("http://www.opengis.net/gml","geom");var context={node:geom,hasZ:this.hasZ,srsName:this.srsName,curve:this.curve_,surface:this.surface_,multiSurface:this.multiSurface_,multiCurve:this.multiCurve_};if(opt_options)ol.obj.assign(context,opt_options);this.writeGeometryElement(geom,geometry,[context]);return geom};de.novasib.ol.format.GML3.prototype.writeFeatures;
de.novasib.ol.format.GML3.prototype.writeFeaturesNode=function(features,opt_options){opt_options=this.adaptOptions(opt_options);var node=ol.xml.createElementNS("http://www.opengis.net/gml","featureMembers");ol.xml.setAttributeNS(node,"http://www.w3.org/2001/XMLSchema-instance","xsi:schemaLocation",this.schemaLocation);var context={srsName:this.srsName,hasZ:this.hasZ,curve:this.curve_,surface:this.surface_,multiSurface:this.multiSurface_,multiCurve:this.multiCurve_,featureNS:this.featureNS,featureType:this.featureType};
if(opt_options)ol.obj.assign(context,opt_options);this.writeFeatureMembers_(node,features,[context]);return node};goog.provide("de.novasib.ol.xml");goog.require("ol.xml");
de.novasib.ol.xml.makeFeatureMemberNodeFactory=function(opt_nodeName,opt_namespaceURI){var fixedNodeName=opt_nodeName;return function(value,objectStack,opt_nodeName){var context=objectStack[objectStack.length-1];var node=context.node;var nodeName=fixedNodeName;if(nodeName===undefined)nodeName=opt_nodeName;var namespaceURI=opt_namespaceURI;if(opt_namespaceURI===undefined)namespaceURI=node.namespaceURI;var ret=ol.xml.createElementNS(namespaceURI,nodeName);var parent=ol.xml.createElementNS(ol.format.GMLBase.GMLNS,
"featureMember");parent.appendChild(ret);return parent}};goog.provide("de.novasib.ol.format.GML3Export");goog.require("ol");goog.require("ol.format.Feature");goog.require("ol.format.GML3");goog.require("ol.format.XSD");goog.require("ol.geom.Geometry");goog.require("ol.obj");goog.require("ol.proj");goog.require("ol.xml");goog.require("de.novasib.ol");goog.require("de.novasib.ol.xml");
de.novasib.ol.format.GML3Export=function(opt_options){var options=opt_options?opt_options:{};ol.format.GML3.call(this,options);this.ignoreProperties=["featureType","layername","withOrientation"];this.currentExtent=options.extent;this.onceIsEnough=0};ol.inherits(de.novasib.ol.format.GML3Export,ol.format.GML3);de.novasib.ol.format.GMLBase.TTSIBNS="http://xml.novasib.de/tt-sib5";
de.novasib.ol.format.GML3Export.prototype.writePos_=function(node,value,objectStack){var context=objectStack[objectStack.length-1];var hasZ=context["hasZ"];var srsDimension=hasZ?3:2;node.setAttribute("srsDimension",srsDimension);var point=value.getCoordinates();var x=de.novasib.ol.toFixedIfNumber(point[0],5);var y=de.novasib.ol.toFixedIfNumber(point[1],5);var coords=x+" "+y;if(hasZ){var z=de.novasib.ol.toFixedIfNumber(point[2],5)||0;coords+=" "+z}ol.format.XSD.writeStringTextNode(node,coords)};
de.novasib.ol.format.GML3Export.prototype.getCoords_=function(point,opt_srsName,opt_hasZ){var x=de.novasib.ol.toFixedIfNumber(point[0],5);var y=de.novasib.ol.toFixedIfNumber(point[1],5);var coords=x+" "+y;if(opt_hasZ){var z=de.novasib.ol.toFixedIfNumber(point[2],5)||0;coords+=" "+z}return coords};
de.novasib.ol.format.GML3Export.prototype.writePoint_=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var pos=ol.xml.createElementNS(node.namespaceURI,"gml:pos");node.appendChild(pos);this.writePos_(pos,geometry,objectStack)};de.novasib.ol.format.GML3Export.ENVELOPE_SERIALIZERS_={"http://www.opengis.net/gml":{"lowerCorner":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),"upperCorner":ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)}};
de.novasib.ol.format.GML3Export.prototype.writeEnvelope=function(node,extent,objectStack){var context=objectStack[objectStack.length-1];var srsName=context["srsName"];if(srsName)node.setAttribute("srsName",srsName);var hasZ=context["hasZ"];var srsDimension=hasZ?3:2;node.setAttribute("srsDimension",srsDimension);var keys=["gml:lowerCorner","gml:upperCorner"];var bounds;if(context.dataProjection)bounds=ol.proj.transformExtent(extent,context.featureProjection,context.dataProjection);else bounds=extent.slice();
var minx=de.novasib.ol.toFixedIfNumber(bounds[0],5);var miny=de.novasib.ol.toFixedIfNumber(bounds[1],5);var maxx=de.novasib.ol.toFixedIfNumber(bounds[2],5);var maxy=de.novasib.ol.toFixedIfNumber(bounds[3],5);var values=[minx+" "+miny,maxx+" "+maxy];ol.xml.pushSerializeAndPop({node:node},de.novasib.ol.format.GML3Export.ENVELOPE_SERIALIZERS_,ol.xml.makeSimpleNodeFactory(undefined,ol.format.GMLBase.GMLNS),values,objectStack,keys,this)};
de.novasib.ol.format.GML3Export.prototype.writeEnvelopeBody=function(node,extent,objectStack){var context=objectStack[objectStack.length-1];var ns=ol.format.GMLBase.GMLNS;var type="Envelope";var serializers={};serializers[ns]={};serializers[ns][type]=ol.xml.makeChildAppender(this.writeEnvelope,this);var item=ol.obj.assign({},context);item.node=node;ol.xml.pushSerializeAndPop(item,serializers,ol.xml.makeSimpleNodeFactory(type,ns),[extent],objectStack,undefined,this)};
de.novasib.ol.format.GML3Export.prototype.writeBoundedBy=function(node,extent,objectStack){var context=objectStack[objectStack.length-1];var ns=ol.format.GMLBase.GMLNS;var type="boundedBy";var serializers={};serializers[ns]={};serializers[ns][type]=ol.xml.makeChildAppender(this.writeEnvelopeBody,this);var item=ol.obj.assign({},context);item.node=node;ol.xml.pushSerializeAndPop(item,serializers,ol.xml.makeSimpleNodeFactory(type,ns),[extent],objectStack,undefined,this)};
de.novasib.ol.format.GML3Export.prototype.writeCurveOrLineString_=function(node,geometry,objectStack){if(node.localName==="LineString"){var posList=ol.xml.createElementNS(node.namespaceURI,"gml:posList");node.appendChild(posList);this.writePosList_(posList,geometry,objectStack)}};de.novasib.ol.format.GML3Export.prototype.writePointMember_=function(node,point,objectStack){var child=ol.xml.createElementNS(node.namespaceURI,"gml:Point");node.appendChild(child);this.writePoint_(child,point,objectStack)};
de.novasib.ol.format.GML3Export.prototype.writeGeometryElement=function(node,geometry,objectStack){var context=objectStack[objectStack.length-1];var item=ol.obj.assign({},context);item.node=node;var value;if(Array.isArray(geometry))if(context.dataProjection)value=ol.proj.transformExtent(geometry,context.featureProjection,context.dataProjection);else value=geometry;else value=ol.format.Feature.transformWithOptions(geometry,true,context);ol.xml.pushSerializeAndPop(item,ol.format.GML3.GEOMETRY_SERIALIZERS_,
this.GEOMETRY_NODE_FACTORY_,[value],objectStack,undefined,this)};
de.novasib.ol.format.GML3Export.prototype.writeFeatureElement=function(parentNode,feature,objectStack){var node=parentNode.firstChild;var fid=feature.getId();if(fid){node.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns","http://www.opengis.net/gml");node.setAttributeNS("http://www.opengis.net/gml","gml:id",fid)}var context=objectStack[objectStack.length-1];var featureNS=context["featureNS"];var geometryName=feature.getGeometryName();if(!context.serializers){context.serializers={};context.serializers[featureNS]=
{}}var properties=feature.getProperties();var keys=[],values=[];var bbKey="boundedBy";var bbValue=feature.getGeometry()?feature.getGeometry().getExtent():null;if(bbValue){keys.push(bbKey);values.push(bbValue);context.serializers[featureNS][bbKey]=ol.xml.makeChildAppender(this.writeBoundedBy,this)}for(var key in properties){if(this.ignoreProperties.indexOf(key)!=-1)continue;var value=properties[key];if(value!==null){keys.push(key);values.push(value);var setAttributeType=function(key,value,childElement_){var ret;
var val=de.novasib.ol.getTypeOfString(value);if(key==geometryName||value instanceof ol.geom.Geometry){childElement_.setAttribute("type","gml"+":"+"GeometryPropertyType");return}else{if(val==="float")val="decimal";if(val===undefined)val="string";childElement_.setAttribute("type","xsd"+":"+val);ret=val}return ret};var childElement_=ol.xml.createElementNS("http://www.w3.org/2001/XMLSchema","xsd:element");childElement_.setAttribute("maxOccurs","1");childElement_.setAttribute("minOccurs","0");childElement_.setAttribute("name",
key);childElement_.setAttribute("nillable","true");setAttributeType(key,value,childElement_);var parentElement_=this.nodeXsd.getElementsByTagName("xsd"+":"+"sequence")[0];if(childElement_.getAttribute("name")=="geometry")this.onceIsEnough+=1;if(this.onceIsEnough<2)parentElement_.insertAdjacentElement("beforeend",childElement_);if(key==geometryName||value instanceof ol.geom.Geometry){if(!(key in context.serializers[featureNS]))context.serializers[featureNS][key]=ol.xml.makeChildAppender(this.writeGeometryElement,
this)}else if(!(key in context.serializers[featureNS]))context.serializers[featureNS][key]=ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)}}var item=ol.obj.assign({},context);item.node=node;ol.xml.pushSerializeAndPop(item,context.serializers,ol.xml.makeSimpleNodeFactory(undefined,featureNS),values,objectStack,keys)};
de.novasib.ol.format.GML3Export.prototype.writeFeatureMembers=function(node,features,objectStack){var context=objectStack[objectStack.length-1];var featureType=context["featureType"];var featureNS=context["featureNS"];var type="featureMember";var serializers={};var parentElement,childElement,sibling;childElement=ol.xml.createElementNS("http://www.w3.org/2001/XMLSchema","xsd:sequence");parentElement=ol.xml.createElementNS("http://www.w3.org/2001/XMLSchema","xsd:extension");parentElement.setAttribute("base",
"gml:AbstractFeatureType");parentElement.appendChild(childElement);childElement=parentElement;parentElement=ol.xml.createElementNS("http://www.w3.org/2001/XMLSchema","xsd:complexContent");parentElement.appendChild(childElement);childElement=parentElement;parentElement=ol.xml.createElementNS("http://www.w3.org/2001/XMLSchema","xsd:complexType");parentElement.setAttribute("name",this.featureType);parentElement.appendChild(childElement);sibling=this.nodeXsd.getElementsByTagName("xsd:import")[0];sibling.insertAdjacentElement("afterend",
parentElement);serializers[ol.format.GMLBase.GMLNS]={};serializers[ol.format.GMLBase.GMLNS][type]=ol.xml.makeChildAppender(this.writeFeatureElement,this);var item=ol.obj.assign({},context);item.node=node;ol.xml.pushSerializeAndPop(item,serializers,de.novasib.ol.xml.makeFeatureMemberNodeFactory(featureType,featureNS),features,objectStack)};de.novasib.ol.format.GML3Export.prototype.writeFeatures;
de.novasib.ol.format.GML3Export.prototype.writeFeaturesNode=function(features,opt_options){opt_options=this.adaptOptions(opt_options);var node=ol.xml.createElementNS("http://www.opengis.net/wfs","wfs:FeatureCollection");node.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns","http://www.opengis.net/wfs");node.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:ttsib",de.novasib.ol.format.GMLBase.TTSIBNS);node.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xs","http://www.w3.org/2001/XMLSchema");
node.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:wfs","http://www.opengis.net/wfs");node.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:gml",ol.format.GMLBase.GMLNS);node.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:ogc","http://www.opengis.net/ogc");node.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:ows","http://www.opengis.net/ows");node.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink");node.setAttributeNS("http://www.w3.org/2000/xmlns/",
"xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");ol.xml.setAttributeNS(node,"http://www.w3.org/2001/XMLSchema-instance","xsi:schemaLocation",this.schemaLocation);var childElement;this.nodeXsd=ol.xml.createElementNS("http://www.w3.org/2001/XMLSchema","xsd:schema");this.nodeXsd.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xsd","http://www.w3.org/2001/XMLSchema");this.nodeXsd.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:gml","http://www.opengis.net/gml");this.nodeXsd.setAttributeNS("http://www.w3.org/2000/xmlns/",
"xmlns:ttsib",de.novasib.ol.format.GMLBase.TTSIBNS);this.nodeXsd.setAttribute("elementFormDefault","qualified");this.nodeXsd.setAttribute("targetNamespace",this.featureNS);childElement=ol.xml.createElementNS("http://www.w3.org/2001/XMLSchema","xsd:import");childElement.setAttribute("namespace","http://www.opengis.net/gml");childElement.setAttribute("schemaLocation","http://schemas.opengis.net/gml/3.1.1/base/gml.xsd");this.nodeXsd.appendChild(childElement);childElement=ol.xml.createElementNS("http://www.w3.org/2001/XMLSchema",
"xsd:element");childElement.setAttribute("name",this.featureType);childElement.setAttribute("substitutionGroup","gml:_Feature");childElement.setAttribute("type","ttsib:"+this.featureType);this.nodeXsd.appendChild(childElement);var context={srsName:this.srsName,hasZ:this.hasZ,curve:this.curve_,surface:this.surface_,multiSurface:this.multiSurface_,multiCurve:this.multiCurve_,featureNS:this.featureNS,featureType:this.featureType,schemaLocation:this.schemaLocation};if(opt_options)ol.obj.assign(context,
opt_options);var objectStack=[context];if(this.currentExtent)this.writeBoundedBy(node,this.currentExtent,objectStack);this.writeFeatureMembers(node,features,objectStack);return node};goog.provide("de.novasib.ol.InitialView");de.novasib.ol.InitialView=function(options){options=options||{};this.centerX=options["centerX"];this.centerY=options["centerY"];this.resolution=options["resolution"];this.zoom=options["zoom"];this.maxZoom=options["maxZoom"];this.minZoom=options["minZoom"]};goog.provide("de.novasib.ol.interaction.ClickBox");goog.require("de.novasib.ol.condition");goog.require("ol");goog.require("ol.events.Event");goog.require("ol.interaction.Pointer");goog.require("ol.render.Box");
de.novasib.ol.interaction.ClickBox=function(opt_options){var options=opt_options||{};ol.interaction.Pointer.call(this,{handleUpEvent:de.novasib.ol.interaction.ClickBox.handleUpEvent_,handleDownEvent:de.novasib.ol.interaction.ClickBox.handleDownEvent_,handleDragEvent:de.novasib.ol.interaction.ClickBox.handleDragEvent_});this.wasDragging_=false;this.box_=new ol.render.Box(options.className||"ol-dragbox");this.minArea_=options.minArea!==undefined?options.minArea:64;this.startPixel_=null;this.condition_=
options.condition?options.condition:de.novasib.ol.condition.ctrlKeyOnly;this.boxEndCondition_=options.boxEndCondition?options.boxEndCondition:ol.interaction.DragBox.defaultBoxEndCondition;this.clickOnly_=false;this.clickTimeoutId_=0};ol.inherits(de.novasib.ol.interaction.ClickBox,ol.interaction.Pointer);
de.novasib.ol.interaction.ClickBox.handleUpEvent_=function(evt){if(evt instanceof ol.MapBrowserPointerEvent&&evt.frameState&&evt.frameState.viewState)if(this.condition_(evt)&&!this.clickOnly_){this.box_.setMap(null);if(this.boxEndCondition_(evt,this.startPixel_,evt.pixel)){var extent=this.box_.getGeometry().getExtent();var zoom=evt.frameState.viewState.zoom;this.dispatchEvent(new de.novasib.ol.interaction.ClickBox.BoxEvent(extent,zoom))}}else if(!this.wasDragging_){var coord=evt.coordinate;var zoom$18=
evt.frameState.viewState.zoom;if(this.clickTimeoutId_!==0){clearTimeout(this.clickTimeoutId_);this.clickTimeoutId_=0}else this.clickTimeoutId_=setTimeout(function(){this.clickTimeoutId_=0;this.dispatchEvent(new de.novasib.ol.interaction.ClickBox.ClickEvent(coord,zoom$18))}.bind(this),250)}this.wasDragging_=false;return true};
de.novasib.ol.interaction.ClickBox.handleDownEvent_=function(evt){if(evt instanceof ol.MapBrowserPointerEvent&&evt.type==ol.MapBrowserEventType.POINTERDOWN&&!this.clickOnly_)if(this.condition_(evt)){this.startPixel_=evt.pixel;this.box_.setMap(evt.map);this.box_.setPixels(this.startPixel_,this.startPixel_)}return true};de.novasib.ol.interaction.ClickBox.handleDragEvent_=function(event){this.wasDragging_=true;if(!this.clickOnly_&&this.condition_(event))this.box_.setPixels(this.startPixel_,event.pixel)};
de.novasib.ol.interaction.ClickBox.prototype.shouldStopEvent=function(handled){return!handled};de.novasib.ol.interaction.ClickBox.prototype.setClickOnly=function(clickOnly){this.clickOnly_=clickOnly};de.novasib.ol.interaction.ClickBox.ClickEvent=function(coord,zoom){ol.events.Event.call(this,"mapclick");this.coordinate=coord;this.zoom=zoom};ol.inherits(de.novasib.ol.interaction.ClickBox.ClickEvent,ol.events.Event);
de.novasib.ol.interaction.ClickBox.BoxEvent=function(extent,zoom){ol.events.Event.call(this,"boxend");this.extent=extent;this.zoom=zoom};ol.inherits(de.novasib.ol.interaction.ClickBox.BoxEvent,ol.events.Event);goog.provide("de.novasib.ol.style");goog.require("de.novasib.ol");goog.require("de.novasib.ol.feature");goog.require("de.novasib.ol.geom");goog.require("ol.xml");goog.require("ol.Feature");goog.require("ol.geom.Point");goog.require("ol.geom.LineString");goog.require("ol.style.Icon");goog.require("ol.style.Stroke");goog.require("ol.style.Style");de.novasib.ol.style.ARROW_BASE_64="iVBORw0KGgoAAAANSUhEUgAAAAwAAAATCAYAAACk9eypAAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gcKDgcdbBz7SQAAAFdJREFUKM+tk0ESACAIAuX/j7ZLlwoxpjw6rSloxIzMzLgI7I8BQAKssoJQtVNBUDMwaEncQEeFDqJ9KqhUo4Kk5hT68oM1g6WS5YPltLVLz9vaeRPuxQ1bhkwGG1rrJAAAAABJRU5ErkJggg==";
de.novasib.ol.style.ARROW_IMG="data:image/png;base64,"+de.novasib.ol.style.ARROW_BASE_64;de.novasib.ol.style.ARROW_2_BASE_64="iVBORw0KGgoAAAANSUhEUgAAAAwAAAATCAYAAACk9eypAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4wkNCDIP0KJheAAAAEBJREFUKM/t0DEKADAMAkD9/6PtVigVk4yFuuZECPDzZJiOktQuWEySE2wXEr4KFT4KHbwLXQwAnGC7kHD5HZcFzhooAiMQrxwAAAAASUVORK5CYII=";de.novasib.ol.style.ARROW_2_IMG="data:image/png;base64,"+de.novasib.ol.style.ARROW_2_BASE_64;de.novasib.ol.style.MAX_SCALE_DENOMINATOR="maxScaleDenominator";
de.novasib.ol.style.WELL_KNOWN_NAMES=["circle","square","triangle","star","cross","x"];de.novasib.ol.style.ImageTypes={CIRCLE:"circle",SHAPE:"regularShape",ICON:"icon"};de.novasib.ol.style.DEFAULT_LINE_CAP="butt";de.novasib.ol.style.LINE_CAP=["butt","round","square"];de.novasib.ol.style.DEFAULT_LINE_JOIN="bevel";de.novasib.ol.style.LINE_JOIN=["bevel","round","miter"];de.novasib.ol.style.DEFAULT_STYLE_NAME="default";de.novasib.ol.style.DEFAULT_SELECTION_STYLE_NAME="select";
de.novasib.ol.style.getLineCap=function(linecap){if(de.novasib.ol.style.LINE_CAP.includes(linecap))return linecap;else return de.novasib.ol.style.DEFAULT_LINE_CAP};de.novasib.ol.style.getLineJoin=function(linejoin){if(de.novasib.ol.style.LINE_JOIN.includes(linejoin))return linejoin;else return de.novasib.ol.style.DEFAULT_LINE_JOIN};
de.novasib.ol.style.getColorLike=function(color,opacity){opacity=opacity===undefined?1:opacity;var ret=color;if(color)if(typeof color==="string")if(opacity>=0&&opacity<=1)if(color.startsWith("#")){var r=0;var g=0;var b=0;if(color.length===7){r=color.substring(1,3);g=color.substring(3,5);b=color.substring(5,7)}else if(color.length===4){r=color.substring(1,2);r+=r;g=color.substring(2,3);g+=g;b=color.substring(3,4);b+=b}ret="rgba("+parseInt(r,16)+","+parseInt(g,16)+","+parseInt(b,16)+","+opacity+")"}else if(color.startsWith("rgb(")){ret=
"rgba(";var substr=color.substring(color.indexOf("(")+1,color.indexOf(")"));var rgb=substr.split(",");rgb.forEach(function(el){ret+=el.trim()+","});ret+=opacity+")"}else if(color.startsWith("rgba("))ret=de.novasib.ol.style.updateColorOpacity(color,opacity);return ret};
de.novasib.ol.style.updateColorOpacity=function(color,newOpacity){if(color&&newOpacity){var ret=color;var oldOpacity;if(color.startsWith("#")||color.startsWith("rgb("))oldOpacity=1;else oldOpacity=de.novasib.ol.style.getRgbaColorOpacity(color);if(oldOpacity!==newOpacity){var idx=color.lastIndexOf(",");ret=color.substring(0,idx+1)+" "+newOpacity+")"}return ret}return"#000"};
de.novasib.ol.style.getRgbaColorOpacity=function(color){var sub=color.substring(color.lastIndexOf(",")+1,color.lastIndexOf(")")).trim();return parseFloat(sub)||1};de.novasib.ol.style.font=function(style,weight,size,family){var ret="";if(style)ret+=style+" ";if(weight)ret+=weight+" ";ret+=size+"px "+family;return ret};
de.novasib.ol.style.getStyledFeatureFunctionForLayer=function(map,styleManager,featureType,layerName,changeProperties){changeProperties=changeProperties===undefined?[]:changeProperties;return function(features,dataProjection){var featuresWithGeometry=[];if(styleManager){var res=map.getView().getResolution();features.forEach(function(feature){var breite_=feature.get("breite");var bisBreite_=feature.get("bisBreite");if(breite_==="0"&&bisBreite_==="0"||breite_===""&&bisBreite_===""){var layer=de.novasib.ol.getLayersByName(map,
layerName)[0];layer.set("nullGeometryFeatures_",feature);return}feature.set(de.novasib.ol.FeatureProperties.LAYER_NAME,layerName);var styleFunction=de.novasib.ol.style.getFeatureStyleFunction(feature,map,styleManager,featureType);var style=styleFunction(res);feature.setStyle(style);de.novasib.ol.feature.setFeatureStyleChangeListeners(feature,changeProperties,function(){var res=map.getView().getResolution();var style=styleFunction(res);feature.setStyle(style)});featuresWithGeometry.push(feature)})}this.addFeatures(featuresWithGeometry)}};
de.novasib.ol.style.getFeatureStyleFunction=function(feature,map,styleManager,featureType){return function(resolution){var layerName=this.get(de.novasib.ol.FeatureProperties.LAYER_NAME);var layer=de.novasib.ol.getLayersByName(map,layerName,ol.layer.Vector)[0];if(layer&&layer.get("stylename")){var lyrStyleName=layer.get("stylename");this.set("layerStyleName",lyrStyleName)}if(layer&&layer.get("forceLayerStyle")){var styleFunction=layer.getStyleFunction();if(styleFunction)return styleFunction.call(layer,
this,resolution);else{var style=layer.getStyle();if(style)if(typeof style=="function")return style.call(layer,this,resolution);else return style}}else if(styleManager.hasStyleForLayer(layerName)){this.set(de.novasib.ol.FeatureProperties.WITH_ORIENTATION,false);var scale=de.novasib.ol.getScaleFromResolution(resolution);var style$19=styleManager.getFeatureStyle(this,featureType,layerName,scale);var ret=null;if(style$19||Array.isArray(style$19)&&style$19.length>0){if(Array.isArray(style$19))ret=style$19;
else ret=[style$19];if(this.get(de.novasib.ol.FeatureProperties.WITH_ORIENTATION)||layer.get("showOrientation")){var orientStyles=de.novasib.ol.style.getOrientationStyles.call(this,map);if(orientStyles&&orientStyles.length>0)ret=orientStyles.concat(ret)}if(ret.length===0)ret=null}return ret}else{if(this.getGeometry())return ol.style.Style.createDefaultEditing()[this.getGeometry().getType()];return null}}.bind(feature)};
de.novasib.ol.style.getOrientationStyles=function(map){var $jscomp$this=this;var ret=[];var color="#A3BAE9";var prevPoint=null;var prevLen=Number.POSITIVE_INFINITY;var from=this.get(de.novasib.ol.FeatureProperties.VST);var to=this.get(de.novasib.ol.FeatureProperties.BST);var geom;if(this.get("HERKUNFT")=="EX")geom=this.getGeometry();else geom=de.novasib.ol.geom.getShortenedLineString(this.getGeometry(),from,to,this.get("ALEN")||this.get("LEN"));geom.forEachSegment(function(start,end){var dx=end[0]-
start[0];var dy=end[1]-start[1];var rotation=Math.atan2(dy,dx);var pointCoords=[start[0]+dx*.5,start[1]+dy*.5];if(prevPoint){var px1=map.getPixelFromCoordinate(end);var px2=map.getPixelFromCoordinate(prevPoint);prevLen=Math.sqrt(Math.pow(px1[0]-px2[0],2)+Math.pow(px1[1]-px2[1],2))}var so=$jscomp$this.get("RICHTUNG")=="G";rotation=so?Math.PI-rotation:-rotation;if(prevLen>40){ret.push(new ol.style.Style({geometry:new ol.geom.Point(pointCoords),image:new ol.style.Icon({src:de.novasib.ol.style.ARROW_IMG,
rotation:rotation,color:color}),zIndex:0}));prevPoint=pointCoords.slice()}},this);return ret};
de.novasib.ol.style.loadSld=function(url,username,password,success,failure,this_obj){if(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);if(username&&password){var credentials=username+":"+password;xhr.setRequestHeader("Authorization","Basic "+btoa(credentials))}xhr.onload=function(event){if(!xhr.status||xhr.status>=200&&xhr.status<300){var sld=xhr.responseXML;if(!sld)sld=ol.xml.parse(xhr.responseText);if(sld)success.call(this,sld);else failure.call(this)}}.bind(this_obj);xhr.onerror=function(){failure.call(this,
new de.novasib.ol.style.Error({type:de.novasib.ol.style.ErrorType.SLD_LOADING_ERROR,message:"Fehler beim laden der SLD"}))}.bind(this_obj);xhr.send()}else failure.call(this_obj,new de.novasib.ol.style.Error({type:de.novasib.ol.style.ErrorType.NO_SLD,message:"Keine URL f\u00fcr SLD gefunden"}))};de.novasib.ol.style.getDefaultStyleFunction=function(){var styles=de.novasib.ol.style.createDefaultVector();return function(feature,resolution){return styles[feature.getGeometry().getType()]}};
de.novasib.ol.style.createDefaultVector=function(){var styles={};styles[ol.geom.GeometryType.LINE_STRING]=[new ol.style.Style({stroke:new ol.style.Stroke({color:[0,0,0,.3],width:5})})];return styles};de.novasib.ol.style.getFeatureRotation=function(feature){if(feature){var style=feature.getStyle();if(style instanceof ol.style.Style){var img=style.getImage();if(img)return img.getRotation();var txt=style.getText();if(txt)return txt.getRotation()||0}}return 0};
goog.exportSymbol("NovaMapUtils.getFeatureRotation",de.novasib.ol.style.getFeatureRotation);de.novasib.ol.style.setFeatureRotation=function(feature,rotation){if(feature){var style=feature.getStyle();if(style instanceof ol.style.Style){var img=style.getImage();if(img){img.setRotation(rotation);feature.changed()}var txt=style.getText();if(txt){txt.setRotation(rotation);feature.changed()}}}};goog.exportSymbol("NovaMapUtils.setFeatureRotation",de.novasib.ol.style.setFeatureRotation);
de.novasib.ol.style.setFeatureStyle=function(feature,options){if(feature&&options){var strokeColor=options["strokeColor"]||"#000";var strokeOpacity=options["strokeOpacity"]||1;var sColor=de.novasib.ol.style.getColorLike(strokeColor,strokeOpacity);var strokeLineCap=options["strokeLineCap"]||"butt";var strokeLineJoin=options["strokeLineJoin"]||"bevel";var strokeWidth=options["strokeWidth"]||5;var style=new ol.style.Style({stroke:new ol.style.Stroke({color:sColor,width:strokeWidth,linecap:strokeLineCap,
linejoin:strokeLineJoin}),zIndex:1E4});feature.setStyle(style)}};goog.exportSymbol("NovaMapUtils.setFeatureStyle",de.novasib.ol.style.setFeatureStyle);de.novasib.ol.style.setFeatureIconStyle=function(feature,options){if(feature&&options){var opacity=options.opacity;var src=options.path;var rotation=options.rotation;var size=options.size;var scale=options.scale;var style=new ol.style.Style({image:new ol.style.Icon({src:src,opacity:opacity,rotation:rotation,size:size,scale:scale}),zIndex:1E3});feature.setStyle(style)}};
goog.exportSymbol("NovaMapUtils.setFeatureIconStyle",de.novasib.ol.style.setFeatureIconStyle);
de.novasib.ol.style.addIconOnGeometry=function(coordinates,options,callback){if(coordinates&&Array.isArray(coordinates)&&coordinates.length>1){var point;if(!Array.isArray(coordinates[0]))point=new ol.geom.Point(coordinates);else{var ls=new ol.geom.LineString(coordinates);var offset=options["offset"]||.5;if(options["external"]){var pos=ls.getLength()*offset;var coords=de.novasib.ol.geom.getPointOnLineString(ls,pos);point=new ol.geom.Point(coords)}else{var from=options["from"];var to=options["to"];
var alen=options["alen"];var sls=de.novasib.ol.geom.getShortenedLineString(ls,from,to,alen);var pos$20=sls.getLength()*offset;var coords$21=de.novasib.ol.geom.getPointOnLineString(sls,pos$20);point=new ol.geom.Point(coords$21)}}var feature=new ol.Feature(point);feature.setStyle(new ol.style.Style({image:new ol.style.Icon({src:options["path"],rotation:options["rotation"],opacity:options["opacity"],size:options["size"]})}));if(callback&&typeof callback=="function")callback.call(null,feature)}};
goog.exportSymbol("NovaMapUtils.addIconOnGeometry",de.novasib.ol.style.addIconOnGeometry);de.novasib.ol.style.Error=function(opt_options){var options=opt_options||{};this.type=options.type;this.message=options.message};de.novasib.ol.style.ErrorType={NO_SLD:"noSld",SLD_LOADING_ERROR:"sldLoadingError"};
de.novasib.ol.style.fromSLD=function(sld,map,preventShortGeom){var styles={};if(sld){if(typeof sld==="string")sld=ol.xml.parse(sld);styles=de.novasib.ol.style.StyleManager.loadFromSLD(sld.documentElement,map,preventShortGeom)}return function(feature,resolution){if(styles&&feature){var geom=feature.getGeometry();if(geom){var type=geom.getType();if(styles[type]){var styleName=feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME);if(styleName==="hover"||styleName==="select")return de.novasib.ol.style.NamedLayer.prototype.getHoverStyle.call(null,
styles[type]);else return styles[type]}}}return null}};de.novasib.ol.style.randomColor=function(opacity){opacity=opacity===undefined?1:opacity;var r=de.novasib.ol.getRandomInt(256);var g=de.novasib.ol.getRandomInt(256);var b=de.novasib.ol.getRandomInt(256);return"rgba("+r+", "+g+", "+b+", "+opacity+")"};
de.novasib.ol.style.getIconClone=function(icon,newSrc,newSize){return new ol.style.Icon({anchor:icon.anchor_.slice(),anchorOrigin:icon.anchorOrigin_,anchorXUnits:icon.anchorXUnits_,anchorYUnits:icon.anchorYUnits_,crossOrigin:icon.crossOrigin_,color:icon.color_&&icon.color_.slice?icon.color_.slice():icon.color_||undefined,src:newSrc,offset:icon.offset_.slice(),offsetOrigin:icon.offsetOrigin_,size:newSize,opacity:icon.getOpacity(),scale:icon.getScale(),snapToPixel:icon.getSnapToPixel(),rotation:icon.getRotation(),
rotateWithView:icon.getRotateWithView()})};goog.provide("de.novasib.ol.interaction.FreeText");goog.require("de.novasib.ol.style");goog.require("ol");goog.require("ol.events.Event");goog.require("ol.geom.Point");goog.require("ol.interaction.Pointer");goog.require("ol.layer.Vector");goog.require("ol.source.Vector");goog.require("ol.style.Fill");goog.require("ol.style.Stroke");goog.require("ol.style.Style");goog.require("ol.style.Text");
de.novasib.ol.interaction.FreeText=function(options){ol.interaction.Pointer.call(this,{handleDownEvent:de.novasib.ol.interaction.FreeText.handleDownEvent_,handleDragEvent:de.novasib.ol.interaction.FreeText.handleDragEvent_,handleEvent:de.novasib.ol.interaction.FreeText.handleEvent,handleUpEvent:de.novasib.ol.interaction.FreeText.handleUpEvent_});this.text_="Text";this.rotation_=0;this.fontSize_=10;this.font_="Arial";this.color_="#000";this.bgColor_="#fff";this.borderColor_="#000";this.opacity_=1;
this.pixelTolerance_=options.pixelTolerance||0;this.dragging_=false;this.down_=false;this.overlay_=new ol.layer.Vector({source:new ol.source.Vector({useSpatialIndex:false,wrapX:false}),style:ol.style.Style.createDefaultEditing()[ol.geom.GeometryType.POINT],updateWhileAnimating:true,updateWhileInteracting:true,zIndex:1E5});this.pointFeature_=null;this.textFeature_=null;this.source_=null;if(options.source)this.source_=options.source;else throw new Error("The free text interaction requires a source");
this.style_=null;this.createStyle_()};ol.inherits(de.novasib.ol.interaction.FreeText,ol.interaction.Pointer);de.novasib.ol.interaction.FreeText.prototype.abort=function(){if(this.textFeature_){this.source_.removeFeature(this.textFeature_);this.textFeature_=null;this.createStyle_()}};de.novasib.ol.interaction.FreeText.prototype.finish=function(){var ret=this.textFeature_;this.textFeature_=null;this.createStyle_();return ret};
de.novasib.ol.interaction.FreeText.prototype.setActive=function(active){if(this.pointFeature_&&!active){this.overlay_.getSource().removeFeature(this.pointFeature_);this.pointFeature_=null}ol.interaction.Pointer.prototype.setActive.call(this,active)};de.novasib.ol.interaction.FreeText.prototype.setMap=function(map){ol.interaction.Pointer.prototype.setMap.call(this,map);this.overlay_.setMap(this.getActive()?map:null)};de.novasib.ol.interaction.FreeText.prototype.shouldStopEvent=ol.functions.FALSE;
de.novasib.ol.interaction.FreeText.prototype.setFeature=function(feature){if(feature){this.textFeature_=feature;this.textFeature_.setStyle(this.style_);if(this.source_.getFeatures().indexOf(this.textFeature_)==-1)this.source_.addFeature(this.textFeature_)}};de.novasib.ol.interaction.FreeText.prototype.setText=function(text){text=text||"Text";this.text_=text;this.updateStyle_()};
de.novasib.ol.interaction.FreeText.prototype.setRotation=function(rotation){rotation=rotation||0;this.rotation_=rotation;this.updateStyle_()};de.novasib.ol.interaction.FreeText.prototype.setFontSize=function(fontSize){fontSize=fontSize||10;this.fontSize_=fontSize;this.updateStyle_()};de.novasib.ol.interaction.FreeText.prototype.setFont=function(font){font=font||"Arial";this.font_=font;this.updateStyle_()};
de.novasib.ol.interaction.FreeText.prototype.setColor=function(color){color=color||"#fff";this.color_=color;this.updateStyle_()};de.novasib.ol.interaction.FreeText.prototype.setBackgroundColor=function(color){color=color||"#000";this.bgColor_=color;this.updateStyle_()};de.novasib.ol.interaction.FreeText.prototype.setBorderColor=function(color){color=color||"#fff";this.borderColor_=color;this.updateStyle_()};
de.novasib.ol.interaction.FreeText.prototype.setOpacity=function(opacity){opacity=opacity===0?opacity:opacity||1;this.opacity_=opacity;this.updateStyle_()};
de.novasib.ol.interaction.FreeText.prototype.updateStyle_=function(){var txt=this.style_.getText();txt.setText(this.text_);txt.setRotation(this.rotation_);var font_=de.novasib.ol.style.font("","",this.fontSize_,this.font_);txt.setFont(font_);var textColor_=de.novasib.ol.style.getColorLike(this.color_);var fill=txt.getFill();if(fill)fill.setColor(textColor_);else txt.setFill(new ol.style.Fill({color:textColor_}));var bgColor_=de.novasib.ol.style.getColorLike(this.bgColor_,this.opacity_);var bgFill=
txt.getBackgroundFill();if(bgFill)bgFill.setColor(bgColor_);else txt.setBackgroundFill(new ol.style.Fill({color:bgColor_}));var bgStroke_=de.novasib.ol.style.getColorLike(this.borderColor_,this.opacity_);var stroke=txt.getBackgroundStroke();if(stroke)stroke.setColor(bgStroke_);else txt.setBackgroundStroke(new ol.style.Stroke({color:bgStroke_,width:2}));if(this.textFeature_)this.textFeature_.changed()};de.novasib.ol.interaction.FreeText.handleDragEvent_=function(evt){this.dragging_=true};
de.novasib.ol.interaction.FreeText.handleDownEvent_=function(evt){this.down_=true;return true};de.novasib.ol.interaction.FreeText.handleUpEvent_=function(evt){if(!this.dragging_)this.createOrUpdateTextFeature_(evt.coordinate);this.dragging_=false;return false};
de.novasib.ol.interaction.FreeText.handleEvent=function(mapBrowserEvent){if(!mapBrowserEvent.map.getView().getInteracting())if(mapBrowserEvent.type==ol.MapBrowserEventType.POINTERMOVE)this.handlePointerMove_(mapBrowserEvent);return ol.interaction.Pointer.handleEvent.call(this,mapBrowserEvent)};de.novasib.ol.interaction.FreeText.prototype.handlePointerMove_=function(evt){var map=evt.map;var coord=map.getCoordinateFromPixel(evt.pixel);this.createOrUpdatePointFeature_(coord)};
de.novasib.ol.interaction.FreeText.prototype.createOrUpdatePointFeature_=function(coordinates){var pointFeature=this.pointFeature_;if(!pointFeature){pointFeature=new ol.Feature(new ol.geom.Point(coordinates));this.pointFeature_=pointFeature;this.overlay_.getSource().addFeature(pointFeature)}else{var geometry=pointFeature.getGeometry();geometry.setCoordinates(coordinates)}return pointFeature};
de.novasib.ol.interaction.FreeText.prototype.createOrUpdateTextFeature_=function(coordinates){if(!this.textFeature_){this.textFeature_=new ol.Feature(new ol.geom.Point(coordinates));this.textFeature_.setStyle(this.style_);this.source_.addFeature(this.textFeature_);this.dispatchEvent(new de.novasib.ol.interaction.FreeText.Event_)}else{var geometry=this.textFeature_.getGeometry();geometry.setCoordinates(coordinates)}};
de.novasib.ol.interaction.FreeText.prototype.createStyle_=function(){var font_=de.novasib.ol.style.font("","",this.fontSize_,this.font_);var textColor_=de.novasib.ol.style.getColorLike(this.color_);var bgColor_=de.novasib.ol.style.getColorLike(this.bgColor_,this.opacity_);var bgStroke_=de.novasib.ol.style.getColorLike(this.borderColor_,this.opacity_);this.style_=new ol.style.Style({text:new ol.style.Text({font:font_,placement:"point",scale:1,rotation:this.rotation_,text:this.text_,fill:new ol.style.Fill({color:textColor_}),
backgroundFill:new ol.style.Fill({color:bgColor_}),backgroundStroke:new ol.style.Stroke({color:bgStroke_,width:2}),padding:[5,5,5,5],overflow:true})})};de.novasib.ol.interaction.FreeText.Event_=function(){ol.events.Event.call(this,"freetextadded")};ol.inherits(de.novasib.ol.interaction.FreeText.Event_,ol.events.Event);goog.provide("de.novasib.ol.layer.IndexedOverlayLayer");goog.require("ol");goog.require("ol.events");goog.require("ol.layer.Vector");de.novasib.ol.layer.IndexedOverlayLayer=function(opt_options){ol.layer.Vector.call(this,opt_options);var options=opt_options||{};this.zIndex_=options.zIndex||Infinity;this.precomposeKey_=null;this.renderKey_=null};ol.inherits(de.novasib.ol.layer.IndexedOverlayLayer,ol.layer.Vector);
de.novasib.ol.layer.IndexedOverlayLayer.prototype.setMap=function(map){if(this.precomposeKey_){ol.events.unlistenByKey(this.precomposeKey_);this.precomposeKey_=null}if(!map)this.changed();if(this.renderKey_){ol.events.unlistenByKey(this.renderKey_);this.renderKey_=null}if(map){this.precomposeKey_=ol.events.listen(map,ol.render.EventType.PRECOMPOSE,function(evt){var layerState=this.getLayerState();layerState.managed=false;layerState.zIndex=this.zIndex_;evt.frameState.layerStatesArray.push(layerState);
evt.frameState.layerStates[ol.getUid(this)]=layerState},this);this.renderKey_=ol.events.listen(this,ol.events.EventType.CHANGE,map.render,map);this.changed()}};goog.provide("de.novasib.ol.interaction.HoverSelect");goog.require("de.novasib.ol");goog.require("de.novasib.ol.geom");goog.require("de.novasib.ol.layer.IndexedOverlayLayer");goog.require("de.novasib.ol.style");goog.require("ol");goog.require("ol.array");goog.require("ol.events");goog.require("ol.events.condition");goog.require("ol.events.Event");goog.require("ol.geom.Point");goog.require("ol.interaction.Interaction");goog.require("ol.source.Vector");goog.require("ol.style.Icon");goog.require("ol.style.Stroke");
goog.require("ol.style.Style");
de.novasib.ol.interaction.HoverSelect=function(opt_options){ol.interaction.Interaction.call(this,{handleEvent:de.novasib.ol.interaction.HoverSelect.handleEvent});var options=opt_options?opt_options:{};this.condition_=options.condition?options.condition:ol.events.condition.singleClick;this.hoverCondition_=ol.events.condition.pointerMove;this.multi_=options.multi||false;this.filter_=options.filter||ol.functions.TRUE;this.hitTolerance_=options.hitTolerance||0;var featureOverlay=new de.novasib.ol.layer.IndexedOverlayLayer({source:new ol.source.Vector({useSpatialIndex:false,
features:options.features,wrapX:options.wrapX}),style:options.style?options.style:de.novasib.ol.interaction.HoverSelect.getDefaultStyleFunction(this),updateWhileAnimating:true,updateWhileInteracting:true,zIndex:1E6-1});this.featureOverlay_=featureOverlay;var hoverOverlay=new de.novasib.ol.layer.IndexedOverlayLayer({source:new ol.source.Vector({useSpatialIndex:false,wrapX:false}),style:options.hoverStyle?options.hoverStyle:de.novasib.ol.interaction.HoverSelect.getHoverStyleFunction(this),updateWhileAnimating:true,
updateWhileInteracting:true});this.hoverOverlay_=hoverOverlay;this.hoverOnly_=options.hoverOnly||false;this.layerFilter_=this.createLayerFilter_(options.layers);this.featureLayerAssociation_={};this.featureStyleAssociation_={};this.lastSelected_=[];this.shiftKeyCondition_=ol.events.condition.shiftKeyOnly;this.shiftDown_=false;this.ctrlKeyCondition_=de.novasib.ol.condition.ctrlKeyOnly;this.ctrlDown_=false;this.featureSearchDepth_=0;this.mouseWheelCounter1_=0;this.mouseWheelCounter2_=0;this.mouseWheelMarker_=
true;this.mouseWheelInterval_=100;var features=this.featureOverlay_.getSource().getFeaturesCollection();ol.events.listen(features,ol.CollectionEventType.ADD,this.addFeature_,this);ol.events.listen(features,ol.CollectionEventType.REMOVE,this.removeFeature_,this);var hoverFeatures=this.hoverOverlay_.getSource().getFeaturesCollection();ol.events.listen(hoverFeatures,ol.CollectionEventType.ADD,this.addFeature_,this);ol.events.listen(hoverFeatures,ol.CollectionEventType.REMOVE,this.removeFeature_,this)};
ol.inherits(de.novasib.ol.interaction.HoverSelect,ol.interaction.Interaction);de.novasib.ol.interaction.HoverSelect.prototype.setLayerFilter=function(layerFilter){this.layerFilter_=this.createLayerFilter_(layerFilter)};de.novasib.ol.interaction.HoverSelect.prototype.getLayerFilter=function(){return this.layerFilter_};
de.novasib.ol.interaction.HoverSelect.prototype.createLayerFilter_=function(layerFilter){if(typeof layerFilter==="function")return layerFilter;else if(Array.isArray(layerFilter)){var layers=layerFilter;return function(layer){return ol.array.includes(layers,layer)}}else return ol.functions.TRUE};
de.novasib.ol.interaction.HoverSelect.prototype.setActive=function(active){if(!active){var src=this.hoverOverlay_.getSource();var features=src.getFeaturesCollection();for(var i=0;i<features.getLength();++i){var feature=features.item(i);var style=this.getStyle_(feature);if(style){feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,style);this.removeFeatureStyleAssociation_(feature)}}src.clear()}ol.interaction.Interaction.prototype.setActive.call(this,active)};
de.novasib.ol.interaction.HoverSelect.prototype.setHoverOnly=function(hover){this.hoverOnly_=hover};de.novasib.ol.interaction.HoverSelect.prototype.addFeatureLayerAssociation_=function(feature,layer){var key=ol.getUid(feature);this.featureLayerAssociation_[key]=layer};de.novasib.ol.interaction.HoverSelect.prototype.addFeatureStyleAssociation_=function(feature,stylename){if(stylename&&stylename!="hover"){var key=ol.getUid(feature);this.featureStyleAssociation_[key]=stylename}};
de.novasib.ol.interaction.HoverSelect.prototype.getFeatures=function(){return this.featureOverlay_.getSource().getFeaturesCollection()};de.novasib.ol.interaction.HoverSelect.prototype.getHitTolerance=function(){return this.hitTolerance_};de.novasib.ol.interaction.HoverSelect.prototype.getLayer=function(feature){var key=ol.getUid(feature);return this.featureLayerAssociation_[key]};de.novasib.ol.interaction.HoverSelect.prototype.getStyle_=function(feature){var key=ol.getUid(feature);return this.featureStyleAssociation_[key]};
de.novasib.ol.interaction.HoverSelect.handleEvent=function(mapBrowserEvent){this.ctrlDown_=this.ctrlKeyCondition_(mapBrowserEvent);this.shiftDown_=this.shiftKeyCondition_(mapBrowserEvent);if(this.shiftDown_&&this.isWheelEvent_(mapBrowserEvent))return this.handleMouseWheel_(mapBrowserEvent);if(this.condition_(mapBrowserEvent)&&!this.hoverOnly_){if(de.novasib.ol.PARENT_APP_NAME===de.novasib.ol.KNOWN_APP_NAMES.NOVAMAP)return this.handleDownNovamap_(mapBrowserEvent);return this.handleDown_(mapBrowserEvent)}else if(this.hoverCondition_(mapBrowserEvent)){if(de.novasib.ol.PARENT_APP_NAME===
de.novasib.ol.KNOWN_APP_NAMES.NOVAMAP)return this.handleHoverNovamap_(mapBrowserEvent);return this.handleHover_(mapBrowserEvent)}return true};de.novasib.ol.interaction.HoverSelect.prototype.handleMouseWheel_=function(evt){this.mouseWheelCounter1_++;if(this.mouseWheelMarker_)this.mouseWheelStart_(evt);return false};de.novasib.ol.interaction.HoverSelect.prototype.mouseWheelStart_=function(evt){this.mouseWheelMarker_=false;this.mouseWheelAct_(evt)};
de.novasib.ol.interaction.HoverSelect.prototype.mouseWheelAct_=function(evt){this.mouseWheelCounter2_=this.mouseWheelCounter1_;setTimeout(function(that){if(that.mouseWheelCounter2_==that.mouseWheelCounter1_)that.mouseWheelEnd_(evt);else that.mouseWheelAct_(evt)},this.mouseWheelInterval_,this)};
de.novasib.ol.interaction.HoverSelect.prototype.mouseWheelEnd_=function(evt){this.mouseWheelMarker_=true;this.mouseWheelCounter1_=this.mouseWheelCounter2_=0;var wheelEvent=evt.originalEvent;var delta;if(evt.type===ol.events.EventType.WHEEL)delta=-wheelEvent.deltaY;else if(evt.type==ol.events.EventType.MOUSEWHEEL)delta=wheelEvent.deltaY;var offset=delta<0?-1:1;this.featureSearchDepth_+=offset;this.handleHover_(evt)};
de.novasib.ol.interaction.HoverSelect.prototype.handleDown_=function(mapBrowserEvent){var map=mapBrowserEvent.map;var features=this.featureOverlay_.getSource().getFeaturesCollection();var hoverFeatures=this.hoverOverlay_.getSource().getFeaturesCollection();var deselected=[];var selected=[];var index=0;var searchDepth=0;if(this.featureSearchDepth_!=0){var pxF=map.getFeaturesAtPixel(mapBrowserEvent.pixel,{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});if(pxF){var len=pxF.length;searchDepth=
Math.abs(this.featureSearchDepth_)%len}}hoverFeatures.clear();map.forEachFeatureAtPixel(mapBrowserEvent.pixel,function(feature,layer){if(this.filter_(feature,layer)){if(searchDepth!=index){index++;return false}if(!ol.array.includes(features.getArray(),feature)){if(selected.indexOf(feature)==-1)selected.push(feature);this.addFeatureLayerAssociation_(feature,layer);feature.set(de.novasib.ol.FeatureProperties.SELECTED,true,true);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,de.novasib.ol.style.DEFAULT_SELECTION_STYLE_NAME);
var arr=this.handleGroupSelect_(map,layer,feature,false);ol.array.extend(selected,arr)}else if(ol.array.includes(features.getArray(),feature)){if(deselected.indexOf(feature)==-1)deselected.push(feature);feature.unset(de.novasib.ol.FeatureProperties.SELECTED,true);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,de.novasib.ol.style.DEFAULT_STYLE_NAME);var arr$22=this.handleGroupSelect_(map,layer,feature,true);ol.array.extend(deselected,arr$22)}}return!this.multi_}.bind(this),{layerFilter:this.layerFilter_,
hitTolerance:this.hitTolerance_});if(de.novasib.ol.PARENT_APP_NAME===de.novasib.ol.KNOWN_APP_NAMES.SPERRINFOSYS||de.novasib.ol.PARENT_APP_NAME===de.novasib.ol.KNOWN_APP_NAMES.TTSIB)if(features.array_.length!==0&&hoverFeatures.array_.length===0){var src=this.featureOverlay_.getSource();src.forEachFeature(function(feature){if(ol.array.includes(features.getArray(),feature)){if(deselected.indexOf(feature)==-1)deselected.push(feature);feature.unset(de.novasib.ol.FeatureProperties.SELECTED,true);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,
de.novasib.ol.style.DEFAULT_STYLE_NAME);var layer_=this.getLayer(feature);var arr=this.handleGroupSelect_(map,layer_,feature,true);ol.array.extend(deselected,arr)}},this)}for(var i=deselected.length-1;i>=0;--i){var feature=deselected[i];var arr=features.getArray();if(arr.indexOf(feature)!==-1){features.remove(feature);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,"default")}}features.extend(selected);if(selected.length>0||deselected.length>0){var lyr,layername;if(selected.length>0)lyr=this.getLayer(selected[0]);
else if(deselected.length>0)lyr=this.getLayer(deselected[0]);if(lyr)layername=lyr.get("name")||lyr.get("title");this.dispatchEvent(new de.novasib.ol.interaction.HoverSelect.Event(de.novasib.ol.interaction.HoverSelect.EventType_.SELECT,selected,deselected,layername,mapBrowserEvent))}deselected.forEach(function(feature){this.removeFeatureLayerAssociation_(feature)}.bind(this));this.lastSelected_=selected.slice();return true};
de.novasib.ol.interaction.HoverSelect.prototype.handleDownNovamap_=function(mapBrowserEvent){var map=mapBrowserEvent.map;var selectedFeatures=this.featureOverlay_.getSource().getFeaturesCollection();var hoveredFeatures=this.hoverOverlay_.getSource().getFeaturesCollection();var deselected=[];var selected=[];var index=0;var searchDepth=0;if(this.featureSearchDepth_!=0){var pxF=map.getFeaturesAtPixel(mapBrowserEvent.pixel,{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});if(pxF){var len=
pxF.length;searchDepth=Math.abs(this.featureSearchDepth_)%len}}map.forEachFeatureAtPixel(mapBrowserEvent.pixel,function(feature,layer){if(this.filter_(feature,layer)){if(searchDepth!=index){index++;return false}var isFeatureInSelectOverlay=ol.array.includes(selectedFeatures.getArray(),feature);if(!isFeatureInSelectOverlay){if(selected.indexOf(feature)==-1)selected.push(feature);this.addFeatureLayerAssociation_(feature,layer);feature.set(de.novasib.ol.FeatureProperties.SELECTED,true,true);selected[0].getStyle()[0].getImage().setScale(1.5);
var arr=this.handleGroupSelect_(map,layer,feature,false);ol.array.extend(selected,arr)}else if(isFeatureInSelectOverlay){if(deselected.indexOf(feature)==-1)deselected.push(feature);feature.unset(de.novasib.ol.FeatureProperties.SELECTED,true);deselected[0].getStyle()[0].getImage().setScale(1);var arr$23=this.handleGroupSelect_(map,layer,feature,true);ol.array.extend(deselected,arr$23)}}return!this.multi_}.bind(this),{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});if(!this.ctrlDown_)if(this.lastSelected_.length!=
0){this.featureOverlay_.getSource().clear();this.lastSelected_[0].unset(de.novasib.ol.FeatureProperties.SELECTED,true)}hoveredFeatures.clear();for(var i=deselected.length-1;i>=0;--i){var feature=deselected[i];var arr=selectedFeatures.getArray();if(arr.indexOf(feature)!==-1){selectedFeatures.remove(feature);feature.getStyle()[0].getImage().setScale(1.5)}}selectedFeatures.extend(selected);if(selected.length>0||deselected.length>0){var lyr,layername;if(selected.length>0)lyr=this.getLayer(selected[0]);
else if(deselected.length>0)lyr=this.getLayer(deselected[0]);if(lyr)layername=lyr.get("name")||lyr.get("title");this.dispatchEvent(new de.novasib.ol.interaction.HoverSelect.Event(de.novasib.ol.interaction.HoverSelect.EventType_.SELECT,selected,deselected,layername,mapBrowserEvent))}deselected.forEach(function(feature){this.removeFeatureLayerAssociation_(feature)}.bind(this));this.lastSelected_=selected.slice();return true};
de.novasib.ol.interaction.HoverSelect.prototype.handleGroupSelect_=function(map,layer,_feature,deselect){var $jscomp$this=this;var ret=[];if(layer&&layer.get(de.novasib.ol.LayerProperties.GROUP_SELECT)){var fid=_feature.getId();var extent=map.getView().calculateExtent();var groupSelect=layer.get(de.novasib.ol.LayerProperties.GROUP_SELECT);var propertyName=groupSelect["property"];var value=_feature.get(propertyName);if(layer instanceof ol.layer.Vector)layer.getSource().forEachFeatureInExtent(extent,
function(feature){if(feature.getId()!=fid){var prop=feature.get(propertyName);if(prop===value){if(deselect){feature.unset(de.novasib.ol.FeatureProperties.SELECTED,true);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,"default");this.removeFeatureLayerAssociation_(feature)}else{feature.set(de.novasib.ol.FeatureProperties.SELECTED,true,true);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,de.novasib.ol.style.DEFAULT_SELECTION_STYLE_NAME);this.addFeatureLayerAssociation_(feature,layer)}if(ret.indexOf(feature)==
-1)ret.push(feature)}}}.bind(this));var otherLayers=groupSelect["layers"];if(otherLayers&&Array.isArray(otherLayers)&&otherLayers.length>0)map.getLayers().forEach(function(layer){var name=layer.get(de.novasib.ol.LayerProperties.NAME);var title=layer.get(de.novasib.ol.LayerProperties.TITLE);if(otherLayers.indexOf(name)!=-1||otherLayers.indexOf(title)!=-1)if(layer instanceof ol.layer.Vector&&layer.getVisible())layer.getSource().forEachFeatureInExtent(extent,function(feature){var prop=feature.get(propertyName);
if(prop===value){if(deselect){feature.unset(de.novasib.ol.FeatureProperties.SELECTED,true);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,"default");this.removeFeatureLayerAssociation_(feature)}else{feature.set(de.novasib.ol.FeatureProperties.SELECTED,true,true);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,"select");this.addFeatureLayerAssociation_(feature,layer)}if(ret.indexOf(feature)==-1)ret.push(feature)}}.bind($jscomp$this))})}return ret};
de.novasib.ol.interaction.HoverSelect.prototype.select=function(features,layer){var $jscomp$this=this;if(features){if(!Array.isArray(features))features=[features];if(typeof layer==="string"&&this.getMap()){var layerByName=de.novasib.ol.getLayersByName(this.getMap(),layer,ol.layer.Vector);if(layerByName)layer=layerByName[0]}var selectedFeatures=this.featureOverlay_.getSource().getFeaturesCollection();var hoverFeatures=this.hoverOverlay_.getSource().getFeaturesCollection();hoverFeatures.clear();var selected=
[];features.forEach(function(feature){if(layer&&layer.getSource()instanceof ol.source.Vector){var source=layer.getSource();var id=feature.getId();if(!source.getFeatureById(id))return}if(!ol.array.includes(selectedFeatures.getArray(),feature))if(de.novasib.ol.PARENT_APP_NAME===de.novasib.ol.KNOWN_APP_NAMES.MBDE){if(!ol.array.includes(selected,feature))selected.push(feature);$jscomp$this.addFeatureLayerAssociation_(feature,layer);feature.set(de.novasib.ol.FeatureProperties.SELECTED,true,true);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,
"select");var arr=$jscomp$this.handleGroupSelect_($jscomp$this.getMap(),layer,feature,false);arr.forEach(function(sameGroup){if(!ol.array.includes(selected,sameGroup))ol.array.extend(selected,sameGroup)})}else{selected.push(feature);$jscomp$this.addFeatureLayerAssociation_(feature,layer);feature.set(de.novasib.ol.FeatureProperties.SELECTED,true,true);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,"select");var arr$24=$jscomp$this.handleGroupSelect_($jscomp$this.getMap(),layer,feature,false);
ol.array.extend(selected,arr$24)}});selectedFeatures.extend(selected)}};
de.novasib.ol.interaction.HoverSelect.prototype.deselect=function(features){var $jscomp$this=this;if(features){if(!Array.isArray(features))features=[features];var selectedFeatures=this.featureOverlay_.getSource().getFeaturesCollection();var hoveredFeatures=this.hoverOverlay_.getSource().getFeaturesCollection();var deselected=[];features.forEach(function(feature){if(ol.array.includes(selectedFeatures.getArray(),feature)||ol.array.includes(hoveredFeatures.getArray(),feature))if(de.novasib.ol.PARENT_APP_NAME===
de.novasib.ol.KNOWN_APP_NAMES.MBDE){if(!ol.array.includes(deselected,feature))deselected.push(feature);feature.unset(de.novasib.ol.FeatureProperties.SELECTED,true);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,"default");var arr=$jscomp$this.handleGroupSelect_($jscomp$this.getMap(),$jscomp$this.getLayer(feature),feature,true);arr.forEach(function(sameGroup){if(!ol.array.includes(deselected,sameGroup))ol.array.extend(deselected,sameGroup)});$jscomp$this.removeFeatureLayerAssociation_(feature)}else{deselected.push(feature);
feature.unset(de.novasib.ol.FeatureProperties.SELECTED,true);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,"default");var arr$25=$jscomp$this.handleGroupSelect_($jscomp$this.getMap(),$jscomp$this.getLayer(feature),feature,true);ol.array.extend(deselected,arr$25);$jscomp$this.removeFeatureLayerAssociation_(feature)}});for(var i=deselected.length-1;i>=0;--i){var feature=deselected[i];if(selectedFeatures.getArray().indexOf(feature)!==-1){selectedFeatures.remove(feature);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,
"default")}if(hoveredFeatures.getArray().indexOf(feature)!==-1)hoveredFeatures.remove(feature)}}};
de.novasib.ol.interaction.HoverSelect.prototype.handleHover_=function(mapBrowserEvent){var map=mapBrowserEvent.map;var features=this.hoverOverlay_.getSource().getFeaturesCollection();var hovered=[];var index=0;var searchDepth=0;var pixelFeatures;if(this.featureSearchDepth_!=0){pixelFeatures=map.getFeaturesAtPixel(mapBrowserEvent.pixel,{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});if(pixelFeatures){var len=pixelFeatures.length;searchDepth=Math.abs(this.featureSearchDepth_)%len}else searchDepth=
this.featureSearchDepth_}map.forEachFeatureAtPixel(mapBrowserEvent.pixel,function(feature,layer){var $jscomp$this=this;if(this.filter_(feature,layer)){if(searchDepth!=index){index++;return false}if(!feature.get(de.novasib.ol.FeatureProperties.SELECTED)){if(hovered.indexOf(feature)==-1)hovered.push(feature);var stylename=feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME);this.addFeatureStyleAssociation_(feature,stylename);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,"hover");if(layer&&
layer.get(de.novasib.ol.LayerProperties.GROUP_SELECT)){var extent=map.getView().calculateExtent();var groupSelect=layer.get(de.novasib.ol.LayerProperties.GROUP_SELECT);var propertyName=groupSelect["property"];var value=feature.get(propertyName);if(layer&&layer instanceof ol.layer.Vector)layer.getSource().forEachFeatureInExtent(extent,function(feature){if(feature.get(propertyName)===value){this.addFeatureStyleAssociation_(feature,feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME));feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,
"hover");if(hovered.indexOf(feature)==-1)hovered.push(feature)}},this);var otherLayers=groupSelect["layers"];if(otherLayers&&Array.isArray(otherLayers)&&otherLayers.length>0)map.getLayers().forEach(function(layer){var name=layer.get("name");var title=layer.get("title");if(otherLayers.indexOf(name)!=-1||otherLayers.indexOf(title)!=-1)if(layer instanceof ol.layer.Vector&&layer.getVisible())layer.getSource().forEachFeatureInExtent(extent,function(feature){if(feature.get(propertyName)===value){this.addFeatureStyleAssociation_(feature,
feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME));feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,"hover");if(hovered.indexOf(feature)==-1)hovered.push(feature)}},$jscomp$this)},this)}}}return!this.multi_}.bind(this),{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});var unhovered=[];for(var i=features.getLength()-1;i>=0;--i){var feature=features.item(i);var index$26=hovered.indexOf(feature);if(index$26>-1)hovered.splice(index$26,1);else{unhovered.push(feature);if(features.getArray().indexOf(feature)!==
-1)features.remove(feature);if(!feature.get(de.novasib.ol.FeatureProperties.SELECTED)){var stylename=this.getStyle_(feature);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,stylename);this.removeFeatureStyleAssociation_(feature)}}}if(hovered.length>0)features.extend(hovered);if(hovered.length>0||unhovered.length>0){var lyr,layername;if(hovered.length>0)lyr=this.getLayer(hovered[0]);else if(unhovered.length>0)lyr=this.getLayer(unhovered[0]);if(lyr)layername=lyr.get("name")||lyr.get("title");
this.dispatchEvent(new de.novasib.ol.interaction.HoverSelect.Event(de.novasib.ol.interaction.HoverSelect.EventType_.HOVER,hovered,unhovered,layername,mapBrowserEvent))}return true};
de.novasib.ol.interaction.HoverSelect.prototype.handleHoverNovamap_=function(mapBrowserEvent){var map=mapBrowserEvent.map;var features=this.hoverOverlay_.getSource().getFeaturesCollection();var hovered=[];var index=0;var searchDepth=0;var pixelFeatures;if(this.featureSearchDepth_!=0){pixelFeatures=map.getFeaturesAtPixel(mapBrowserEvent.pixel,{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});if(pixelFeatures){var len=pixelFeatures.length;searchDepth=Math.abs(this.featureSearchDepth_)%
len}else searchDepth=this.featureSearchDepth_}map.forEachFeatureAtPixel(mapBrowserEvent.pixel,function(feature,layer){if(this.filter_(feature,layer)){if(searchDepth!=index){index++;return false}if(!feature.get(de.novasib.ol.FeatureProperties.SELECTED)){if(hovered.indexOf(feature)==-1)hovered.push(feature);var stylename=feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME);this.addFeatureStyleAssociation_(feature,stylename);feature.getStyle()[0].getImage().setScale(1.5);if(layer.get(de.novasib.ol.LayerProperties.GROUP_SELECT)){var extent=
map.getView().calculateExtent();var groupSelect=layer.get(de.novasib.ol.LayerProperties.GROUP_SELECT);var propertyName=groupSelect["property"];var value=feature.get(propertyName);if(layer instanceof ol.layer.Vector)layer.getSource().forEachFeatureInExtent(extent,function(feature){if(feature.get(propertyName)===value){this.addFeatureStyleAssociation_(feature,feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME));feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,"hover");if(hovered.indexOf(feature)==
-1)hovered.push(feature)}},this);var otherLayers=groupSelect["layers"];if(otherLayers&&Array.isArray(otherLayers)&&otherLayers.length>0)map.getLayers().forEach(function(layer){var name=layer.get("name");var title=layer.get("title");if(otherLayers.indexOf(name)!=-1||otherLayers.indexOf(title)!=-1)if(layer instanceof ol.layer.Vector&&layer.getVisible())layer.getSource().forEachFeatureInExtent(extent,function(feature){if(feature.get(propertyName)===value){this.addFeatureStyleAssociation_(feature,feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME));
feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,"hover");if(hovered.indexOf(feature)==-1)hovered.push(feature)}},this)},this)}}}return!this.multi_}.bind(this),{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});var unhovered=[];for(var i=features.getLength()-1;i>=0;--i){var feature=features.item(i);var index_=hovered.indexOf(feature);if(index_>-1)hovered.splice(index_,1);else{unhovered.push(feature);if(features.getArray().indexOf(feature)!==-1)features.remove(feature);if(!feature.get(de.novasib.ol.FeatureProperties.SELECTED)){var stylename=
this.getStyle_(feature);feature.set(de.novasib.ol.FeatureProperties.STYLE_NAME,stylename);this.removeFeatureStyleAssociation_(feature)}}}if(hovered.length>0)features.extend(hovered);if(hovered.length>0||unhovered.length>0){var lyr,layername;if(hovered.length>0)lyr=this.getLayer(hovered[0]);else if(unhovered.length>0)lyr=this.getLayer(unhovered[0]);if(lyr)layername=lyr.get("name")||lyr.get("title");this.dispatchEvent(new de.novasib.ol.interaction.HoverSelect.Event(de.novasib.ol.interaction.HoverSelect.EventType_.HOVER,
hovered,unhovered,layername,mapBrowserEvent))}return true};de.novasib.ol.interaction.HoverSelect.prototype.setHitTolerance=function(hitTolerance){this.hitTolerance_=hitTolerance};
de.novasib.ol.interaction.HoverSelect.prototype.setMap=function(map){var currentMap=this.getMap();var selectedFeatures=this.featureOverlay_.getSource().getFeaturesCollection();var hoveredFeatures=this.hoverOverlay_.getSource().getFeaturesCollection();if(currentMap){selectedFeatures.forEach(currentMap.unskipFeature,currentMap);hoveredFeatures.forEach(currentMap.unskipFeature,currentMap)}ol.interaction.Interaction.prototype.setMap.call(this,map);this.featureOverlay_.setMap(map);this.hoverOverlay_.setMap(map);
if(map){selectedFeatures.forEach(map.skipFeature,map);hoveredFeatures.forEach(map.skipFeature,map)}};
de.novasib.ol.interaction.HoverSelect.getDefaultStyleFunction=function(opt_this){return function(feature,resolution){var $jscomp$this=this;if(feature.getGeometry()){var featureGeometry=feature.getGeometry();var newStyles=[];if(featureGeometry.getType()===ol.geom.GeometryType.LINE_STRING){if(feature.get("HERKUNFT")=="EX")return featureGeometry;var geom;var von=feature.get(de.novasib.ol.FeatureProperties.VST);var nach=feature.get(de.novasib.ol.FeatureProperties.BST);if(von||nach){if(!von&&von!==0)von=
0;if(!nach&&nach!==0)nach=featureGeometry.getLength();geom=de.novasib.ol.geom.getShortenedLineString(feature.getGeometry(),von,nach,feature.get("ALEN")||feature.get("LEN"))}else geom=featureGeometry;var style=this.getStyle_(feature);var fs;if(typeof style==="function")fs=style(resolution);else if(style instanceof ol.style.Style||Array.isArray(style))fs=style;if(fs)ol.array.extend(newStyles,fs);var prevPoint=null;var prevLen=Number.POSITIVE_INFINITY;var strokeColor=feature.get(de.novasib.ol.FeatureProperties.STROKE_COLOR)||
"rgba(192, 0, 0, 0.5)";geom.forEachSegment(function(start,end){var dx=end[0]-start[0];var dy=end[1]-start[1];var rotation=Math.atan2(dy,dx);var pointCoords=[start[0]+dx*.5,start[1]+dy*.5];if(prevPoint){var px1=$jscomp$this.getMap().getPixelFromCoordinate(end);var px2=$jscomp$this.getMap().getPixelFromCoordinate(prevPoint);prevLen=Math.sqrt(Math.pow(px1[0]-px2[0],2)+Math.pow(px1[1]-px2[1],2))}var so=feature.get("RICHTUNG")=="G";rotation=so?Math.PI-rotation:-rotation;if(prevLen>40){newStyles.push(new ol.style.Style({geometry:new ol.geom.Point(pointCoords),
image:new ol.style.Icon({src:de.novasib.ol.style.ARROW_IMG,rotation:rotation,color:"#fff"}),zIndex:30}));prevPoint=pointCoords.slice()}});var color_="#A3BAE9";newStyles.push(new ol.style.Style({geometry:geom,stroke:new ol.style.Stroke({color:color_,width:5,lineCap:"butt"}),zIndex:25}));newStyles.push(new ol.style.Style({geometry:geom,stroke:new ol.style.Stroke({color:strokeColor,width:20,lineCap:"butt"}),zIndex:50}))}else if(featureGeometry.getType()===ol.geom.GeometryType.POINT);return newStyles}}.bind(opt_this)};
de.novasib.ol.interaction.HoverSelect.getHoverStyleFunction=function(opt_this){return function(feature,resolution){var $jscomp$this=this;if(feature.getGeometry()&&feature.getGeometry().getType()===ol.geom.GeometryType.LINE_STRING){var styles=[];var geom=feature.getGeometry();var color_="#A3BAE9";styles.push(new ol.style.Style({stroke:new ol.style.Stroke({color:color_,width:4}),zIndex:50}));var prevPoint=null;var prevLen=Number.POSITIVE_INFINITY;geom.forEachSegment(function(start,end){var dx=end[0]-
start[0];var dy=end[1]-start[1];var rotation=Math.atan2(dy,dx);var pointCoords=[start[0]+dx*.5,start[1]+dy*.5];if(prevPoint){var px1=$jscomp$this.getMap().getPixelFromCoordinate(end);var px2=$jscomp$this.getMap().getPixelFromCoordinate(prevPoint);prevLen=Math.sqrt(Math.pow(px1[0]-px2[0],2)+Math.pow(px1[1]-px2[1],2))}var so=feature.get("RICHTUNG")=="G";rotation=so?Math.PI-rotation:-rotation;if(prevLen>40){styles.push(new ol.style.Style({geometry:new ol.geom.Point(pointCoords),image:new ol.style.Icon({src:de.novasib.ol.style.ARROW_IMG,
rotation:rotation,color:color_}),zIndex:35}));prevPoint=pointCoords.slice()}});return styles}}.bind(opt_this)};de.novasib.ol.interaction.HoverSelect.prototype.addFeature_=function(evt){var map=this.getMap();if(map)map.skipFeature(evt.element)};de.novasib.ol.interaction.HoverSelect.prototype.removeFeature_=function(evt){var map=this.getMap();if(map)map.unskipFeature(evt.element)};
de.novasib.ol.interaction.HoverSelect.prototype.removeFeatureLayerAssociation_=function(feature){var key=ol.getUid(feature);delete this.featureLayerAssociation_[key]};de.novasib.ol.interaction.HoverSelect.prototype.removeFeatureStyleAssociation_=function(feature){var key=ol.getUid(feature);delete this.featureStyleAssociation_[key]};
de.novasib.ol.interaction.HoverSelect.prototype.setStyles=function(style,hoverStyle){if(style)this.featureOverlay_.setStyle(style);else this.featureOverlay_.setStyle(de.novasib.ol.interaction.HoverSelect.getDefaultStyleFunction(this));if(hoverStyle)this.hoverOverlay_.setStyle(hoverStyle);else this.hoverOverlay_.setStyle(de.novasib.ol.interaction.HoverSelect.getHoverStyleFunction(this))};
de.novasib.ol.interaction.HoverSelect.prototype.isWheelEvent_=function(event){return event.type===ol.events.EventType.WHEEL||event.type===ol.events.EventType.MOUSEWHEEL};de.novasib.ol.interaction.HoverSelect.Event=function(type,selected,deselected,layername,mapBrowserEvent){ol.events.Event.call(this,type);this.selected=selected;this.deselected=deselected;this.layerName=layername;this.mapBrowserEvent=mapBrowserEvent};ol.inherits(de.novasib.ol.interaction.HoverSelect.Event,ol.events.Event);
de.novasib.ol.interaction.HoverSelect.EventType_={SELECT:"select",HOVER:"hover"};goog.provide("de.novasib.ol.interaction.Icon");goog.require("ol");goog.require("ol.Collection");goog.require("ol.Feature");goog.require("ol.MapBrowserEventType");goog.require("ol.MapBrowserPointerEvent");goog.require("ol.coordinate");goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.events.EventType");goog.require("ol.events.condition");goog.require("ol.extent");goog.require("ol.geom.GeometryType");goog.require("ol.geom.Point");goog.require("ol.interaction.Pointer");goog.require("ol.layer.Vector");
goog.require("ol.source.Vector");goog.require("ol.source.VectorEventType");goog.require("ol.structs.RBush");goog.require("ol.style.Circle");goog.require("ol.style.Fill");goog.require("ol.style.Stroke");goog.require("ol.style.Style");
de.novasib.ol.interaction.Icon=function(options){ol.interaction.Pointer.call(this,{handleDownEvent:de.novasib.ol.interaction.Icon.handleDownEvent_,handleDragEvent:de.novasib.ol.interaction.Icon.handleDragEvent_,handleEvent:de.novasib.ol.interaction.Icon.handleEvent,handleUpEvent:de.novasib.ol.interaction.Icon.handleUpEvent_});this.condition_=options.condition?options.condition:ol.events.condition.primaryAction;this.rotateCondition_=options.rotateCondition?options.rotateCondition:ol.events.condition.shiftKeyOnly;
this.downPx_=null;this.down_=false;this.shouldHandle_=false;this.squaredClickTolerance_=options.clickTolerance?options.clickTolerance*options.clickTolerance:36;this.stopClick_=options.stopClick||false;this.vertexFeature_=null;this.sketchFeature_=null;this.snappedFeature_=null;this.geometryName_=options.geometryName;this.lastPixel_=[0,0];this.ignoreNextSingleClick_=false;this.modified_=false;this.rBush_=new ol.structs.RBush;this.pixelTolerance_=options.pixelTolerance!==undefined?options.pixelTolerance:
0;this.snappedToVertex_=false;this.changingFeature_=false;this.featureStyle_=options.featureStyle?options.featureStyle:de.novasib.ol.interaction.Icon.getDefaultFeatureStyleFunction();this.dragSegments_=[];this.overlay_=new ol.layer.Vector({source:new ol.source.Vector({useSpatialIndex:false,wrapX:options.wrapX}),style:options.style?options.style:de.novasib.ol.interaction.Icon.getDefaultStyleFunction(),updateWhileAnimating:true,updateWhileInteracting:true,zIndex:1E5});this.source_=null;if(options.source){this.source_=
options.source;ol.events.listen(this.source_,ol.source.VectorEventType.ADDFEATURE,this.handleSourceAdd_,this);ol.events.listen(this.source_,ol.source.VectorEventType.REMOVEFEATURE,this.handleSourceRemove_,this)}else throw new Error("The icon interaction requires a source");this.switchAfterAction_=false;this.mode_=options.mode?de.novasib.ol.interaction.Icon.getMode_(options.mode):de.novasib.ol.interaction.Icon.Mode.DRAW;ol.events.listen(this,ol.Object.getChangeEventType(ol.interaction.Property.ACTIVE),
this.updateState_,this);this.uniqueCandidate=null};ol.inherits(de.novasib.ol.interaction.Icon,ol.interaction.Pointer);de.novasib.ol.interaction.Icon.ONE_DEGREE_IN_RAD=Math.PI*2/360;de.novasib.ol.interaction.Icon.TEN_DEGREES_IN_RAD=de.novasib.ol.interaction.Icon.ONE_DEGREE_IN_RAD*10;
de.novasib.ol.interaction.Icon.prototype.addFeature_=function(feature){var geometry=feature.getGeometry();if(geometry&&geometry.getType()===ol.geom.GeometryType.POINT)this.writePointGeometry_(feature,geometry);var map=this.getMap();if(map&&map.isRendered()&&this.getActive())this.handlePointerAtPixel_(this.lastPixel_,map);ol.events.listen(feature,ol.events.EventType.CHANGE,this.handleFeatureChange_,this)};
de.novasib.ol.interaction.Icon.prototype.willModifyFeatures_=function(evt){if(!this.modified_){this.modified_=true;var features=this.source_?this.source_.getFeatures():[];this.dispatchEvent(new de.novasib.ol.interaction.Icon.Event(de.novasib.ol.interaction.IconEventType.MODIFYSTART,features))}};
de.novasib.ol.interaction.Icon.prototype.removeFeature_=function(feature){this.removeFeatureSegmentData_(feature);if(this.vertexFeature_&&this.source_.getFeatures().length===0){this.overlay_.getSource().removeFeature(this.vertexFeature_);this.vertexFeature_=null}ol.events.unlisten(feature,ol.events.EventType.CHANGE,this.handleFeatureChange_,this)};
de.novasib.ol.interaction.Icon.prototype.removeFeatureSegmentData_=function(feature){var rBush=this.rBush_;var nodesToRemove=[];rBush.forEach(function(node){if(feature===node.feature)nodesToRemove.push(node)});for(var i=nodesToRemove.length-1;i>=0;--i)rBush.remove(nodesToRemove[i])};
de.novasib.ol.interaction.Icon.prototype.setActive=function(active){if(this.getActive()!=active){if(this.vertexFeature_&&!active){this.overlay_.getSource().removeFeature(this.vertexFeature_);this.vertexFeature_=null;if(this.uniqueCandidate){this.overlay_.getSource().removeFeature(this.uniqueCandidate);this.uniqueCandidate=null}}ol.interaction.Pointer.prototype.setActive.call(this,active)}};
de.novasib.ol.interaction.Icon.prototype.setMap=function(map){ol.interaction.Pointer.prototype.setMap.call(this,map);this.updateState_()};
de.novasib.ol.interaction.Icon.prototype.startDrawing_=function(coords){var geometry=new ol.geom.Point(coords);this.sketchFeature_=new ol.Feature;if(this.geometryName_)this.sketchFeature_.setGeometryName(this.geometryName_);this.sketchFeature_.setGeometry(geometry);this.updateSketchFeatures_();this.dispatchEvent(new de.novasib.ol.interaction.Icon.Event(de.novasib.ol.interaction.IconEventType.DRAWSTART,[this.sketchFeature_]))};
de.novasib.ol.interaction.Icon.prototype.finishDrawing=function(){var sketchFeature=this.abortDrawing_();if(this.featureStyle_)sketchFeature.setStyle(this.featureStyle_);this.dispatchEvent(new de.novasib.ol.interaction.Icon.Event(de.novasib.ol.interaction.IconEventType.DRAWEND,[sketchFeature]));if(this.source_)this.source_.addFeature(sketchFeature)};
de.novasib.ol.interaction.Icon.prototype.abortDrawing_=function(){var sketchFeature=this.sketchFeature_;if(sketchFeature){this.sketchFeature_=null;this.vertexFeature_=null;this.overlay_.getSource().clear(true)}return sketchFeature};
de.novasib.ol.interaction.Icon.prototype.updateSketchFeatures_=function(){var sketchFeatures=[];if(this.sketchFeature_)sketchFeatures.push(this.sketchFeature_);if(this.vertexFeature_)sketchFeatures.push(this.vertexFeature_);var overlaySource=this.overlay_.getSource();overlaySource.clear(true);overlaySource.addFeatures(sketchFeatures)};de.novasib.ol.interaction.Icon.prototype.handleSourceAdd_=function(event){if(event.feature)this.addFeature_(event.feature)};
de.novasib.ol.interaction.Icon.prototype.handleSourceRemove_=function(event){if(event.feature)this.removeFeature_(event.feature)};de.novasib.ol.interaction.Icon.prototype.handleFeatureChange_=function(evt){if(!this.changingFeature_){var feature=evt.target;this.removeFeature_(feature);this.addFeature_(feature)}};de.novasib.ol.interaction.Icon.prototype.handleFeatureRemove_=function(evt){var feature=evt.element;this.removeFeature_(feature)};
de.novasib.ol.interaction.Icon.prototype.writePointGeometry_=function(feature,geometry){var coordinates=geometry.getCoordinates();var segmentData={feature:feature,geometry:geometry,segment:[coordinates,coordinates]};this.rBush_.insert(geometry.getExtent(),segmentData)};
de.novasib.ol.interaction.Icon.prototype.createOrUpdateVertexFeature_=function(coordinates){var vertexFeature=this.vertexFeature_;if(!vertexFeature){vertexFeature=new ol.Feature(new ol.geom.Point(coordinates));this.vertexFeature_=vertexFeature;this.overlay_.getSource().addFeature(vertexFeature)}else{var geometry=vertexFeature.getGeometry();geometry.setCoordinates(coordinates)}return vertexFeature};de.novasib.ol.interaction.Icon.compareIndexes_=function(a,b){return a.index-b.index};
de.novasib.ol.interaction.Icon.handleDownEvent_=function(evt){if(!this.condition_(evt))return false;this.down_=true;var ret=true;if(this.mode_===de.novasib.ol.interaction.Icon.Mode.DRAW){this.downPx_=evt.pixel;ret=true}else if(this.mode_===de.novasib.ol.interaction.Icon.Mode.MODIFY){this.handlePointerAtPixel_(evt.pixel,evt.map);this.dragSegments_.length=0;this.modified_=false;var vertexFeature=this.vertexFeature_;if(vertexFeature){var geometry=vertexFeature.getGeometry();var vertex=geometry.getCoordinates();
var vertexExtent=ol.extent.boundingExtent([vertex]);var segmentDataMatches=this.rBush_.getInExtent(vertexExtent);var componentSegments={};segmentDataMatches.sort(de.novasib.ol.interaction.Icon.compareIndexes_);for(var i=0,ii=segmentDataMatches.length;i<ii;++i){var segmentDataMatch=segmentDataMatches[i];var segment=segmentDataMatch.segment;var uid=ol.getUid(segmentDataMatch.feature);var depth=segmentDataMatch.depth;if(depth)uid+="-"+depth.join("-");if(!componentSegments[uid])componentSegments[uid]=
new Array(2);if(ol.coordinate.equals(segment[0],vertex)&&!componentSegments[uid][0]){this.dragSegments_.push([segmentDataMatch,0]);componentSegments[uid][0]=segmentDataMatch}else if(ol.coordinate.equals(segment[1],vertex)&&!componentSegments[uid][1]){this.dragSegments_.push([segmentDataMatch,1]);componentSegments[uid][1]=segmentDataMatch}}}ret=this.vertexFeature_!=null?true:false}return ret};
de.novasib.ol.interaction.Icon.handleDragEvent_=function(evt){if(this.mode_===de.novasib.ol.interaction.Icon.Mode.MODIFY){this.ignoreNextSingleClick_=false;this.willModifyFeatures_(evt);var vertex=evt.coordinate;for(var i=0,ii=this.dragSegments_.length;i<ii;++i){var dragSegment=this.dragSegments_[i];var segmentData=dragSegment[0];var geometry=segmentData.geometry;var coordinates=undefined;var segment=segmentData.segment;var index=dragSegment[1];while(vertex.length<geometry.getStride())vertex.push(segment[index][vertex.length]);
coordinates=vertex;segment[0]=segment[1]=vertex;if(coordinates)this.setGeometryCoordinates_(geometry,coordinates)}this.createOrUpdateVertexFeature_(vertex)}};
de.novasib.ol.interaction.Icon.handleUpEvent_=function(evt){this.down_=false;if(this.mode_===de.novasib.ol.interaction.Icon.Mode.DRAW){this.handlePointerMove_(evt);if(this.shouldHandle_){this.startDrawing_(evt.coordinate);this.finishDrawing();if(this.switchAfterAction_){this.switchAfterAction_=false;this.setMode(de.novasib.ol.interaction.Icon.Mode.MODIFY)}}if(this.stopClick_)evt.stopPropagation()}else if(this.mode_===de.novasib.ol.interaction.Icon.Mode.MODIFY){var segmentData;for(var i=this.dragSegments_.length-
1;i>=0;--i){segmentData=this.dragSegments_[i][0];try{this.rBush_.remove(segmentData)}catch(ignore){}this.rBush_.insert(ol.extent.boundingExtent(segmentData.segment),segmentData)}if(this.modified_){var features=this.source_?this.source_.getFeatures():[];this.dispatchEvent(new de.novasib.ol.interaction.Icon.Event(de.novasib.ol.interaction.IconEventType.MODIFYEND,features));this.modified_=false}}return true};
de.novasib.ol.interaction.Icon.handleEvent=function(mapBrowserEvent){var pass=true;if(!mapBrowserEvent.map.getView().getInteracting())if(mapBrowserEvent.type==ol.MapBrowserEventType.POINTERMOVE)this.handlePointerMove_(mapBrowserEvent);else if(mapBrowserEvent.type===ol.events.EventType.WHEEL||mapBrowserEvent.type===ol.events.EventType.MOUSEWHEEL)if(this.mode_===de.novasib.ol.interaction.Icon.Mode.MODIFY&&this.down_&&this.snappedToVertex_){this.dispatchEvent(new de.novasib.ol.interaction.Icon.Event(de.novasib.ol.interaction.IconEventType.ROTATESTART,
[this.snappedFeature_]));this.handleMouseWheel_(mapBrowserEvent);pass=false}if(mapBrowserEvent.type==ol.MapBrowserEventType.SINGLECLICK)this.ignoreNextSingleClick_=false;else if(mapBrowserEvent.type===ol.MapBrowserEventType.DBLCLICK)pass=false;return ol.interaction.Pointer.handleEvent.call(this,mapBrowserEvent)&&pass};de.novasib.ol.interaction.Icon.prototype.shouldStopEvent=function(handled){if(this.mode_===de.novasib.ol.interaction.Icon.Mode.DRAW)return false;else return handled};
de.novasib.ol.interaction.Icon.prototype.handlePointerMove_=function(evt){if(this.mode_===de.novasib.ol.interaction.Icon.Mode.DRAW){if(this.downPx_){var downPx=this.downPx_;var clickPx=evt.pixel;var dx=downPx[0]-clickPx[0];var dy=downPx[1]-clickPx[1];var squaredDistance=dx*dx+dy*dy;this.shouldHandle_=squaredDistance<=this.squaredClickTolerance_}var map$27=evt.map;var coord=map$27.getCoordinateFromPixel(evt.pixel);this.createOrUpdateVertexFeature_(coord)}else if(this.mode_===de.novasib.ol.interaction.Icon.Mode.MODIFY&&
!this.handlingDownUpSequence){this.lastPixel_=evt.pixel;this.handlePointerAtPixel_(evt.pixel,evt.map)}return true};
de.novasib.ol.interaction.Icon.prototype.handlePointerAtPixel_=function(pixel,map){var pixelCoordinate=map.getCoordinateFromPixel(pixel);var sortByDistance=function(a,b){return ol.coordinate.squaredDistanceToSegment(pixelCoordinate,a.segment)-ol.coordinate.squaredDistanceToSegment(pixelCoordinate,b.segment)};var box=ol.extent.buffer(ol.extent.createOrUpdateFromCoordinate(pixelCoordinate),map.getView().getResolution()*this.pixelTolerance_);var rBush=this.rBush_;var nodes=rBush.getInExtent(box);if(nodes.length>
0){var node;if(this.uniqueCandidate)for(var i=0;i<nodes.length;++i){var n=nodes[i];if(n.feature==this.uniqueCandidate){node=n;break}}else{nodes.sort(sortByDistance);node=nodes[0]}if(node){var closestSegment=node.segment;var vertex=ol.coordinate.closestOnSegment(pixelCoordinate,node.segment);var vertexPixel=map.getPixelFromCoordinate(vertex);var dist=ol.coordinate.distance(pixel,vertexPixel);if(dist<=this.pixelTolerance_){var pixel1=map.getPixelFromCoordinate(closestSegment[0]);var pixel2=map.getPixelFromCoordinate(closestSegment[1]);
var squaredDist1=ol.coordinate.squaredDistance(vertexPixel,pixel1);var squaredDist2=ol.coordinate.squaredDistance(vertexPixel,pixel2);dist=Math.sqrt(Math.min(squaredDist1,squaredDist2));this.snappedToVertex_=dist<=this.pixelTolerance_;if(this.snappedToVertex_){vertex=squaredDist1>squaredDist2?closestSegment[1]:closestSegment[0];this.snappedFeature_=node.feature}this.createOrUpdateVertexFeature_(vertex);return}}}if(this.vertexFeature_){this.overlay_.getSource().removeFeature(this.vertexFeature_);this.vertexFeature_=
null}};de.novasib.ol.interaction.Icon.prototype.handleMouseWheel_=function(evt){if(this.rotateCondition_(evt)){evt.preventDefault();var wheelEvent=evt.originalEvent;var delta;if(evt.type===ol.events.EventType.WHEEL)delta=wheelEvent.deltaY;else if(evt.type===ol.events.EventType.MOUSEWHEEL)delta=-wheelEvent.wheelDeltaY;var sign=1;if(delta<0)sign=-1;if(sign)this.rotateFeature_(sign)}};
de.novasib.ol.interaction.Icon.prototype.rotateFeature_=function(sign){if(this.snappedFeature_){var signedDegrees=de.novasib.ol.interaction.Icon.TEN_DEGREES_IN_RAD*sign;var style=this.snappedFeature_.getStyle();if(style){if(style.getImage()){var oldRotation=style.getImage().getRotation();var newRotation=oldRotation+signedDegrees;style.getImage().setRotation(newRotation)}if(style.getText()){var oldRotation$28=style.getText().getRotation();var newRotation$29=oldRotation$28+signedDegrees;style.getText().setRotation(newRotation$29)}this.snappedFeature_.setStyle(style);
this.dispatchEvent(new de.novasib.ol.interaction.Icon.Event(de.novasib.ol.interaction.IconEventType.ROTATEEND,[this.snappedFeature_]))}}};de.novasib.ol.interaction.Icon.prototype.setGeometryCoordinates_=function(geometry,coordinates){this.changingFeature_=true;geometry.setCoordinates(coordinates);this.changingFeature_=false};de.novasib.ol.interaction.Icon.getDefaultStyleFunction=function(){var style=ol.style.Style.createDefaultEditing()[ol.geom.GeometryType.POINT];return function(feature,resolution){return style}};
de.novasib.ol.interaction.Icon.getDefaultFeatureStyleFunction=function(){return function(resolution){return new ol.style.Style({image:new ol.style.Circle({fill:new ol.style.Fill({color:"rgba(0, 200, 200, 0.75)"}),stroke:new ol.style.Stroke({color:"rgba(200, 200, 0, 0.75)",width:3}),radius:15})})}};de.novasib.ol.interaction.Icon.prototype.updateState_=function(){var map=this.getMap();var active=this.getActive();if(!map||!active)this.abortDrawing_();this.overlay_.setMap(active?map:null)};
de.novasib.ol.interaction.Icon.prototype.setMode=function(mode){var newMode_=de.novasib.ol.interaction.Icon.getMode_(mode);this.mode_=newMode_;if(newMode_===de.novasib.ol.interaction.Icon.Mode.SWITCH){this.switchAfterAction_=true;this.mode_=de.novasib.ol.interaction.Icon.Mode.DRAW}};de.novasib.ol.interaction.Icon.prototype.drawIconAt=function(coords){if(this.getActive()&&coords){this.startDrawing_(coords);this.finishDrawing()}};
de.novasib.ol.interaction.Icon.prototype.setUniqueCandidate=function(feature){this.uniqueCandidate=feature};de.novasib.ol.interaction.Icon.Mode={DRAW:"draw",MODIFY:"modify",SWITCH:"switch"};de.novasib.ol.interaction.Icon.getMode_=function(mode){for(var key in de.novasib.ol.interaction.Icon.Mode)if(de.novasib.ol.interaction.Icon.Mode[key]===mode)return de.novasib.ol.interaction.Icon.Mode[key];console.log("Mode '"+mode+"' not supported for this interaction. Using mode 'draw'");return de.novasib.ol.interaction.Icon.Mode.DRAW};
de.novasib.ol.interaction.Icon.Event=function(type,features){ol.events.Event.call(this,type);this.features=features};ol.inherits(de.novasib.ol.interaction.Icon.Event,ol.events.Event);goog.provide("de.novasib.ol.interaction.IconEventType");de.novasib.ol.interaction.IconEventType={DRAWSTART:"drawstart",DRAWEND:"drawend",MODIFYSTART:"modifystart",MODIFYEND:"modifyend",ROTATESTART:"rotatestart",ROTATEEND:"rotateend"};goog.provide("de.novasib.ol.interaction.Measure");goog.require("de.novasib.ol");goog.require("de.novasib.ol.style");goog.require("ol");goog.require("ol.events");goog.require("ol.geom.LineString");goog.require("ol.geom.Point");goog.require("ol.interaction.Pointer");goog.require("ol.layer.Vector");goog.require("ol.source.Vector");goog.require("ol.style.Fill");goog.require("ol.style.RegularShape");goog.require("ol.style.Stroke");goog.require("ol.style.Style");goog.require("ol.style.Text");
de.novasib.ol.interaction.Measure=function(options){ol.interaction.Pointer.call(this,{handleDownEvent:de.novasib.ol.interaction.Measure.handleDownEvent_,handleEvent:de.novasib.ol.interaction.Measure.handleEvent,handleUpEvent:de.novasib.ol.interaction.Measure.handleUpEvent_});this.shouldHandle_=false;this.downPx_=null;this.snapTolerance_=options.snapTolerance?options.snapTolerance:12;var type=options.type;if(type!==ol.geom.GeometryType.LINE_STRING&&type!=ol.geom.GeometryType.POLYGON)throw new Error("Measure interaction only supports 'LineString' or 'Polygon' as type!");
this.type_=type;this.mode_=de.novasib.ol.interaction.Measure.getMode_(this.type_);this.stopClick_=!!options.stopClick;this.minPoints_=options.minPoints?options.minPoints:this.mode_===de.novasib.ol.interaction.Measure.Mode_.POLYGON?3:2;this.maxPoints_=options.maxPoints?options.maxPoints:Infinity;this.finishCondition_=options.finishCondition?options.finishCondition:ol.functions.TRUE;var geometryFunction=options.geometryFunction;if(!geometryFunction)geometryFunction=this.getGeometryFunction_();this.geometryFunction_=
geometryFunction;this.finishCoordinate_=null;this.sketchFeature_=null;this.sketchPoint_=null;this.sketchCoords_=null;this.sketchLine_=null;this.sketchLineCoords_=null;this.squaredClickTolerance_=options.clickTolerance?options.clickTolerance*options.clickTolerance:36;this.sketchOverlay_=new ol.layer.Vector({source:new ol.source.Vector({useSpatialIndex:false,wrapX:false}),style:options.style?options.style:this.getDefaultStyleFunction_()});this.overlay_=new ol.layer.Vector({source:new ol.source.Vector({useSpatialIndex:false,
wrapX:false}),style:this.getDefaultStyleFunction_()});this.condition_=options.condition?options.condition:ol.events.condition.noModifierKeys;ol.events.listen(this,ol.Object.getChangeEventType(ol.interaction.Property.ACTIVE),this.updateState_,this);this.strokeColor_="#666666";this.fillColor_="#FFFFFF"};ol.inherits(de.novasib.ol.interaction.Measure,ol.interaction.Pointer);de.novasib.ol.interaction.Measure.prototype.setMap=function(map){ol.interaction.Pointer.prototype.setMap.call(this,map);this.updateState_()};
de.novasib.ol.interaction.Measure.handleEvent=function(event){var pass=true;if(event.type===ol.MapBrowserEventType.POINTERMOVE)pass=this.handlePointerMove_(event);else if(event.type===ol.MapBrowserEventType.DBLCLICK)pass=false;return ol.interaction.Pointer.handleEvent.call(this,event)&&pass};de.novasib.ol.interaction.Measure.handleDownEvent_=function(event){this.shouldHandle_=true;if(this.condition_(event)){this.downPx_=event.pixel;return true}else return false};
de.novasib.ol.interaction.Measure.handleUpEvent_=function(event){var pass=true;this.handlePointerMove_(event);if(this.shouldHandle_){if(!this.finishCoordinate_){this.overlay_.getSource().clear(true);this.startDrawing_(event)}else if(this.atFinish_(event)){if(this.finishCondition_(event))this.finishDrawing()}else this.addToDrawing_(event);pass=false}if(!pass&&this.stopClick_)event.stopPropagation();return pass};
de.novasib.ol.interaction.Measure.prototype.handlePointerMove_=function(event){if(this.downPx_&&this.shouldHandle_){var downPx=this.downPx_;var clickPx=event.pixel;var dx=downPx[0]-clickPx[0];var dy=downPx[1]-clickPx[1];var squaredDistance=dx*dx+dy*dy;this.shouldHandle_=squaredDistance<=this.squaredClickTolerance_}if(this.finishCoordinate_)this.modifyDrawing_(event);else this.createOrUpdateSketchPoint_(event);return true};
de.novasib.ol.interaction.Measure.prototype.atFinish_=function(event){var at=false;if(this.sketchFeature_){var potentiallyDone=false;var potentiallyFinishCoordinates=[this.finishCoordinate_];if(this.mode_===de.novasib.ol.interaction.Measure.Mode_.LINE_STRING)potentiallyDone=this.sketchCoords_.length>this.minPoints_;else if(this.mode_===de.novasib.ol.interaction.Measure.Mode_.POLYGON){potentiallyDone=this.sketchCoords_[0].length>this.minPoints_;potentiallyFinishCoordinates=[this.sketchCoords_[0][0],
this.sketchCoords_[0][this.sketchCoords_[0].length-2]]}if(potentiallyDone){var map$30=event.map;for(var i=0;i<potentiallyFinishCoordinates.length;++i){var finishCoordinate=potentiallyFinishCoordinates[i];var finishPixel=map$30.getPixelFromCoordinate(finishCoordinate);var pixel=event.pixel;var dx=pixel[0]-finishPixel[0];var dy=pixel[1]-finishPixel[1];var snapTolerance=this.snapTolerance_;at=Math.sqrt(dx*dx+dy*dy)<=snapTolerance;if(at){this.finishCoordinate_=finishCoordinate;break}}}}return at};
de.novasib.ol.interaction.Measure.prototype.createOrUpdateSketchPoint_=function(event){var coordinates=event.coordinate.slice();if(!this.sketchPoint_){this.sketchPoint_=new ol.Feature(new ol.geom.Point(coordinates));this.updateSketchFeatures_()}else{var sketchPointGeom=this.sketchPoint_.getGeometry();sketchPointGeom.setCoordinates(coordinates)}};
de.novasib.ol.interaction.Measure.prototype.startDrawing_=function(event){var start=event.coordinate;this.finishCoordinate_=start;if(this.mode_===de.novasib.ol.interaction.Measure.Mode_.POLYGON){this.sketchCoords_=[[start.slice(),start.slice()]];this.sketchLineCoords_=this.sketchCoords_[0]}else this.sketchCoords_=[start.slice(),start.slice()];if(this.sketchLineCoords_)this.sketchLine_=new ol.Feature(new ol.geom.LineString(this.sketchLineCoords_));var geometry=this.geometryFunction_(this.sketchCoords_);
this.sketchFeature_=new ol.Feature;this.sketchFeature_.setGeometry(geometry);this.updateSketchFeatures_()};
de.novasib.ol.interaction.Measure.prototype.modifyDrawing_=function(event){var coordinate=event.coordinate;var geometry=this.sketchFeature_.getGeometry();var coordinates,last;if(this.mode_===de.novasib.ol.interaction.Measure.Mode_.POLYGON){coordinates=this.sketchCoords_[0];last=coordinates[coordinates.length-1];if(this.atFinish_(event))coordinate=this.finishCoordinate_.slice()}else{coordinates=this.sketchCoords_;last=coordinates[coordinates.length-1]}last[0]=coordinate[0];last[1]=coordinate[1];this.geometryFunction_(this.sketchCoords_,
geometry);if(this.sketchPoint_){var sketchPointGeom=this.sketchPoint_.getGeometry();sketchPointGeom.setCoordinates(coordinate)}var sketchLineGeom;if(geometry instanceof ol.geom.Polygon&&this.mode_!==de.novasib.ol.interaction.Measure.Mode_.POLYGON){if(!this.sketchLine_)this.sketchLine_=new ol.Feature(new ol.geom.LineString(null));var ring=geometry.getLinearRing(0);sketchLineGeom=this.sketchLine_.getGeometry();sketchLineGeom.setFlatCoordinates(ring.getLayout(),ring.getFlatCoordinates())}else if(this.sketchLineCoords_){sketchLineGeom=
this.sketchLine_.getGeometry();sketchLineGeom.setCoordinates(this.sketchLineCoords_)}this.updateSketchFeatures_()};
de.novasib.ol.interaction.Measure.prototype.addToDrawing_=function(event){var coordinate=event.coordinate;var geometry=this.sketchFeature_.getGeometry();var done;var coordinates;if(this.mode_===de.novasib.ol.interaction.Measure.Mode_.LINE_STRING){this.finishCoordinate_=coordinate.slice();coordinates=this.sketchCoords_;if(coordinates.length>=this.maxPoints_)done=true;coordinates.push(coordinate.slice());this.geometryFunction_(coordinates,geometry)}else if(this.mode_===de.novasib.ol.interaction.Measure.Mode_.POLYGON){coordinates=
this.sketchCoords_[0];if(coordinates.length>=this.maxPoints_)done=true;coordinates.push(coordinate.slice());if(done)this.finishCoordinate_=coordinates[0];this.geometryFunction_(this.sketchCoords_,geometry)}this.updateSketchFeatures_();if(done)this.finishDrawing()};
de.novasib.ol.interaction.Measure.prototype.removeLastPoint=function(){if(!this.sketchFeature_)return;var geometry=this.sketchFeature_.getGeometry();var coordinates,sketchLineGeom;if(this.mode_===de.novasib.ol.interaction.Measure.Mode_.LINE_STRING){coordinates=this.sketchCoords_;coordinates.splice(-2,1);this.geometryFunction_(coordinates,geometry);if(coordinates.length>=2)this.finishCoordinate_=coordinates[coordinates.length-2].slice()}else if(this.mode_===de.novasib.ol.interaction.Measure.Mode_.POLYGON){coordinates=
this.sketchCoords_[0];coordinates.splice(-2,1);sketchLineGeom=this.sketchLine_.getGeometry();sketchLineGeom.setCoordinates(coordinates);this.geometryFunction_(this.sketchCoords_,geometry)}if(coordinates.length===0)this.finishCoordinate_=null;this.updateSketchFeatures_()};
de.novasib.ol.interaction.Measure.prototype.finishDrawing=function(){var sketchFeature=this.abortDrawing_();var coordinates=this.sketchCoords_;var geometry=sketchFeature.getGeometry();if(this.mode_===de.novasib.ol.interaction.Measure.Mode_.LINE_STRING){coordinates.pop();this.geometryFunction_(coordinates,geometry)}else if(this.mode_===de.novasib.ol.interaction.Measure.Mode_.POLYGON){coordinates[0].pop();this.geometryFunction_(coordinates,geometry);coordinates=geometry.getCoordinates()}this.overlay_.getSource().addFeature(sketchFeature)};
de.novasib.ol.interaction.Measure.prototype.abortDrawing_=function(){this.finishCoordinate_=null;var sketchFeature=this.sketchFeature_;if(sketchFeature){this.sketchFeature_=null;this.sketchPoint_=null;this.sketchLine_=null;this.sketchOverlay_.getSource().clear(true)}return sketchFeature};
de.novasib.ol.interaction.Measure.prototype.extend=function(feature){var geometry=feature.getGeometry();var lineString=geometry;this.sketchFeature_=feature;this.sketchCoords_=lineString.getCoordinates();var last=this.sketchCoords_[this.sketchCoords_.length-1];this.finishCoordinate_=last.slice();this.sketchCoords_.push(last.slice());this.updateSketchFeatures_()};de.novasib.ol.interaction.Measure.prototype.shouldStopEvent=ol.functions.FALSE;
de.novasib.ol.interaction.Measure.prototype.updateSketchFeatures_=function(){var sketchFeatures=[];if(this.sketchFeature_)sketchFeatures.push(this.sketchFeature_);if(this.sketchLine_)sketchFeatures.push(this.sketchLine_);if(this.sketchPoint_)sketchFeatures.push(this.sketchPoint_);var overlaySource=this.sketchOverlay_.getSource();overlaySource.clear(true);overlaySource.addFeatures(sketchFeatures)};
de.novasib.ol.interaction.Measure.prototype.updateState_=function(){var map=this.getMap();var active=this.getActive();if(!map||!active){this.abortDrawing_();this.overlay_.getSource().clear(true)}this.sketchOverlay_.setMap(active?map:null);this.overlay_.setMap(active?map:null)};de.novasib.ol.interaction.Measure.prototype.setColors=function(stroke,fill){if(stroke)this.strokeColor_=stroke;if(fill)this.fillColor_=fill;this.overlay_.getSource().refresh();this.sketchOverlay_.getSource().refresh()};
de.novasib.ol.interaction.Measure.prototype.setType=function(type){if(this.type_===type)return;if(type!==ol.geom.GeometryType.LINE_STRING&&type!=ol.geom.GeometryType.POLYGON)throw new Error("Measure interaction only supports 'LineString' or 'Polygon' as type!");this.abortDrawing_();this.sketchCoords_=null;this.sketchLineCoords_=null;this.overlay_.getSource().clear(true);this.type_=type;this.mode_=de.novasib.ol.interaction.Measure.getMode_(type);this.geometryFunction_=this.getGeometryFunction_()};
de.novasib.ol.interaction.Measure.prototype.getGeometryFunction_=function(){var Constructor;var mode=this.mode_;if(mode===de.novasib.ol.interaction.Measure.Mode_.LINE_STRING)Constructor=ol.geom.LineString;else if(mode===de.novasib.ol.interaction.Measure.Mode_.POLYGON)Constructor=ol.geom.Polygon;return function(coordinates,opt_geometry){var geometry=opt_geometry;if(geometry)if(mode===de.novasib.ol.interaction.Measure.Mode_.POLYGON)if(coordinates[0].length)geometry.setCoordinates([coordinates[0].concat([coordinates[0][0]])]);
else geometry.setCoordinates([]);else geometry.setCoordinates(coordinates);else geometry=new Constructor(coordinates);return geometry}};de.novasib.ol.interaction.Measure.getMode_=function(type){var mode;if(type===ol.geom.GeometryType.LINE_STRING)mode=de.novasib.ol.interaction.Measure.Mode_.LINE_STRING;else if(type===ol.geom.GeometryType.POLYGON)mode=de.novasib.ol.interaction.Measure.Mode_.POLYGON;return mode};de.novasib.ol.interaction.Measure.Mode_={LINE_STRING:"LineString",POLYGON:"Polygon"};
de.novasib.ol.interaction.Measure.prototype.getDefaultStyleFunction_=function(){return function(feature,resolution){var type=feature.getGeometry().getType();if(type===ol.geom.GeometryType.POINT)return new ol.style.Style({image:new ol.style.RegularShape({radius:4,points:4,angle:de.novasib.ol.degToRad(45),stroke:new ol.style.Stroke({color:"#333333",width:1}),fill:new ol.style.Fill({color:"white"})})});else if(type===ol.geom.GeometryType.LINE_STRING){var ret=[];ret.push(new ol.style.Style({stroke:new ol.style.Stroke({color:this.strokeColor_,
width:3,lineDash:[10,10]})}));if(this.mode_===de.novasib.ol.interaction.Measure.Mode_.LINE_STRING){var text_="";var geom=feature.getGeometry();var len=geom.getLength();if(len>=1E3)text_="L\u00e4nge: "+de.novasib.ol.round(len/1E3,3).toLocaleString()+" km";else text_="L\u00e4nge: "+de.novasib.ol.round(len,3).toLocaleString()+" m";ret.push(new ol.style.Style({geometry:function(feature){var geom=feature.getGeometry();var coords=geom.getCoordinates();return new ol.geom.Point(coords[coords.length-1])},
text:new ol.style.Text({text:text_,textBaseline:"top",offsetX:10,offsetY:-20,font:"10pt sans-serif",fill:new ol.style.Fill({color:"black"}),stroke:new ol.style.Stroke({color:"white",width:3})})}))}return ret}else if(type===ol.geom.GeometryType.POLYGON){var geom$31=feature.getGeometry();var outerRingGeom=new ol.geom.LineString(geom$31.getLinearRing(0).getCoordinates());var area=geom$31.getArea();var perimeter=outerRingGeom.getLength();var areaText,perimeterText,text_;if(perimeter>=1E3)perimeterText=
"Umfang: "+de.novasib.ol.round(perimeter/1E3,3).toLocaleString()+" km";else perimeterText="Umfang: "+de.novasib.ol.round(perimeter,3).toLocaleString()+" m";if(area>=1E6)areaText="Fl\u00e4che: "+de.novasib.ol.round(area/1E6,3).toLocaleString()+" km\u00b2";else areaText="Fl\u00e4che: "+de.novasib.ol.round(area,3).toLocaleString()+" m\u00b2";text_=areaText+"\n"+perimeterText;return new ol.style.Style({stroke:new ol.style.Stroke({color:this.strokeColor_,width:2,lineDash:[10,10]}),fill:new ol.style.Fill({color:de.novasib.ol.style.getColorLike(this.fillColor_,
.3)}),text:new ol.style.Text({text:text_,font:"10pt sans-serif",fill:new ol.style.Fill({color:"black"}),stroke:new ol.style.Stroke({color:"white",width:3}),overflow:true})})}return null}.bind(this)};goog.provide("de.novasib.ol.interaction.Segmentation");goog.require("de.novasib.ol.geom");goog.require("de.novasib.ol.style");goog.require("ol");goog.require("ol.coordinate");goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.geom.LineString");goog.require("ol.geom.Point");goog.require("ol.interaction.Pointer");goog.require("ol.layer.Vector");goog.require("ol.source.Vector");goog.require("ol.style.Circle");goog.require("ol.style.Fill");goog.require("ol.style.Icon");goog.require("ol.style.Stroke");
goog.require("ol.style.Style");goog.require("ol.style.Text");
de.novasib.ol.interaction.Segmentation=function(opt_options){ol.interaction.Pointer.call(this,{handleDownEvent:de.novasib.ol.interaction.Segmentation.handleDownEvent_,handleDragEvent:de.novasib.ol.interaction.Segmentation.handleDragEvent_,handleEvent:de.novasib.ol.interaction.Segmentation.handleEvent,handleUpEvent:de.novasib.ol.interaction.Segmentation.handleUpEvent_});var options=opt_options||{};this.feature_=options.feature||null;this.segmentFeature_=null;this.vertexFeature_=null;this.snappedToVertex_=
false;this.selectedSide_=undefined;this.startPropertyName_=options.startPropertyName;this.endPropertyName_=options.endPropertyName;this.changeFeature_=false;this.overlay_=new ol.layer.Vector({source:new ol.source.Vector({useSpatialIndex:false,wrapX:false}),style:options.style?options.style:de.novasib.ol.interaction.Segmentation.getDefaultStyleFunction(),updateWhileAnimating:true,updateWhileInteracting:true,zIndex:Infinity});this.pixelTolerance_=options.pixelTolerance||0;this.down_=false;this.wasDragging_=
false};ol.inherits(de.novasib.ol.interaction.Segmentation,ol.interaction.Pointer);de.novasib.ol.interaction.Segmentation.handleEvent=function(mapBrowserEvent){if(this.feature_){if(!(mapBrowserEvent instanceof ol.MapBrowserPointerEvent))return true;var type=mapBrowserEvent.type;if(!mapBrowserEvent.map.getView().getInteracting()&&type===ol.MapBrowserEventType.POINTERMOVE&&!this.handlingDownUpSequence)this.handlePointerMove_(mapBrowserEvent);return ol.interaction.Pointer.handleEvent.call(this,mapBrowserEvent)}return true};
de.novasib.ol.interaction.Segmentation.handleDownEvent_=function(evt){this.down_=true;return this.vertexFeature_!=null};
de.novasib.ol.interaction.Segmentation.handleDragEvent_=function(evt){if(this.feature_&&this.down_&&this.selectedSide_!==undefined&&this.snappedToVertex_&&this.vertexFeature_){var vertex=evt.coordinate;var idx=this.selectedSide_===de.novasib.ol.interaction.Segmentation.Side.START?0:1;var geometry=this.segmentFeature_.getGeometry();var coordinates=geometry.getCoordinates();var newVertex=de.novasib.ol.geom.closestOnLine(vertex,this.feature_.getGeometry());coordinates[idx]=newVertex;geometry.setCoordinates(coordinates);
this.createOrUpdateVertexFeature_(newVertex);this.wasDragging_=true}};
de.novasib.ol.interaction.Segmentation.handleUpEvent_=function(evt){this.down_=false;if(this.wasDragging_){this.wasDragging_=false;var segmentGeom=this.segmentFeature_.getGeometry();var featureGeom=this.feature_.getGeometry();var featureCoords=featureGeom.getCoordinates();var point,prop=null;var length=0;if(this.selectedSide_===de.novasib.ol.interaction.Segmentation.Side.START){point=segmentGeom.getFirstCoordinate();prop=this.startPropertyName_}else if(this.selectedSide_===de.novasib.ol.interaction.Segmentation.Side.END){point=
segmentGeom.getLastCoordinate();prop=this.endPropertyName_}if(point){for(var i=0;i<featureCoords.length-1;++i){var segment=featureCoords.slice(i,i+2);if(de.novasib.ol.geom.isOnSegment(point,segment)){var lenTilPoint=de.novasib.ol.geom.segmentLength([segment[0],point]);length+=lenTilPoint;break}else{var segLen=de.novasib.ol.geom.segmentLength(segment);length+=segLen}}var prevStart=this.feature_.get(this.startPropertyName_);var prevEnd=this.feature_.get(this.endPropertyName_);if(prop){var alen=this.feature_.get("ALEN")||
this.feature_.get("LEN");if(typeof alen==="number"&&alen>0){var geomLength=featureGeom.getLength();var ratio=alen/geomLength;length*=ratio}if(length&&typeof length=="number")length=Math.round(length);this.feature_.set(prop,length);console.log(prop+"="+length)}this.dispatchEvent(new de.novasib.ol.interaction.Segmentation.Event(de.novasib.ol.interaction.Segmentation.EventType_.SEGMENTATIONFINISHED,this.feature_,prevStart,prevEnd,prop))}}return false};
de.novasib.ol.interaction.Segmentation.prototype.handlePointerMove_=function(evt){if(this.feature_&&this.segmentFeature_){var pixel=evt.pixel;var map$32=evt.map;var pixelCoordinate=map$32.getCoordinateFromPixel(pixel);var coords=this.segmentFeature_.getGeometry().getCoordinates();var start=coords[0];var end=coords[1];var startDist=ol.coordinate.distance(pixelCoordinate,start);var endDist=ol.coordinate.distance(pixelCoordinate,end);var closestCoord;if(startDist<endDist){closestCoord=start;this.selectedSide_=
de.novasib.ol.interaction.Segmentation.Side.START}else{closestCoord=end;this.selectedSide_=de.novasib.ol.interaction.Segmentation.Side.END}var vertexPixel=map$32.getPixelFromCoordinate(closestCoord);var dist=ol.coordinate.distance(pixel,vertexPixel);this.snappedToVertex_=dist<=this.pixelTolerance_;if(this.snappedToVertex_){this.createOrUpdateVertexFeature_(closestCoord);return}}if(this.vertexFeature_){this.overlay_.getSource().removeFeature(this.vertexFeature_);this.vertexFeature_=null}else this.selectedSide_=
undefined};de.novasib.ol.interaction.Segmentation.prototype.finish=function(){this.removePropertyChangeListeners_();this.overlay_.getSource().clear();if(this.feature_){var map$33=this.getMap();var styleFunction=this.feature_.getStyleFunction();if(map$33&&map$33.getView()&&styleFunction&&typeof styleFunction=="function"){var styles=styleFunction.call(this.feature_,map$33.getView().getResolution());this.feature_.setStyle(styles)}}this.feature_=null;this.segmentFeature_=null};
de.novasib.ol.interaction.Segmentation.prototype.setActive=function(active){if(!active)this.finish();else this.addPropertyChangeListeners_();ol.interaction.Pointer.prototype.setActive.call(this,active)};de.novasib.ol.interaction.Segmentation.prototype.setMap=function(map){ol.interaction.Pointer.prototype.setMap.call(this,map);var active=this.getActive();this.overlay_.setMap(active?map:null)};
de.novasib.ol.interaction.Segmentation.prototype.setFeature=function(feature){this.removePropertyChangeListeners_();this.feature_=feature;this.addPropertyChangeListeners_();this.createOrUpdateSegmentationFeature_()};
de.novasib.ol.interaction.Segmentation.prototype.handleFeatureChange_=function(evt){if(!this.segmentFeature_)this.createOrUpdateSegmentationFeature_();var featureGeom=this.feature_.getGeometry();var key=evt.key;var index=0;var pos=0;if(key===this.startPropertyName_){index=0;pos=this.feature_.get(this.startPropertyName_)||0}else if(key===this.endPropertyName_){index=1;var propEnd=this.feature_.get(this.endPropertyName_);pos=propEnd!==undefined?propEnd:featureGeom.getLength()}var point=de.novasib.ol.geom.getPointOnLineString(featureGeom,
pos);var geom=this.segmentFeature_.getGeometry();var coords=[];coords[index]=point;var otherIdx=Math.abs(index-1);coords[otherIdx]=geom.getCoordinates()[otherIdx];geom.setCoordinates(coords)};
de.novasib.ol.interaction.Segmentation.prototype.addPropertyChangeListeners_=function(){if(this.feature_){var eventType=ol.Object.getChangeEventType(this.startPropertyName_);ol.events.listen(this.feature_,eventType,this.handleFeatureChange_,this);eventType=ol.Object.getChangeEventType(this.endPropertyName_);ol.events.listen(this.feature_,eventType,this.handleFeatureChange_,this)}};
de.novasib.ol.interaction.Segmentation.prototype.removePropertyChangeListeners_=function(){if(this.feature_){var eventType=ol.Object.getChangeEventType(this.startPropertyName_);ol.events.unlisten(this.feature_,eventType,this.handleFeatureChange_,this);eventType=ol.Object.getChangeEventType(this.endPropertyName_);ol.events.unlisten(this.feature_,eventType,this.handleFeatureChange_,this)}};
de.novasib.ol.interaction.Segmentation.prototype.createOrUpdateSegmentationFeature_=function(){var segmentFeature=this.segmentFeature_;if(this.feature_){var geom=this.feature_.getGeometry();var coordinates=geom.getCoordinates();var so=this.feature_.get("RICHTUNG")==="G"&&this.feature_.get("VST")<this.feature_.get("BST");var startPropName=so?this.endPropertyName_:this.startPropertyName_;var endPropName=so?this.startPropertyName_:this.endPropertyName_;var startProp=this.feature_.get(startPropName);
var start=startProp!==undefined?de.novasib.ol.geom.getPointOnLineString(geom,startProp):coordinates[0];var endProp=this.feature_.get(endPropName);var end=endProp!==undefined?de.novasib.ol.geom.getPointOnLineString(geom,endProp):coordinates[coordinates.length-1];if(!segmentFeature){segmentFeature=new ol.Feature(new ol.geom.LineString([start,end]));this.segmentFeature_=segmentFeature;this.overlay_.getSource().addFeature(this.segmentFeature_)}else{var geometry=segmentFeature.getGeometry();geometry.setCoordinates([start,
end])}}return segmentFeature};de.novasib.ol.interaction.Segmentation.prototype.createOrUpdateVertexFeature_=function(coordinates){var vertexFeature=this.vertexFeature_;if(!vertexFeature){vertexFeature=new ol.Feature(new ol.geom.Point(coordinates));this.vertexFeature_=vertexFeature;this.overlay_.getSource().addFeature(vertexFeature)}else{var geom=vertexFeature.getGeometry();geom.setCoordinates(coordinates)}return vertexFeature};
de.novasib.ol.interaction.Segmentation.getDefaultStyleFunction=function(){return function(feature,resolution){var styles=[];var geom=feature.getGeometry();if(geom instanceof ol.geom.LineString){var coordinates=geom.getCoordinates();if(coordinates.length!==2)return;var color_="#A3BAE9";styles.push(new ol.style.Style({stroke:new ol.style.Stroke({color:color_,width:4}),zIndex:1E6}));var so=feature.get("RICHTUNG")=="G";var start=coordinates[0];var end=coordinates[1];styles.push(new ol.style.Style({geometry:new ol.geom.Point(start),
image:new ol.style.Circle({radius:8,fill:new ol.style.Fill({color:"#3076C2"}),stroke:new ol.style.Stroke({color:"#333",width:2})}),text:new ol.style.Text({font:"10px sans-serif",fill:new ol.style.Fill({color:"#FFF"}),stroke:new ol.style.Stroke({color:"#111",width:1}),text:"S",placement:"point",textAlign:"center"}),zIndex:Infinity}));styles.push(new ol.style.Style({geometry:new ol.geom.Point(end),image:new ol.style.Circle({radius:8,fill:new ol.style.Fill({color:"#3076C2"}),stroke:new ol.style.Stroke({color:"#333",
width:2})}),text:new ol.style.Text({font:"10px sans-serif",fill:new ol.style.Fill({color:"#FFF"}),stroke:new ol.style.Stroke({color:"#111",width:1}),text:"E",placement:"point",textAlign:"center"}),zIndex:Infinity}));var dx=end[0]-start[0];var dy=end[1]-start[1];var cx=start[0]+dx/2;var cy=start[1]+dy/2;var center=[cx,cy];var rotation=so?Math.PI-Math.atan2(dy,dx):-Math.atan2(dy,dx);styles.push(new ol.style.Style({geometry:new ol.geom.Point(center),image:new ol.style.Icon({src:de.novasib.ol.style.ARROW_IMG,
rotation:rotation,color:color_}),zIndex:Infinity}));return styles}else if(geom instanceof ol.geom.Point){var pointStyle=ol.style.Style.createDefaultEditing()[ol.geom.GeometryType.POINT];return pointStyle}return null}};de.novasib.ol.interaction.Segmentation.Side={START:"start",END:"end"};
de.novasib.ol.interaction.Segmentation.Event=function(type,feature,prevStart,prevEnd,prop){ol.events.Event.call(this,type);this.feature=feature;this.previousStartValue=prevStart;this.previousEndValue=prevEnd;this.changed=prop};ol.inherits(de.novasib.ol.interaction.Segmentation.Event,ol.events.Event);de.novasib.ol.interaction.Segmentation.EventType_={SEGMENTATIONFINISHED:"segmentationfinished"};goog.provide("de.novasib.ol.interaction.Snap");goog.require("de.novasib.ol.geom");goog.require("ol");goog.require("ol.coordinate");goog.require("ol.events");goog.require("ol.events.condition");goog.require("ol.extent");goog.require("ol.geom.Point");goog.require("ol.geom.LineString");goog.require("ol.interaction.Interaction");goog.require("ol.layer.Vector");goog.require("ol.source.Vector");goog.require("ol.structs.RBush");goog.require("ol.style.Circle");goog.require("ol.style.Fill");goog.require("ol.style.Stroke");
goog.require("ol.style.Style");
de.novasib.ol.interaction.Snap=function(options){ol.interaction.Interaction.call(this,{handleEvent:de.novasib.ol.interaction.Snap.handleEvent});this.moveCondition_=ol.events.condition.pointerMove;this.clickCondition_=ol.events.condition.singleClick;this.shiftKeyCondition_=ol.events.condition.shiftKeyOnly;this.ctrlKeyCondition_=de.novasib.ol.condition.ctrlKeyOnly;this.pixelTolerance_=options.pixelTolerance!=undefined?options.pixelTolerance:30;this.tooltipPixelTolerance_=0;this.rBush_=new ol.structs.RBush;
this.sketchFeature_=null;this.snappedFeature=null;this.snappedVertex=null;this.positionGeometry_=null;this.overlay_=new ol.layer.Vector({source:new ol.source.Vector({useSpatialIndex:false,wrapX:false}),style:de.novasib.ol.interaction.Snap.getDefaultOverlayStyleFunction_(this),updateWhileAnimating:true,updateWhileInteracting:true});ol.events.listen(this,ol.Object.getChangeEventType(ol.interaction.Property.ACTIVE),this.updateState_,this);this.layer_=options.layer;if(!this.layer_)throw new Error("The snap interaction requires a layer!");
this.source_=this.layer_.getSource();ol.events.listen(this.source_,ol.source.VectorEventType.ADDFEATURE,this.handleSourceAdd_,this);ol.events.listen(this.source_,ol.source.VectorEventType.REMOVEFEATURE,this.handleSourceRemove_,this);this.source_.forEachFeature(this.addFeature_,this);this.tooltip_=options.tooltip;this.withDistance_=!!options.withDistance;this.shiftDown_=false;this.ctrlDown_=false};ol.inherits(de.novasib.ol.interaction.Snap,ol.interaction.Interaction);
de.novasib.ol.interaction.Snap.MIN_PIXEL_TOLERANCE=5;de.novasib.ol.interaction.Snap.MAX_PIXEL_TOLERANCE=100;
de.novasib.ol.interaction.Snap.handleEvent=function(mapBrowserEvent){this.shiftDown_=this.shiftKeyCondition_(mapBrowserEvent);this.ctrlDown_=this.ctrlKeyCondition_(mapBrowserEvent);if(this.moveCondition_(mapBrowserEvent)&&!this.isDragEvent_(mapBrowserEvent))return this.handlePointerMove_(mapBrowserEvent);else if(this.shiftDown_&&this.isWheelEvent_(mapBrowserEvent))return this.handleMouseWheel_(mapBrowserEvent);else if(ol.events.condition.singleClick(mapBrowserEvent))this.handleClick_(mapBrowserEvent);
return true};de.novasib.ol.interaction.Snap.prototype.handleClick_=function(event){if(this.snappedFeature&&this.snappedVertex){var map$34=event.map;var pixel=event.pixel;var coord=map$34.getCoordinateFromPixel(pixel);this.dispatchEvent(new de.novasib.ol.interaction.Snap.SnapEvent_(coord,this.snappedVertex,this.snappedFeature))}};
de.novasib.ol.interaction.Snap.prototype.handlePointerMove_=function(evt){var map=evt.map;var pixel=evt.pixel;var coord=map.getCoordinateFromPixel(pixel);this.createOrUpdateSketchFeature_(coord);this.handlePointerAtPixel_(pixel,map);return this.positionGeometry_!=null};
de.novasib.ol.interaction.Snap.prototype.handlePointerAtPixel_=function(pixel,map){var pixelCoordinate=map.getCoordinateFromPixel(pixel);if((this.shiftDown_||this.ctrlDown_)&&this.snappedFeature!=null){var geometry=this.snappedFeature.getGeometry();var coordinates=geometry.getCoordinates();var vertex;var segment;var distance=Infinity;var firstCoord=coordinates[0];var lastCoord=coordinates[coordinates.length-1];if(this.ctrlDown_){var vertexPixel=map.getPixelFromCoordinate(firstCoord);var dist=ol.coordinate.distance(pixel,
vertexPixel);if(dist<=this.pixelTolerance_)vertex=firstCoord;if(!vertex){vertexPixel=map.getPixelFromCoordinate(lastCoord);dist=ol.coordinate.distance(pixel,vertexPixel);if(dist<=this.pixelTolerance_)vertex=lastCoord}}if(!vertex)for(var i=0;i<coordinates.length-1;++i){var closestSegment=coordinates.slice(i,i+2);var closestVertex=ol.coordinate.closestOnSegment(pixelCoordinate,closestSegment);var vertexPixel$35=map.getPixelFromCoordinate(closestVertex);var dist$36=ol.coordinate.distance(pixel,vertexPixel$35);
if(dist$36<=this.pixelTolerance_)if(dist$36<distance){distance=dist$36;vertex=closestVertex;segment=closestSegment}}if(vertex){this.createOrUpdatePositionGeometry_(pixelCoordinate,vertex);var feature=this.snappedFeature;var station=de.novasib.ol.geom.getWeightedStation(vertex,feature.getGeometry(),feature.get("GISLEN"),feature.get("LEN")||feature.get("ALEN"));feature.set("station",station,true);if(this.withDistance_){var lage=de.novasib.ol.geom.calcLage(segment[0],segment[1],pixelCoordinate);var distance$37=
lage*this.positionGeometry_.getLength();distance$37=distance$37.toLocaleString("de-DE",{useGrouping:false,minimumFractionDigits:2,maximumFractionDigits:2});feature.set("distance",distance$37,true)}this.snappedVertex=vertex;return}}else{var sortByDistance=function(a,b){return ol.coordinate.squaredDistanceToSegment(pixelCoordinate,a.segment)-ol.coordinate.squaredDistanceToSegment(pixelCoordinate,b.segment)};var box=ol.extent.buffer(ol.extent.createOrUpdateFromCoordinate(pixelCoordinate),map.getView().getResolution()*
this.pixelTolerance_);var rBush=this.rBush_;var nodes=rBush.getInExtent(box);if(nodes.length>0){nodes.sort(sortByDistance);var node=nodes[0];var vertex$38=ol.coordinate.closestOnSegment(pixelCoordinate,node.segment);var vertexPixel$39=map.getPixelFromCoordinate(vertex$38);var dist$40=ol.coordinate.distance(pixel,vertexPixel$39);if(dist$40<=this.pixelTolerance_){this.createOrUpdatePositionGeometry_(pixelCoordinate,vertex$38);var feature$41=node.feature;var station$42=de.novasib.ol.geom.getWeightedStation(vertex$38,
feature$41.getGeometry(),feature$41.get("GISLEN"),feature$41.get("LEN")||feature$41.get("ALEN"));feature$41.set("station",station$42,true);if(this.withDistance_){var lage$43=de.novasib.ol.geom.calcLage(node.segment[0],node.segment[1],pixelCoordinate);var distance$44=lage$43*this.positionGeometry_.getLength();distance$44=distance$44.toLocaleString("de-DE",{useGrouping:false,minimumFractionDigits:2,maximumFractionDigits:2});feature$41.set("distance",distance$44,true)}if(feature$41!=this.snappedFeature){if(this.snappedFeature)this.snappedFeature.unset("tooltipPattern",
true);var ttPattern=this.getTooltipPattern_(feature$41);feature$41.set("tooltipPattern",ttPattern);if(this.tooltip_)this.tooltip_.setTooltipFeature(feature$41,this.layer_)}this.snappedFeature=feature$41;this.snappedVertex=vertex$38;return}}}this.positionGeometry_=null;if(this.snappedFeature)if(!this.shiftDown_){this.snappedFeature.unset("tooltipPattern",true);this.snappedFeature=null;if(this.tooltip_)this.tooltip_.setTooltipFeature(null)}this.snappedVertex=null;if(this.tooltip_)this.tooltip_.hide()};
de.novasib.ol.interaction.Snap.prototype.handleMouseWheel_=function(evt){var wheelEvent=evt.originalEvent;var delta;if(evt.type===ol.events.EventType.WHEEL)delta=-wheelEvent.deltaY;else if(evt.type===ol.events.EventType.MOUSEWHEEL)delta=wheelEvent.wheelDeltaY;var sign=delta<0?-1:1;var newTolerance=this.pixelTolerance_+sign*5;if(newTolerance>=de.novasib.ol.interaction.Snap.MIN_PIXEL_TOLERANCE&&newTolerance<=de.novasib.ol.interaction.Snap.MAX_PIXEL_TOLERANCE){this.pixelTolerance_=newTolerance;if(this.tooltip_)this.tooltip_.setHitTolerance(newTolerance);
this.dispatchEvent(new de.novasib.ol.interaction.Snap.ToleranceEvent_(newTolerance));if(this.sketchFeature_)this.overlay_.getSource().refresh()}return false};
de.novasib.ol.interaction.Snap.prototype.setActive=function(active){if(this.getActive()!=active){if(!active){if(this.sketchFeature_){this.overlay_.getSource().removeFeature(this.sketchFeature_);this.sketchFeature_=null}if(this.snappedFeature){this.snappedFeature.unset("tooltipPattern",true);this.snappedFeature=null}}else if(active){this.pixelTolerance_=30;if(this.sketchFeature_)this.overlay_.getSource().refresh()}if(this.tooltip_){this.tooltip_.setForceSingleFeature(active);this.tooltip_.hide();if(active){this.tooltipPixelTolerance_=
this.tooltip_.getHitTolerance();this.tooltip_.setHitTolerance(this.pixelTolerance_)}else this.tooltip_.setHitTolerance(this.tooltipPixelTolerance_)}ol.interaction.Interaction.prototype.setActive.call(this,active)}};de.novasib.ol.interaction.Snap.prototype.setMap=function(map){ol.interaction.Interaction.prototype.setMap.call(this,map);this.updateState_()};
de.novasib.ol.interaction.Snap.prototype.updateState_=function(){var map=this.getMap();var active=this.getActive();this.overlay_.setMap(active?map:null)};de.novasib.ol.interaction.Snap.prototype.createOrUpdateSketchFeature_=function(coordinates){var feature=this.sketchFeature_;if(!feature){feature=new ol.Feature(new ol.geom.Point(coordinates));this.sketchFeature_=feature;this.overlay_.getSource().addFeature(feature)}else{var geometry=feature.getGeometry();geometry.setCoordinates(coordinates)}return feature};
de.novasib.ol.interaction.Snap.prototype.createOrUpdatePositionGeometry_=function(mouseCoordinate,snapCoordinate){if(mouseCoordinate&&snapCoordinate)this.positionGeometry_=new ol.geom.LineString([mouseCoordinate,snapCoordinate]);else this.positionGeometry_=null};de.novasib.ol.interaction.Snap.prototype.isDragEvent_=function(event){return event.type===ol.MapBrowserEventType.POINTERDRAG};
de.novasib.ol.interaction.Snap.prototype.isWheelEvent_=function(event){return event.type===ol.events.EventType.WHEEL||event.type===ol.events.EventType.MOUSEWHEEL};de.novasib.ol.interaction.Snap.prototype.handleSourceAdd_=function(event){if(event.feature)this.addFeature_(event.feature)};de.novasib.ol.interaction.Snap.prototype.handleSourceRemove_=function(event){if(event.feature)this.removeFeature_(event.feature)};
de.novasib.ol.interaction.Snap.prototype.addFeature_=function(feature){var geometry=feature.getGeometry();if(geometry&&geometry.getType()===ol.geom.GeometryType.LINE_STRING)this.writeGeometry_(feature,geometry);ol.events.listen(feature,ol.events.EventType.CHANGE,this.handleFeatureChange_,this)};de.novasib.ol.interaction.Snap.prototype.removeFeature_=function(feature){this.removeFeatureSegmentData_(feature);ol.events.unlisten(feature,ol.events.EventType.CHANGE,this.handleFeatureChange_,this)};
de.novasib.ol.interaction.Snap.prototype.removeFeatureSegmentData_=function(feature){var rBush=this.rBush_;var nodesToRemove=[];rBush.forEach(function(node){if(feature===node.feature)nodesToRemove.push(node)});for(var i=nodesToRemove.length-1;i>=0;--i)rBush.remove(nodesToRemove[i])};
de.novasib.ol.interaction.Snap.prototype.writeGeometry_=function(feature,geometry){var coordinates=geometry.getCoordinates();var i,ii,segment,segmentData;for(i=0,ii=coordinates.length-1;i<ii;++i){segment=coordinates.slice(i,i+2);segmentData={feature:feature,geometry:geometry,index:i,segment:segment};this.rBush_.insert(ol.extent.boundingExtent(segment),segmentData)}};de.novasib.ol.interaction.Snap.prototype.handleFeatureChange_=function(evt){var feature=evt.target;this.removeFeature_(feature);this.addFeature_(feature)};
de.novasib.ol.interaction.Snap.prototype.setWithDistance=function(withDistance){this.withDistance_=withDistance};
de.novasib.ol.interaction.Snap.prototype.getTooltipPattern_=function(feature){var pattern="";var strasse=feature.get("STRASSENBEZEICHNUNG");if(strasse)pattern+="Strasse ${STRASSENBEZEICHNUNG}<br/>";pattern+="Abschnitt von ${VNK} nach ${NNK}<br/>";var anr=feature.get("ABSCHNNR");if(anr)pattern+="Abschnittsnummer ${ABSCHNNR}<br/>";pattern+="Station ${station}<br/>";if(this.withDistance_)pattern+="Abstand ${distance} m";return pattern};
de.novasib.ol.interaction.Snap.getDefaultOverlayStyleFunction_=function(opt_this){return function(feature,resolution){var ret=[];ret.push(new ol.style.Style({image:new ol.style.Circle({fill:new ol.style.Fill({color:"rgba(0, 89, 159, 0.125)"}),stroke:new ol.style.Stroke({color:"rgba(0, 89, 159, 1)",width:1,lineDash:[10,10],lineDashOffset:10}),radius:this.pixelTolerance_})}));ret.push(new ol.style.Style({geometry:this.positionGeometry_,stroke:new ol.style.Stroke({color:"rgba(0, 89, 159, 1)",width:2.5})}));
return ret}.bind(opt_this)};de.novasib.ol.interaction.Snap.ToleranceEvent_=function(tolerance){ol.events.Event.call(this,"toleranceChange");this.tolerance=tolerance};ol.inherits(de.novasib.ol.interaction.Snap.ToleranceEvent_,ol.events.Event);de.novasib.ol.interaction.Snap.SnapEvent_=function(pixelCoordinate,vertex,feature){ol.events.Event.call(this,"featuresnapped");this.pixelCoordinate=pixelCoordinate;this.vertex=vertex;this.feature=feature};
ol.inherits(de.novasib.ol.interaction.Snap.SnapEvent_,ol.events.Event);goog.provide("de.novasib.ol.interaction.Tooltip");goog.require("de.novasib.ol");goog.require("de.novasib.ol.feature");goog.require("ol");goog.require("ol.array");goog.require("ol.dom");goog.require("ol.events.condition");goog.require("ol.events.Event");goog.require("ol.interaction.Interaction");
de.novasib.ol.interaction.Tooltip=function(options){this.condition_=ol.events.condition.pointerMove;this.mapTargetElement_=options.mapTargetElement;this.element_=document.createElement("DIV");this.element_.className=options.className!==undefined?options.className:"de-novasib-ol-tooltip";this.element_.id=de.novasib.ol.interaction.Tooltip.ELEMENT_ID;ol.interaction.Interaction.call(this,{handleEvent:de.novasib.ol.interaction.Tooltip.handleEvent});var opt_this=this;this.element_["tooltip"].call(this.element_,
{"animation":false,"trigger":"manual","html":true,"placement":function(){return this.tooltipPlacement_}.bind(opt_this)});var layerFilter;if(options.layers)if(typeof options.layers==="function")layerFilter=options.layers;else{var layers=options.layers;layerFilter=function(layer){return ol.array.includes(layers,layer)}}else layerFilter=ol.functions.TRUE;this.layerFilter_=layerFilter;this.hitTolerance_=options.hitTolerance||0;this.featureLayerAssociation_={};this.currentFeature=null;this.lastPixel_=
[0,0];this.tooltipPlacement_="right";this.tooltipPlacementDelay_=250;this.lastTimeChecked_=Date.now();this.singleFeature_=null;this.forceSingle_=false;this.maxDisplayedValues=options.maxDisplayedValues||6};ol.inherits(de.novasib.ol.interaction.Tooltip,ol.interaction.Interaction);de.novasib.ol.interaction.Tooltip.ELEMENT_ID="tooltip_element";
de.novasib.ol.interaction.Tooltip.prototype.handlePointerMove_=function(mapBrowserEvent){var $jscomp$this=this;var map=mapBrowserEvent.map;var pixel=mapBrowserEvent.pixel;var features=[];var ttFeature;if(this.singleFeature_!=null||this.forceSingle_)ttFeature=this.singleFeature_;else map.forEachFeatureAtPixel(pixel,function(feature,layer){var stylename=feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME);this.addFeatureLayerAssociation_(feature,layer);features.push(feature);if(stylename=="hover"||
stylename=="select"){ttFeature=feature;return false}return true}.bind(this),{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});if(!ttFeature&&features.length>0)ttFeature=features[0];ol.array.remove(features,ttFeature);features.forEach(function(feature){$jscomp$this.removeFeatureLayerAssociation_(feature)});features=null;if(ttFeature&&ttFeature!==this.currentFeature)this.currentFeature=ttFeature;else if(!ttFeature)this.currentFeature=null;if(this.currentFeature){this.dispatchEvent(new de.novasib.ol.interaction.Tooltip.Event(this.currentFeature));
var placement=this.tooltipPlacement_;var now=Date.now();if(now-this.lastTimeChecked_>=this.tooltipPlacementDelay_){placement=this.getTooltipPlacement_(pixel);this.lastTimeChecked_=now}var offset=10;if(placement==="left")offset=-10;this.element_["css"].call(this.element_,{"left":pixel[0]+offset+"px","top":pixel[1]+"px"});this.element_["attr"].call(this.element_,"data-original-title",this.getTooltip_(ttFeature))["tooltip"].call(this.element_,"fixTitle")["tooltip"].call(this.element_,"show")}else this.element_["tooltip"].call(this.element_,
"hide");this.lastPixel_=pixel;return true};
de.novasib.ol.interaction.Tooltip.handleEvent=function(mapBrowserEvent){if(this.condition_(mapBrowserEvent)&&!this.isDragEvent_(mapBrowserEvent))switch(de.novasib.ol.PARENT_APP_NAME){case de.novasib.ol.KNOWN_APP_NAMES.NOVAMAP:return this.handlePointerMoveNovaMap_(mapBrowserEvent);case de.novasib.ol.KNOWN_APP_NAMES.SPERRINFOSYS:return this.handlePointerMoveSperrinfosys_(mapBrowserEvent);case de.novasib.ol.KNOWN_APP_NAMES.TTSIB:return this.handlePointerMoveNovaMap_(mapBrowserEvent);case de.novasib.ol.KNOWN_APP_NAMES.MBDE:return this.handlePointerMove_(mapBrowserEvent);
default:return this.handlePointerMove_(mapBrowserEvent)}else if(this.isDragEvent_(mapBrowserEvent))this.show(false);return true};
de.novasib.ol.interaction.Tooltip.prototype.handlePointerMoveNovaMap_=function(mapBrowserEvent){var map=mapBrowserEvent.map;var pixel=mapBrowserEvent.pixel;var features=[];if(this.singleFeature_!=null||this.forceSingle_)features.push(this.singleFeature_);else map.forEachFeatureAtPixel(pixel,function(feature,layer){var stylename=feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME);this.addFeatureLayerAssociation_(feature,layer);features.push(feature);if(stylename==="hover"||stylename==="select")return false}.bind(this),
{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});var originalEvent=mapBrowserEvent.originalEvent;if(originalEvent){var target=originalEvent.target;if(target){var targetLocalName=target.localName;if(targetLocalName!=="canvas"){this.show(false);return true}}}if(features.length!==0){this.currentFeature=features[0];this.dispatchEvent(new de.novasib.ol.interaction.Tooltip.Event(this.currentFeature));var placement=this.tooltipPlacement_;var now=Date.now();if(now-this.lastTimeChecked_>=this.tooltipPlacementDelay_){placement=
this.getTooltipPlacement_(pixel);this.lastTimeChecked_=now}var offset=10;if(placement==="left")offset=-10;this.element_["css"].call(this.element_,{"left":pixel[0]+offset+"px","top":pixel[1]+"px"});var tooltipCurrentFeature_,tooltipNextFeature_;var uniqueFeatures=features.filter(function(feature,index,array){tooltipCurrentFeature_=this.getTooltip_(feature);if(index!==array.length-1)tooltipNextFeature_=this.getTooltip_(array[index+1]);else tooltipNextFeature_="";return tooltipCurrentFeature_!==tooltipNextFeature_}.bind(this));
var tooltip_="";uniqueFeatures=uniqueFeatures.slice(0,this.maxDisplayedValues);uniqueFeatures.forEach(function(feature,index,array){if(index<this.maxDisplayedValues){tooltip_+=this.getTooltip_(feature);if(index<array.length-1)tooltip_+="<br>--------------------------<br>"}}.bind(this));tooltip_="<br>"+tooltip_+"<br><br>";this.element_["attr"].call(this.element_,"data-original-title",tooltip_)["tooltip"].call(this.element_,"fixTitle")["tooltip"].call(this.element_,"show")}else this.show(false);this.lastPixel_=
pixel;return true};
de.novasib.ol.interaction.Tooltip.prototype.handlePointerMoveSperrinfosys_=function(mapBrowserEvent){var this_=this;var map=mapBrowserEvent.map;var pixel=mapBrowserEvent.pixel;var features=[];if(this_.singleFeature_!=null||this_.forceSingle_);else map.forEachFeatureAtPixel(pixel,function(feature,layer){var stylename=feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME);this_.addFeatureLayerAssociation_(feature,layer);features.push(feature);if(stylename==="hover"||stylename==="select")return false}.bind(this_),
{layerFilter:this_.layerFilter_,hitTolerance:this_.hitTolerance_});if(features.length!==0){this_.dispatchEvent(new de.novasib.ol.interaction.Tooltip.Event(this_.currentFeature));var placement=this_.tooltipPlacement_;var now=Date.now();if(now-this_.lastTimeChecked_>=this_.tooltipPlacementDelay_){placement=this_.getTooltipPlacement_(pixel);this_.lastTimeChecked_=now}var offset=10;if(placement==="left")offset=-10;this_.element_["css"].call(this_.element_,{"left":pixel[0]+offset+"px","top":pixel[1]+"px"});
var tooltip_="<br>";var uniqueFeatures=[];features.forEach(function(feature){var doksperrid=feature.values_.DOKSPERRID;var i=uniqueFeatures.findIndex(function(x){return x.values_.DOKSPERRID==doksperrid});if(i<=-1)uniqueFeatures.push(feature)});uniqueFeatures=uniqueFeatures.slice(0,this.maxDisplayedValues);var elementLast=uniqueFeatures.length-1;uniqueFeatures.forEach(function(feature){tooltip_+=this_.getTooltip_(feature);if(feature.id_!==uniqueFeatures[elementLast].id_)tooltip_+="<br>--------------------------<br>"});
tooltip_+="<br><br>";this_.element_["attr"].call(this_.element_,"data-original-title",tooltip_)["tooltip"].call(this_.element_,"fixTitle")["tooltip"].call(this_.element_,"show")}else this_.element_["tooltip"].call(this_.element_,"hide");this_.lastPixel_=pixel;return true};
de.novasib.ol.interaction.Tooltip.prototype.setActive=function(active){if(!active)ol.dom.removeNode(this.element_);else{if(!this.mapTargetElement_)document.body.appendChild(this.element_);else this.mapTargetElement_.appendChild(this.element_);this.element_=window["$"].call(null,"#"+de.novasib.ol.interaction.Tooltip.ELEMENT_ID)}ol.interaction.Interaction.prototype.setActive.call(this,active)};
de.novasib.ol.interaction.Tooltip.prototype.isDragEvent_=function(mapBrowserEvent){var type=mapBrowserEvent.type;return type===ol.MapBrowserEventType.POINTERDRAG};
de.novasib.ol.interaction.Tooltip.prototype.getTooltip_=function(feature){var layer=this.getLayer(feature);var pattern=feature.get(de.novasib.ol.FeatureProperties.TOOLTIP_PATTERN);if(!pattern&&layer)pattern=layer.get(de.novasib.ol.FeatureProperties.TOOLTIP_PATTERN);if(!pattern)return"";var tooltip="";var context=feature.getProperties();if(pattern.search(",date,")!==-1){var myPlaceholder=de.novasib.ol.getDatePlaceholder(",date,",pattern);var myFormatOption=de.novasib.ol.getDateFormatOption(",date,",
pattern);var strSearch=de.novasib.ol.getDateContextFullExtent(myPlaceholder,pattern);pattern=pattern.replace(strSearch,myPlaceholder);var strDate=feature.get(myPlaceholder);var myDate=new Date(strDate);var strDateFormatted=de.novasib.ol.formatDate(myDate,myFormatOption);context[myPlaceholder]=strDateFormatted}if(pattern)tooltip=de.novasib.ol.feature.formatTemplate(pattern,context);return this.trimTooltip_(tooltip)};
de.novasib.ol.interaction.Tooltip.prototype.trimTooltip_=function(tt){if(tt&&typeof tt=="string")return tt.replace(/(undefined)/g,"").replace(/(<br>)/g,"<br/>").replace(/^(<br\/>)*/,"").replace(/(<br\/>)*$/,"").replace(/(<br\/><br\/>)/g,"<br/>").replace(/(<br\/><br\/>m)/g,"");return tt};de.novasib.ol.interaction.Tooltip.prototype.addFeatureLayerAssociation_=function(feature,layer){var key=ol.getUid(feature);this.featureLayerAssociation_[key]=layer};
de.novasib.ol.interaction.Tooltip.prototype.removeFeatureLayerAssociation_=function(feature){if(feature){var key=ol.getUid(feature);delete this.featureLayerAssociation_[key]}};de.novasib.ol.interaction.Tooltip.prototype.getLayer=function(feature){var key=ol.getUid(feature);return this.featureLayerAssociation_[key]};
de.novasib.ol.interaction.Tooltip.prototype.getTooltipPlacement_=function(pixel){if(pixel&&this.lastPixel_)if(this.lastPixel_[0]<pixel[0])this.tooltipPlacement_="left";else this.tooltipPlacement_="right";return this.tooltipPlacement_};de.novasib.ol.interaction.Tooltip.prototype.setHitTolerance=function(tolerance){this.hitTolerance_=tolerance};de.novasib.ol.interaction.Tooltip.prototype.getHitTolerance=function(){return this.hitTolerance_};
de.novasib.ol.interaction.Tooltip.prototype.setTooltipFeature=function(feature,layer){if(feature){this.singleFeature_=feature;this.addFeatureLayerAssociation_(this.singleFeature_,layer)}else{this.removeFeatureLayerAssociation_(this.singleFeature_);this.singleFeature_=null}};de.novasib.ol.interaction.Tooltip.prototype.setForceSingleFeature=function(force){this.forceSingle_=force;if(!force&&this.singleFeature_){this.removeFeatureLayerAssociation_(this.singleFeature_);this.singleFeature_=null}};
de.novasib.ol.interaction.Tooltip.prototype.hide=function(){this.element_["tooltip"].call(this.element_,"hide")};de.novasib.ol.interaction.Tooltip.prototype.show=function(show){var desiredState;if(show===true||show===undefined)desiredState="show";if(show===false)desiredState="hide";this.element_["tooltip"].call(this.element_,desiredState)};de.novasib.ol.interaction.Tooltip.Event=function(feature){ol.events.Event.call(this,"beforeFeatureTooltip");this.feature=feature};
ol.inherits(de.novasib.ol.interaction.Tooltip.Event,ol.events.Event);goog.provide("de.novasib.ol.Layer");
de.novasib.ol.Layer=function(opt_options){var opt=opt_options||{};this.type=opt["type"]||"";this.title=opt["title"]||"";this.name=opt["name"]||"";this.urls=opt["urls"];this.url=opt["url"];if(this.urls&&this.url)throw new Error('Es darf nur Eigenschaft "url" ODER "urls" gesetzt sein, nicht beide!');this.schemaLocation=opt["schemaLocation"]||"";this.featureNS=opt["featureNS"]||"";this.featureType=opt["featureType"]||"";this.format=opt["format"]||"";this.extent=opt["extent"]||undefined;this.minResolution=
opt["minResolution"];this.maxResolution=opt["maxResolution"];this.version=opt["version"]||"";this.visible=opt["visible"]||false;this.username=opt["username"]||"";this.password=opt["password"]||"";this.params=opt["params"]||{};this.serverType=opt["serverType"]||"";this.layers=[];this.styles=[];this.setLayersAndStyles_(opt);if(this.layers.length>0&&this.styles.length>0&&this.layers.length!=this.styles.length)throw new Error("Kann WMS-Layer nicht erstellen: Anzahl der angegebenen Ebenen und Stile muss gleich sein!\n"+
"(Name: "+(this.title||this.name)+"; Anz. Ebenen="+this.layers.length+"; Anz. Stile="+this.styles.length+")");this.epsgSRID=opt["epsgSRID"]||"";this.opacity=opt["opacity"]!=undefined?opt["opacity"]:1;this.selectable=opt["selectable"]||false;this.groupSelect=opt["groupSelect"]||null;this.tooltip=opt["tooltip"]||opt["tooltipPattern"]||false;this.zIndex=opt["zIndex"];this.matrixSet=opt["matrixSet"];this.matrixIds=opt["matrixIds"];this.capabilitiesUrl=opt["capabilitiesUrl"];this.data=opt["data"];this.backgroundLayer=
opt["backgroundLayer"]||opt["baseLayer"];this.sourceExtract=opt["sourceExtract"];this.styleProperties=opt["styleProperties"]||[];this.styleName=opt["stylename"]||opt["styleName"];this.forceLayerStyle=opt["forceLayerStyle"]||false;this.showOrientation=opt["showOrientation"]||false;this.provider=opt["provider"];this.key=opt["key"];this.maxZoom=opt["maxZoom"];this.minZoom=opt["minZoom"];this.inLayerSwitcher=opt["inLayerSwitcher"]||false;this.snapLayer=opt["snapLayer"]||false;this.attributions=opt["attributions"];
if(this.name&&!this.featureType&&(this.type==="vector"||this.type==="wfs"))this.featureType=this.name;this.ignoreAxisOrientation=!!opt["ignoreAxisOrientation"];this.featureFilter=opt["featureFilter"];this.imageLoadFunction=opt["imageLoadFunction"];this.declutter=opt["declutter"]||false};
de.novasib.ol.Layer.prototype.setLayersAndStyles_=function(options){var lyrs=options["layers"]||options["layer"];if(lyrs)if(Array.isArray(lyrs)&&lyrs.length>0)if(typeof lyrs[0]=="object")if(lyrs.length==1)this.addLayerAndStyle_(lyrs[0]);else lyrs.forEach(this.addLayerAndStyle_);else{if(typeof lyrs[0]=="string")this.layers=lyrs.slice()}else if(typeof lyrs=="object")this.addLayerAndStyle_(lyrs);else if(typeof lyrs=="string")this.layers.push(lyrs)};
de.novasib.ol.Layer.prototype.addLayerAndStyle_=function(layerObj){var name=layerObj["name"];var style=layerObj["style"];this.layers.push(name);this.styles.push(style)};goog.provide("de.novasib.ol.source.ImageWMSExt");goog.require("ol");goog.require("ol.asserts");goog.require("ol.source.ImageWMS");goog.require("ol.uri");de.novasib.ol.source.ImageWMSExt=function(opt_options){var options=opt_options||{};ol.source.ImageWMS.call(this,opt_options);this.ignoreAxisOrientation=!!options.ignoreAxisOrientation};ol.inherits(de.novasib.ol.source.ImageWMSExt,ol.source.ImageWMS);
de.novasib.ol.source.ImageWMSExt.prototype.getRequestUrl_=function(extent,size,pixelRatio,projection,params){ol.asserts.assert(this.url_!==undefined,9);params[this.v13_?"CRS":"SRS"]=projection.getCode();if(!("STYLES"in this.params_))params["STYLES"]="";if(pixelRatio!=1)switch(this.serverType_){case ol.source.WMSServerType.GEOSERVER:var dpi=90*pixelRatio+.5|0;if("FORMAT_OPTIONS"in params)params["FORMAT_OPTIONS"]+=";dpi:"+dpi;else params["FORMAT_OPTIONS"]="dpi:"+dpi;break;case ol.source.WMSServerType.MAPSERVER:params["MAP_RESOLUTION"]=
90*pixelRatio;break;case ol.source.WMSServerType.CARMENTA_SERVER:case ol.source.WMSServerType.QGIS:params["DPI"]=90*pixelRatio;break;default:ol.asserts.assert(false,8);break}params["WIDTH"]=size[0];params["HEIGHT"]=size[1];var axisOrientation=projection.getAxisOrientation();var bbox;if(this.v13_&&(axisOrientation.substr(0,2)=="ne"&&!this.ignoreAxisOrientation||axisOrientation.substr(0,2)=="en"&&this.ignoreAxisOrientation))bbox=[extent[1],extent[0],extent[3],extent[2]];else bbox=extent;params["BBOX"]=
bbox.join(",");return ol.uri.appendParams(this.url_,params)};
de.novasib.ol.source.ImageWMSExt.defaultImageLoadFunction=function(image,src){var img=image.getImage();if(src.length>=6144&&typeof window.btoa=="function"){var urlArray=src.split("?");var url=urlArray[0];var params=urlArray[1];var xhr=new XMLHttpRequest;xhr.onload=function(e){if(xhr.status===200){var response=xhr.response;var uInt8Array=new Uint8Array(response);var len=uInt8Array.length;var binaryString=new Array(len);for(var i=len-1;i>=0;--i)binaryString[i]=String.fromCharCode(uInt8Array[i]);var data=
binaryString.join("");var type=xhr.getResponseHeader("content-type");if(type.indexOf("image")==0)img.src="data:"+type+";base64,"+window.btoa(data)}};xhr.open("POST",url,true);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.responseType="arraybuffer";xhr.send(params)}else img.src=src};goog.provide("de.novasib.ol.style.StyleManager");goog.require("de.novasib.ol.style");de.novasib.ol.style.StyleManager=function(sld,map){this.styles_={};this.olStyles_={};this.sld=sld;this.loadStyles(this.sld,map)};
de.novasib.ol.style.StyleManager.prototype.loadStyles=function(node,map){var $jscomp$this=this;if(node.hasChildNodes()){var children=node.childNodes;children.forEach(function(child){if(child&&child.localName==="NamedLayer")for(var n=child.firstChild;n;n=n.nextSibling)if(n&&n.localName==="Name"){var val=n.nodeValue||n.textContent;$jscomp$this.styles_[val]=new de.novasib.ol.style.NamedLayer(child,map);break}},this)}};
de.novasib.ol.style.StyleManager.prototype.getFeatureStyle=function(feature,featureType,layerName,scale){if(this.styles_){var namedLayer=this.styles_[layerName];if(namedLayer)return namedLayer.getStyle(feature,featureType,scale)}};de.novasib.ol.style.StyleManager.prototype.hasStyleForLayer=function(layerName){return this.styles_!=undefined&&this.styles_[layerName]!=undefined};
de.novasib.ol.style.StyleManager.loadFromSLD=function(sld,map,preventShortGeom){if(sld.hasChildNodes()){var children=sld.childNodes;var namedLayer=null;children.forEach(function(child){if(child&&child.localName==="NamedLayer")for(var n=child.firstChild;n;n=n.nextSibling)if(n&&n.localName==="Name"){namedLayer=new de.novasib.ol.style.NamedLayer(child,map,preventShortGeom);break}});if(namedLayer)return namedLayer.getDefaultStyle()}return null};goog.provide("de.novasib.ol.VisibilityConfig");de.novasib.ol.VisibilityConfig=function(options){this.tipLabel=options["tipLabel"];this.label=options["label"];this.elements=options["elements"];this.collapsed=options["collapsed"]};goog.provide("de.novasib.ol.Workspace");goog.require("de.novasib.ol");goog.require("de.novasib.ol.InitialView");goog.require("de.novasib.ol.Layer");goog.require("de.novasib.ol.VisibilityConfig");goog.require("ol.proj");
de.novasib.ol.Workspace=function(options){options=options||{};var srid=options["epsgSRID"]||options["ePSGSrid"]||3857;this.projection=de.novasib.ol.loadProjection(srid);if(!this.projection)console.log("Projektion f\u00fcr SRID "+srid+" nicht gefunden!");var res=options["resolutions"]||options["resolution"];if(res&&Array.isArray(res)&&res.length>0){var val=res[0];if(typeof val==="object")res=res.map(function(x){return x.value})}this.resolutions=res;var mbb=options["maxBoundingBox"];if(mbb)if(!Array.isArray(mbb)){var mbbSrid=
mbb["projection"]||mbb["ePSGSrid"];var mbbProj=de.novasib.ol.loadProjection(mbbSrid);var extent=mbb["extent"];if(!extent&&mbb["minX"])extent=[mbb["minX"],mbb["minY"],mbb["maxX"],mbb["maxY"]];if(mbbProj&&mbbProj!=this.projection)mbb=ol.proj.transformExtent(extent,mbbProj,this.projection);else mbb=extent}this.maxBoundingBox=mbb;this.layers=[];var lyrs=options["layers"]||options["layer"];if(lyrs&&lyrs.length>0)for(var l in lyrs)this.layers.push(new de.novasib.ol.Layer(lyrs[l]));this.initialView=new de.novasib.ol.InitialView(options["initialView"]);
this.visibilityConfig=options["visibilityConfig"]?new de.novasib.ol.VisibilityConfig(options["visibilityConfig"]):null;var controls=options["controls"];if(controls&&Array.isArray(controls))controls.map(function(value){if(value&&typeof value==="string")return value.toLocaleLowerCase();return value});this.controls=controls;this.showLogos=!!options["showLogos"]};
de.novasib.ol.Workspace.prototype.getLayersByNameAndType=function(name,type){var layers=this.layers;var ret=[];if(layers&&layers.length>0)for(var i=0;i<layers.length;++i){var l=layers[i];var t=l.title;var n=l.name;if((name===t||name===n)&&(type==undefined||de.novasib.ol.isSameLayerType_(type,l.type)))ret.push(l)}return ret};goog.provide("de.novasib.ol.NovaMap");goog.require("de.novasib.ol");goog.require("de.novasib.ol.control.Button");goog.require("de.novasib.ol.control.InfoBox");goog.require("de.novasib.ol.control.LayerSwitcher");goog.require("de.novasib.ol.control.ToolboxPanel");goog.require("de.novasib.ol.control.Radio");goog.require("de.novasib.ol.control.Visibility");goog.require("de.novasib.ol.control.ZoomStep");goog.require("de.novasib.ol.Events");goog.require("de.novasib.ol.extent");goog.require("de.novasib.ol.feature");
goog.require("de.novasib.ol.featureloader");goog.require("de.novasib.ol.geom");goog.require("de.novasib.ol.interaction.ClickBox");goog.require("de.novasib.ol.interaction.FreeText");goog.require("de.novasib.ol.interaction.HoverSelect");goog.require("de.novasib.ol.interaction.Icon");goog.require("de.novasib.ol.interaction.Measure");goog.require("de.novasib.ol.interaction.Segmentation");goog.require("de.novasib.ol.interaction.Snap");goog.require("de.novasib.ol.interaction.Tooltip");goog.require("de.novasib.ol.source.ImageWMSExt");
goog.require("de.novasib.ol.style");goog.require("de.novasib.ol.style.StyleManager");goog.require("de.novasib.ol.Workspace");goog.require("ol");goog.require("ol.array");goog.require("ol.control");goog.require("ol.control.Attribution");goog.require("ol.control.MousePosition");goog.require("ol.control.ScaleLine");goog.require("ol.control.ZoomSlider");goog.require("ol.events");goog.require("ol.events.Event");goog.require("ol.extent");goog.require("ol.format.GeoJSON");goog.require("ol.format.WKT");goog.require("ol.format.WMTSCapabilities");
goog.require("ol.functions");goog.require("ol.geom.Point");goog.require("ol.interaction");goog.require("ol.interaction.Draw");goog.require("ol.interaction.Modify");goog.require("ol.layer.Image");goog.require("ol.layer.Tile");goog.require("ol.layer.Vector");goog.require("ol.loadingstrategy");goog.require("ol.Map");goog.require("ol.proj");goog.require("ol.source.BingMaps");goog.require("ol.source.OSM");goog.require("ol.source.TileImage");goog.require("ol.source.Vector");goog.require("ol.source.WMTS");
goog.require("ol.source.XYZ");goog.require("ol.style.Circle");goog.require("ol.style.Fill");goog.require("ol.style.Stroke");goog.require("ol.style.Style");goog.require("ol.style.Text");goog.require("ol.tilegrid");goog.require("ol.View");goog.require("ol.Feature");
de.novasib.ol.NovaMap=function(ws,target,loggerFunc){target=target===undefined?"map":target;ol.Object.call(this);this.skippedFeaturesForLayers={};this.logger=loggerFunc||de.novasib.ol.baseLogger;this.workspace=new de.novasib.ol.Workspace(ws);this.projection=this.workspace.projection;this.selectableLayers=[];this.tooltipLayers=[];this.snapLayer=null;this.olmap=null;this.iconLayer_=null;this.drawModifyLayer_=null;de.novasib.ol.loadKnownProjections();this.view_=this.initView_();this.attributionGlobalMode=
ws.attributionGlobalMode||null;this.globalAttribution=ws.globalAttribution||null;this.controls_=this.initControls_();this.interactions_=this.initInteractions_();this.styleManager=null;this.currentZoomLevel=null;var sldCfg=ws["sld"];var url=sldCfg;var usr=undefined;var pass=undefined;if(typeof sldCfg==="object"){url=sldCfg["url"];usr=sldCfg["username"];pass=sldCfg["password"]}this.olmap=new ol.Map({view:this.view_,layers:[],controls:this.controls_,interactions:this.interactions_,target:target,logo:this.workspace.showLogos});
this.olmap.on("moveend",function(evt){var map=evt.map;if(map){var view=map.getView();if(view){var res=view.getResolution();var center=view.getCenter();this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.VIEWPORTCHANGED,{"centerX":center[0],"centerY":center[1],"resolution":res}));var newZoomLevel_=map.getView().getZoom();var direction_;if(newZoomLevel_!==this.currentZoomLevel){if(newZoomLevel_>this.currentZoomLevel)direction_="+";if(newZoomLevel_<this.currentZoomLevel)direction_=
"-";var previousZoomLevel=this.currentZoomLevel;this.currentZoomLevel=newZoomLevel_;this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.ZOOMEND,{"centerX":center[0],"centerY":center[1],"resolution":res,"previousZoomLevel":previousZoomLevel,"zoomLevel":newZoomLevel_,"direction":direction_}))}else this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.MAPMOVED,{"centerX":center[0],"centerY":center[1],"resolution":res}))}}},this);this.initTooltip();if(url)de.novasib.ol.style.loadSld(url,
usr,pass,function(doc){this.styleManager=new de.novasib.ol.style.StyleManager(doc.documentElement,this.olmap);var wsLayers=this.workspace.layers;this.initLayers_(wsLayers);this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.MAPINITIALIZED))},function(err){if(err.type===de.novasib.ol.style.ErrorType.SLD_LOADING_ERROR)this.logger(err.message)},this);else{var wsLayers=this.workspace.layers;this.initLayers_(wsLayers)}this.fileWatcherKey="utyQ6qZdhSdr9wexKJsx8kk2k";this.version="4.2.51";
de.novasib.ol.PARENT_APP_NAME=this.getParentAppName();console.log("novamap version: "+this.version)};ol.inherits(de.novasib.ol.NovaMap,ol.Object);
de.novasib.ol.NovaMap.prototype.initControls_=function(){var controls=[];var ress=this.workspace.resolutions||[];var wsControls=this.workspace.controls||[];controls.push(new de.novasib.ol.control.Attribution({collapsible:false,globalMode:this.attributionGlobalMode,globalAttribution:this.globalAttribution}));controls.push(new ol.control.Zoom);controls.push(new ol.control.ZoomSlider({maxResolution:ress[ress.length-1],minResolution:ress[0]}));controls.push(new ol.control.ZoomToExtent({extent:this.workspace.maxBoundingBox,
tipLabel:"Zoom auf maximale Ausdehnung"}));if(wsControls.indexOf("scale")!=-1)controls.push(new ol.control.ScaleLine);if(wsControls.indexOf("mouseposition")!=-1)controls.push(new ol.control.MousePosition({projection:this.projection,coordinateFormat:function(coord){var code=this.projection.getCode();var x=de.novasib.ol.round(coord[0],6);var y=de.novasib.ol.round(coord[1],6);var locale="de-DE";var options={useGrouping:false,minimumFractionDigits:6};var xs=x.toLocaleString(locale,options);var ys=y.toLocaleString(locale,
options);return"Koordinaten: ("+code+"): "+xs+" | "+ys}.bind(this)}));if(wsControls.indexOf("zoomstep")!=-1)controls.push(new de.novasib.ol.control.ZoomStep({zoomFormat:function(zoom){return"Zoomstufe: "+zoom}}));if(this.workspace&&this.workspace.visibilityConfig){var conf=this.workspace.visibilityConfig;var visibility=new de.novasib.ol.control.Visibility({tipLabel:conf.tipLabel,label:conf.label,elements:conf.elements,collapsed:conf.collapsed});visibility.on("visibilitychanged",function(){this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.VISIBILITYCHANGED))}.bind(this));
controls.push(visibility)}if(wsControls.indexOf("infobox")!=-1)controls.push(new de.novasib.ol.control.InfoBox);return controls};de.novasib.ol.NovaMap.prototype.getInfoBoxControl=function(){return this.getControlByClass(de.novasib.ol.control.InfoBox)};de.novasib.ol.NovaMap.prototype.getLayerSwitcherControl=function(){return control=this.getControlByClass(de.novasib.ol.control.LayerSwitcher)};de.novasib.ol.NovaMap.prototype.getToolboxPanelControl=function(){return control=this.getControlByClass(de.novasib.ol.control.ToolboxPanel)};
de.novasib.ol.NovaMap.prototype.addToolboxPanelControl=function(options,empty){var ctrl=new de.novasib.ol.control.ToolboxPanel({caption:options.caption,handleClick:options.clickListener,label:options.label,tipLabel:options.tipLabel,className:options.className,idDiv:options.idDiv,target:options.target},empty);this.olmap.addControl(ctrl);return ctrl};de.novasib.ol.NovaMap.prototype.getImportPanelControl=function(){return control=this.getControlByClass(de.novasib.ol.control.ImportPanel)};
de.novasib.ol.NovaMap.prototype.addImportPanelControl=function(options,empty){var ctrl=new de.novasib.ol.control.ImportPanel({caption:options.caption,handleClick:options.clickListener,label:options.label,tipLabel:options.tipLabel,className:options.className,idDiv:options.idDiv,target:options.target},empty);this.olmap.addControl(ctrl);return ctrl};
de.novasib.ol.NovaMap.prototype.addButtonControl=function(clickListener,label,tipLabel,className,idDiv){var ctrl=new de.novasib.ol.control.Button({handleClick:clickListener,label:label,tipLabel:tipLabel,className:className,idDiv:idDiv});this.olmap.addControl(ctrl);return ctrl};de.novasib.ol.NovaMap.prototype.addInputControl=function(listener,label,tipLabel,className){var ctrl=new de.novasib.ol.control.Input({label:label,tipLabel:tipLabel,handleClick:listener,className:className});this.olmap.addControl(ctrl)};
de.novasib.ol.NovaMap.prototype.addRadioControl=function(elements,tipLabel,collapsed,className){var elObjs=[];elements.forEach(function(el){elObjs.push({label:el})});var ctrl=new de.novasib.ol.control.Radio({elements:elObjs,tipLabel:tipLabel,className:className,collapsed:collapsed});ctrl.on("radiochange",function(event){this.dispatchEvent(new de.novasib.ol.NovaMap.Event("radiochange",{label:event.label}))}.bind(this));this.olmap.addControl(ctrl)};
de.novasib.ol.NovaMap.prototype.updateLayerSwitcher=function(layers){if(layers){if(!Array.isArray(layers))layers=[layers];var ctrl=this.getControlByClass(de.novasib.ol.control.LayerSwitcher);if(!ctrl){ctrl=new de.novasib.ol.control.LayerSwitcher({layers:layers});this.olmap.addControl(ctrl)}else layers.forEach(function(layer){ctrl.addElement(layer)})}};
de.novasib.ol.NovaMap.prototype.updateToolboxPanel=function(layers){if(layers){if(!Array.isArray(layers))layers=[layers];var ctrl=this.getControlByClass(de.novasib.ol.control.ToolboxPanel);if(!ctrl){ctrl=new de.novasib.ol.control.ToolboxPanel({layers:layers});this.olmap.addControl(ctrl)}else layers.forEach(function(layer){ctrl.addElement(layer)})}};
de.novasib.ol.NovaMap.prototype.initInteractions_=function(){var $jscomp$this=this;var interactions=ol.interaction.defaults({altShiftDragRotate:false,pinchRotate:false,pinchZoom:false});var segmentation=new de.novasib.ol.interaction.Segmentation({startPropertyName:de.novasib.ol.FeatureProperties.VST,endPropertyName:de.novasib.ol.FeatureProperties.BST,pixelTolerance:10});segmentation.on("segmentationfinished",function(evt){var f=evt.feature;$jscomp$this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.FEATURESTATIONED,
{"feature":f,"previousStartValue":evt.previousStartValue,"previousEndValue":evt.previousEndValue,"changed":evt.changed}))});interactions.push(segmentation);return interactions};de.novasib.ol.NovaMap.prototype.getSelectInteraction=function(){return this.getInteractionByClass(de.novasib.ol.interaction.HoverSelect)};
de.novasib.ol.NovaMap.prototype.initLayers_=function(wsLayers){if(wsLayers){if(!Array.isArray(wsLayers))wsLayers=[wsLayers];var layerSwitcherElements=[];var $jscomp$loop$62={};var i=0;for(;i<wsLayers.length;$jscomp$loop$62={wl:$jscomp$loop$62.wl},++i){$jscomp$loop$62.wl=wsLayers[i];var olLayer=null;var type=typeof $jscomp$loop$62.wl.type=="string"?$jscomp$loop$62.wl.type.toLowerCase():"";switch(type){case "wfs":case "vector":{olLayer=this.createVectorLayer_($jscomp$loop$62.wl);if($jscomp$loop$62.wl.selectable){this.selectableLayers.push(olLayer);
if($jscomp$loop$62.wl.groupSelect)olLayer.set("groupSelect",$jscomp$loop$62.wl.groupSelect)}if($jscomp$loop$62.wl.tooltip){if(typeof $jscomp$loop$62.wl.tooltip==="string")olLayer.set(de.novasib.ol.LayerProperties.TOOLTIP_PATTERN,$jscomp$loop$62.wl.tooltip);this.tooltipLayers.push(olLayer)}if($jscomp$loop$62.wl.snapLayer)this.snapLayer=olLayer;if($jscomp$loop$62.wl.styleProperties)olLayer.set(de.novasib.ol.LayerProperties.STYLE_CHANGE_PROPERTIES,$jscomp$loop$62.wl.styleProperties);break}case "tile":case "tms":{olLayer=
this.createTmsLayer_($jscomp$loop$62.wl);break}case "wms":{olLayer=this.createWmsLayer_($jscomp$loop$62.wl);break}case "wmts":{if($jscomp$loop$62.wl.capabilitiesUrl)this.createWmtsLayerFromCapabilities_($jscomp$loop$62.wl,function($jscomp$loop$62){return function(layer){this.addLayer_(layer);if($jscomp$loop$62.wl.inLayerSwitcher)this.updateLayerSwitcher(layer)}}($jscomp$loop$62).bind(this),ol.nullFunction);else olLayer=this.createWmtsLayer_($jscomp$loop$62.wl);break}default:{this.logger("Couldn't create layer of type "+
$jscomp$loop$62.wl.type);break}}if(olLayer){this.addLayer_(olLayer);if($jscomp$loop$62.wl.inLayerSwitcher)layerSwitcherElements.push(olLayer)}}if(layerSwitcherElements.length>0)this.updateLayerSwitcher(layerSwitcherElements)}};
de.novasib.ol.NovaMap.prototype.initView_=function(){var initialView=this.workspace.initialView;var wsRes=this.workspace.resolutions;var res=initialView.resolution;if(!res&&wsRes)res=wsRes[Math.floor(wsRes.length/2)];return new ol.View({center:[initialView.centerX,initialView.centerY],resolutions:wsRes,projection:this.projection,resolution:res,enableRotation:false,zoom:initialView.zoom,minZoom:initialView.minZoom,maxZoom:initialView.maxZoom})};
de.novasib.ol.NovaMap.prototype.createVectorLayer_=function(wsLayer){var mbb=wsLayer.extent||this.workspace.maxBoundingBox;var minRes=wsLayer.minResolution;var maxRes=wsLayer.maxResolution;var visible=wsLayer.visible;var isBackgroundLayer=wsLayer.backgroundLayer;return new ol.layer.Vector({title:wsLayer.title,name:wsLayer.name,"backgroundLayer":isBackgroundLayer,"stylename":wsLayer.styleName,"forceLayerStyle":wsLayer.forceLayerStyle,"showOrientation":wsLayer.showOrientation,source:this.createVectorSource_(wsLayer),
minResolution:minRes,maxResolution:maxRes,extent:mbb,visible:visible,zIndex:wsLayer.zIndex,style:function(feature,resolution){return feature.getStyle()},declutter:wsLayer.declutter})};
de.novasib.ol.NovaMap.prototype.createVectorSource_=function(wsLayer){var $jscomp$this=this;var ft=wsLayer.featureType;var url_=wsLayer.url||"";var urlFunc=url_;var name=wsLayer.name||wsLayer.title;if(wsLayer.type==="wfs")urlFunc=de.novasib.ol.getWfsUrlFunction(url_,ft,wsLayer.version,name,this.olmap);var formatId=wsLayer.format;var format_=de.novasib.ol.loadFormat(formatId,this.workspace,wsLayer);var user=wsLayer.username;var password=wsLayer.password;var styleChangeProperties=wsLayer.styleProperties;
var successFunction=de.novasib.ol.style.getStyledFeatureFunctionForLayer(this.olmap,this.styleManager,ft,name,styleChangeProperties);var failureFunction=function(){};var loader_;if(wsLayer.data&&urlFunc){var data=wsLayer.data;loader_=de.novasib.ol.featureloader.loadFeaturesXhrPost(urlFunc,format_,data,user,password,successFunction,failureFunction,wsLayer.sourceExtract)}else if(urlFunc)loader_=de.novasib.ol.featureloader.loadFeaturesXhr(urlFunc,format_,user,password,successFunction,failureFunction);
var src=new ol.source.Vector({format:format_,loader:loader_,strategy:function(extent,resolution){if(wsLayer.format==="TTSIB"){var olSourceVector=this;if(olSourceVector.resolution&&olSourceVector.resolution!==resolution)if(!olmap.vectorLayerBlacklist.includes(name))olSourceVector.clear(true)}return[extent]},wrapX:false,attributions:wsLayer.attributions});src.on(ol.source.VectorEventType.ADDFEATURE,function(evt){var f=evt.feature;if(f)$jscomp$this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.FEATUREADDED,
{"layer":name,"feature":f}))});return src};de.novasib.ol.NovaMap.prototype.createWmsLayer_=function(wsLayer){var minRes=wsLayer.minResolution;var maxRes=wsLayer.maxResolution;var visible_=wsLayer.visible;var isBackgroundLayer=wsLayer.backgroundLayer;return new ol.layer.Image({title:wsLayer.title,name:wsLayer.name,"backgroundLayer":isBackgroundLayer,source:this.createWmsSource_(wsLayer),visible:visible_,minResolution:minRes,maxResolution:maxRes,zIndex:wsLayer.zIndex,opacity:wsLayer.opacity})};
de.novasib.ol.NovaMap.prototype.createWmsSource_=function(wsLayer){var url_=wsLayer.url;var lyrs=wsLayer.layers.join(",");var styles=wsLayer.styles.join(",");var ver=wsLayer.version;if(!ver)ver="1.3.0";var proj_=de.novasib.ol.loadProjection(wsLayer.epsgSRID)||this.projection;var params_={"LAYERS":lyrs,"STYLES":styles,"VERSION":ver};if(wsLayer.params)for(var prop in wsLayer.params)params_[prop]=wsLayer.params[prop];var imageLoadFunction=wsLayer.imageLoadFunction||de.novasib.ol.source.ImageWMSExt.defaultImageLoadFunction;
return new de.novasib.ol.source.ImageWMSExt({url:url_,params:params_,projection:proj_,crossOrigin:"anonymous",attributions:wsLayer.attributions,ignoreAxisOrientation:wsLayer.ignoreAxisOrientation,imageLoadFunction:imageLoadFunction})};
de.novasib.ol.NovaMap.prototype.createTmsLayer_=function(wsLayer){var minRes=wsLayer.minResolution;var maxRes=wsLayer.maxResolution;var visible_=wsLayer.visible||false;var isBackgroundLayer=wsLayer.backgroundLayer;return new ol.layer.Tile({title:wsLayer.title,name:wsLayer.name,"backgroundLayer":isBackgroundLayer,source:this.createTileSource_(wsLayer),minResolution:minRes,maxResolution:maxRes,visible:visible_,preload:0,zIndex:wsLayer.zIndex})};
de.novasib.ol.NovaMap.prototype.createTileSource_=function(wsLayer){var proj_=de.novasib.ol.loadProjection(wsLayer.epsgSRID)||this.projection;var wsRes=this.workspace.resolutions||[];var mbb=wsLayer.extent||this.workspace.maxBoundingBox;var provider=wsLayer.provider;var ret=null;var tileLoadFunction=wsLayer.imageLoadFunction;switch(provider){case "bing":{ret=new ol.source.BingMaps({key:wsLayer.key,imagerySet:wsLayer.url||"",maxZoom:wsLayer.maxZoom,wrapX:false,attributions:wsLayer.attributions,crossOrigin:"anonymous",
tileLoadFunction:tileLoadFunction});break}case "xyz":{ret=new ol.source.XYZ({url:wsLayer.url,maxZoom:wsLayer.maxZoom,projection:proj_,wrapX:false,attributions:wsLayer.attributions,crossOrigin:"anonymous",tileLoadFunction:tileLoadFunction});break}case "osm":{ret=new ol.source.OSM({url:wsLayer.url,wrapX:false,attributions:wsLayer.attributions,crossOrigin:"anonymous",tileLoadFunction:tileLoadFunction});break}case "ttsib":{ret=new ol.source.TileImage({tileUrlFunction:function(coordinate){if(coordinate){var url;
if(wsLayer.url)url=wsLayer.url;else if(wsLayer.urls){var max=wsLayer.urls.length-1;url=wsLayer.urls[de.novasib.ol.getRandomInt(max)]}if(url)return url+coordinate[0]+"/"+coordinate[1]+"/"+coordinate[2]+".png"}return null},projection:proj_,wrapX:false,transition:0,opaque:false,tileGrid:new ol.tilegrid.TileGrid({extent:mbb,resolutions:wsRes,origin:ol.extent.getBottomLeft(mbb)}),crossOrigin:"anonymous",attributions:wsLayer.attributions});break}default:{ret=new ol.source.TileImage({url:wsLayer.url,urls:wsLayer.urls,
projection:proj_,wrapX:false,transition:0,opaque:false,tileGrid:new ol.tilegrid.TileGrid({extent:mbb,resolutions:wsRes}),crossOrigin:"anonymous",attributions:wsLayer.attributions,tileLoadFunction:tileLoadFunction})}}return ret};
de.novasib.ol.NovaMap.prototype.createWmtsLayer_=function(wsLayer){var minRes=wsLayer.minResolution;var maxRes=wsLayer.maxResolution;var visible_=wsLayer.visible||false;var isBackgroundLayer=wsLayer.backgroundLayer;return new ol.layer.Tile({title:wsLayer.title,name:wsLayer.name,"backgroundLayer":isBackgroundLayer,source:this.createWmtsSource_(wsLayer),minResolution:minRes,maxResolution:maxRes,visible:visible_,preload:2,zIndex:wsLayer.zIndex})};
de.novasib.ol.NovaMap.prototype.createWmtsSource_=function(wsLayer){var proj_=de.novasib.ol.loadProjection(wsLayer.epsgSRID)||this.projection;var version_=wsLayer.version||"1.0.0";var layer_=wsLayer.layers.join(",");var style_=wsLayer.styles.join(",");var format_=wsLayer.format||"image/png";var matrixSet_=wsLayer.matrixSet;var tileLoadFunction=wsLayer.imageLoadFunction;return new ol.source.WMTS({tileGrid:this.createWmtsTileGrid_(wsLayer),projection:proj_,layer:layer_,style:style_,version:version_,
format:format_,matrixSet:matrixSet_,urls:wsLayer.urls,url:wsLayer.url,attributions:wsLayer.attributions,tileLoadFunction:tileLoadFunction})};de.novasib.ol.NovaMap.prototype.createWmtsTileGrid_=function(wsLayer){var mbb=wsLayer.extent||this.workspace.maxBoundingBox;var wsRes=this.workspace.resolutions||[];var ids=wsLayer.matrixIds||[];return new ol.tilegrid.WMTS({extent:mbb,resolutions:wsRes,matrixIds:ids})};
de.novasib.ol.NovaMap.prototype.createWmtsLayerFromCapabilities_=function(wsLayer,success,failure){var capabilitiesUrl=wsLayer.capabilitiesUrl||"";var layer_=wsLayer.layers;var matrixSet_=wsLayer.matrixSet;var isBackgroundLayer=wsLayer.backgroundLayer;var zindex=wsLayer.zIndex;var visible_=wsLayer.visible;var xhr=new XMLHttpRequest;xhr.open("GET",capabilitiesUrl,true);if(wsLayer.username&&wsLayer.password){var usr=wsLayer.username;var pass=wsLayer.password;var creds=usr+":"+pass;xhr.setRequestHeader("Authorization",
"Basic "+btoa(creds))}xhr.onload=function(evt){if(xhr.status>=200&&xhr.status<300){var parser=new ol.format.WMTSCapabilities;var txt=xhr.responseText;var res=parser.read(txt);var options=ol.source.WMTS.optionsFromCapabilities(res,{"layer":layer_,"matrixSet":matrixSet_,"crossOrigin":"anonymous"})||{"crossOrigin":"anonymous"};if(wsLayer.attributions)options.attributions=wsLayer.attributions;var tileLoadFunction=wsLayer.imageLoadFunction;var layer=new ol.layer.Tile({source:new ol.source.WMTS(options||
{}),title:wsLayer.title,name:wsLayer.name,"backgroundLayer":isBackgroundLayer,opacity:1,visible:visible_,zIndex:zindex,tileLoadFunction:tileLoadFunction});success.call(this,layer)}};xhr.onerror=function(){failure.call(this)};xhr.send()};de.novasib.ol.NovaMap.prototype.initIconLayer_=function(){var src=new ol.source.Vector;this.iconLayer_=new ol.layer.Vector({source:src,title:"symbols",name:"symbols",zIndex:1E4});this.addLayer_(this.iconLayer_)};
de.novasib.ol.NovaMap.prototype.initDrawModifyLayer_=function(){var src=new ol.source.Vector;this.drawModifyLayer_=new ol.layer.Vector({source:src,title:"freehand",zIndex:9999});this.addLayer_(this.drawModifyLayer_)};
de.novasib.ol.NovaMap.prototype.initSelect_=function(style,hoverstyle){var $jscomp$this=this;var select=this.getInteractionByClass(de.novasib.ol.interaction.HoverSelect);if(!select){select=new de.novasib.ol.interaction.HoverSelect({layers:function(layer){return ol.array.includes(this.selectableLayers,layer)}.bind(this),wrapX:false,hitTolerance:5,style:style,hoverStyle:hoverstyle});select.setActive(false);select.on("select",function(evt){var selectedObjs=[];var deselectedObjs=[];evt.selected.forEach(function(feature){selectedObjs.push({"id":feature.getId(),
"feature":feature,"coordinates":feature.getGeometry().getCoordinates()})});evt.deselected.forEach(function(feature){deselectedObjs.push({"id":feature.getId(),"feature":feature,"coordinates":feature.getGeometry().getCoordinates()})});$jscomp$this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.SELECT,{"selected":selectedObjs,"deselected":deselectedObjs,"layer":evt.layerName}))});select.on("hover",function(evt){$jscomp$this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.HOVER,
{"hovered":evt.selected,"unhovered":evt.deselected}))});this.olmap.addInteraction(select)}else select.setStyles(style,hoverstyle);return select};de.novasib.ol.NovaMap.prototype.unselectIfSelected_=function(feature){if(feature){var styleName=feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME);if(styleName&&styleName!=="default"){var select=this.getInteractionByClass(de.novasib.ol.interaction.HoverSelect);if(select)select.deselect(feature)}}};
de.novasib.ol.NovaMap.prototype.initTooltip=function(){var $jscomp$this=this;var tooltip=new de.novasib.ol.interaction.Tooltip({layers:function(layer){return ol.array.includes(this.tooltipLayers,layer)}.bind(this),hitTolerance:5,mapTargetElement:this.olmap.getTargetElement()});tooltip.on("beforeFeatureTooltip",function(evt){$jscomp$this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.BEFOREFEATURETOOLTIP,{"feature":evt.feature}))});this.olmap.addInteraction(tooltip)};
de.novasib.ol.NovaMap.prototype.setTooltipHitTolerance=function(tolerance){var tooltip=this.getInteractionByClass(de.novasib.ol.interaction.Tooltip);if(tooltip&&tooltip.getActive())tooltip.setHitTolerance(tolerance)};
de.novasib.ol.NovaMap.prototype.initIconInteraction_=function(){var $jscomp$this=this;if(!this.iconLayer_)this.initIconLayer_();var icon=new de.novasib.ol.interaction.Icon({source:this.iconLayer_.getSource(),features:new ol.Collection,iconStyle:function(resolution){return new ol.style.Style({image:new ol.style.Circle({fill:new ol.style.Fill({color:"rgba(200, 0, 0, 0.25)"}),stroke:new ol.style.Stroke({color:"rgba(200, 0, 0, 0.5)",width:2}),radius:12})})},pixelTolerance:10});this.olmap.addInteraction(icon);
icon.setActive(false);icon.on("drawend",function(evt){var arr=evt.features;var len=arr?arr.length:-1;if(len!=-1){var feature=arr[len-1];var coordinates=feature.getGeometry().getCoordinates();$jscomp$this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.ADDICON,{"feature":feature,"coordinates":coordinates}))}});icon.on("rotateend",function(evt){var arr=evt.features;var len=arr?arr.length:-1;if(len!=-1){var feature=arr[len-1];var coordinates=feature.getGeometry().getCoordinates();
var rota=de.novasib.ol.style.getFeatureRotation(feature);$jscomp$this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.FEATUREROTATED,{"feature":feature,"coordinates":coordinates,"rotation":rota}))}});icon.on("modifyend",function(evt){var arr=evt.features;var len=arr?arr.length:-1;if(len!=-1){var feature=arr[len-1];var coordinates=feature.getGeometry().getCoordinates();$jscomp$this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.FEATUREMOVED,{"feature":feature,
"coordinates":coordinates}))}});return icon};de.novasib.ol.NovaMap.prototype.initFreeTextInteraction_=function(){var $jscomp$this=this;if(!this.iconLayer_)this.initIconLayer_();var freeText=new de.novasib.ol.interaction.FreeText({source:this.iconLayer_.getSource(),pixelTolerance:10});freeText.on("freetextadded",function(){$jscomp$this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.FREETEXTADDED))});this.olmap.addInteraction(freeText);freeText.setActive(false);return freeText};
de.novasib.ol.NovaMap.prototype.initDrawInteraction_=function(){var $jscomp$this=this;if(!this.drawModifyLayer_)this.initDrawModifyLayer_();var src=this.drawModifyLayer_.getSource();var draw=new ol.interaction.Draw({source:src,type:ol.geom.GeometryType.LINE_STRING});draw.on("drawend",function(evt){var feature=evt.feature;var coordinates=feature.getGeometry().getCoordinates();$jscomp$this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.FEATUREDRAWN,{"feature":feature,"coordinates":coordinates}))});
this.olmap.addInteraction(draw);draw.setActive(false);return draw};
de.novasib.ol.NovaMap.prototype.initModifyInteraction_=function(){var $jscomp$this=this;if(!this.drawModifyLayer_)this.initDrawModifyLayer_();var src=this.drawModifyLayer_.getSource();var modify=new ol.interaction.Modify({source:src});modify.on("modifyend",function(evt){var features=evt.features;if(features&&features.getLength()>0){var f=features.item(0);var coords=f.getGeometry().getCoordinates();$jscomp$this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.FEATUREMODIFIED,{"feature":f,
"coordinates":coords}))}});this.olmap.addInteraction(modify);modify.setActive(false);return modify};de.novasib.ol.NovaMap.prototype.getInteractionByClass=function(type,callback){if(type===undefined)return;var ret=null;var interactions=this.olmap.getInteractions();for(var i=0;i<interactions.getLength();++i){var inter=interactions.item(i);if(inter instanceof type){ret=inter;if(callback&&typeof callback==="function")callback(ret);break}}return ret};
de.novasib.ol.NovaMap.prototype.getControlByClass=function(type,callback){if(type===undefined)return;var ret=null;var controls=this.olmap.getControls();for(var i=0;i<controls.getLength();++i){var control$45=controls.item(i);if(control$45 instanceof type){ret=control$45;if(callback&&typeof callback==="function")callback(ret);break}}return ret};
de.novasib.ol.NovaMap.prototype.addLayer_=function(layer){if(this.olmap){this.olmap.addLayer(layer);this.dispatchEvent(new de.novasib.ol.NovaMap.Event(de.novasib.ol.Events.LAYERADDED,{"layer":layer,"properties":layer.getProperties()}))}};de.novasib.ol.NovaMap.Event=function(type,content){this.content={};if(content)for(var prop in content)if(content.hasOwnProperty(prop)){this[prop]=content[prop];this.content[prop]=content[prop]}ol.events.Event.call(this,type)};
ol.inherits(de.novasib.ol.NovaMap.Event,ol.events.Event);goog.exportSymbol("NovaMap",de.novasib.ol.NovaMap);de.novasib.ol.NovaMap.prototype.getLayersByName=function(name){return de.novasib.ol.getLayersByName(this.olmap,name)};goog.exportSymbol("NovaMap.prototype.getLayersByName",de.novasib.ol.NovaMap.prototype.getLayersByName);de.novasib.ol.NovaMap.prototype.getZoomForExtent=function(extent){return de.novasib.ol.getZoomForExtent(extent,this.olmap)};
de.novasib.ol.NovaMap.prototype.getLayersByNameAndType=function(name,type,callback){var ret=null;if(name&&type){type=type.toLocaleLowerCase();switch(type){case "wfs":case "vector":{ret=de.novasib.ol.getLayersByName(this.olmap,name,ol.layer.Vector);break}case "wmts":case "tile":case "tms":{ret=de.novasib.ol.getLayersByName(this.olmap,name,ol.layer.Tile);break}case "image":case "wms":{ret=de.novasib.ol.getLayersByName(this.olmap,name,ol.layer.Image);break}}}if(callback&&typeof callback==="function")if(Array.isArray(ret)&&
ret.length>0)callback(ret);return ret};de.novasib.ol.NovaMap.prototype.setLayerVisible=function(name,visible){if(name&&typeof name==="string"){var layers=this.getLayersByName(name);layers.forEach(function(lyr){lyr.setVisible(visible)}.bind(this))}};de.novasib.ol.NovaMap.prototype.toggleLayer=function(name){if(name&&typeof name=="string"){var layers=this.getLayersByName(name);layers.forEach(function(lyr){if(lyr)lyr.setVisible(!lyr.getVisible())})}};
de.novasib.ol.NovaMap.prototype.getLayerNames=function(propertyFilter){var filter=ol.functions.TRUE;if(propertyFilter){var prop=propertyFilter.name;var val=propertyFilter.value;filter=function(layer){return layer.get(prop)===val}}var names=[];this.olmap.getLayers().forEach(function(layer){if(filter(layer)){var name=layer.get(de.novasib.ol.LayerProperties.TITLE)||layer.get(de.novasib.ol.LayerProperties.NAME);if(name)names.push(name)}});return names};
de.novasib.ol.NovaMap.prototype.isLayerVisible=function(name){var l=this.getLayersByName(name)[0];return l?l.getVisible():false};de.novasib.ol.NovaMap.prototype.getHoverOverlay=function(){var interaction_=this.getInteractionByClass(de.novasib.ol.interaction.HoverSelect);if(interaction_){interaction_.hoverOverlay_.set("NOMINE","interaction.HoverSelect.hoverOverlay_");return interaction_.hoverOverlay_}};
de.novasib.ol.NovaMap.prototype.getFeatureOverlay=function(){var interaction_=this.getInteractionByClass(de.novasib.ol.interaction.HoverSelect);if(interaction_){interaction_.featureOverlay_.set("NOMINE","interaction.HoverSelect.featureOverlay_");return interaction_.featureOverlay_}};
de.novasib.ol.NovaMap.prototype.getSegmentationOverlay=function(){var interaction_=this.getInteractionByClass(de.novasib.ol.interaction.Segmentation);if(interaction_){interaction_.overlay_.set("NOMINE","interaction.Segmentation.overlay_");return interaction_.overlay_}};de.novasib.ol.NovaMap.prototype.getIconOverlay=function(){var interaction_=this.getInteractionByClass(de.novasib.ol.interaction.Icon);if(interaction_){interaction_.overlay_.set("NOMINE","interaction.Icon.overlay_");return interaction_.overlay_}};
de.novasib.ol.NovaMap.prototype.getSnapOverlay=function(){var interaction_=this.getInteractionByClass(de.novasib.ol.interaction.Snap);if(interaction_){interaction_.overlay_.set("NOMINE","interaction.Snap.overlay_");return interaction_.overlay_}};de.novasib.ol.NovaMap.prototype.getInteractions=function(){var ret=false;var interactions_=this.olmap.getInteractions();if(interactions_){var array_=interactions_.getArray();if(array_)ret=array_}return ret};
de.novasib.ol.NovaMap.prototype.getOverlays=function(){var overlays=[];overlays.push(this.getHoverOverlay());overlays.push(this.getFeatureOverlay());overlays.push(this.getSegmentationOverlay());overlays.push(this.getIconOverlay());overlays.push(this.getSnapOverlay());return overlays};
de.novasib.ol.NovaMap.prototype.addFeatureToLayer=function(feature,layerName,skipFeatures){if(feature&&layerName){var featureType=layerName;feature.set(de.novasib.ol.FeatureProperties.LAYER_NAME,layerName);if(layerName=="symbols"){if(!this.iconLayer_)this.initIconLayer_();this.iconLayer_.getSource().addFeature(feature)}else if(layerName=="freehand"){if(!this.drawModifyLayer_)this.initDrawModifyLayer_();this.drawModifyLayer_.getSource().addFeature(feature)}else{var layer=this.getLayersByNameAndType(layerName,
"vector")[0];if(!layer){console.log("Keinen Layer '"+layerName+"' gefunden!");return}if(layer instanceof ol.layer.Vector){var res=this.olmap.getView().getResolution();if(res)if(layer.get("forceLayerStyle")){var styleFunction=layer.getStyleFunction();if(styleFunction)return styleFunction.call(layer,feature,res);else{var style=layer.getStyle();if(style)if(typeof style=="function")return style.call(layer,feature,res);else return style}}else{var changeProperties=layer.get(de.novasib.ol.LayerProperties.STYLE_CHANGE_PROPERTIES);
var styleFunction$46=de.novasib.ol.style.getFeatureStyleFunction(feature,this.olmap,this.styleManager,featureType);var style$47=styleFunction$46(res);feature.setStyle(style$47);var map$48=this.olmap;de.novasib.ol.feature.setFeatureStyleChangeListeners(feature,changeProperties,function(event){var res=map$48.getView().getResolution();var style=styleFunction$46(res);feature.setStyle(style)})}layer.getSource().addFeature(feature);if(skipFeatures)this.skipFeatureIfAtSameLocation_(feature,layer)}}}};
de.novasib.ol.NovaMap.prototype.skipFeatureIfAtSameLocation_=function(feature,layer){if(feature&&layer){var source=layer.getSource();if(source&&source instanceof ol.source.Vector){var geom=feature.getGeometry();var coord=geom.getFirstCoordinate();if(coord){var feature$49=source.getClosestFeatureToCoordinate(coord);console.log("found "+(feature$49?"":"no ")+"features at coord "+coord);if(feature$49){var fGeom=feature$49.getGeometry();if(de.novasib.ol.geom.equals(geom,fGeom))this.skipFeature(feature$49,
layer.get("name")||layer.get("title"))}}}}};
de.novasib.ol.NovaMap.prototype.getFeatureWithSameGeom=function(feature,layername,godeep){var ret=null;if(feature&&layername){var layer=this.getLayersByNameAndType(layername,"vector")[0];if(layer){var source=layer.getSource();if(source instanceof ol.source.Vector){var callback=function(feat){if(de.novasib.ol.feature.haveEqualGeometries(feature,feat))return feat};if(!godeep){var extent=de.novasib.ol.extent.getBufferedExtent(feature.getGeometry().getExtent());if(!ol.extent.isEmpty(extent))ret=source.forEachFeatureInExtent(extent,
callback)}else ret=source.forEachFeature(callback)}}}return ret};goog.exportSymbol("NovaMap.prototype.getFeatureWithSameGeom",de.novasib.ol.NovaMap.prototype.getFeatureWithSameGeom);
de.novasib.ol.NovaMap.prototype.getClosestFeatureToFeature=function(feature,layername){if(feature&&layername){var layer=this.getLayersByNameAndType(layername,"vector")[0];if(layer){var source=layer.getSource();if(source instanceof ol.source.Vector){var geom=feature.getGeometry();if(geom){var coord;if(geom.getType()===ol.geom.GeometryType.POINT)coord=geom.getFirstCoordinate();else{var coords=geom.getCoordinates();coord=coords[Math.floor(coords.length/2)]}var ret;var px=this.olmap.getPixelFromCoordinate(coord);
this.olmap.forEachFeatureAtPixel(px,function(f,layer){var found=false;if(de.novasib.ol.feature.haveEqualGeometries(f,feature)){ret=f;found=true}return found},{layerFilter:function(layer){var lyr=layer.get("name")||layer.get("title");if(lyr===layername)return true;return false},hitTolerance:25});if(!ret)ret=source.getClosestFeatureToCoordinate(coord);return ret}}}}return null};goog.exportSymbol("NovaMap.prototype.getClosestFeatureToFeature",de.novasib.ol.NovaMap.prototype.getClosestFeatureToFeature);
de.novasib.ol.NovaMap.prototype.skipFeature=function(feature,layerName){if(feature&&layerName){if(!this.getLayersByNameAndType(layerName,"vector")[0]){console.log("Could not skip feature! Layer with name '"+layerName+"' does not exist.");return}if(!this.skippedFeaturesForLayers[layerName])this.skippedFeaturesForLayers[layerName]=[];this.skippedFeaturesForLayers[layerName].push(feature);this.olmap.skipFeature(feature);console.log("skipping feature")}};
de.novasib.ol.NovaMap.prototype.unskipFeatures=function(layerName){var $jscomp$this=this;if(!layerName);else{if(!this.getLayersByNameAndType(layerName,"vector")[0]||!this.skippedFeaturesForLayers[layerName]||this.skippedFeaturesForLayers[layerName].length===0)return;this.skippedFeaturesForLayers[layerName].forEach(function(feature){$jscomp$this.olmap.unskipFeature(feature)});delete this.skippedFeaturesForLayers[layerName]}};
de.novasib.ol.NovaMap.prototype.setLayerSelectable=function(layerName,selectable){var layers=this.getLayersByNameAndType(layerName,"vector");layers.forEach(function(layer){if(!selectable){var idx=this.selectableLayers.indexOf(layer);if(idx>=0)this.selectableLayers.splice(idx,1)}else if(this.selectableLayers.indexOf(layer)===-1)this.selectableLayers.push(layer)}.bind(this))};
de.novasib.ol.NovaMap.prototype.setLayerTooltip=function(layerName,tooltip){var layers=this.getLayersByNameAndType(layerName,"vector");layers.forEach(function(layer){if(tooltip){layer.set(de.novasib.ol.LayerProperties.TOOLTIP_PATTERN,tooltip);this.tooltipLayers.push(layer)}else{layer.unset(de.novasib.ol.LayerProperties.TOOLTIP_PATTERN);var idx=this.tooltipLayers.indexOf(layer);if(idx>=0)this.tooltipLayers.splice(idx,1)}}.bind(this))};
de.novasib.ol.NovaMap.prototype.setLayerData=function(layerName,data,opt_options){var options=opt_options||{};var layers=this.getLayersByNameAndType(layerName,"vector");var wsLayers=this.workspace.getLayersByNameAndType(layerName,"vector");function getWsLayer(l){for(var i=0;i<wsLayers.length;++i){var wsLyr=wsLayers[i];var t=l.get(de.novasib.ol.LayerProperties.TITLE);var n=l.get(de.novasib.ol.LayerProperties.NAME);if(wsLyr&&wsLyr.name==n&&wsLyr.title==t&&de.novasib.ol.isSameLayerType_("vector",wsLyr.type))return wsLyr}}
layers.forEach(function(layer){var source=layer.getSource();var wsLayer=getWsLayer(layer);var ft=wsLayer.featureType;var user=wsLayer.username;var password=wsLayer.password;var name=wsLayer.name||wsLayer.title;var styleChangeProperties=wsLayer.styleProperties;var successFunction=de.novasib.ol.style.getStyledFeatureFunctionForLayer(this.olmap,this.styleManager,ft,name,styleChangeProperties);var failureFunction=function(){};var url=source.getUrl()||wsLayer.url;var format=source.getFormat();if(!format){var formatId=
wsLayer.format;if(!formatId)formatId="GeoJSON";format=de.novasib.ol.loadFormat(formatId,this.workspace,wsLayer)}var loader=de.novasib.ol.featureloader.loadFeaturesXhrPost(url,format,data,user,password,successFunction,failureFunction,wsLayer.sourceExtract);var extent=this.olmap.getView().calculateExtent();var projection=source.getProjection()||this.projection;var resolution=this.olmap.getView().getResolution();if(resolution){source.setLoader(loader);if(options.clear||options.fastClear)source.clear(options.fastClear);
if(options.reload&&layer.getVisible())source.loadFeatures(extent,resolution,projection)}}.bind(this))};
de.novasib.ol.NovaMap.prototype.reloadFeatures=function(options){var $jscomp$this=this;var layers=this.olmap.getLayers();var resolution=this.olmap.getView().getResolution()||0;var filter=ol.functions.TRUE;var layersToLoad=options["layers"];if(layersToLoad){if(!Array.isArray(layersToLoad))layersToLoad=[layersToLoad];filter=function(layer){if(layer){var name=layer.get("name");var title=layer.get("title");return layersToLoad.indexOf(name)!=-1||layersToLoad.indexOf(title)!=-1}return false}}if(resolution)layers.forEach(function(layer){if(layer&&
layer.getVisible()&&layer instanceof ol.layer.Vector)if(filter(layer)){var source=layer.getSource();if(source&&source instanceof ol.source.Vector){var extent=$jscomp$this.olmap.getView().calculateExtent();var projection=source.getProjection()||$jscomp$this.projection;if(options["clear"]||options["fastClear"])source.clear(options["fastClear"]);if(options["reload"])source.loadFeatures(extent,resolution,projection)}}})};goog.exportSymbol("NovaMap.prototype.toggleLayer",de.novasib.ol.NovaMap.prototype.toggleLayer);
goog.exportSymbol("NovaMap.prototype.getLayerNames",de.novasib.ol.NovaMap.prototype.getLayerNames);goog.exportSymbol("NovaMap.prototype.isLayerVisible",de.novasib.ol.NovaMap.prototype.isLayerVisible);goog.exportSymbol("NovaMap.prototype.addFeatureToLayer",de.novasib.ol.NovaMap.prototype.addFeatureToLayer);goog.exportSymbol("NovaMap.prototype.setLayerSelectable",de.novasib.ol.NovaMap.prototype.setLayerSelectable);goog.exportSymbol("NovaMap.prototype.setLayerTooltip",de.novasib.ol.NovaMap.prototype.setLayerTooltip);
goog.exportSymbol("NovaMap.prototype.setLayerData",de.novasib.ol.NovaMap.prototype.setLayerData);goog.exportSymbol("NovaMap.prototype.reloadFeatures",de.novasib.ol.NovaMap.prototype.reloadFeatures);
de.novasib.ol.NovaMap.prototype.zoomToSelection=function(){var i=this.olmap.getInteractions();var extent=null;i.forEach(function(interaction){if(interaction instanceof ol.interaction.Select){var features=interaction.getFeatures();if(features)if(features.getLength()===1)extent=features.item(0).getGeometry().getExtent();else if(features.getLength()>1){extent=[0,0,0,0];features.forEach(function(feature){var ex=feature.getGeometry().getExtent();var minx=ex[0];var miny=ex[1];var maxx=ex[2];var maxy=ex[3];
if(minx<extent[0]||extent[0]===0)extent[0]=minx;if(miny<extent[1]||extent[1]===0)extent[1]=miny;if(maxx>extent[2]||extent[2]===0)extent[2]=maxx;if(maxy>extent[3]||extent[3]===0)extent[3]=maxy})}}});if(extent)this.olmap.getView().fit(extent)};de.novasib.ol.NovaMap.prototype.zoomToFeature=function(feature,opt_options){var extent=feature.getGeometry().getExtent();if(extent){var broaderExtent=de.novasib.ol.extent.getBufferedExtent(extent);this.zoomToExtent(broaderExtent,opt_options)}};
de.novasib.ol.NovaMap.prototype.zoomToExtent=function(extent,opt_options){if(extent&&extent.length==4)this.olmap.getView().fit(extent,opt_options)};
de.novasib.ol.NovaMap.prototype.zoomToFeatures=function(features,opt_options){if(features&&features.length>0){var coordinates=[];features.forEach(function(feature){var geom;if(feature.get("HERKUNFT")=="EX")geom=feature.getGeometry();else{var vst=feature.get("VST");var bst=feature.get("BST");var alen=feature.get("ALEN")||feature.get("LEN");geom=de.novasib.ol.geom.getShortenedLineString(feature.getGeometry(),vst,bst,alen)}var featureCoords=geom.getCoordinates();ol.array.extend(coordinates,featureCoords)});
var extent=ol.extent.boundingExtent(coordinates);if(extent){var broaderExtent=de.novasib.ol.extent.getBufferedExtent(extent);this.zoomToExtent(broaderExtent,opt_options)}}};goog.exportSymbol("NovaMap.prototype.zoomToFeatures",de.novasib.ol.NovaMap.prototype.zoomToFeatures);
de.novasib.ol.NovaMap.prototype.setSnapInteractionActive=function(active){if(this.snapLayer){var snap=this.getInteractionByClass(de.novasib.ol.interaction.Snap);if(!snap){var lyr=this.snapLayer;var tooltip=this.getInteractionByClass(de.novasib.ol.interaction.Tooltip);snap=new de.novasib.ol.interaction.Snap({layer:lyr,tooltip:tooltip,withDistance:true});this.olmap.addInteraction(snap);snap.on("featuresnapped",function(evt){this.dispatchEvent(new de.novasib.ol.NovaMap.Event("featuresnapped",{"clickcoordinate":evt.pixelCoordinate,
"vertex":evt.vertex,"feature":evt.feature}))},this)}snap.setActive(active)}else console.error("Cannot activate snap interaction: No snap layer found!")};de.novasib.ol.NovaMap.prototype.setSnapInteractionWithDistance=function(withDistance){var snap=this.getInteractionByClass(de.novasib.ol.interaction.Snap);if(snap)snap.setWithDistance(withDistance)};
de.novasib.ol.NovaMap.prototype.initMeasureInteraction=function(type){var measure=new de.novasib.ol.interaction.Measure({type:type});this.olmap.addInteraction(measure);return measure};de.novasib.ol.NovaMap.prototype.setMeasureInteractionActive=function(active,type){var measure=this.getInteractionByClass(de.novasib.ol.interaction.Measure);if(!measure)measure=this.initMeasureInteraction(type);measure.setActive(active);if(active){if(!type)type=ol.geom.GeometryType.LINE_STRING;measure.setType(type)}};
de.novasib.ol.NovaMap.prototype.setMeasureInteractionType=function(type){var measure=this.getInteractionByClass(de.novasib.ol.interaction.Measure);if(measure&&measure.getActive())measure.setType(type)};
de.novasib.ol.NovaMap.prototype.setMeasureInteractionColors=function(stroke,fill){var measure=this.getInteractionByClass(de.novasib.ol.interaction.Measure);if(de.novasib.ol.PARENT_APP_NAME===de.novasib.ol.KNOWN_APP_NAMES.TTSIB){if(measure)measure.setColors(stroke,fill)}else if(measure&&measure.getActive())measure.setColors(stroke,fill)};
de.novasib.ol.NovaMap.prototype.setSelectInteractionActive=function(active,hoverOnly){if(active&&this.selectableLayers.length==0)console.warn("Auswahlwerkzeug aktviert, aber keine selektierbaren Ebenen gefunden!");var select_=this.getInteractionByClass(de.novasib.ol.interaction.HoverSelect);if(!select_)select_=this.initSelect_(undefined,undefined);select_.setActive(active);if(active&&hoverOnly!=undefined)select_.setHoverOnly(hoverOnly)};
de.novasib.ol.NovaMap.prototype.selectFeatures=function(features,layername,force){var select_=this.getInteractionByClass(de.novasib.ol.interaction.HoverSelect);if(select_&&(select_.getActive()||force))select_.select(features,layername)};de.novasib.ol.NovaMap.prototype.deselectFeatures=function(features,force){var select_=this.getInteractionByClass(de.novasib.ol.interaction.HoverSelect);if(select_&&(select_.getActive()||force))try{select_.deselect(features)}catch(e){}};
goog.exportSymbol("NovaMap.prototype.selectFeatures",de.novasib.ol.NovaMap.prototype.selectFeatures);goog.exportSymbol("NovaMap.prototype.deselectFeatures",de.novasib.ol.NovaMap.prototype.deselectFeatures);de.novasib.ol.NovaMap.prototype.setIconInteractionActive=function(active,mode){mode=mode===undefined?"draw":mode;var iconTool=this.getInteractionByClass(de.novasib.ol.interaction.Icon);if(!iconTool)iconTool=this.initIconInteraction_();iconTool.setActive(active);if(active)iconTool.setMode(mode)};
de.novasib.ol.NovaMap.prototype.setIconInteractionUniqueCandidate=function(feature){var iconTool=this.getInteractionByClass(de.novasib.ol.interaction.Icon);if(!iconTool){console.error("Icon interaction undefined.");return}iconTool.setUniqueCandidate(feature)};goog.exportSymbol("NovaMap.prototype.setIconInteractionUniqueCandidate",de.novasib.ol.NovaMap.prototype.setIconInteractionUniqueCandidate);
de.novasib.ol.NovaMap.prototype.drawIconAt=function(coords,mode){mode=mode===undefined?"modify":mode;var iconTool=this.getInteractionByClass(de.novasib.ol.interaction.Icon);if(iconTool&&iconTool.getActive()){iconTool.drawIconAt(coords);iconTool.setMode(mode)}};goog.exportSymbol("NovaMap.prototype.drawIconAt",de.novasib.ol.NovaMap.prototype.drawIconAt);
de.novasib.ol.NovaMap.prototype.setFreeTextInteractionActive=function(active){var freeText=this.getInteractionByClass(de.novasib.ol.interaction.FreeText);if(!freeText)freeText=this.initFreeTextInteraction_();freeText.setActive(active)};
de.novasib.ol.NovaMap.prototype.setFreeTextOptions=function(options){if(!options)return;var freeText=this.getInteractionByClass(de.novasib.ol.interaction.FreeText);if(freeText&&freeText.getActive())for(var prop in options)if(options.hasOwnProperty(prop)){var val=options[prop];switch(prop){case "text":{freeText.setText(val);break}case "rotation":{freeText.setRotation(val);break}case "fontSize":case "fontsize":{freeText.setFontSize(val);break}case "font":{freeText.setFont(val);break}case "color":{freeText.setColor(val);
break}case "backgroundColor":case "backgroundcolor":case "bgColor":case "bgcolor":{freeText.setBackgroundColor(val);break}case "borderColor":case "bordercolor":{freeText.setBorderColor(val);break}case "opacity":{freeText.setOpacity(val);break}}}};de.novasib.ol.NovaMap.prototype.modifyFreeText=function(feature){var freeText=this.getInteractionByClass(de.novasib.ol.interaction.FreeText);if(freeText){if(!freeText.getActive())freeText.setActive(true);freeText.setFeature(feature)}};
goog.exportSymbol("NovaMap.prototype.modifyFreeText",de.novasib.ol.NovaMap.prototype.modifyFreeText);de.novasib.ol.NovaMap.prototype.setFreeTextLocation=function(coords){var freeText=this.getInteractionByClass(de.novasib.ol.interaction.FreeText);if(freeText){if(!freeText.getActive())freeText.setActive(true);if(coords&&Array.isArray(coords)&&coords.length==2&&!Array.isArray(coords[0])){var feature=new ol.Feature(new ol.geom.Point(coords));freeText.setFeature(feature)}}};
goog.exportSymbol("NovaMap.prototype.setFreeTextLocation",de.novasib.ol.NovaMap.prototype.setFreeTextLocation);de.novasib.ol.NovaMap.prototype.cancelFreeText=function(){var freeText=this.getInteractionByClass(de.novasib.ol.interaction.FreeText);if(freeText&&freeText.getActive())freeText.abort()};goog.exportSymbol("NovaMap.prototype.cancelFreeText",de.novasib.ol.NovaMap.prototype.cancelFreeText);
de.novasib.ol.NovaMap.prototype.finishFreeText=function(){var freeText=this.getInteractionByClass(de.novasib.ol.interaction.FreeText);if(freeText&&freeText.getActive()){var feature=freeText.finish();if(feature)return{"feature":feature,"coordinates":feature.getGeometry().getFirstCoordinate()}}return null};goog.exportSymbol("NovaMap.prototype.finishFreeText",de.novasib.ol.NovaMap.prototype.finishFreeText);
de.novasib.ol.NovaMap.prototype.setDrawInteractionActive=function(active){var draw=this.getInteractionByClass(ol.interaction.Draw);if(!draw)draw=this.initDrawInteraction_();draw.setActive(active)};de.novasib.ol.NovaMap.prototype.setModifyInteractionActive=function(active){var modify=this.getInteractionByClass(ol.interaction.Modify);if(!modify)modify=this.initModifyInteraction_();modify.setActive(active)};
de.novasib.ol.NovaMap.prototype.setDoubleClickZoomActive=function(active){var dblClkZoom=this.getInteractionByClass(ol.interaction.DoubleClickZoom);if(dblClkZoom)dblClkZoom.setActive(active)};de.novasib.ol.NovaMap.prototype.setIconInteractionMode=function(mode){var iconTool=this.getInteractionByClass(de.novasib.ol.interaction.Icon);if(!iconTool)throw new Error("setIconToolMode: icon tool not found, try calling 'setIconToolActive' first");iconTool.setMode(mode)};
de.novasib.ol.NovaMap.prototype.removeIcon=function(feature){if(this.iconLayer_&&feature){this.unselectIfSelected_(feature);try{this.iconLayer_.getSource().removeFeature(feature)}catch(e){console.warn(e)}}};de.novasib.ol.NovaMap.prototype.clearIcons=function(fast){if(this.iconLayer_)try{var src=this.iconLayer_.getSource();src.forEachFeature(function(feature){this.unselectIfSelected_(feature)},this);src.clear(fast)}catch(e){console.warn(e)}};
de.novasib.ol.NovaMap.prototype.removeDrawnFeature=function(feature){if(this.drawModifyLayer_&&feature)try{this.drawModifyLayer_.getSource().removeFeature(feature)}catch(e){console.warn(e)}};de.novasib.ol.NovaMap.prototype.stationFeature=function(feature){var segmentation=this.getInteractionByClass(de.novasib.ol.interaction.Segmentation);if(segmentation){if(!segmentation.getActive())segmentation.setActive(true);segmentation.setFeature(feature)}};
de.novasib.ol.NovaMap.prototype.stopStationing=function(){var segmentation=this.getInteractionByClass(de.novasib.ol.interaction.Segmentation);if(segmentation&&segmentation.getActive())segmentation.setActive(false)};
de.novasib.ol.NovaMap.prototype.setClickBoxInteractionActive=function(active){var clickTool=this.getInteractionByClass(de.novasib.ol.interaction.ClickBox);if(!clickTool){clickTool=new de.novasib.ol.interaction.ClickBox;clickTool.on("mapclick",function(evt){this.dispatchEvent(new de.novasib.ol.NovaMap.Event("mapclick",{"coordinate":evt.coordinate,"zoom":evt.zoom}))}.bind(this));clickTool.on("boxend",function(evt){this.dispatchEvent(new de.novasib.ol.NovaMap.Event("boxend",{extent:evt.extent,zoom:evt.zoom}))}.bind(this));
this.olmap.addInteraction(clickTool)}clickTool.setActive(active)};de.novasib.ol.NovaMap.prototype.setClickBoxInteractionClickOnly=function(only){var clickTool=this.getInteractionByClass(de.novasib.ol.interaction.ClickBox);if(clickTool&&clickTool.getActive())clickTool.setClickOnly(only)};
de.novasib.ol.NovaMap.prototype.addLayerSwitcherElements=function(layers){if(layers){if(!Array.isArray(layers))layers=[layers];layers=layers.map(function(lyr){if(typeof lyr==="string"){var arr=this.getLayersByName(lyr);if(arr.length>0)return arr[0]}return lyr},this);var ctrl=this.getControlByClass(de.novasib.ol.control.LayerSwitcher);if(ctrl)layers.forEach(function(layer){ctrl.addElement(layer)},this)}};
de.novasib.ol.NovaMap.prototype.removeLayerSwitcherElements=function(layers){if(layers){if(!Array.isArray(layers))layers=[layers];layers=layers.map(function(lyr){if(typeof lyr==="string"){var arr=this.getLayersByName(lyr);if(arr.length>0)return arr[0]}return lyr},this);var ctrl=this.getControlByClass(de.novasib.ol.control.LayerSwitcher);if(ctrl)layers.forEach(function(layer){ctrl.removeElement(layer)},this)}};
de.novasib.ol.NovaMap.prototype.setLayerSwitcherElementsActive=function(layers,active){if(layers){if(!Array.isArray(layers))layers=[layers];layers=layers.map(function(lyr){if(typeof lyr==="string"){var arr=this.getLayersByName(lyr);if(arr.length>0)return arr[0]}return lyr},this);var ctrl=this.getControlByClass(de.novasib.ol.control.LayerSwitcher);if(ctrl)ctrl.setElementsActive(layers,active)}};de.novasib.ol.NovaMap.prototype.addToolboxPanelElements=function(){};
de.novasib.ol.NovaMap.prototype.removeToolboxPanelElements=function(){};de.novasib.ol.NovaMap.prototype.setToolboxPanelElementsActive=function(active){};goog.exportSymbol("NovaMap.prototype.zoomToSelection",de.novasib.ol.NovaMap.prototype.zoomToSelection);goog.exportSymbol("NovaMap.prototype.zoomToFeature",de.novasib.ol.NovaMap.prototype.zoomToFeature);goog.exportSymbol("NovaMap.prototype.zoomToExtent",de.novasib.ol.NovaMap.prototype.zoomToExtent);
goog.exportSymbol("NovaMap.prototype.setSelectInteractionActive",de.novasib.ol.NovaMap.prototype.setSelectInteractionActive);goog.exportSymbol("NovaMap.prototype.setIconInteractionActive",de.novasib.ol.NovaMap.prototype.setIconInteractionActive);goog.exportSymbol("NovaMap.prototype.setIconInteractionMode",de.novasib.ol.NovaMap.prototype.setIconInteractionMode);goog.exportSymbol("NovaMap.prototype.setDrawInteractionActive",de.novasib.ol.NovaMap.prototype.setDrawInteractionActive);
goog.exportSymbol("NovaMap.prototype.setModifyInteractionActive",de.novasib.ol.NovaMap.prototype.setModifyInteractionActive);goog.exportSymbol("NovaMap.prototype.setDoubleClickZoomActive",de.novasib.ol.NovaMap.prototype.setDoubleClickZoomActive);goog.exportSymbol("NovaMap.prototype.removeIcon",de.novasib.ol.NovaMap.prototype.removeIcon);goog.exportSymbol("NovaMap.prototype.removeDrawnFeature",de.novasib.ol.NovaMap.prototype.removeDrawnFeature);
goog.exportSymbol("NovaMap.prototype.stationFeature",de.novasib.ol.NovaMap.prototype.stationFeature);goog.exportSymbol("NovaMap.prototype.stopStationing",de.novasib.ol.NovaMap.prototype.stopStationing);goog.exportSymbol("NovaMap.prototype.setFreeTextInteractionActive",de.novasib.ol.NovaMap.prototype.setFreeTextInteractionActive);goog.exportSymbol("NovaMap.prototype.setFreeTextOptions",de.novasib.ol.NovaMap.prototype.setFreeTextOptions);
de.novasib.ol.NovaMap.prototype.addGeoJSONLayer=function(json,opt_options){var $jscomp$this=this;var options=opt_options||{};var proj=de.novasib.ol.loadProjection(json.projection)||this.projection;var format=new ol.format.GeoJSON({geometryName:"geometry"});var features=format.readFeatures(json,{dataProjection:proj,featureProjection:this.projection});var id=1;var newFeatures=[];features.forEach(function(feature){feature.setId(++id);newFeatures.push(feature)});var ft=options["featureType"];var name=
options["name"];newFeatures.forEach(function(feature){feature.set("FUTURE_ART","S");feature.setStyle(function(resolution){var scale=de.novasib.ol.getScaleFromResolution(resolution);var style=$jscomp$this.styleManager.getFeatureStyle(feature,ft,name,scale);var ret=null;if(style){if(Array.isArray(style)){ret=[];style.forEach(function(s){if(s)ret.push(s.clone())})}else ret=[style.clone()];if(feature.get(de.novasib.ol.FeatureProperties.WITH_ORIENTATION)){var orientStyles=de.novasib.ol.style.getOrientationStyles.call(feature,
$jscomp$this.olmap);if(orientStyles&&orientStyles.length>0)ret=orientStyles.concat(ret)}if(ret.length===0)ret=null}return ret})});var mbb=options["extent"]||this.workspace.maxBoundingBox;var maxRes=options["maxResolution"];var minRes=options["minResolution"];var visible=options["visible"]!==undefined?options["visible"]:true;var isBackgroundLayer=options["backgroundLayer"];var layer=new ol.layer.Vector({source:new ol.source.Vector({features:newFeatures}),title:options["title"],name:options["name"],
backgroundLayer:isBackgroundLayer,extent:mbb,visible:visible,minResolution:minRes,maxResolution:maxRes,zIndex:50,wrapX:false});if(options["selectable"]){this.selectableLayers.push(layer);if(options.groupSelect)layer.set("groupSelect",options.groupSelect)}if(options["tooltip"]){if(typeof options["tooltip"]==="string")layer.set(de.novasib.ol.LayerProperties.TOOLTIP_PATTERN,options["tooltip"]);this.tooltipLayers.push(layer)}this.addLayer_(layer)};
goog.exportSymbol("NovaMap.prototype.addGeoJSONLayer",de.novasib.ol.NovaMap.prototype.addGeoJSONLayer);de.novasib.ol.NovaMap.prototype.getCurrentViewport=function(){if(this.view_){var res=this.view_.getResolution();var center=this.view_.getCenter();return{"centerX":center[0],"centerY":center[1],"resolution":res}}};
de.novasib.ol.NovaMap.prototype.getCurrentBoundingBox=function(projection){var bb=this.olmap.getView().calculateExtent();var proj;if(projection instanceof ol.proj.Projection)proj=projection;else if(typeof projection==="string")proj=de.novasib.ol.loadProjection(projection);if(proj&&!ol.proj.equivalent(proj,this.projection))bb=ol.proj.transformExtent(bb,this.projection,proj);return bb};de.novasib.ol.NovaMap.prototype.getCurrentZoom=function(){if(this.view_)return Math.round(this.view_.getZoom())};
de.novasib.ol.NovaMap.prototype.updateSize=function(){if(this.olmap)this.olmap.updateSize()};de.novasib.ol.NovaMap.prototype.getResolutions=function(){if(this.view_)return this.view_.getResolutions()};
de.novasib.ol.NovaMap.prototype.removeFeatures=function(features,layerName){var $jscomp$this=this;if(features&&layerName){if(!Array.isArray(features))features=[features];var layer=this.getLayersByNameAndType(layerName,"vector")[0];if(layer){var src=layer.getSource();if(src instanceof ol.source.Vector)features.forEach(function(feature){try{$jscomp$this.unselectIfSelected_(feature);src.removeFeature(feature)}catch(e){console.warn(e)}})}}};goog.exportSymbol("NovaMap.prototype.removeFeatures",de.novasib.ol.NovaMap.prototype.removeFeatures);
de.novasib.ol.NovaMap.prototype.addGeoJSONFeatures=function(options){var $jscomp$this=this;var json=options.json;var layerName=options.layerName;var featureType=options.featureType;var clear=options.clear;var fastClear=options["fastClear"];var zoomToExtent=!!options.zoomToExtent;var layer=this.getLayersByNameAndType(layerName,"vector")[0];if(layerName==="freehand")layer=this.drawModifyLayer_;var features=[];if(layer){if(!featureType)featureType=layerName;var format=new ol.format.GeoJSON({geometryName:"geometry"});
var proj=options.useMapCRS?this.projection:de.novasib.ol.loadProjection(json.projection)||format.readProjectionFromObject(json);features=format.readFeatures(json,{dataProjection:proj,featureProjection:this.projection});var changeProperties=layer.get(de.novasib.ol.LayerProperties.STYLE_CHANGE_PROPERTIES);if(!features){console.log("addGeoJSONFeatures - Fehler beim parsen der featurecollection");return[]}var map$50=this.olmap;var res=map$50.getView().getResolution();features.forEach(function(feature){feature.set(de.novasib.ol.FeatureProperties.LAYER_NAME,
layerName);var styleFunction=de.novasib.ol.style.getFeatureStyleFunction(feature,map$50,$jscomp$this.styleManager,featureType);var style=styleFunction(res);feature.setStyle(style);de.novasib.ol.feature.setFeatureStyleChangeListeners(feature,changeProperties,function(event){var res=map$50.getView().getResolution();var style=styleFunction(res);feature.setStyle(style)})});var src=layer.getSource();if(clear||fastClear){src.forEachFeature(function(feature){this.unselectIfSelected_(feature)},this);src.clear(fastClear)}src.addFeatures(features);
if(zoomToExtent){var view=map$50.getView();var extent=src.getExtent();view.fit(extent,{duration:1E3})}}else console.error('addGeoJSONFeatures - konnte layer "'+layerName+'" nicht finden');return features};goog.exportSymbol("NovaMap.prototype.addGeoJSONFeatures",de.novasib.ol.NovaMap.prototype.addGeoJSONFeatures);
de.novasib.ol.NovaMap.prototype.addWKTFeature=function(options){var layerName=options.layer;var wkt=options.wkt;var clear=options.clear;var fastClear=options["fastClear"];if(layerName&&wkt){var layers=this.getLayersByNameAndType(layerName,"vector");if(layers&&layers.length>0){var wktFormat=new ol.format.WKT({splitCollection:options.splitCollection});var geom=wktFormat.readGeometry(wkt);if(geom){var feature=new ol.Feature(geom);feature.set("stylename",options["featureStyle"]);layers.forEach(function(layer){if(layer&&
layer.getSource()){var src=layer.getSource();if(clear||fastClear)src.clear(fastClear);src.addFeature(feature)}})}}}};de.novasib.ol.NovaMap.prototype.addLayer=function(config){var wsLayer=new de.novasib.ol.Layer(config);this.initLayers_(wsLayer);return wsLayer||null};de.novasib.ol.NovaMap.prototype.removeLayer=function(layer){if(layer){this.removeLayerSwitcherElements(layer);this.olmap.removeLayer(layer)}};
de.novasib.ol.NovaMap.prototype.parseGeoJSONFeatures=function(json){var features=[];if(json){var format=new ol.format.GeoJSON({geometryName:"geometry"});var proj=de.novasib.ol.loadProjection(json.projection)||format.readProjectionFromObject(json);features=format.readFeatures(json,{dataProjection:proj,featureProjection:this.projection});if(features.length==0)console.log("parseGeoJSONFeatures - Fehler beim parsen der featurecollection")}return features};
goog.exportSymbol("NovaMap.prototype.parseGeoJSONFeatures",de.novasib.ol.NovaMap.prototype.parseGeoJSONFeatures);
de.novasib.ol.NovaMap.prototype.getFeaturesByProperties=function(layerName,properties,singleResult,callback){singleResult=singleResult===undefined?false:singleResult;var ret=[];var layers=this.getLayersByNameAndType(layerName,"vector");if(layers.length>0&&properties)for(var i=0;i<layers.length;++i){var layer=layers[i];var source=layer.getSource();if(source&&source instanceof ol.source.Vector){var features=source.getFeatures();for(var i$51=0;i$51<features.length;++i$51){var feature=features[i$51];
var fits=true;for(var prop in properties)if(prop==="id"||prop==="ID"||prop==="Id"||prop==="id_")fits&=feature.getId()===properties[prop];else fits&=(feature.getProperty(prop)?feature.getProperty(prop).trim():false)===properties[prop];if(fits){if(singleResult){if(callback&&typeof callback==="function"){callback(feature);return}return feature}ret.push(feature)}}}}if(!singleResult)if(callback&&typeof callback==="function"){callback(ret);return}else return ret};
goog.exportSymbol("NovaMap.prototype.getFeaturesByProperties",de.novasib.ol.NovaMap.prototype.getFeaturesByProperties);goog.exportSymbol("NovaMap.prototype.getCurrentViewport",de.novasib.ol.NovaMap.prototype.getCurrentViewport);goog.exportSymbol("NovaMap.prototype.getCurrentZoom",de.novasib.ol.NovaMap.prototype.getCurrentZoom);goog.exportSymbol("NovaMap.prototype.updateSize",de.novasib.ol.NovaMap.prototype.updateSize);goog.exportSymbol("NovaMap.prototype.getCurrentBoundingBox",de.novasib.ol.NovaMap.prototype.getCurrentBoundingBox);
goog.exportSymbol("NovaMap.prototype.getResolutions",de.novasib.ol.NovaMap.prototype.getResolutions);goog.exportSymbol("NovaMap.prototype.on",de.novasib.ol.NovaMap.prototype.on);goog.exportSymbol("NovaMap.prototype.un",de.novasib.ol.NovaMap.prototype.un);goog.exportSymbol("NovaMap.prototype.once",de.novasib.ol.NovaMap.prototype.once);
de.novasib.ol.NovaMap.prototype.test3=function(font_,scale_,rota_,textColor_,bgColor_,bgStroke_,bgStrokeWidth_,text_){var text=new ol.style.Style({text:new ol.style.Text({font:font_,placement:"point",scale:scale_,rotation:rota_,text:text_,fill:new ol.style.Fill({color:textColor_}),backgroundFill:new ol.style.Fill({color:bgColor_}),backgroundStroke:new ol.style.Stroke({color:bgStroke_,width:bgStrokeWidth_}),padding:[5,5,5,5]})});var f=new ol.Feature(new ol.geom.Point([654924.5254430794,5647066.18256469]));
f.setStyle(text);if(!this.iconLayer_)this.initIconLayer_();this.iconLayer_.getSource().addFeature(f)};goog.exportSymbol("NovaMap.prototype.test3",de.novasib.ol.NovaMap.prototype.test3);de.novasib.ol.NovaMap.prototype.getVersion=function(){return this.version};goog.exportSymbol("NovaMap.prototype.getVersion",de.novasib.ol.NovaMap.prototype.getVersion);
de.novasib.ol.NovaMap.prototype.getFeaturesInCurrentExtent=function(){var $jscomp$this=this;var features={};if(this.olmap){var layers=this.olmap.getLayers();if(layers)layers.forEach(function(layer){if(layer&&layer instanceof ol.layer.Layer){var src=layer.getSource();if(src&&src instanceof ol.source.Vector){var name=layer.get("name")||layer.get("title");if(src.getFeatures().length!==0)features[name]=[];src.forEachFeatureInExtent($jscomp$this.olmap.getView().calculateExtent(),function(feature){features[name].push(feature)})}}})}return features};
goog.exportSymbol("NovaMap.prototype.getFeaturesInCurrentExtent",de.novasib.ol.NovaMap.prototype.getFeaturesInCurrentExtent);
de.novasib.ol.NovaMap.prototype.getParentAppName=function(){var ret;if(typeof appName!="undefined")ret=appName;else if(typeof Vwc!="undefined")ret=de.novasib.ol.KNOWN_APP_NAMES.SPERRINFOSYS;else if(typeof olwrapper!="undefined"&&typeof olwrapper.currentMap!="undefined")ret=de.novasib.ol.KNOWN_APP_NAMES.MBDE;else if(typeof olmap!="undefined")ret=de.novasib.ol.KNOWN_APP_NAMES.TTSIB;else ret=null;return ret};goog.exportSymbol("NovaMap.prototype.getParentAppName",de.novasib.ol.NovaMap.prototype.getParentAppName);
de.novasib.ol.NovaMap.prototype.waitForWithTimeout=function(payload,doneRecall,interval,timeout){(function(){var iv=setInterval(function(){payload()},interval);return setTimeout(function(){clearInterval(iv);doneRecall()},timeout)})()};goog.exportSymbol("NovaMap.prototype.waitForWithTimeout",de.novasib.ol.NovaMap.prototype.waitForWithTimeout);
de.novasib.ol.NovaMap.prototype.removeFeaturesByProperties=function(layerName,properties,callback){var this_=this;this_.getLayersByNameAndType(layerName,"vector",function(layer_){var source_=layer_[0].getSource();if(source_&&source_ instanceof ol.source.Vector){var features_=source_.getFeatures();if(features_&&properties)features_.some(function(feature_){var fits=false;for(var prop in properties)if(prop==="id"||prop==="ID"||prop==="Id"||prop==="id_")fits=feature_.getId()==properties[prop];else{var propValue=
feature_.getProperty(prop);if(propValue)if(typeof propValue==="string")fits=propValue.trim()===properties[prop].trim();else fits=propValue==properties[prop]}if(fits===true){this_.unselectIfSelected_(feature_);source_.removeFeature(feature_);if(callback&&typeof callback==="function")callback(feature_)}})}})};goog.exportSymbol("NovaMap.prototype.removeFeaturesByProperties",de.novasib.ol.NovaMap.prototype.removeFeaturesByProperties);
de.novasib.ol.NovaMap.prototype.getBasemapVectorTileLayer=function(args,callback){var strUrlLandesamt="https://sgx.geodatenzentrum.de";var strOpenInNewTab="target='_blank' rel='noopener noreferrer'";var strUrlLicense=strUrlLandesamt+"/web_public/gdz/lizenz/deu/basemapde_web_dienste_lizenz.pdf";var strCopyright="\u00a9";var constAttributions="<a href='"+strUrlLicense+"' "+strOpenInNewTab+">"+strCopyright+" basemap.de / BKG</a>";var constName="Basemap";var constUrl=strUrlLandesamt+"/gdz_basemapde_vektor/tiles/v1/bm_web_de_3857/{z}/{x}/{y}.pbf";
var constZIndex=0;var layers=[];var attributions_,name_,url_,zIndex_;if(args&&!ol.obj.isEmpty(args)){attributions_=args.attributions||constAttributions;name_=args.name||constName;url_=args.url||constUrl;zIndex_=args.zIndex||constZIndex}else{attributions_=constAttributions;name_=constName;url_=constUrl;zIndex_=constZIndex}var mvtformat=new ol.format.MVT;mvtformat.setLayers(["Vegetationsflaeche","Verkehrslinie","Siedlungsflaeche","Gewaesserflaeche","Name_Punkt","Grenze_Linie"]);layers.push(new ol.layer.VectorTile({backgroundLayer:true,
declutter:true,name:name_,source:new ol.source.VectorTile({attributions:attributions_,crossOrigin:"Anonymous",format:mvtformat,url:url_}),style:de.novasib.ol.getBaseMapVectorTileStyleFunction(),zIndex:zIndex_}));layers.push(new ol.layer.Tile({name:"BasemapHillshade",opacity:.3,source:new ol.source.WMTS({attributions:null,crossOrigin:"Anonymous",url:strUrlLandesamt+"/wmts_basemapde_schummerung/tile/1.0.0/de_basemapde_web_raster_hillshade/{Style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
layer:"0",matrixSet:"GLOBAL_WEBMERCATOR",format:"image/png",projection:ol.proj.get("EPSG:3857"),requestEncoding:"REST",tileGrid:new ol.tilegrid.WMTS({origin:[-2.00375083428E7,2.00375083428E7],resolutions:[156543.03392811998,78271.51696419998,39135.758481959994,19567.879241008,9783.939620504,4891.969810252,2445.984905126,1222.9924525644,611.4962262807999,305.74811314039994,152.87405657047998,76.43702828523999,38.21851414248,19.109257071295996,9.554628535647998,4.777314267823999,2.3886571339119995,
1.1943285669559998,.5971642834779999,.2985821417404,.1,.05],matrixIds:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21"],minZoom:0,maxZoom:20}),style:"default"})}));if(callback&&typeof callback==="function")if(layers&&layers.length>0)callback(layers);return layers};goog.exportSymbol("NovaMap.prototype.getBasemapVectorTileLayer",de.novasib.ol.NovaMap.prototype.getBasemapVectorTileLayer);
ol.Feature.prototype.getProperty=function(propKey){var props_=this.getProperties();var objectKeys=Object.keys(props_);if(typeof propKey==="string")for(var i=0;i<objectKeys.length;i++){var p=objectKeys[i];if(p.toLowerCase()===propKey.toLowerCase())return props_[p]}};goog.provide("de.novasib.ol.style.Cross");goog.require("ol");goog.require("ol.colorlike");goog.require("ol.render.canvas");goog.require("ol.style.RegularShape");de.novasib.ol.style.Cross=function(options){this.type_=de.novasib.ol.style.Cross.getType_(options.type);ol.style.RegularShape.call(this,{fill:options.fill,stroke:options.stroke,radius:options.radius,points:12})};ol.inherits(de.novasib.ol.style.Cross,ol.style.RegularShape);
de.novasib.ol.style.Cross.prototype.draw_=function(renderOptions,context,x,y){context.setTransform(1,0,0,1,0,0);context.translate(x+5,y+5.6);var radius=this.getRadius();var radiusThird=radius/3;var padding=2;var crossEdgeLength=2*radiusThird;if(this.type_==de.novasib.ol.style.Cross.Type_.X){context.rotate(Math.PI/4);context.translate(radius,-radius)}context.beginPath();context.moveTo(crossEdgeLength+padding,crossEdgeLength+padding);context.lineTo(crossEdgeLength+padding,padding);context.lineTo(2*
crossEdgeLength-padding,padding);context.lineTo(2*crossEdgeLength-padding,crossEdgeLength+padding);context.lineTo(3*crossEdgeLength-padding,crossEdgeLength+padding);context.lineTo(3*crossEdgeLength-padding,2*crossEdgeLength-padding);context.lineTo(2*crossEdgeLength-padding,2*crossEdgeLength-padding);context.lineTo(2*crossEdgeLength-padding,3*crossEdgeLength-padding);context.lineTo(crossEdgeLength+padding,3*crossEdgeLength-padding);context.lineTo(crossEdgeLength+padding,2*crossEdgeLength-padding);
context.lineTo(padding,2*crossEdgeLength-padding);context.lineTo(padding,crossEdgeLength+padding);context.lineTo(crossEdgeLength+padding,crossEdgeLength+padding);if(this.getFill()){var color=this.getFill().getColor();if(color==null)color=ol.render.canvas.defaultFillStyle;context.fillStyle=ol.colorlike.asColorLike(color);context.fill()}if(this.getStroke()){context.strokeStyle=renderOptions.strokeStyle;context.lineWidth=renderOptions.strokeWidth;if(renderOptions.lineDash){context.setLineDash(renderOptions.lineDash);
context.lineDashOffset=renderOptions.lineDashOffset}context.lineCap=renderOptions.lineCap;context.lineJoin=renderOptions.lineJoin;context.miterLimit=renderOptions.miterLimit;context.stroke()}context.closePath()};de.novasib.ol.style.Cross.Type_={CROSS:"cross",X:"x"};de.novasib.ol.style.Cross.getType_=function(type){var ret;if(type&&typeof type=="string"){type=type.toLowerCase();if(type==="x")ret=de.novasib.ol.style.Cross.Type_.X;else ret=de.novasib.ol.style.Cross.Type_.CROSS}return ret};goog.provide("de.novasib.ol.style.filter");goog.require("de.novasib.ol");de.novasib.ol.style.filter.PropertyName=function(node){return node.nodeValue||node.textContent};de.novasib.ol.style.filter.Literal=function(node){return node.nodeValue||node.textContent};
de.novasib.ol.style.filter.Function=function(node){if(node.attributes!=undefined&&node.attributes["name"]!=undefined){var context=window;if(de.novasib.ol.PARENT_APP_NAME===de.novasib.ol.KNOWN_APP_NAMES.SPERRINFOSYS)if(olwrapper.sldFilter!=undefined)context=olwrapper.sldFilter;var functionName=node.attributes["name"].value;var args=[];if(typeof functionName==="undefined")throw"ogc:Function - function name not specified";if(typeof context[functionName]!=="function")throw context+"."+functionName+" is not a function";
return function(){return context[functionName].apply(context,args)}}else new Error("ogc:Function - bad or missing function name")};
de.novasib.ol.style.filter.propertyAndExpectation=function(node){var property=null;var expectation=null;var children=node.childNodes;for(var i=0;i<children.length;++i){var child=children[i];var ln=child.localName;switch(ln){case "PropertyName":{property=de.novasib.ol.style.filter.PropertyName(child);break}case "Literal":{expectation=de.novasib.ol.style.filter.Literal(child);break}case "Function":{expectation=de.novasib.ol.style.filter.Function(child);break}}}return[property,expectation]};
de.novasib.ol.style.filter.getExpectionDate=function(expectation){var expectationDate;if(typeof expectation==="function")expectationDate=expectation();else if(expectation==="now")expectationDate=Date.now();else expectationDate=de.novasib.ol.parseDate(expectation);return expectationDate};
de.novasib.ol.style.filter.COMPARISON_OPERATORS=["PropertyIsEqualTo","PropertyIsNotEqualTo","PropertyIsLessThan","PropertyIsGreaterThan","PropertyIsLessThanOrEqualTo","PropertyIsGreaterThanOrEqualTo","PropertyIsLike","PropertyIsNull","PropertyIsNil","PropertyIsBetween"];
de.novasib.ol.style.filter["PropertyIsEqualTo"]=function(node){var args=de.novasib.ol.style.filter.propertyAndExpectation(node);var property=args[0];var expectation=args[1];return function(feature){if(de.novasib.ol.style.filter.isNumberOrStringOfNumber(feature,property)){var propNumber=Number(feature.get(property));var expectationNumber=Number(expectation);return propNumber===expectationNumber}else return feature.get(property)==expectation}};
de.novasib.ol.style.filter["PropertyIsNotEqualTo"]=function(node){var args=de.novasib.ol.style.filter.propertyAndExpectation(node);var property=args[0];var expectation=args[1];return function(feature){if(de.novasib.ol.style.filter.isNumberOrStringOfNumber(feature,property)){var propNumber=Number(feature.get(property));var expectationNumber=Number(expectation);return propNumber!==expectationNumber}else return feature.get(property)!=expectation}};
de.novasib.ol.style.filter["PropertyIsLessThan"]=function(node){var args=de.novasib.ol.style.filter.propertyAndExpectation(node);var property=args[0];var expectation=args[1];return function(feature){if(de.novasib.ol.style.filter.isDate(feature,property)){var propDate=de.novasib.ol.parseDate(feature.get(property));var expectationDate=de.novasib.ol.style.filter.getExpectionDate(expectation);return propDate<expectationDate}else if(de.novasib.ol.style.filter.isNumberOrStringOfNumber(feature,property)){var propNumber=
Number(feature.get(property));var expectationNumber=Number(expectation);return propNumber<expectationNumber}else return feature.get(property)<expectation}};
de.novasib.ol.style.filter["PropertyIsGreaterThan"]=function(node){var args=de.novasib.ol.style.filter.propertyAndExpectation(node);var property=args[0];var expectation=args[1];return function(feature){if(de.novasib.ol.style.filter.isDate(feature,property)){var propDate=de.novasib.ol.parseDate(feature.get(property));var expectationDate=de.novasib.ol.style.filter.getExpectionDate(expectation);return propDate>expectationDate}else if(de.novasib.ol.style.filter.isNumberOrStringOfNumber(feature,property)){var propNumber=
Number(feature.get(property));var expectationNumber=Number(expectation);return propNumber>expectationNumber}else return feature.get(property)>expectation}};
de.novasib.ol.style.filter["PropertyIsLessThanOrEqualTo"]=function(node){var args=de.novasib.ol.style.filter.propertyAndExpectation(node);var property=args[0];var expectation=args[1];return function(feature){if(de.novasib.ol.style.filter.isDate(feature,property)){var propDate=de.novasib.ol.parseDate(feature.get(property));var expectationDate=de.novasib.ol.style.filter.getExpectionDate(expectation);return propDate<=expectationDate}else if(de.novasib.ol.style.filter.isNumberOrStringOfNumber(feature,
property)){var propNumber=Number(feature.get(property));var expectationNumber=Number(expectation);return propNumber<=expectationNumber}else return feature.get(property)<=expectation}};
de.novasib.ol.style.filter["PropertyIsGreaterThanOrEqualTo"]=function(node){var args=de.novasib.ol.style.filter.propertyAndExpectation(node);var property=args[0];var expectation=args[1];return function(feature){if(de.novasib.ol.style.filter.isDate(feature,property)){var propDate=de.novasib.ol.parseDate(feature.get(property));var expectationDate=de.novasib.ol.style.filter.getExpectionDate(expectation);return propDate>=expectationDate}else if(de.novasib.ol.style.filter.isNumberOrStringOfNumber(feature,
property)){var propNumber=Number(feature.get(property));var expectationNumber=Number(expectation);return propNumber>=expectationNumber}else return feature.get(property)>=expectation}};de.novasib.ol.style.filter["PropertyIsNull"]=function(node){var args=de.novasib.ol.style.filter.propertyAndExpectation(node);var property=args[0];return function(feature){if(typeof feature.get(property)==="boolean"||typeof feature.get(property)==="number"||typeof feature.get(property)==="string")return false;else return!feature.get(property)}};
de.novasib.ol.style.filter["PropertyIsLike"]=function(node){var args=de.novasib.ol.style.filter.propertyAndExpectation(node);var property=args[0];var wildCard=node.getAttribute("wildCard");var singleChar=node.getAttribute("singleChar");var escapeChar=node.getAttribute("escape")||node.getAttribute("escapeChar");var expectation=de.novasib.ol.style.filter.value2regex(args[1],wildCard,singleChar,escapeChar);return function(feature){var regExp=new RegExp(expectation,"gi");return regExp.test(feature.get(property))}};
de.novasib.ol.style.filter.value2regex=function(value,wildCard,singleChar,escapeChar){if(wildCard==".")throw new Error("'.' is an unsupported wildCard character for the PropertyIsLike filter");wildCard=wildCard?wildCard:"*";singleChar=singleChar?singleChar:".";escapeChar=escapeChar?escapeChar:"!";value=value.replace(new RegExp("\\"+escapeChar+"(.|$)","g"),"\\$1");value=value.replace(new RegExp("\\"+singleChar,"g"),".");value=value.replace(new RegExp("\\"+wildCard,"g"),".*");value=value.replace(new RegExp("\\\\.\\*",
"g"),"\\"+wildCard);value=value.replace(new RegExp("\\\\\\.","g"),"\\"+singleChar);return value};de.novasib.ol.style.filter.SPATIAL_OPERATORS=["Equals","Disjoint","Touches","Within","Overlaps","Crosses","Intersects","Contains","DWithin","Beyond","BBOX"];de.novasib.ol.style.filter.TEMPORAL_OPERTATORS=["After","Before","Begins","BegunBy","TContains","During","EndedBy","Ends","TEquals","Meets","MetBy","TOverlaps","OverlappedBy","AnyInteracts"];
de.novasib.ol.style.filter.LOGICAL_OPERATORS=["And","Or","Not"];de.novasib.ol.style.filter["And"]=function(node){var expressions=de.novasib.ol.style.filter.createExpressions(node);return function(feature){var ret=true;if(expressions.length>=2)for(var i=0;i<expressions.length;++i){var func=expressions[i];ret&=func.call(this,feature);if(!ret)return false}return ret}};
de.novasib.ol.style.filter["Or"]=function(node){var expressions=de.novasib.ol.style.filter.createExpressions(node);return function(feature){var ret=false;if(expressions.length>=2)for(var i=0;i<expressions.length;++i){var func=expressions[i];ret|=func.call(this,feature);if(ret)return true}return ret}};
de.novasib.ol.style.filter["Not"]=function(node){var expressions=de.novasib.ol.style.filter.createExpressions(node);return function(feature){var ret=false;if(expressions.length===1){var func=expressions[0];return!func.call(this,feature)}return ret}};de.novasib.ol.style.filter.EXTENSION_OPERATORS=[];
de.novasib.ol.style.filter.create=function(node){var filter=null;if(node&&node.hasChildNodes()){var firstNode=node.firstChild;var ln=firstNode.localName;if(!de.novasib.ol.style.filter[ln])console.log("Filter-Ausdruck '"+ln+"' nicht unterst\u00fctzt!");else filter=de.novasib.ol.style.filter[ln].call(this,firstNode)}return filter};
de.novasib.ol.style.filter.createExpressions=function(node){var filters=[];if(node&&node.hasChildNodes()){var children=node.childNodes;for(var i=0;i<children.length;++i){var child=children[i];var ln=child.localName;if(!de.novasib.ol.style.filter[ln]){console.log("Filter-Ausdruck '"+ln+"' nicht unterst\u00fctzt!");continue}var f=de.novasib.ol.style.filter[ln].call(this,child);filters.push(f)}}return filters};
de.novasib.ol.style.filter.isDate=function(feature,property){var ret=false;var prop=feature.get(property);if(typeof prop==="string"){if(!Number(prop)){var timecode=de.novasib.ol.parseDate(prop);ret=timecode!=null}}else if(typeof prop==="object"&&prop instanceof Date)ret=true;return ret};de.novasib.ol.style.filter.isNumberOrStringOfNumber=function(feature,property){var prop=feature.get(property);return parseFloat(prop)==prop};goog.provide("de.novasib.ol.style.Rule");goog.require("de.novasib.ol.feature");goog.require("de.novasib.ol.geom");goog.require("de.novasib.ol.style");goog.require("de.novasib.ol.style.Cross");goog.require("de.novasib.ol.style.filter");goog.require("ol.array");goog.require("ol.geom.LineString");goog.require("ol.geom.Point");goog.require("ol.style.Circle");goog.require("ol.style.Fill");goog.require("ol.style.Icon");goog.require("ol.style.RegularShape");goog.require("ol.style.Stroke");goog.require("ol.style.Style");
goog.require("ol.style.Text");
de.novasib.ol.style.Rule=function(node,map,preventShortGeom){var $jscomp$this=this;this.name=undefined;this.title=undefined;this.abstract=undefined;this.maxScaleDenominator=Number.POSITIVE_INFINITY;this.minScaleDenominator=Number.NEGATIVE_INFINITY;this.filter=undefined;this.styles={};this.textProperty=undefined;this.withOrientation_=false;this.featureBasedIcons={};this.map_=map;this.preventShortGeom_=!!preventShortGeom;if(node&&node.hasChildNodes()){var children=node.childNodes;children.forEach(function(child){var ln=
child.localName;var val=child.nodeValue||child.textContent;switch(ln){case "Name":{$jscomp$this.name=val;break}case "Title":{$jscomp$this.title=val;break}case "MaxScaleDenominator":{$jscomp$this.maxScaleDenominator=parseFloat(val);break}case "MinScaleDenominator":{$jscomp$this.minScaleDenominator=parseFloat(val);break}case "PolygonSymbolizer":{$jscomp$this.addSymbolizerStyle(ol.geom.GeometryType.POLYGON,child);break}case "LineSymbolizer":{$jscomp$this.addSymbolizerStyle(ol.geom.GeometryType.LINE_STRING,
child);break}case "PointSymbolizer":{$jscomp$this.addSymbolizerStyle(ol.geom.GeometryType.POINT,child);break}case "TextSymbolizer":{$jscomp$this.addTextSymbolizerStyle(child);break}case "ogc:Filter":case "Filter":{$jscomp$this.filter=$jscomp$this.createFilter(child);break}}},this)}};de.novasib.ol.style.Rule.prototype.createFilter=function(filterNode){var ret=undefined;if(filterNode&&filterNode.hasChildNodes())ret=de.novasib.ol.style.filter.create(filterNode);return ret};
de.novasib.ol.style.Rule.prototype.filterApplies=function(feature){var applies=true;if(this.filter&&typeof this.filter==="function")applies=this.filter.call(this,feature);return applies};
de.novasib.ol.style.Rule.prototype.addTextSymbolizerStyle=function(node){var fill=null;var halo=null;var font="";if(node&&node.hasChildNodes()){var children=node.childNodes;for(var i=0;i<children.length;++i){var child=children[i];var ln=child.localName;switch(ln){case "Geometry":{break}case "Label":{if(child.hasChildNodes()){var propNode=child.firstChild;if(propNode)this.textProperty=propNode.nodeValue||propNode.textContent}else this.textProperty=child.nodeValue||child.textContent;break}case "Font":{font=
this.readFont(child);break}case "LabelPlacement":{break}case "Halo":{halo=this.readFill(child);break}case "Fill":{fill=this.readFill(child);break}}}}var newStyle=new ol.style.Style({text:new ol.style.Text({font:font,fill:fill,backgroundFill:halo}),zIndex:2E5});this.addStyle("Text",newStyle)};
de.novasib.ol.style.Rule.prototype.addSymbolizerStyle=function(type,node){var $jscomp$this=this;var stroke=null;var fill=null;var image=null;var offsets=[];if(node&&node.hasChildNodes()){var children=node.childNodes;for(var i=0;i<children.length;++i){var child=children[i];var ln=child.localName;switch(ln){case "Stroke":{stroke=this.readStroke(child);break}case "Fill":{fill=this.readFill(child);break}case "Graphic":case "Image":{image=this.readImage(type,child);break}case "Offset":{offsets.push(this.readOffset(child));
break}case "Orientation":{var val=child.nodeValue||child.textContent;this.withOrientation_=val==1;break}}}}if(offsets.length>0)offsets.forEach(function(offset){$jscomp$this.addStyle(type,$jscomp$this.getStyleForOffset(offset,stroke))});if(fill||stroke||image){var idx=this.withOrientation_?5:10;var newStyle=new ol.style.Style({geometry:this.getDefaultGeometryFunction(),fill:fill,stroke:stroke,image:image,zIndex:idx});this.addStyle(type,newStyle)}};
de.novasib.ol.style.Rule.prototype.addStyle=function(type,newStyle){if(!this.styles[type])this.styles[type]=[];this.styles[type].push(newStyle)};de.novasib.ol.style.Rule.prototype.addFeatureIconStyle=function(type,newStyle){if(!this.featureBasedIcons[type])this.featureBasedIcons[type]=[];this.featureBasedIcons[type].push(newStyle)};
de.novasib.ol.style.Rule.prototype.getStyleForOffset=function(offset,stroke){var perpendicular=offset.perpendicular;var geometryFunc=function(feature){var resolution=this.map_.getView().getResolution();var geom=feature.getGeometry().clone();if(feature.get("HERKUNFT")=="EX"||this.preventShortGeom_)return geom;var coords=geom.getCoordinates();var distance=perpendicular*resolution;var vst=feature.get("VST");var bst=feature.get("BST");if(!vst&&vst!=0)vst=0;if(!bst&&bst!=0)bst=feature.get("ALEN")||feature.get("LEN");
if(feature.get("RICHTUNG")=="G")distance*=-1;var length=geom.getLength();var newCoords=de.novasib.ol.geom.computeOffsetLineString(coords,length,distance,distance);var newGeom=new ol.geom.LineString(newCoords);return de.novasib.ol.geom.getShortenedLineString(newGeom,feature.get("VST"),feature.get("BST"),feature.get("ALEN")||feature.get("LEN"))}.bind(this);if(!stroke)stroke=new ol.style.Stroke;var offsetStroke=offset.stroke||{};var oColor=offsetStroke.color;var oOpacity=offsetStroke.opacity;var sColor=
stroke.getColor();var color=null;if(oColor)color=de.novasib.ol.style.getColorLike(oColor,oOpacity);else if(sColor&&oOpacity)color=de.novasib.ol.style.getColorLike(sColor,oOpacity);var width=offsetStroke.width||stroke.getWidth()||1;var dashoffset=offsetStroke.dashoffset||stroke.getLineDashOffset()||0;var linecap=offsetStroke.linecap||stroke.getLineCap();var linejoin=offsetStroke.linejoin||stroke.getLineJoin();var miterlimit=offsetStroke.miterlimit||stroke.getMiterLimit()||1;var newStroke=new ol.style.Stroke({color:color,
lineCap:linecap,lineJoin:linejoin,lineDashOffset:dashoffset,miterLimit:miterlimit,width:width});return new ol.style.Style({geometry:geometryFunc,stroke:newStroke,zIndex:10})};
de.novasib.ol.style.Rule.prototype.readOffset=function(node){var perpendicular=0;var stroke=null;if(node&&node.hasChildNodes()){var children=node.childNodes;for(var i=0;i<children.length;++i){var child=children[i];var ln=child.localName;var val=child.nodeValue||child.textContent;switch(ln){case "Stroke":{stroke=this.readOffsetStroke(child);break}case "Perpendicular":{perpendicular=parseFloat(val);break}}}}return new de.novasib.ol.style.Rule.PerpendicularOffset_({perpendicular:perpendicular,stroke:stroke})};
de.novasib.ol.style.Rule.prototype.readFill=function(node){var color="#000";var opacity=1;if(node&&node.hasChildNodes()){var children=node.childNodes;for(var i=0;i<children.length;++i){var child=children[i];var ln=child.localName;switch(ln){case "CssParameter":{var attrName=child.getAttribute("name");var val=child.nodeValue||child.textContent;switch(attrName){case "fill":{color=val;break}case "fill-opacity":{opacity=parseFloat(val);break}}break}}}}color=de.novasib.ol.style.getColorLike(color,opacity);
return new ol.style.Fill({color:color})};
de.novasib.ol.style.Rule.prototype.readStroke=function(node){var color="#000";var opacity=1;var width=1;var dashoffset=0;var dashArray=undefined;var linecap=undefined;var linejoin=undefined;var miterlimit=1;if(node&&node.hasChildNodes()){var children=node.childNodes;for(var i=0;i<children.length;++i){var child=children[i];var ln=child.localName;switch(ln){case "CssParameter":{var attrName=child.getAttribute("name");var val=child.nodeValue||child.textContent;switch(attrName){case "stroke":{color=val;
break}case "stroke-opacity":{opacity=parseFloat(val);break}case "stroke-width":{width=parseFloat(val);break}case "stroke-dashoffset":{dashoffset=parseFloat(val);break}case "stroke-dasharray":{if(val&&typeof val=="string"){var arr=val.split(" ");dashArray=[];arr.forEach(function(s){var number=parseInt(s,10);dashArray.push(number)})}break}case "stroke-linecap":{linecap=de.novasib.ol.style.getLineCap(val);break}case "stroke-linejoin":{linejoin=de.novasib.ol.style.getLineJoin(val);break}case "stroke-miterlimit":{miterlimit=
parseFloat(val);break}}break}}}}color=de.novasib.ol.style.getColorLike(color,opacity);return new ol.style.Stroke({color:color,lineCap:linecap,lineJoin:linejoin,lineDash:dashArray,lineDashOffset:dashoffset,miterLimit:miterlimit,width:width})};
de.novasib.ol.style.Rule.prototype.readOffsetStroke=function(node){var color=undefined;var width=undefined;var opacity=undefined;var dashoffset=undefined;var linecap=undefined;var linejoin=undefined;var miterlimit=undefined;if(node&&node.hasChildNodes()){var children=node.childNodes;for(var i=0;i<children.length;++i){var child=children[i];var ln=child.localName;switch(ln){case "CssParameter":{var attrName=child.getAttribute("name");var val=child.nodeValue||child.textContent;switch(attrName){case "stroke":{color=
val;break}case "stroke-opacity":{opacity=parseFloat(val);break}case "stroke-width":{width=parseFloat(val);break}case "stroke-dashoffset":{dashoffset=parseFloat(val);break}case "stroke-linecap":{linecap=de.novasib.ol.style.getLineCap(val);break}case "stroke-linejoin":{linejoin=de.novasib.ol.style.getLineJoin(val);break}case "stroke-miterlimit":{miterlimit=parseFloat(val);break}}break}}}}return new de.novasib.ol.style.Rule.PerpendicularOffsetStroke_({color:color,width:width,opacity:opacity,dashoffset:dashoffset,
linecap:linecap,linejoin:linejoin,miterlimit:miterlimit})};
de.novasib.ol.style.Rule.prototype.readImage=function(type,node){var opacity=1;var size=-1;var rotation=0;var fill=null;var stroke=null;var iconType=null;var wkn=null;var propertyColors=[];if(node&&node.hasChildNodes){var children=node.childNodes;for(var i=0;i<children.length;++i){var child=children[i];var ln=child.localName;var val=child.nodeValue||child.textContent;switch(ln){case "ExternalGraphic":{var extGraphicChildren=child.childNodes;for(var j=0;j<extGraphicChildren.length;++j){var extGraphChild=
extGraphicChildren[j];var extGraphLn=extGraphChild.localName;switch(extGraphLn){case "OnlineResource":{wkn=extGraphChild.getAttribute("xlink:href");iconType=de.novasib.ol.style.ImageTypes.ICON;break}}}break}case "Mark":{var markChildren=child.childNodes;for(var j$52=0;j$52<markChildren.length;++j$52){var markChild=markChildren[j$52];var markLn=markChild.localName;switch(markLn){case "WellKnownName":{wkn=markChild.nodeValue||markChild.textContent;if(de.novasib.ol.style.WELL_KNOWN_NAMES.includes(wkn))if(wkn===
de.novasib.ol.style.ImageTypes.CIRCLE)iconType=de.novasib.ol.style.ImageTypes.CIRCLE;else iconType=de.novasib.ol.style.ImageTypes.SHAPE;else iconType=de.novasib.ol.style.ImageTypes.ICON;break}case "Fill":{fill=this.readFill(markChild);break}case "Stroke":{stroke=this.readStroke(markChild);break}}}break}case "Opacity":{opacity=parseFloat(val);break}case "Size":{size=parseFloat(val);break}case "Rotation":{rotation=parseFloat(val);break}case "PropertyColor":{propertyColors.push(this.readPropertyColor(child));
break}}}}if(iconType)if(iconType===de.novasib.ol.style.ImageTypes.CIRCLE)return new ol.style.Circle({fill:fill,stroke:stroke,radius:size/2,opacity:opacity});else if(iconType===de.novasib.ol.style.ImageTypes.SHAPE){var pts=0;var angle=0;var radius1=undefined;var radius2=undefined;switch(wkn){case "square":{pts=4;angle=Math.PI/4;break}case "triangle":{pts=3;break}case "star":{pts=5;radius2=size/5;break}case "cross":{return new de.novasib.ol.style.Cross({fill:fill,stroke:stroke,radius:size})}case "x":{return new de.novasib.ol.style.Cross({fill:fill,
stroke:stroke,radius:size,type:"x"})}}return new ol.style.RegularShape({fill:fill,stroke:stroke,rotation:rotation,radius:size/2,radius1:radius1,radius2:radius2,points:pts,angle:angle,opacity:opacity})}else if(iconType===de.novasib.ol.style.ImageTypes.ICON){if(wkn.indexOf("~")!==-1)wkn=wkn.split("~")[0];var imgPath=wkn;var icon=new de.novasib.ol.style.Rule.FeatureIconStyle_({rotation:rotation,opacity:opacity,size:size,path:imgPath});this.addFeatureIconStyle(type,icon)}};
de.novasib.ol.style.Rule.prototype.readPropertyColor=function(node){var propertyName="";var propetyValue="";if(node&&node.hasChildNodes){var children=node.childNodes;for(var i=0;i<children.length;++i){var child=children[i];var ln=child.localName;var val=child.nodeValue||child.textContent;switch(ln){case "PropertyName":{propertyName=val;break}case "PropertyValue":{propetyValue=val;break}}}}return{name:propertyName,value:propetyValue}};
de.novasib.ol.style.Rule.prototype.readFont=function(node){var family="Arial";var style="";var weight="";var size=10;if(node&&node.hasChildNodes){var children=node.childNodes;for(var i=0;i<children.length;++i){var child=children[i];var ln=child.localName;switch(ln){case "CssParameter":{var attrName=child.getAttribute("name");var val=child.nodeValue||child.textContent;switch(attrName){case "font-family":{family=val;break}case "font-style":{style=val;break}case "font-weight":{weight=val;break}case "font-size":{size=
parseInt(val,10);break}}break}}}}return de.novasib.ol.style.font(style,weight,size,family)};
de.novasib.ol.style.Rule.prototype.setTextStyleOptions=function(feature,style){if(Array.isArray(style))style.forEach(function(s){this.setTextStyleOptions(feature,s)},this);else{var text=feature.get(this.textProperty)||"";style.getText().setText(text);var type=feature.getGeometry().getType();if(ol.geom.GeometryType.POINT===type){style.getText().setPlacement("point");style.getText().setTextAlign("left");style.getText().setOffsetX(10);style.getText().setOffsetY(-10)}else if(ol.geom.GeometryType.LINE_STRING===
type||ol.geom.GeometryType.POLYGON===type||ol.geom.GeometryType.MULTI_LINE_STRING===type||ol.geom.GeometryType.MULTI_POLYGON===type){style.getText().setPlacement("line");style.getText().setTextAlign("center")}}};de.novasib.ol.style.Rule.prototype.getStyles_=function(type){var ret=[];if(this.styles[type])ol.array.extend(ret,this.styles[type]);return ret};
de.novasib.ol.style.Rule.prototype.getStyle=function(feature){var type=feature.getGeometry().getType();var styles=this.getStyles_(type);if(this.withOrientation_)feature.set(de.novasib.ol.FeatureProperties.WITH_ORIENTATION,true);if(this.featureBasedIcons[type]){var icons=this.featureBasedIcons[type];for(var i=0;i<icons.length;++i){var fbi=icons[i];var path=fbi.getPath(feature);var style=feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME);var zidx=1E3;if(style==="select"||style==="hover")zidx=1001;
var size=undefined;if(fbi.size>0)size=[fbi.size,fbi.size];styles.push(new ol.style.Style({geometry:this.getDefaultIconGeometryFunction(),image:new ol.style.Icon({src:path,size:size,rotation:fbi.rotation,opacity:fbi.opacity}),zIndex:zidx}))}}return styles};de.novasib.ol.style.Rule.prototype.getTextStyle=function(){var ret;var styles=this.styles["Text"];if(styles)if(Array.isArray(styles)){ret=[];styles.forEach(function(style){if(style)ret.push(style.clone())})}else ret=styles.clone();return ret};
de.novasib.ol.style.Rule.prototype.getMaxScaleDenominator=function(){return this.maxScaleDenominator};de.novasib.ol.style.Rule.prototype.getMinScaleDenominator=function(){return this.minScaleDenominator};de.novasib.ol.style.Rule.PerpendicularOffset_=function(options){this.perpendicular=options.perpendicular||0;this.stroke=options.stroke};
de.novasib.ol.style.Rule.PerpendicularOffsetStroke_=function(options){this.color=options.color;this.width=options.width;this.opacity=options.opacity;this.dashoffset=options.dashoffset;this.linecap=options.linecap;this.linejoin=options.linejoin;this.miterlimit=options.miterlimit};
de.novasib.ol.style.Rule.FeatureIconStyle_=function(options){this.path=options.path;this.rotation=options.rotation;this.size=options.size;this.opacity=options.opacity;this.primaryProperty=options.primaryProperty;this.primaryValue=options.primaryValue;this.secondaryProperty=options.secondaryProperty;this.secondaryValue=options.secondaryValue};
de.novasib.ol.style.Rule.FeatureIconStyle_.prototype.getPath=function(feature){if(!feature)return this.path;else return de.novasib.ol.feature.formatTemplate(this.path,feature.getProperties())};
de.novasib.ol.style.Rule.prototype.getDefaultGeometryFunction=function(){return function(feature){var geom=feature.getGeometry();if(geom){var type=geom.getType();if(type===ol.geom.GeometryType.LINE_STRING){if(feature.get("HERKUNFT")=="EX"||this.preventShortGeom_)return geom;var start=feature.get(de.novasib.ol.FeatureProperties.VST);var end=feature.get(de.novasib.ol.FeatureProperties.BST);if(start==undefined&&end==undefined)return geom;return de.novasib.ol.geom.getShortenedLineString(feature.getGeometry(),
start,end,feature.get("ALEN")||feature.get("LEN"))}}return geom}.bind(this)};
de.novasib.ol.style.Rule.prototype.getDefaultIconGeometryFunction=function(){return function(feature){if(feature.getGeometry()){var geom=feature.getGeometry();var type=geom.getType();if(type===ol.geom.GeometryType.LINE_STRING){if(feature.get("HERKUNFT")=="EX"||this.preventShortGeom_)return geom;var startProp="VST";var endProp="BST";var start=feature.get(startProp);var end=feature.get(endProp);var shortendGeom=de.novasib.ol.geom.getShortenedLineString(geom,start,end,feature.get("ALEN")||feature.get("LEN"));
if(shortendGeom&&shortendGeom.getType()==ol.geom.GeometryType.LINE_STRING&&shortendGeom.getCoordinates().length>0){var pos=shortendGeom.getLength()/2;var coord=de.novasib.ol.geom.getPointOnLineString(shortendGeom,pos);return new ol.geom.Point(coord)}else{var pos$53=geom.getLength()/2;var coord$54=de.novasib.ol.geom.getPointOnLineString(geom,pos$53);return new ol.geom.Point(coord$54)}}return geom}}.bind(this)};de.novasib.ol.style.Rule.prototype.getDefaultStyle=function(){return this.styles};goog.provide("de.novasib.ol.style.FeatureTypeStyle");goog.require("de.novasib.ol.style.Rule");
de.novasib.ol.style.FeatureTypeStyle=function(node,map,preventShortGeom){var $jscomp$this=this;this.featureTypeName="";this.rules=[];if(node&&node.hasChildNodes()){var children=node.childNodes;children.forEach(function(child){var ln=child.localName;var val=child.nodeValue||child.textContent;switch(ln){case "FeatureTypeName":{$jscomp$this.featureTypeName=val;break}case "Rule":{$jscomp$this.rules.push(new de.novasib.ol.style.Rule(child,map,preventShortGeom));break}}},this)}};
de.novasib.ol.style.FeatureTypeStyle.prototype.getStyle=function(feature,featureType,scale){if(this.featureTypeName===featureType)if(this.rules&&this.rules.length>0){var ret=[];for(var i=0;i<this.rules.length;++i){var rule=this.rules[i];var applies=rule.filterApplies(feature);if(applies&&rule.getMaxScaleDenominator()>=scale&&rule.getMinScaleDenominator()<=scale){var style=rule.getStyle(feature);if(style)if(Array.isArray(style))ret=ret.concat(style);else ret.push(style);var tStyle=rule.getTextStyle();
if(tStyle){rule.setTextStyleOptions(feature,tStyle);if(Array.isArray(tStyle))ret=ret.concat(tStyle);else ret.push(tStyle)}}}return ret}};de.novasib.ol.style.FeatureTypeStyle.prototype.getDefaultStyle=function(){if(this.rules&&this.rules.length>0)return this.rules[0].getDefaultStyle()};goog.provide("de.novasib.ol.style.UserStyle");goog.require("de.novasib.ol.style.FeatureTypeStyle");
de.novasib.ol.style.UserStyle=function(node,map,preventShortGeom){var $jscomp$this=this;this.name="";this.title="";this.defaultStyle=false;this.featureTypeStyle=null;if(node&&node.hasChildNodes()){var children=node.childNodes;children.forEach(function(child){var ln=child.localName;var val=child.nodeValue||child.textContent;switch(ln){case "Name":{$jscomp$this.name=val;if($jscomp$this.name=="highlight")$jscomp$this.name="hover";break}case "Title":{$jscomp$this.title=val;break}case "IsDefault":{$jscomp$this.defaultStyle=
val=="1";break}case "FeatureTypeStyle":{$jscomp$this.featureTypeStyle=new de.novasib.ol.style.FeatureTypeStyle(child,map,preventShortGeom);break}}},this)}};de.novasib.ol.style.UserStyle.prototype.isDefault=function(){return this.defaultStyle};de.novasib.ol.style.UserStyle.prototype.getStyle=function(feature,featureType,scale){if(this.featureTypeStyle)return this.featureTypeStyle.getStyle(feature,featureType,scale)};de.novasib.ol.style.UserStyle.prototype.getDefaultStyle=function(){if(this.featureTypeStyle)return this.featureTypeStyle.getDefaultStyle()};goog.provide("de.novasib.ol.style.NamedLayer");goog.require("ol.array");goog.require("de.novasib.ol.style");goog.require("de.novasib.ol.style.UserStyle");
de.novasib.ol.style.NamedLayer=function(node,map,preventShortGeom){var $jscomp$this=this;this.name=undefined;this.userStyles=[];this.defaultUserStyle=null;if(node.hasChildNodes()){var children=node.childNodes;children.forEach(function(child){var ln=child.localName;var val=child.nodeValue||child.textContent;switch(ln){case "Name":{$jscomp$this.name=val;break}case "UserStyle":{var ustyle=new de.novasib.ol.style.UserStyle(child,map,preventShortGeom);if(ustyle){$jscomp$this.userStyles.push(ustyle);if(ustyle.defaultStyle)$jscomp$this.defaultUserStyle=
ustyle}break}}},this)}};
de.novasib.ol.style.NamedLayer.prototype.getStyle=function(feature,featureType,scale){if(this.userStyles&&this.userStyles.length>0)if(this.userStyles.length==1){var featureStyleName=feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME);if(featureStyleName=="hover"||featureStyleName=="select"){var layerStyles=this.userStyles[0].getStyle(feature,featureType,scale);var cloneStyles=this.getHoverStyle(layerStyles);return cloneStyles}else return this.userStyles[0].getStyle(feature,featureType,scale)}else{var ret=
null;var styleName=feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME)||feature.get(de.novasib.ol.FeatureProperties.LAYER_STYLE_NAME)||de.novasib.ol.style.DEFAULT_STYLE_NAME;if(styleName===de.novasib.ol.style.DEFAULT_STYLE_NAME)return this.defaultUserStyle.getStyle(feature,featureType,scale);for(var i=0;i<this.userStyles.length;++i){var userStyle=this.userStyles[i];if(userStyle&&userStyle.name==styleName){ret=userStyle.getStyle(feature,featureType,scale);break}}if(!ret||Array.isArray(ret)&&ret.length==
0){ret=[];var featureStyleName$55=feature.get(de.novasib.ol.FeatureProperties.STYLE_NAME);var layerStyleName=feature.get(de.novasib.ol.FeatureProperties.LAYER_STYLE_NAME);if((featureStyleName$55=="hover"||featureStyleName$55=="select")&&layerStyleName){var layerStyles$56;for(var i$57=0;i$57<this.userStyles.length;++i$57){var userStyle$58=this.userStyles[i$57];if(userStyle$58&&userStyle$58.name==layerStyleName){layerStyles$56=userStyle$58.getStyle(feature,featureType,scale);break}}var cloneStyles$59=
this.getHoverStyle(layerStyles$56);if(cloneStyles$59.length>0)ol.array.extend(ret,cloneStyles$59)}}return ret}};de.novasib.ol.style.NamedLayer.prototype.getDefaultStyle=function(){return this.defaultUserStyle.getDefaultStyle()};
de.novasib.ol.style.NamedLayer.prototype.getHoverStyle=function(styles){var ret=[];if(styles){if(!Array.isArray(styles))styles=[styles];styles.forEach(function(style){var cloneStyle=style.clone();if(cloneStyle.getStroke()){var newWidth=cloneStyle.getStroke().getWidth()*2;cloneStyle.getStroke().setWidth(newWidth)}if(cloneStyle.getImage()){var img=cloneStyle.getImage();var sizeString="size=";if(img instanceof ol.style.Icon&&typeof img.getSrc=="function"&&img.getSrc()&&typeof img.getSrc()=="string"&&
img.getSrc().indexOf(sizeString)!=-1){var src=img.getSrc();var idx=src.indexOf(sizeString);var size=src.substring(idx+sizeString.length,src.length+1);var sizeNum=parseFloat(size);if(typeof sizeNum=="number"&&!isNaN(sizeNum)){var newSize=2*sizeNum;var newSrc=src.replace(sizeString+size,sizeString+newSize);var newSizeArray=img.getSize()!==null?img.getSize().slice():undefined;if(newSizeArray&&Array.isArray(newSizeArray)&&newSizeArray.length==2&&newSizeArray[0]==sizeNum&&newSizeArray[1]==sizeNum)newSizeArray=
newSizeArray.map(function(x){return x*2});var newImg=de.novasib.ol.style.getIconClone(img,newSrc,newSizeArray);cloneStyle.setImage(newImg)}}else if(img instanceof ol.style.Circle){var newRadius=(img.getRadius()||1)*2;cloneStyle.getImage().setRadius(newRadius);var circleStroke=img.getStroke();if(circleStroke){var strokeClone=circleStroke.clone();var newWidth$60=strokeClone.getWidth()*2;cloneStyle.getImage().getStroke().setWidth(newWidth$60)}}else{var newScale=cloneStyle.getImage().getScale()*2;cloneStyle.getImage().setScale(newScale)}}if(cloneStyle.getText()){var newScale$61=
(cloneStyle.getText().getScale()||1)*2;cloneStyle.getText().setScale(newScale$61)}var newZindex=(cloneStyle.getZIndex()||0)+1;cloneStyle.setZIndex(newZindex);ret.push(cloneStyle)})}return ret};goog.addDependency("demos/editor/equationeditor.js",["goog.demos.editor.EquationEditor"],["goog.ui.equation.EquationEditorDialog"]);goog.addDependency("demos/editor/helloworld.js",["goog.demos.editor.HelloWorld"],["goog.dom","goog.dom.TagName","goog.editor.Plugin"]);
goog.addDependency("demos/editor/helloworlddialog.js",["goog.demos.editor.HelloWorldDialog","goog.demos.editor.HelloWorldDialog.OkEvent"],["goog.dom.TagName","goog.events.Event","goog.string","goog.ui.editor.AbstractDialog","goog.ui.editor.AbstractDialog.Builder","goog.ui.editor.AbstractDialog.EventType"]);
goog.addDependency("demos/editor/helloworlddialogplugin.js",["goog.demos.editor.HelloWorldDialogPlugin","goog.demos.editor.HelloWorldDialogPlugin.Command"],["goog.demos.editor.HelloWorldDialog","goog.dom.TagName","goog.editor.plugins.AbstractDialogPlugin","goog.editor.range","goog.functions","goog.ui.editor.AbstractDialog.EventType"]);})();
;
var olwrapper = {};

function MapInitException(message) {
    this.message = message;
    this.name = 'MapInitException';
}

function olWrapperGetCurrentDate() {
    var d = new Date();

    return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
}

function olWrapperInit() {
    olwrapper = {
        map: null,
        currentBackgroundLayer: '',
        selectedFeatures: [],
        freehandFeature: null,
        neueAnordnungSymbol: null,
        selectedSymbol: null,
        neueAnordnungOldSymbol: null,
        selectedInGrid: null,
        iconFeatureAssociation: {},
        detbeschIds: [],
        workspaces: {},
        dummyId: 0,
        freieUmleitungCancelled: false,
        sperrungenTooltipPrefix: '<b>${AMT}: ${AKTENZEICHEN}</b><br/>',
        sperrungenTooltip: '${VON_BIS}<br/>${S_ORTBEZ}<br/>${S_GRUND}',
        strassennetzTooltip: '<b>${STRNAME}</b><br/>${VNK}-${NNK}: ${ALEN}m',
        gstrassenTooltip: '<b>${STRNAME}</b><br/>${ALEN}m',
        tooltip: '',
        isBAB: null,
        resolutions: [],
        listeners: {
            anordnungen: {},
            dataRequest: {}
        },
        freeTextOptions: {},
        detailBeschilderung: null,
        version: "1.2.05",
        pathBgLayersXml: "../Content/hintergrundebenen.xml?v=" + olWrapperGetCurrentDate(),
        layerConfig: null,
        postJsonContent: false,
        dateTimeRef: null,
        sldFilter: {
            getDateTimeRef: function () {
                if (olwrapper.dateTimeRef != undefined) {
                    return olwrapper.dateTimeRef;
                }
                return Date.now();
            }
        }
    };

    olwrapper.init = function (config, layerCfg, target, sldpath, timebegin, timeend) {
        let workspace = {};

        patchNovaMap();

        if (!config) {
            throw new MapInitException('configobjekt ist null');
        }
        if (!layerCfg) {
            throw new MapInitException('layerconfig ist null');
        }
        this.layerConfig = layerCfg;

        let proj = config.PROJECTION;
        let mbr = config.MBR;
        let center = config.CENTROID;
        let initRes = config.INITIRES;
        let res = config.RESOLUTIONS.map(function (x) {
            return x[1];
        });
        this.resolutions = res;
        this.isBAB = !!config.BABUSER;

        if (config.TOOLTIP != undefined) {
            this.sperrungenTooltip = config.TOOLTIP;
        }
        this.tooltip = this.sperrungenTooltipPrefix + this.sperrungenTooltip;

        console.log("olwrapper version: " + this.version);

        workspace = this.getWorkspace(proj, mbr, center, initRes, res, layerCfg, sldpath, timebegin, timeend);
        let bgLyrs = this.loadBackgroundLayers(this.pathBgLayersXml);
        for (let i = 0; i < bgLyrs.length; ++i) {
            workspace.layers.push(bgLyrs[i]);
        }

        this.map = new NovaMap(workspace, target);
        this.map.once('mapinitialized', function () {
            this.map.setSelectInteractionActive(true);

            let lyrs = olwrapper.map.getLayersByName('editing');
            if (lyrs && lyrs.length === 1) {
                let lyr = lyrs[0];
                lyr.setStyle(editLayerStylesFunction());
            }

            olwrapper.map.addButtonControl(function () {
                refreshMap(true);
                console.log("button control mapRefresh click");
            }, "\u21BB", 'Karte neu laden', "de-novasib-ol-button-mapRefresh");

        }.bind(this));

        this.map.on(de.novasib.ol.Events.REFRESHMAP, function (e) {
            refreshMap(true);
        })
        
        this.map.on('visibilitychanged', function () {
            let selectFilter = {
                'stylename': 'select'
            };
            let hoverFilter = {
                'stylename': 'hover'
            };

            let selected = this.map.getFeaturesByProperties('SPERRUNGEN_SYMB', selectFilter);
            selected = $.merge(selected, this.map.getFeaturesByProperties('SPERRUNGEN_SYMB', hoverFilter));
            this.map.deselectFeatures(selected, true);

            this.map.reloadFeatures({
                layers: 'SPERRUNGEN_SYMB',
                clear: true
            });
        }.bind(this));

        this.map.on('featureadded', function (evt) {
            if (evt.layer === 'DET_BESCH') {
                let feature = evt.feature;
                if (feature.get('FILENAME')) {
                    let fname = feature.get('FILENAME').replace('.svg', '').replace('.SVG', '');
                    let path = Vwc.constants.imgPath.VZK_KLEIN + fname + '.png';
                    // 'ARC' kommt schon in Radians an, nicht wie erwartet in Degrees 
                    let rotaRadians = feature.get('ARC');

                    feature.setStyle(new ol.style.Style({
                        image: new ol.style.Icon({
                            src: path,
                            opacity: 1,
                            rotation: rotaRadians // rota
                        }),
                        zIndex: 1000
                    }));
                } else {
                    let font_ = de.novasib.ol.style.font('', '', feature.get('FONTSIZE'), feature.get('FONT'));
                    let textColor_ = de.novasib.ol.style.getColorLike(feature.get('COLOUR'));
                    let transparency = feature.get('TRANSPARENCY');
                    if (typeof transparency === 'string') {
                        transparency = Number.parseFloat(transparency);
                    }
                    let opacity = 1 - transparency;
                    let bgColor_ = de.novasib.ol.style.getColorLike(feature.get('BGRCOLOUR'), opacity);
                    let bgStroke_ = de.novasib.ol.style.getColorLike(feature.get('FRAMECOLOUR'), opacity);

                    let arc = feature.get('ARC');
                    let text = feature.get('BEZEICHNUNG');

                    feature.setStyle(new ol.style.Style({
                        text: new ol.style.Text({
                            font: font_,
                            placement: 'point',
                            scale: 1,
                            rotation: arc,
                            text: text,
                            fill: new ol.style.Fill({
                                color: textColor_
                            }),
                            backgroundFill: new ol.style.Fill({
                                color: bgColor_
                            }),
                            backgroundStroke: new ol.style.Stroke({
                                color: bgStroke_,
                                width: 2
                            }),
                            padding: [5, 5, 5, 5],
                            overflow: true
                        })
                    }));
                }
            }
        });
    };

    olwrapper.setDateTimeRef = function (stichTag) {
        this.dateTimeRef = stichTag;
    }

    olwrapper.logFeatures = function (heading, array) {
        if (array) {
            console.warn(heading);
            console.dir(array);
        }
    }
    olwrapper.showDetailbeschilderungFeatureArrays = function () {

        if (Vwc.gui.gridID !== "VwcNeueAnordnungDetailsBeschilderungGrid") {
            return 0;
        }

        let features;

        features = Vwc.gui.grid.dataSource.data();
        features ? olwrapper.logFeatures("Grid-Data", features) : null;

        features = olwrapper.getSelectedFeatures();
        features ? olwrapper.logFeatures("selectedFeatures-Array", features) : null;

        features = olwrapper.map.getLayersByName("symbols")[0].getSource().getFeatures();
        features ? olwrapper.logFeatures("Map-Features", features) : null;
    }

    olwrapper.addSelectedFeatures = function (arr) {
        if (arr) {
            // FIX fuer Detailbeschilderung/FreeText
            // features, die schon im selectedFeatures-Array vorhanden sind, werden ignoriert          
            if (arr.id) {
                let sf_ = this.selectedFeatures;
                for (let i = 0; i < sf_.length; ++i) {
                    if (sf_[i].id === arr.id) {
                        return 0;
                    }
                }
            }

            if (Array.isArray(arr)) {
                for (let i = 0; i < arr.length; ++i) {
                    this.selectedFeatures.push(arr[i]);
                }
            } else {
                this.selectedFeatures.push(arr);
            }
        }
    };

    olwrapper.removeSelectedFeatures = function (arr) {
        if (arr) {
            if (!Array.isArray(arr)) {
                arr = [arr];
            }
            for (let i = 0; i < arr.length; ++i) {
                let index = this.getSelectedFeatureIndexById(arr[i].feature.getId());
                if (index === -1) {
                    index = this.getSelectedFeatureIndexById(arr[i].id);
                }
                if (index !== -1) {
                    this.selectedFeatures.splice(index, 1);
                }
            }
        }
    };

    olwrapper.syncSelectedFeaturesWithGrid = function (gridDataItems) {
        /** 
         * find feature in selectedFeatures Array
         * update selectedFeature "id" (dummy-ID) mit gridDataItems.item.FeatureId
         * 
         * Vwc.states.gridItemsAdded ist das Array 
         * welches die dem Grid neu hinzugefuegten Datensaetze zwischenspeichert
        */

        // find added items in gridDataItems via gridItemsAdded.uid
        let gridNewDataItems = gridDataItems.filter(function (prop, index, array) {
            return Vwc.states.gridItemsAdded.filter(function (p, i, arr) {
                return prop.uid === p.uid;
            }).length !== 0
        });

        // damit sollten wir das gefilterte Array haben
        console.log("gridNewDataItems", gridNewDataItems);

        // get selectedFeatures
        let selectedFeatures = olwrapper.getSelectedFeatures();

        // get only selectedFeaturesBeschilderung
        let selectedFeaturesBeschilderung = selectedFeatures.filter(function (prop, index, array) {
            return prop.hasOwnProperty('rotation') 
        })

        // get corresponding features in selectedFeatures via gridNewDataItems.Geometrie
        // update with grid-item-ID (database-ID)
        let selectedFeaturesUpdated = selectedFeaturesBeschilderung.filter(function (prop, index, array) {
            return gridNewDataItems.filter(function (p, i, arr) {
                return JSON.stringify(prop.coordinates) === p.Geometrie ? prop.id = p.FeatureId : false;
            }).length !== 0
        })

        // selectedFeatures nach Update
        console.log("selectedFeaturesUpdated", selectedFeaturesUpdated);

    };

    olwrapper.getSelectedFeatureById = function (id) {
        if (id || id === 0) {
            for (let i = 0; i < this.selectedFeatures.length; ++i) {
                let sel = this.selectedFeatures[i];

                if (sel.feature.getId() == id || sel.id == id) {
                    return sel;
                }
            }
        }
        return null;
    };

    olwrapper.getSelectedFeatureIndexById = function (id) {
        if (id || id === 0) {
            for (let i = 0; i < this.selectedFeatures.length; ++i) {
                let sel = this.selectedFeatures[i];
                let featureId = sel.feature.getId();
                if (sel.id == id || featureId == id) {
                    return i;
                }
            }
        }
        return -1;
    };

    olwrapper.getSelectedFeatureBy = function (prop, val) {
        if (prop && (val || val === 0)) {
            for (let i = 0; i < this.selectedFeatures.length; ++i) {
                let sel = this.selectedFeatures[i];
                let f = sel.feature;
                if (f.get(prop) == val) {
                    return sel;
                }
            }
        }
        return null;
    };

    olwrapper.getSelectedFeatureByProperties = function (properties) {
        if (properties && typeof properties === 'object') {
            for (let i = 0; i < this.selectedFeatures.length; ++i) {
                let sel = this.selectedFeatures[i];
                let f = sel.feature;
                let found = true;
                for (let prop in properties) {
                    if (properties.hasOwnProperty(prop)) {
                        let value = properties[prop];
                        if ("ID" == String(prop).toUpperCase()) {
                            let featureId = f.getId();
                            let selId = sel.id;
                            found = found &&
                                (featureId == value || selId == value);
                        } else {
                            let featureProp = f.get(prop);
                            if ("VST" == prop) {
                                featureProp = f.get('VST') || 0;
                            } else if ("BST" == prop) {
                                featureProp = f.get('BST') || f.get('ALEN');
                            }

                            found = found && featureProp == value;
                        }
                        if (!found) {
                            continue;
                        }
                    }
                }
                if (found) {
                    return f;
                }
            }
        }
        return null;
    };

    olwrapper.getNewDummyId = function () {
        return --this.dummyId;
    };

    olwrapper.getSelectedFeatures = function () {
        return this.selectedFeatures;
    };

    olwrapper.clearSelectedFeatures = function () {
        this.selectedFeatures = [];
    };

    olwrapper.clearLayer = function (layerName) {
        let layers = olwrapper.map.getLayersByNameAndType(layerName, 'vector');
        if (layers && layers.length === 1) {
            let layer = layers[0];
            layer.getSource().clear(true);
        }
    };

    olwrapper.setSelectedInGrid = function (selected, property, newVal) {
        if (this.selectedInGrid && property) {
            let oldVal = this.selectedInGrid.feature.get(property + '_old');
            this.selectedInGrid.feature.set(property, oldVal);
        }
        if (selected) {
            this.selectedInGrid = selected;
            if (property) {
                let oldVal = this.selectedInGrid.feature.get(property);
                this.selectedInGrid.feature.set(property + '_old', oldVal);
                this.selectedInGrid.feature.set(property, newVal);
            }
        } else {
            this.selectedInGrid = null;
        }
    };

    olwrapper.getSelectedInGrid = function () {
        return this.selectedInGrid;
    };

    olwrapper.setBackgroundLayer = function (layer) {
        this.currentBackgroundLayer = layer;
    };

    olwrapper.toggleBackgroundLayer = function (layer) {
        if (layer && layer !== this.currentBackgroundLayer) {

            if (this.currentBackgroundLayer) {
                this.map.toggleLayer(this.currentBackgroundLayer);

                let curLyrs = this.map.getLayersByName(this.currentBackgroundLayer);
                curLyrs.forEach(function (curLyr) {
                    if (curLyr.get('name') === 'DEFAULT_WMTS') {
                        this.map.toggleLayer('DEFAULT_WMTS_LABELS');
                    }
                }.bind(this));
            }
            this.map.toggleLayer(layer);

            let lyrs = this.map.getLayersByName(layer);
            lyrs.forEach(function (lyr) {
                if (lyr.get('name') === 'DEFAULT_WMTS') {
                    this.map.toggleLayer('DEFAULT_WMTS_LABELS');
                }
            }.bind(this));

            this.currentBackgroundLayer = layer;
        }
    };

    olwrapper.timeFilter = function (begin, end) {
        let options = {
            reload: true,
            fastClear: true
        };

        // SPERRUNGEN, SPERRUNGEN_SYMB, UMLEITUNGEN
        let symbdata = olwrapper.getDataFunction('GetGISObjects', 'Y', 'ABLKGSN', begin, end, olwrapper.postJsonContent);
        this.map.setLayerData('SPERRUNGEN_SYMB', symbdata, options);

        let sperrdata = olwrapper.getDataFunction('GetGISObjects', 'S', 'ABLKGSN', begin, end, olwrapper.postJsonContent);
        this.map.setLayerData('SPERRUNGEN', sperrdata, options);

        let umleidata = olwrapper.getDataFunction('GetGISObjects', 'U', 'ABLKGSN', begin, end, olwrapper.postJsonContent);
        this.map.setLayerData('UMLEITUNGEN', umleidata, options);
    };

    olwrapper.getLayer = function (feature) {
        let lyr = null;
        let artsp = feature.get('ARTSP');
        let artuml = feature.get('ARTUML');
        if (artsp) {
            let coords = NovaMapUtils.getFeatureCoordinates(feature);
            if (coords && coords.length === 2 && !Array.isArray(coords[0])) {
                return 'SPERRUNGEN_SYMB';
            } else {
                return 'SPERRUNGEN';
            }
        } else if (artuml) {
            return 'UMLEITUNGEN';
        }

        let klasse = feature.get('AKLASSE');
        if (klasse) {
            lyr = 'STRASSENNETZ_' + klasse;
            if (klasse == 'L' || klasse == 'K' || klasse == 'S') {
                lyr = 'STRASSENNETZ_LK';
            }
        }
        return lyr;
    };

    /**
     * in welchem Vektor-Layer liegen die einzelnen Featuretypen?
     *  S - Sperrung (live erzeugt aus OMC-Features)
        U - Umleitung (live erzeugt aus OMC-Features)
        Y - Sperrsymbol (live erzeugt aus OMC-Features)
        Z - Zusatzbeschilderung (live erzeugt aus OMC-Features + AO_SYMB...)
     * */
    olwrapper.getVectorLayerMap = function () {
        return [
            { type: 'Y', layer: 'SPERRUNGEN_SYMB' },
            { type: 'S', layer: 'SPERRUNGEN' },
            { type: 'U', layer: 'UMLEITUNGEN' },
            { type: 'Z', layer: 'DET_BESCH' }
        ];
    }

    olwrapper.getDataFunction = function (func, netType, subType, von, bis, deliverJson, layerName) {
        let begin = null;
        let end = null;
        if (von !== undefined) {
            begin = von;
        }
        if (bis !== undefined) {
            end = bis;
        }

        return function (extent, resolution, projection) {

            olwrapper.onLayerDataRequestStarted(layerName);

            let time = getFormattedDate();
            let reqJson = {
                'INTERFACE': 'RPI_GI',
                'REM': 'Kommentar',
                'VERSION': '1.0.0',
                'METADATA': {
                    'OID': '',
                    'SESSIONID': '',
                    'ANSWER_TYPE': 'JSON'
                },
                'CATEGORY': {
                    'FUNCTION': func,
                    'TIMESTAMP': time,
                    'USE_MBR': 1,
                    'TIMEFILTER': {
                        'TIMBEGIN': begin,
                        'TIMEND': end
                    },
                    'ROUTING': {
                        'RTGBEGIN': 0,
                        'RTGEND': 0,
                        'RTGDIR': 0
                    }
                },
                'GEODATA': {
                    'COORDS': [],
                    'MBR': olwrapper.map.getCurrentBoundingBox(),
                    'NET_TYPE': netType,
                    'SUB_TYPE': subType,
                    'ZOOM_LEVEL': 0,
                    'RESOLUTION': resolution,
                    'ROTATION': 0
                },
                'CACHEINFO': {
                    'FILE_NAME': '',
                    'FILE_PATH': '',
                    'PACK_DATA': 1
                },
                'METAINFOS': {
                    'REG_CODE': 0
                }
            };

            let data;
            if (deliverJson === true || (olwrapper.postJsonContent === true && deliverJson !== false)) {
                data = { requestJson: reqJson, mapFilter: Vwc.states.mapFilterPara.mapFilter };
            }
            else {
                data = { requestJson: JSON.stringify(reqJson), mapFilter: JSON.stringify(Vwc.states.mapFilterPara.mapFilter) };
            }
            return JSON.stringify(data);
        };
    };

    olwrapper.getSourceExtractFunction = function (layerName) {
        return function (source) {
            let ret = null;

            olwrapper.onLayerDataRequestDone(layerName);

            if (typeof source === 'string') {
                let srcObj = JSON.parse(source);
                ret = srcObj.geojson;
            } else if (typeof source === 'object') {
                ret = source.geojson;
            }
            if (ret) {
                if (typeof ret === 'string') {
                    try {
                        //ret = ret.replace(',]', '}]');
                        ret = JSON.parse(ret);
                    } catch (err) {
                        console.log(err);
                        console.log(ret);
                    }
                }
            } else {
                ret = null;
            }

            return ret;
        };
    };

    ///////////////////////////////////////////////////////////////////////////////////
    // Vektor-Layer Callbacks
    ///////////////////////////////////////////////////////////////////////////////////

    olwrapper.registerDataListener = function (type, listener) {
        switch (type) {
            case "RequestStarted":
                break;
            case "RequestDone":
                break;
            default:
                return;
        }
        if (!this.listeners.dataRequest[type]) {
            this.listeners.dataRequest[type] = [];
        }
        this.listeners.dataRequest[type].push(listener);
    };

    olwrapper.removeDataListener = function (type, listener) {
        if (this.listeners.dataRequest[type]) {
            if (listener != undefined) {
                const index = this.listeners.dataRequest[type].indexOf(listener);
                if (index > -1) {
                    this.listeners.dataRequest[type].splice(index, 1);
                }
            }
            else {
                this.listeners.dataRequest[type] = [];
            }
        }
    };

    olwrapper.onLayerDataRequestStarted = function (layerName) {
        //console.log("onLayerDataRequestStarted -> " + layerName);
        if (this.listeners.dataRequest["RequestStarted"]) {
            this.listeners.dataRequest["RequestStarted"].forEach(function (listener) {
                listener(layerName);
            });
        }
    }

    olwrapper.onLayerDataRequestDone = function(layerName){
        //console.log("onLayerDataRequestDone -> " + layerName);
        if (this.listeners.dataRequest["RequestDone"]) {
            this.listeners.dataRequest["RequestDone"].forEach(function (listener) {
                listener(layerName);
            });
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////

    /**
     *  Centroid berechnen 
     *  
     *  @param {Array.<Number>} mbr Bounding box
     *  @returns {Array.<Number>} Centroid of given bounding box
     */
    olwrapper.getCentroid = function (mbr) {
        let cx = (mbr[0] + mbr[2]) / 2;
        let cy = (mbr[1] + mbr[3]) / 2;

        return [cx, cy];
    };

    olwrapper.getWorkspace = function (proj, mbr, center, initRes, res, layerCfg, sldpath, timebegin, timeend) {
        let cx, cy;
        if (center && Array.isArray(center) && center.length === 2) {
            cx = center[0];
            cy = center[1];
        } else {
            let c = this.getCentroid(mbr);
            cx = c[0];
            cy = c[1];
        }

        return {
            controls: ['scale', 'zoomstep'],
            sld: sldpath || this.getSldPath(),
            epsgSRID: proj,
            initialView: {
                centerX: cx,
                centerY: cy,
                resolution: initRes
            },
            maxBoundingBox: mbr,
            resolutions: res,
            layers: [
                {
                    type: 'vector',
                    title: 'Bundesautobahnen',
                    name: 'STRASSENNETZ_A',
                    featureType: 'STRASSENNETZ_A',
                    url: Vwc.actions.getMap,
                    format: 'GeoJSON',
                    visible: false,
                    selectable: true,
                    styleProperties: [
                        "VST",
                        "BST",
                        "FUTURE_ART"
                    ],
                    maxResolution: res[7],
                    tooltip: this.strassennetzTooltip,
                    data: this.getDataFunction('GetGISObjects', 'A', 'A', timebegin, timeend, olwrapper.postJsonContent, 'STRASSENNETZ_A'),
                    sourceExtract: this.getSourceExtractFunction('STRASSENNETZ_A'),
                    zIndex: 16
                },
                {
                    type: 'vector',
                    title: 'Bundesstrassen',
                    name: 'STRASSENNETZ_B',
                    featureType: 'STRASSENNETZ_B',
                    url: Vwc.actions.getMap,
                    format: 'GeoJSON',
                    visible: false,
                    selectable: true,
                    styleProperties: [
                        "VST",
                        "BST",
                        "FUTURE_ART"
                    ],
                    maxResolution: res[7],
                    tooltip: this.strassennetzTooltip,
                    data: this.getDataFunction('GetGISObjects', 'A', 'B', timebegin, timeend, olwrapper.postJsonContent, 'STRASSENNETZ_B'),
                    sourceExtract: this.getSourceExtractFunction('STRASSENNETZ_B'),
                    zIndex: 15
                },
                {
                    type: 'vector',
                    title: 'Landes-/Staatsstrassen & Kreisstrassen',
                    name: 'STRASSENNETZ_LK',
                    featureType: 'STRASSENNETZ_LK',
                    url: Vwc.actions.getMap,
                    format: 'GeoJSON',
                    visible: false,
                    selectable: true,
                    styleProperties: [
                        "VST",
                        "BST",
                        "FUTURE_ART"
                    ],
                    maxResolution: res[7],
                    tooltip: this.strassennetzTooltip,
                    data: this.getDataFunction('GetGISObjects', 'A', 'LK', timebegin, timeend, olwrapper.postJsonContent, 'STRASSENNETZ_LK'),
                    sourceExtract: this.getSourceExtractFunction('STRASSENNETZ_LK'),
                    zIndex: 14
                },
                {
                    type: 'vector',
                    title: 'Gemeindestrassen',
                    name: 'STRASSENNETZ_G',
                    featureType: 'STRASSENNETZ_G',
                    url: Vwc.actions.getMap,
                    format: 'GeoJSON',
                    visible: false,
                    selectable: true,
                    styleProperties: [
                        "VST",
                        "BST",
                        "FUTURE_ART"
                    ],
                    maxResolution: res[9],
                    tooltip: this.gstrassenTooltip,
                    data: this.getDataFunction('GetGISObjects', 'G', 'G', timebegin, timeend, olwrapper.postJsonContent, 'STRASSENNETZ_G'),
                    sourceExtract: this.getSourceExtractFunction('STRASSENNETZ_G'),
                    zIndex: 13
                },
                /** 
                 *  hier (zIndex) liegen die zuschaltbaren Overlaykarten (z.B. TT-SIB Strassennetz) 
                 *  zIndex Bereich: 50 - 99
                 *  */
                {
                    type: 'vector',
                    title: 'Sperrung (Symbole)',
                    name: 'SPERRUNGEN_SYMB',
                    featureType: 'SPERRUNGEN_SYMB',
                    url: Vwc.actions.getMap,
                    format: 'GeoJSON',
                    visible: true,
                    selectable: true,
                    groupSelect: {
                        property: 'DOKSPERRID',
                        layers: ['SPERRUNGEN', 'UMLEITUNGEN']
                    },
                    styleProperties: [
                        "STATUS",
                        "S_VON",
                        "S_BIS",
                        "ARTSP",
                        "TYPSP"
                    ],
                    maxResolution: res[0] + 1,
                    tooltip: this.tooltip,
                    data: this.getDataFunction('GetGISObjects', 'Y', 'ABLKGSN', timebegin, timeend, olwrapper.postJsonContent, 'SPERRUNGEN_SYMB'),
                    sourceExtract: this.getSourceExtractFunction('SPERRUNGEN_SYMB'),
                    zIndex: 103
                },
                {
                    type: 'vector',
                    title: 'Detailbeschilderungen',
                    name: 'DET_BESCH',
                    url: Vwc.actions.getMap,
                    format: 'GeoJSON',
                    visible: true, // aus config option 'ist detailbeschilderung aktiv'
                    maxResolution: res[5],
                    data: this.getDataFunction('GetSymbols', 'Y', 'G', timebegin, timeend, olwrapper.postJsonContent, 'DET_BESCH'),
                    sourceExtract: function (source) {
                        // TODO this.getSourceExtractFunction() nutzen, wenn haymo json gefixt hat
                        let ret = null;

                        olwrapper.onLayerDataRequestDone('DET_BESCH');

                        if (typeof source === 'string') {
                            let srcObj = JSON.parse(source);
                            ret = srcObj.geojson;
                        } else if (typeof source === 'object') {
                            ret = source.geojson;
                        }
                        if (ret) {
                            if (typeof ret === 'string') {
                                try {
                                    //ret = ret.replace(',\n\n\n', '');
                                    ret = JSON.parse(ret);
                                } catch (err) {
                                    console.log(err);
                                    console.log(ret);
                                }
                            }
                        } else {
                            ret = null;
                        }

                        return ret;
                    },
                    zIndex: 102
                },
                {
                    type: 'vector',
                    title: 'Umleitungen',
                    name: 'UMLEITUNGEN',
                    featureType: 'UMLEITUNGEN',
                    url: Vwc.actions.getMap,
                    format: 'GeoJSON',
                    visible: true,
                    selectable: true,
                    groupSelect: {
                        property: 'DOKSPERRID',
                        layers: ['SPERRUNGEN_SYMB', 'SPERRUNGEN']
                    },
                    styleProperties: [
                        "ARTUML",
                        "S_VON",
                        "S_BIS"
                    ],
                    tooltip: this.tooltip,
                    maxResolution: res[5],
                    data: this.getDataFunction('GetGISObjects', 'U', 'ABLKGSN', timebegin, timeend, olwrapper.postJsonContent, 'UMLEITUNGEN'),
                    sourceExtract: this.getSourceExtractFunction('UMLEITUNGEN'),
                    zIndex: 101
                },
                {
                    type: 'vector',
                    title: 'Sperrungen',
                    name: 'SPERRUNGEN',
                    featureType: 'SPERRUNGEN',
                    url: Vwc.actions.getMap,
                    format: 'GeoJSON',
                    visible: true,
                    selectable: true,
                    groupSelect: {
                        property: 'DOKSPERRID',
                        layers: ['SPERRUNGEN_SYMB', 'UMLEITUNGEN']
                    },
                    styleProperties: [
                        "ARTSP",
                        "S_VON",
                        "S_BIS"
                    ],
                    tooltip: this.tooltip,
                    maxResolution: res[5],
                    data: this.getDataFunction('GetGISObjects', 'S', 'ABLKGSN', timebegin, timeend, olwrapper.postJsonContent, 'SPERRUNGEN'),
                    sourceExtract: this.getSourceExtractFunction('SPERRUNGEN'),
                    zIndex: 100
                },
                {
                    type: 'vector',
                    name: 'editing',
                    forceLayerStyle: true,
                    showOrientation: true,
                    visible: true,
                    zIndex: 110
                }
            ],
            visibilityConfig: this.getVisibilityConfig()
        };
    };

    olwrapper.addAnordnungListener = function (type, listener) {
        this.map.on(type, listener);
        if (!this.listeners.anordnungen[type]) {
            this.listeners.anordnungen[type] = [];
        }
        this.listeners.anordnungen[type].push(listener);
    };

    olwrapper.removeAnordnungListeners = function (type) {
        if (this.listeners.anordnungen[type]) {
            this.listeners.anordnungen[type].forEach(function (listener) {
                this.map.un(type, listener);
            }.bind(this));
            delete this.listeners.anordnungen[type];
        }
    };

    olwrapper.setAnordnungProperty = function (sperrid, property, value) {
        let propFilter = {
            'DOKSPERRID': sperrid
        };
        let cb = function (feature) {
            feature.set(property, value);
        };
        let sperrFeatures = this.map.getFeaturesByProperties('SPERRUNGEN', propFilter);
        sperrFeatures.forEach(cb);
        let umleiFeatures = this.map.getFeaturesByProperties('UMLEITUNGEN', propFilter);
        umleiFeatures.forEach(cb);
        let symbol = this.map.getFeaturesByProperties('SPERRUNGEN_SYMB', propFilter, true);
        if (symbol) {
            symbol.set(property, value);
        }
    };

    olwrapper.removeAnordnungFromMap = function (sperrid, excludeSymbol) {
        let propFilter = {
            'DOKSPERRID': sperrid
        };

        let sperrFeatures = this.map.getFeaturesByProperties('SPERRUNGEN', propFilter);
        this.map.deselectFeatures(sperrFeatures);
        this.map.removeFeatures(sperrFeatures, 'SPERRUNGEN');

        let umleiFeatures = this.map.getFeaturesByProperties('UMLEITUNGEN', propFilter);
        this.map.deselectFeatures(umleiFeatures);
        this.map.removeFeatures(umleiFeatures, 'UMLEITUNGEN');

        if (!excludeSymbol) {
            let symbol = this.map.getFeaturesByProperties('SPERRUNGEN_SYMB', propFilter, true);
            this.map.deselectFeatures(symbol);
            this.map.removeFeatures(symbol, 'SPERRUNGEN_SYMB');
        }
    };

    olwrapper.isPointGeom = function (coordinates) {
        return Array.isArray(coordinates) && coordinates.length === 2 && !Array.isArray(coordinates[0]);
    };

    olwrapper.getSetSymbolData = function (sperrid, coords, rotation) {
        let time = getFormattedDate();
        let reqJson = {
            'INTERFACE': 'RPI_GI',
            'REM': 'Kommentar',
            'VERSION': '1.0.0',
            'METADATA': {
                'OID': sperrid,
                'SESSIONID': '',
                'ANSWER_TYPE': 'JSON'
            },
            'CATEGORY': {
                'FUNCTION': 'SetSymbol',
                'TIMESTAMP': time,
                'USE_MBR': 0,
                'TIMEFILTER': {
                    'TIMBEGIN': null,
                    'TIMEND': null
                },
                'ROUTING': {
                    'RTGBEGIN': 0,
                    'RTGEND': 0,
                    'RTGDIR': 0
                }
            },
            'GEODATA': {
                'COORDS': coords,
                'MBR': [0, 0, 0, 0],
                'NET_TYPE': 'AGSUY',
                'SUB_TYPE': 'ABLKGSN',
                'ZOOM_LEVEL': 0,
                'RESOLUTION': 0,
                'ROTATION': rotation
            },
            'CACHEINFO': {
                'FILE_NAME': '',
                'FILE_PATH': '',
                'PACK_DATA': 1
            },
            'METAINFOS': {
                'REG_CODE': 0
            }
        };

        let data;
        if (olwrapper.postJsonContent === true) {
            data = { requestJson: reqJson };
        }
        else {
            data = { requestJson: JSON.stringify(reqJson) };
        }
        return JSON.stringify(data);
    };

/*
 * SetSymbol uebernimmt nun auch das Erstellen eines Symbols
    olwrapper.getCreateSymbolData = function (doksperrid, coords, rotation) {
        let time = getFormattedDate();
        let reqJson = {
            'INTERFACE': 'RPI_GI',
            'REM': '',
            'VERSION': '1.0.0',
            'METADATA': {
                'OID': doksperrid,
                'SESSIONID': '',
                'ANSWER_TYPE': 'JSON'
            },
            'CATEGORY': {
                'FUNCTION': 'CreateSymbol',
                'TIMESTAMP': time,
                'USE_MBR': 0,
                'TIMEFILTER': {
                    'TIMBEGIN': null,
                    'TIMEND': null
                },
                'ROUTING': {
                    'RTGBEGIN': 0,
                    'RTGEND': 0,
                    'RTGDIR': 0
                }
            },
            'GEODATA': {
                'COORDS': coords,
                'MBR': [0, 0, 0, 0],
                'NET_TYPE': 'AGSUY',
                'SUB_TYPE': 'ABLKGSN',
                'ZOOM_LEVEL': 0,
                'RESOLUTION': 0,
                'ROTATION': rotation
            },
            'CACHEINFO': {
                'FILE_NAME': '',
                'FILE_PATH': '',
                'PACK_DATA': 1
            },
            'METAINFOS': {
                'REG_CODE': 0
            }
        };

        let data;
        if (olwrapper.postJsonContent === true) {
            data = { requestJson: reqJson };
        }
        else {
            data = { requestJson: JSON.stringify(reqJson) };
        }
        return JSON.stringify(data);
    };
*/
    olwrapper.compareNks = function (a, b) {
        let avnk = a.get('VNK');
        let annk = a.get('NNK');
        let bvnk = b.get('VNK');
        let bnnk = b.get('NNK');

        return avnk && annk && bvnk && bnnk && avnk == bvnk && annk == bnnk;
    };

    olwrapper.getRoutingObjectData = function (rtgbegin, rtgend, rtgdir) {
        let time = getFormattedDate();

        let reqJson = {
            'INTERFACE': 'RPI_GI',
            'REM': 'Kommentar',
            'VERSION': '1.0.0',
            'METADATA': {
                'OID': '',
                'SESSIONID': '',
                'ANSWER_TYPE': 'JSON'
            },
            'CATEGORY': {
                'FUNCTION': 'GetRouting',
                'TIMESTAMP': time,
                'USE_MBR': 0,
                'TIMEFILTER': {
                    'TIMBEGIN': null,
                    'TIMEND': null
                },
                'ROUTING': {
                    'RTGBEGIN': rtgbegin,
                    'RTGEND': rtgend,
                    'RTGDIR': rtgdir
                }
            },
            'GEODATA': {
                'COORDS': [[0, 0, 0, 0]],
                'MBR': [0, 0, 0, 0],
                'NET_TYPE': 'A',
                'SUB_TYPE': 'A',
                'ZOOM_LEVEL': 10,
                'RESOLUTION': 1.3229166667,
                'ROTATION': 0
            },
            'CACHEINFO': {
                'FILE_NAME': '',
                'FILE_PATH': '',
                'PACK_DATA': 1
            },
            'METAINFOS': {
                'REG_CODE': 0
            }
        };

        let data;
        if (olwrapper.postJsonContent === true) {
            data = { requestJson: reqJson };
        }
        else {
            data = { requestJson: JSON.stringify(reqJson) };
        }
        return JSON.stringify(data);
    }

    olwrapper.loadDetailBeschilderungForAnordnung = function (id) {
        const dataFunction = function (extent, resolution, projection) {
            let time = getFormattedDate();
            let reqJson = {
                'INTERFACE': 'RPI_GI',
                'REM': 'Kommentar',
                'VERSION': '1.0.0',
                'METADATA': {
                    'OID': id,
                    'SESSIONID': '',
                    'ANSWER_TYPE': 'JSON'
                },
                'CATEGORY': {
                    'FUNCTION': 'GetSymbols',
                    'TIMESTAMP': time,
                    'USE_MBR': 1,
                    'TIMEFILTER': {
                        'TIMBEGIN': '',
                        'TIMEND': ''
                    },
                    'ROUTING': {
                        'RTGBEGIN': 0,
                        'RTGEND': 0,
                        'RTGDIR': 0
                    }
                },
                'GEODATA': {
                    'COORDS': [],
                    'MBR': extent,
                    'NET_TYPE': 'Y',
                    'SUB_TYPE': 'G',
                    'ZOOM_LEVEL': 0,
                    'RESOLUTION': resolution,
                    'ROTATION': 0
                },
                'CACHEINFO': {
                    'FILE_NAME': '',
                    'FILE_PATH': '',
                    'PACK_DATA': 1
                },
                'METAINFOS': {
                    'REG_CODE': 0
                }
            };

            let data;
            if (olwrapper.postJsonContent) {
                data = { requestJson: reqJson, mapFilter: Vwc.states.mapFilterPara.mapFilter };
            }
            else {
                data = { requestJson: JSON.stringify(reqJson), mapFilter: JSON.stringify(Vwc.states.mapFilterPara.mapFilter) };
            }
            return JSON.stringify(data);
        };
        this.map.setLayerVisible('DET_BESCH', true);
        this.map.setLayerData('DET_BESCH', dataFunction, { reload: true, fastClear: true });
    };
    
    olwrapper.reloadAnordnung = async function (sperrid_) {
        try {
            let options;
            let srcFunc_ = await olwrapper.getSourceExtractFunction();
            options = {sperrid: sperrid_, type: 'S', name: 'SPERRUNGEN', srcFunc: srcFunc_}
            await olwrapper.updateFeatures(options);
            options = {sperrid: sperrid_, type: 'U', name: 'UMLEITUNGEN', srcFunc: srcFunc_}
            await olwrapper.updateFeatures(options);
            options = {sperrid: sperrid_, type: 'Y', name: 'SPERRUNGEN_SYMB', srcFunc: srcFunc_}
            await olwrapper.updateFeatures(options);

            await refreshMap(true);
            
            return Promise.resolve(true);
        } catch (err) {
            return Promise.reject(err);
        }
    };
    olwrapper.updateFeatures = async function (options) {
        try {

            let data = getGisObjectData(options.sperrid, options.type, undefined, undefined, olwrapper.postJsonContent);
            await ajaxCall(Vwc.actions.getMap, data, async function (result) {
                let geojson = await options.srcFunc(result);
                if (geojson != null) {
                    await olwrapper.map.addGeoJSONFeatures({
                        json: geojson,
                        layerName: options.name
                    });
                }
            });

            return Promise.resolve(true);
        } catch(err) {
            return Promise.reject(err);
        }
    };

    olwrapper.loadBackgroundLayers = function () {
        let path = this.pathBgLayersXml;
        let xhr = new XMLHttpRequest();
        xhr.open('GET', path, false);
        let ret = [];
        xhr.onload = function (result) {
            if (!xhr.status || xhr.status >= 200 && xhr.status < 300) {
                let xml = xhr.responseXML;
                let doc = xml.documentElement;

                // load wms
                let wmsLayers = doc.getElementsByTagName('wms')[0];
                if (wmsLayers && wmsLayers.hasChildNodes()) {
                    let children = wmsLayers.childNodes;
                    for (let i = 0; i < children.length; ++i) {
                        let node = children[i];
                        if (node && node.nodeType === 1) {
                            ret.push(getWmsConfig(node));
                        }
                    }
                }
                // load wmts
                let wmtsLayers = doc.getElementsByTagName('wmts')[0];
                if (wmtsLayers && wmtsLayers.hasChildNodes()) {
                    let children = wmtsLayers.childNodes;
                    for (let i = 0; i < children.length; ++i) {
                        let node = children[i];
                        if (node && node.nodeType === 1) {
                            ret.push(getWmtsConfig(node));
                        }
                    }
                }
            }
        }.bind(this);

        xhr.onerror = function () {
            displayErrorInStatusInfo('Fehler beim laden der Hintergrundebenenkonfiguration!', "Vwc.Panel.Datatable");
        };
        xhr.send();
        return ret;
    };

    /**
     *  setzt setzt zIndex fuer hoverOverlay_ und featureOverlay_
     *
     *  @returns none
     * @param zIndex
     */
    olwrapper.setHoverOverlaysZindex = function (zIndex) {
        let interaction_ = olwrapper.map.getInteractionByClass(de.novasib.ol.interaction.HoverSelect)
        if (interaction_) {
            // Festlegung: hover soll ueber hoverSelect erscheinen
            let hoverZIndex = zIndex - 1;
            let hoverSelectZIndex = zIndex - 2;

            interaction_.hoverOverlay_.setZIndex(hoverZIndex);
            interaction_.featureOverlay_.setZIndex(hoverSelectZIndex);

            // aus Gruenden haben IndexedOverlayLayer ein zIndex_ im root, deshalb...
            interaction_.hoverOverlay_.zIndex_ = hoverZIndex;
            interaction_.featureOverlay_.zIndex_ = hoverSelectZIndex;
        }
    };

    olwrapper.setLayerZindex = function (layerName, zIndex) {
        if (layerName) {
            let layer = olwrapper.map.getLayersByNameAndType(layerName, 'vector')[0];
            if (layer) {
                if (zIndex) {
                    layer.setZIndex(zIndex);
                }
            }
        }
    };

    olwrapper.getLayerZindex = function (layerName) {
        if (layerName) {
            let layer = olwrapper.map.getLayersByNameAndType(layerName, 'vector')[0];
            if (layer) {
                return layer.getZIndex();
            }
        }
    };

    olwrapper.setLayersMaxResolution = function (layerNames, maxResolution) {
        for (const layerName of layerNames) {
            let layer = olwrapper.map.getLayersByNameAndType(layerName, 'vector')[0];
            if (layer) {
                layer.setMaxResolution(maxResolution);
            }
        }
    };

    /** 
    *  VisibilityConfig per Land (landId) setzen
    *  
    *  @returns {Object} VisibilityConfig Objekt
    */
    olwrapper.getVisibilityConfig = function () {

        const landIdSachsen = 14;
        const landId = Vwc.config.LANDKENNZ;
        let bezeichnungStrasse;

        if (landId !== landIdSachsen) {
            bezeichnungStrasse = "Landesstr.";
        } else {
            bezeichnungStrasse = "Staatsstr.";
        }

        const resolutions_ = Vwc.config.RESOLUTIONS;
        const visibilities_ = resolutions_.filter((current, index, array) => {
            if (index === 0) {
                return current;
            } else {
                let previous = array[index - 1];
                if (previous[2] !== current[2]) {
                    return current;
                }
            }
        });
        const getZoomFromVisibility_ = (labelIndex) => {
            if (visibilities_.length !== 0 && labelIndex != undefined) {
                return visibilities_[labelIndex][0];
            }
        }
        const visibilityConfig = {
            elements: [
                { label: 'Autobahn', zoom: getZoomFromVisibility_(0) },
                { label: 'Bundesstr.', zoom: getZoomFromVisibility_(1) },
                { label: bezeichnungStrasse, zoom: getZoomFromVisibility_(2) },
                { label: 'Kreisstr.', zoom: getZoomFromVisibility_(3) },
                { label: 'Gemeindestr.', zoom: getZoomFromVisibility_(4) }
            ],
            tipLabel: 'Die Sichtbarkeit der Baustellen ist vom eingestellten Maßstab abhängig.',
            label: 'S',
            collapsed: false
        };

        return visibilityConfig;
    }

    /** 
    *  Pfad zur SLD per Land (landId) setzen
    *  
    *  @returns {String} sld path
    */
    olwrapper.getSldPath = function () {
        let ret;
        const landIdSachsen = 14;
        const landId = Vwc.config.LANDKENNZ;

        switch (landId) {
            case landIdSachsen:
                ret = "../Content/sld_vwc.sn.min.xml";
                break;
            default:
                ret = "../Content/sld_vwc.min.xml";
        }
        if (appVersion != undefined) {
            ret += "?v=" + appVersion;
        }
        return ret;
    }

    function getWmsConfig(node) {
        if (node && node.hasChildNodes()) {
            let name_, title_, url_, version_;
            let layers_ = '';
            let inLayerSwitcher_;
            let backgroundLayer_;
            let zidx_ = 0;
            let attributions_;
            let visible_;

            let children = node.childNodes;
            for (let i = 0; i < children.length; ++i) {
                let child = children[i];

                if (!child || child.nodeType !== 1) {
                    continue;
                }

                let ln = child.localName;
                let val = child.nodeValue || child.textContent;

                switch (ln) {
                    case 'title': {
                        title_ = val || "";
                        break;
                    }
                    case 'name': {
                        name_ = val || "";
                        break;
                    }
                    case 'url': {
                        url_ = val || "";
                        break;
                    }
                    case 'version': {
                        version_ = val || "";
                        break;
                    }
                    case 'layers': {
                        if (child.hasChildNodes()) {
                            let grandChildren = child.childNodes;
                            for (let j = 0; j < grandChildren.length; ++j) {
                                let grandChild = grandChildren[j];
                                if (!grandChild || grandChild.nodeType !== 1) {
                                    continue;
                                }

                                if (grandChild.localName === 'layer') {
                                    layers_ += grandChild.nodeValue || grandChild.textContent;
                                    layers_ += ',';
                                }
                            }
                        }
                        break;
                    }
                    case 'inLayerSwitcher': {
                        inLayerSwitcher_ = (val == 'true');
                        break;
                    }
                    case 'backgroundLayer': {
                        backgroundLayer_ = (val == 'true');
                        break;
                    }
                    case 'zIndex': {
                        zidx_ = Number.parseInt(val) || 0;
                        break;
                    }
                    case 'attributions': {
                        attributions_ = val || "";
                        break;
                    }       
                    case 'visible': {
                        visible_ = (val == 'true');
                        break
                    }
                    default: {
                        break;
                    }
                }
            }

            /* Entfernen des letzten Kommas bei Auflistungen  */
            if (layers_ && layers_.lastIndexOf(',') == layers_.length - 1) {
                layers_ = layers_.substring(0, layers_.length - 1);
            }

            return {
                type: "wms",
                name: name_,
                title: title_,
                url: url_,
                version: version_,
                layers: layers_,
                inLayerSwitcher: inLayerSwitcher_,
                backgroundLayer: backgroundLayer_,
                zIndex: zidx_,
                attributions: attributions_,
                visible: visible_
            };
        }
        return null;
    }
    function getWmtsConfig(node) {
        if (node && node.hasChildNodes()) {
            let name_, title_, url_, matrixSet_;
            let layers_ = '';
            let inLayerSwitcher_;
            let backgroundLayer_ = false;
            let zidx_ = 0;
            let attributions_;
            let visible_ = true;

            let children = node.childNodes;
            for (let i = 0; i < children.length; ++i) {
                let child = children[i];

                if (!child || child.nodeType !== 1) {
                    continue;
                }

                let ln = child.localName;
                let val = child.nodeValue || child.textContent;
                val = val.trim();

                switch (ln) {
                    case 'title': {
                        title_ = val || "";
                        break;
                    }
                    case 'name': {
                        name_ = val || "";
                        break;
                    }
                    case 'url': {
                        url_ = val || "";
                        break;
                    }
                    case 'matrixSet': {
                        matrixSet_ = val || "";
                        break;
                    }
                    case 'layers': {
                        if (child.hasChildNodes()) {
                            let grandChildren = child.childNodes;
                            for (let j = 0; j < grandChildren.length; ++j) {
                                let grandChild = grandChildren[j];
                                if (!grandChild || grandChild.nodeType !== 1) {
                                    continue;
                                }

                                if (grandChild.localName === 'layer') {
                                    layers_ += grandChild.nodeValue || grandChild.textContent;
                                    layers_ += ',';
                                }
                            }
                        }
                        break;
                    }
                    case 'inLayerSwitcher': {
                        inLayerSwitcher_ = (val == 'true');
                        break;
                    }
                    case 'backgroundLayer': {
                        backgroundLayer_ = (val == 'true');
                        break;
                    }
                    case 'zIndex': {
                        zidx_ = Number.parseInt(val) || 0;
                        break;
                    }
                    case 'attributions': {
                        attributions_ = val || "";
                        break;
                    }                      
                    case 'visible': {
                        visible_ = (val == 'true');
                        break;
                    }
                    default: {
                        break;
                    }
                }
            }

            if (layers_ && layers_.lastIndexOf(',') == layers_.length - 1) {
                layers_ = layers_.substring(0, layers_.length - 1);
            }

            let cfg = {
                type: 'wmts',
                title: title_,
                name: name_,
                capabilitiesUrl: url_,
                matrixSet: matrixSet_,
                layers: layers_,
                inLayerSwitcher: inLayerSwitcher_,
                backgroundLayer: backgroundLayer_,
                zIndex: zidx_,
                attributions: attributions_,
                visible: visible_
            };
            /*
            if (name_ != 'DEFAULT_WMTS') {
                cfg['backgroundLayer'] = true;
            }
            */
            return cfg;
        }
        return null;
    }

    function patchNovaMap() {
        de.novasib.ol.style.filter.Function = function (node) {
            if (node.attributes != undefined && node.attributes['name'] != undefined) {
                /*  Die Filterfunktion kann entweder im globalen Namespace (window) oder
                    unter olwrapper.sldFilter liegen
                */
                let context = window;
                if (olwrapper != undefined && olwrapper.sldFilter != undefined) {
                    context = olwrapper.sldFilter;
                }
                let functionName = node.attributes['name'].value;
                let args = []; // derzeit werden Argumente nicht supported

                if (typeof functionName === 'undefined') {
                    throw 'ogc:Function - function name not specified';
                }
                if (typeof context[functionName] !== 'function') {
                    throw context + '.' + functionName + ' is not a function';
                }
                return function () {
                    return context[functionName].apply(context, args);
                }
            }
            else {
                new Error("ogc:Function - bad or missing function name");
            }
        };
        de.novasib.ol.style.filter.propertyAndExpectation = function (node) {
            let property = null;
            let expectation = null;

            let children = node.childNodes;
            for (let i = 0; i < children.length; ++i) {
                let child = children[i];
                let ln = child.localName;

                switch (ln) {
                    case 'PropertyName': {
                        property = de.novasib.ol.style.filter.PropertyName(child);
                        break;
                    }
                    case 'Literal': {
                        expectation = de.novasib.ol.style.filter.Literal(child);
                        break;
                    }
                    case 'Function': {
                        expectation = de.novasib.ol.style.filter.Function(child);
                        break;
                    }
                }
            }

            return [property, expectation];
        };
        de.novasib.ol.style.filter.getExpectionDate = function (expectation) {
            let expectationDate;
            if (typeof expectation === 'function') {
                expectationDate = expectation();
            }
            else if (expectation === 'now') {
                expectationDate = Date.now();
            } else {
                expectationDate = de.novasib.ol.parseDate(expectation);
            }
            return expectationDate;
        }
        de.novasib.ol.style.filter['PropertyIsLessThan'] = function (node) {
            let args = de.novasib.ol.style.filter.propertyAndExpectation(node);
            let property = args[0];
            let expectation = args[1];

            return (function (feature) {
                if (de.novasib.ol.style.filter.isDate(feature, property)) {
                    let propDate = de.novasib.ol.parseDate(feature.get(property));
                    let expectationDate = de.novasib.ol.style.filter.getExpectionDate(expectation);

                    return propDate < expectationDate;

                } else if (de.novasib.ol.style.filter.isNumberOrStringOfNumber(feature, property)) {
                    let propNumber = Number(feature.get(property));
                    let expectationNumber = Number(expectation);
                    return propNumber < expectationNumber;
                } else {
                    return feature.get(property) < expectation;
                }
            });
        };
        de.novasib.ol.style.filter['PropertyIsGreaterThan'] = function (node) {
            let args = de.novasib.ol.style.filter.propertyAndExpectation(node);
            let property = args[0];
            let expectation = args[1];

            return (function (feature) {
                if (de.novasib.ol.style.filter.isDate(feature, property)) {
                    let propDate = de.novasib.ol.parseDate(feature.get(property));
                    let expectationDate = de.novasib.ol.style.filter.getExpectionDate(expectation);

                    return propDate > expectationDate;

                } else if (de.novasib.ol.style.filter.isNumberOrStringOfNumber(feature, property)) {
                    let propNumber = Number(feature.get(property));
                    let expectationNumber = Number(expectation);
                    return propNumber > expectationNumber;
                } else {
                    return feature.get(property) > expectation;
                }
            });
        };

        de.novasib.ol.style.filter['PropertyIsLessThanOrEqualTo'] = function (node) {
            let args = de.novasib.ol.style.filter.propertyAndExpectation(node);
            let property = args[0];
            let expectation = args[1];

            return (function (feature) {
                if (de.novasib.ol.style.filter.isDate(feature, property)) {
                    let propDate = de.novasib.ol.parseDate(feature.get(property));
                    let expectationDate = de.novasib.ol.style.filter.getExpectionDate(expectation);

                    return propDate <= expectationDate;

                } else if (de.novasib.ol.style.filter.isNumberOrStringOfNumber(feature, property)) {
                    let propNumber = Number(feature.get(property));
                    let expectationNumber = Number(expectation);
                    return propNumber <= expectationNumber;
                } else {
                    return feature.get(property) <= expectation;
                }
            });
        };

        de.novasib.ol.style.filter['PropertyIsGreaterThanOrEqualTo'] = function (node) {
            let args = de.novasib.ol.style.filter.propertyAndExpectation(node);
            let property = args[0];
            let expectation = args[1];

            return (function (feature) {
                if (de.novasib.ol.style.filter.isDate(feature, property)) {
                    let propDate = de.novasib.ol.parseDate(feature.get(property));
                    let expectationDate = de.novasib.ol.style.filter.getExpectionDate(expectation);

                    return propDate >= expectationDate;

                } else if (de.novasib.ol.style.filter.isNumberOrStringOfNumber(feature, property)) {
                    let propNumber = Number(feature.get(property));
                    let expectationNumber = Number(expectation);
                    return propNumber >= expectationNumber;
                } else {
                    return feature.get(property) >= expectation;
                }
            });
        };
    }

/************************************************************************
 * novamap overwrites  *
 ************************************************************************/
    /**
    * Overwrites: de.novasib.ol.NovaMap.prototype.updateLayerSwitcher
    *
    * @param layers
    */
    de.novasib.ol.NovaMap.prototype.updateLayerSwitcher = function (layers) {
        if (layers) {
            if (!Array.isArray(layers))
                layers = [layers];
            let ctrl = this.getControlByClass(de.novasib.ol.control.LayerSwitcher);
            if (!ctrl) {
                ctrl = new de.novasib.ol.control.LayerSwitcher({
                    layers: layers,
                    tipLabel: "Kartenebenenauswahl",
                    label: "K"
                });
                this.olmap.addControl(ctrl)
            } else
                layers.forEach(function (layer) {
                    ctrl.addElement(layer)
                })
        }
    };

    /**
    * Overwrites: de.novasib.ol.control.LayerSwitcher.prototype.updateElement_
    *
    * @param mapEvent.frameState
    */
    de.novasib.ol.control.LayerSwitcher.prototype.updateElement_ = function(frameState) {
        /* this entspricht: de.novasib.ol.control.LayerSwitcher */
        if (!frameState) {
            if (this.renderedVisible_) {
                this.element.style.display = "none";
                this.renderedVisible_ = false
            }
            return
        } 

        /* 
         * das ist ein temporaerer Workaround gegen das exzessive Auftreten 
         * von Events die diese Funktion aufrufen 
         * (genaugenommen hier: <de.novasib.ol.control.LayerSwitcher.render> Funktion)
         *
         * */
        if (frameState.index > 10) return;

        if (!this.elements_) return;

        while (this.ulElement_.lastChild)
            this.ulElement_.removeChild(this.ulElement_.lastChild);
        let len = this.elements_.length;
        let overlayBarDrawn = false;
        for (let i = 0; i < len; ++i) {
            let element = this.elements_[i];
            element.updateElement();

            /* da dies nur in SPERRINFOSYS stattfindet, wird nur dieser Fall betrachtet */
            let controlType_ = de.novasib.ol.control.LayerSwitcher.Element_.Type_.RADIO;

            if (!overlayBarDrawn && element.getType() === controlType_) {
                let hr = document.createElement("HR");
                this.ulElement_.appendChild(hr);
                overlayBarDrawn = true
            }
            this.ulElement_.appendChild(element.getElement())
        }
    };

    /**
     * Overwrites: de.novasib.ol.control.LayerSwitcher.prototype.sortElements_
     * 
     * Sorts the element array. First by input type, then by zIndex.
     * 
     * @param none
     */
    de.novasib.ol.control.LayerSwitcher.prototype.sortElements_ = function() {
        /* order by element type (checkbox, radio) */
        let _ = de.novasib.ol;
        let sortByType = function (a, b) {
            let aType = a.getType();
            let bType = b.getType();
            if (aType === bType) {
                return 0;
                // das ist der letzte verbleibende Unterschied zur novamap
            } else if (aType === de.novasib.ol.control.LayerSwitcher.Element_.Type_.CHECK) {
                return -1;
            }
            return 1
        };
        /* sort entries alphanumerically */
        let sortAlph = function (a, b) {
            let aLabel = a.getLabel();
            let bLabel = b.getLabel();

            return aLabel.localeCompare(bLabel)
        };
        /* sort entries by zIndex */
        let sortByZindex = function (a, b, ascending) {
            let ret;
            let aZindex = a.getLayer().getZIndex();
            let bZindex = b.getLayer().getZIndex();

            if (ascending) {
                ret = aZindex - bZindex;
            } else {
                ret = bZindex - aZindex;
            }
            return ret;
        };
        /* sort function */
        let sort = function (a, b) {
            let ret = sortByType(a, b);
            if (ret === 0) {
                ret = sortByZindex(a, b, false);
            }
            return ret;
        };

        /* Sortierung ausfuehren */
        this.elements_.sort(sort)
    };

/************************************************************************
 * ende *
 ************************************************************************/
}

// TODO styles in sld auslagern
function editLayerStylesFunction() {
    return function (feature) {
        let zIndex = 10;
        let orientationZIndex = 0;

        let art = feature.get('FUTURE_ART');
        let ret = [];
        let color, orientationColor;

        if (art === 'S') {
            color = '#c00000';
            orientationColor = '#a3bae9';
        } else if (art === 'U') {
            color = '#ffff00';
            orientationColor = '#a3bae9';

            let artuml = feature.get('ARTUML');
            if ("A" == artuml || "L" == artuml || "P" == "artuml") {
                ret.push(new ol.style.Style({
                    geometry: de.novasib.ol.style.Rule.prototype.getDefaultIconGeometryFunction(),
                    image: new ol.style.Icon({
                        opacity: 1,
                        src: '../Content/Images/stvo/UML-' + artuml + '.png'
                    }),
                    zIndex: 1000
                }));
            }
        } else if (art === 'EDIT') {
            color = '#A3BAE9';
            orientationColor = '#FFFFFF';
            zIndex = 100;
            orientationZIndex = 90;
        }
        let geometry = feature.getGeometry();

        let dontShorten = feature.get('HERKUNFT') == 'EX';
        let newGeom;
        if (dontShorten) {
            newGeom = geometry;
        } else {
            let alen = feature.get('ALEN');
            let vst = feature.get('VST') || 0;
            let bst = feature.get('BST');
            bst = (bst >= 0) ? bst : alen;
            newGeom = de.novasib.ol.geom.getShortenedLineString(geometry, vst, bst, alen);
        }

        let map = olwrapper.map.olmap;
        let prevPoint = null;
        let prevLen = Number.POSITIVE_INFINITY;
        newGeom.forEachSegment(function (start, end) {
            let dx = end[0] - start[0];
            let dy = end[1] - start[1];
            let rotation = Math.atan2(dy, dx);
            let pointCoords = [start[0] + dx * 0.5, start[1] + dy * 0.5];

            if (prevPoint) {
                let px1 = map.getPixelFromCoordinate(end);
                let px2 = map.getPixelFromCoordinate(prevPoint);
                // euclidean distance
                prevLen = Math.sqrt(Math.pow(px1[0] - px2[0], 2) + Math.pow(px1[1] - px2[1], 2));
            }

            // hier wird der Style (Pfeile) anhand von 'G' gedreht
            let so = feature.get('RICHTUNG') == 'G';
            rotation = so ? Math.PI - rotation : -rotation;

            if (prevLen > 40) {
                ret.push(new ol.style.Style({
                    geometry: new ol.geom.Point(pointCoords),
                    image: new ol.style.Icon({
                        src: de.novasib.ol.style.ARROW_IMG,
                        rotation: rotation,
                        color: orientationColor
                    }),
                    zIndex: orientationZIndex
                }));
                prevPoint = pointCoords.slice();
            }
        });

        ret.push(new ol.style.Style({
            geometry: newGeom,
            stroke: new ol.style.Stroke({
                width: 20,
                color: de.novasib.ol.style.getColorLike(color, 0.5),
                lineCap: 'butt',
                lineJoin: 'bevel'
            }),
            zIndex: zIndex
        }));

        return ret;
    };
}

/**
 * 
 * @param {boolean} clear_ Alle features vor dem laden aus der Karte löschen?
 */
function refreshMap(clear_) {
    // selektierte features suchen und deselektieren
    // (ausgewählte features scheinen sich nicht löschen zu lassen)
    let selectFilter = {
        'stylename': 'select'
    };
    let hoverFilter = {
        'stylename': 'hover'
    };

    if (olwrapper.map == undefined) {
        return;
    }

    let selected = olwrapper.map.getFeaturesByProperties('SPERRUNGEN_SYMB', selectFilter);
    selected = $.merge(selected, olwrapper.map.getFeaturesByProperties('SPERRUNGEN', selectFilter));
    selected = $.merge(selected, olwrapper.map.getFeaturesByProperties('UMLEITUNGEN', selectFilter));
    selected = $.merge(selected, olwrapper.map.getFeaturesByProperties('SPERRUNGEN_SYMB', hoverFilter));
    selected = $.merge(selected, olwrapper.map.getFeaturesByProperties('SPERRUNGEN', hoverFilter));
    selected = $.merge(selected, olwrapper.map.getFeaturesByProperties('UMLEITUNGEN', hoverFilter));

    olwrapper.map.deselectFeatures(selected, true);

    olwrapper.map.reloadFeatures({
        clear: clear_,
        layers: ['STRASSENNETZ_A', 'STRASSENNETZ_B',
            'STRASSENNETZ_LK', 'STRASSENNETZ_G',
            'SPERRUNGEN_SYMB', 'DET_BESCH',
            'SPERRUNGEN', 'UMLEITUNGEN']
    });
};
/**
 *  läd Griddaten neu von spezifierten Grid oder dem aktuell angezeigten Grid (id == undefined)
 * @param {any} id ID des Grids
 */
function refreshGridContents(id) {
    let grid;

    if (id != undefined) {
        grid = $('#' + id).data("kendoGrid");
    } else {
        grid = Vwc.gui.grid;
    }

    if (grid != null) {
        grid.dataSource.read();
    }
}

/**
 *  entfernt die Selektion im spezifierten Grid oder dem aktuell angezeigten Grid (id == undefined)
 * @param {any} id ID des Grids
 */
function clearGridSelection(id) {
    let grid;

    if (id != undefined) {
        grid = $('#' + id).data("kendoGrid");
    } else {
        grid = Vwc.gui.grid;
    }

    if (grid != null) {
        grid.clearSelection();
    }
}

function expandGroups(gridId) {
    if ($("#" + gridId).find("#chkExpandGroups").prop("checked")) {
        $("#" + gridId).find(".k-icon.k-i-collapse").trigger("click");
    }
    else {
        $("#" + gridId).find(".k-icon.k-i-expand").trigger("click");
    }
}

function suche_selected(e) {
    let obj = { ortFilter: e.dataItem.Text, kennzeichen: e.dataItem.Value };

    ajaxCall(Vwc.actions.searchOrtFilter, JSON.stringify(obj), function (result) {
        if (result.Message.indexOf("SUCCESS") < 0) {
            displayErrorInStatusInfo(result.status, "Vwc.Panel.Datatable");
        }
        else {
            try {
                let bbox = JSON.parse(result.searchResult);
                olwrapper.map.zoomToExtent(bbox);
            } catch (e) {
                displayErrorInStatusInfo(Vwc.errorMessages.jsonParse, "Vwc.Panel.Datatable");
                console.log("suche_selected: " + Vwc.errorMessages.jsonParse);
            }
        }
    });
}

function loadContentForElement(root, element, href, fadeTime) {
    if (root == element) {
        if (fadeTime != undefined) {
            $("#" + element)
                .fadeOut(fadeTime, function () { // zu aktualisierenden Bereich ausblenden
                    $("#" + element)
                        .hide()
                        .load(href, function () { // den Inhalt laden
                            $("#" + element).fadeIn(fadeTime, function () {
                            });
                        });
                });
        }
        else {
            $("#" + element).load(href, function () { });
        }
    }
    else {
        /* VORSICHT: $(document).ready wird nicht mehr aufgerufen, wenn nur ein Teil des 
         * geladenen Inhalts übernommen wird*/
        if (fadeTime != undefined) {
            $("#" + root)
                .fadeOut(fadeTime, function () { // zu aktualisierenden Bereich ausblenden
                    $("#" + element)
                        .hide()
                        .load(href + ' #' + element, function () { // den Inhalt laden
                            $("#" + root).fadeIn(fadeTime, function () {
                            });
                        });
                });
        }
        else {
            $("#" + element).load(href + ' #' + element, function () { });
        }
    }
}

function getSelection(dropDownElement, getText) {

    let field_selection = "";
    let kendo_Multiselect = $(dropDownElement).getKendoMultiSelect();

    let dataItems = kendo_Multiselect.dataItems();
    for (let index = 0; index < kendo_Multiselect.value().length; index++) {
        if (index) {
            field_selection += ",";
        }
        if (getText === true) {
            field_selection += dataItems[index].Text;
        }
        else {
            field_selection += dataItems[index].Value.toString();
        }
    }
    return field_selection;

}

function setVisible(element) {
    if (element == null) {
        Console.log("Abbruch setVisible(): Element (" + element + ") zum Einfärben nicht gefunden!");
        return;
    }
    element.style.display = 'block';
}

/**
* Ändert die Farbe eines eingebetteten SVG-Objekts
* 
* <object type="image/svg+xml" data="/Content/Images/Symbole/101.svg" onload="changeColorOfObjectSvg(this, 'PATH_3', 'black')"></object>
 * 
 * @param {any} element Element des SVGs
 * @param {any} idInSvgElementToColor ID in SVG zum Einfärben
 * @param {any} color Farbe
 * */
function changeColorOfObjectSvg(element, idInSvgElementToColor, color) {
    if (element == null || element.getSVGDocument() == null || element.getSVGDocument().getElementById(idInSvgElementToColor) == null) {
        console.log("Abbruch changeColorOfObjectSvg(): Element zum Einfärben nicht gefunden!");
        return;
    }
    element.getSVGDocument().getElementById(idInSvgElementToColor).setAttribute("style", "fill:" + color);
}

/**
* Ändert die Primär- und Sekundär-Farbe eines eingebetteten SVG-Objekts
* 
* <object type="image/svg+xml" data="/Content/Images/Symbole/101.svg" onload="changePrimaryAndSecondaryColorOfObjectSvg(this, 'red', 'black')"></object>
 * @param {any} element ID des Elements
 * @param {any} primColor erste Farbe
 * @param {any} secColor zweite Farbe
**/
function changePrimaryAndSecondaryColorOfObjectSvg(element, primColor, secColor) {
    if (element != null || element.getSVGDocument() != null) {
        let svg = element.getSVGDocument();

        if (svg != null && svg.getElementById(Vwc.constants.primaryFillPathIdInSvg) != null) {
            svg.getElementById(Vwc.constants.primaryFillPathIdInSvg).setAttribute("style", "fill:" + primColor);
        } else {
            console.log("Abbruch changePrimaryAndSecondaryColorOfObjectSvg(): Primärpfad zum Einfärben nicht gefunden!");
            return;
        }

        if (svg.getElementById(Vwc.constants.secondaryFillPathIdInSvg) != null) {
            element.getSVGDocument().getElementById(Vwc.constants.secondaryFillPathIdInSvg).setAttribute("style", "fill:" + secColor);
        } /*else {
    // bringt derzeit zu viele Logs auf der Console, da SVGs noch nicht angepasst wurden
    console.log("Fehler changePrimaryAndSecondaryColorOfObjectSvg(): Sekundärpfad zum Einfärben nicht gefunden!");
    return;
} */
    } else {
        console.log("Abbruch changePrimaryAndSecondaryColorOfObjectSvg(): Element zum Einfärben nicht gefunden!");
    }
}

/**
 * scroll to the grid row currently selected
 * @param {object} grid -
 */
function gridSetGridScrollPosition(grid) {
    var row = grid.table.find('tr.k-state-selected');
    if (row.length !== 0) {
        grid.content.scrollTop(grid.content.scrollTop() + $(row).position().top); //scroll the content
    }
}

function gridSelectRow(grid, SelectedRow) {
    var currentStartRow = 0;

    if (SelectedRow !== -1) {
        grid.select("tr:eq(" + (SelectedRow - currentStartRow) + ")");
        console.log("gridSelectRow:" + " row: " + (SelectedRow - currentStartRow));
        gridSetGridScrollPosition(grid);
    }
}

function gridGetRowById(grid, ID) {
    var data = grid.dataSource.data();
    var idx = 0;
    let selectedRow = -1;

    if (data) {
        for (idx = 0; idx < data.length; idx++) {
            if (data[idx].Id === ID) {
                selectedRow = idx;
                break;
            }
        }
    }
    return selectedRow;
}

function getNumericCheckboxState(idSelector) {
    return $('#' + idSelector).is(':checked') ? 1 : 0;
}

function setNumericCheckboxState(idSelector, value) {
    $('#' + idSelector).prop("checked", value == 1 ? true : false);
}

function selectRowWithText(grid, searchtext) {
    let foundrow = null;

    let rows = grid.tbody.find(">tr:not(.k-grouping-row)");
    rows.each(function (index, row) {
        let allCells = $(row).find("td");
        if (allCells.length > 0) {
            let found = false;
            allCells.each(function (index, td) {
                let tdtext = $(td).text();
                if (tdtext === searchtext) {
                    found = true;
                    return false;
                }
            });
            if (found === true) {
                foundrow = row;
                return false;
            }
        }
    });

    grid.select(foundrow);

    return (foundrow != undefined);
}

/**
 * 
 * @param {any} idGrid wenn undefined wird aktuelle Grid genommen
 * @param {any} idRow ID der Zeile, die selektiert werden soll
 */
function setGridSelection(idGrid, idRow) {
    let grid = null;
    let rowFound = false;

    if (idGrid != undefined && idGrid != null) {
        grid = $('#' + idGrid).data("kendoGrid");
    } else {
        grid = Vwc.gui.grid;
    }

    if (grid !== undefined && grid != null) {
        rowFound = selectRowWithText(grid, idRow);
    }
    return rowFound;
}

function getGridSelection() {
    if (Vwc.gui.grid !== undefined) {
        return Vwc.gui.grid.dataItem(Vwc.gui.grid.select());
    } else {
        return null;
    }
}


function setPageState(page, stateIdentifier, state) {
    if (Vwc.states.pages[page] == undefined) {
        Vwc.states.pages[page] = {};
    }
    Vwc.states.pages[page][stateIdentifier] = state;
}

function getPageState(page, stateIdentifier) {
    if (Vwc.states.pages[page] != undefined) {
        return Vwc.states.pages[page][stateIdentifier];
    } else {
        return null;
    }
}

function removeStatesForPage(page) {
    if (Vwc.states.pages[page] != undefined) {
        Vwc.states.pages[page] = null;
    }
}

function getConfigRequestPayload( deliverJson) {
    let time = getFormattedDate();

    let reqJson = {
        'INTERFACE': 'RPI_GI',
        'REM': 'Kommentar',
        'VERSION': '1.0.0',
        'METADATA': {
            'OID': '',
            'SESSIONID': '',
            'ANSWER_TYPE': 'JSON'
        },
        'CATEGORY': {
            'FUNCTION': 'GetConfig',
            'TIMESTAMP': time,
            'USE_MBR': 0,
            'TIMEFILTER': {
                'TIMBEGIN': null,
                'TIMEND': null
            },
            'ROUTING': {
                'RTGBEGIN': 0,
                'RTGEND': 0,
                'RTGDIR': 0
            }
        },
        'GEODATA': {
            'COORDS': [[0, 0, 0, 0]],
            'MBR': [0, 0, 0, 0],
            'NET_TYPE': 'AGSUY',
            'SUB_TYPE': 'ABLKGSN',
            'ZOOM_LEVEL': 10,
            'RESOLUTION': 1.3229166667,
            'ROTATION': 0
        },
        'CACHEINFO': {
            'FILE_NAME': '',
            'FILE_PATH': '',
            'PACK_DATA': 1
        },
        'METAINFOS': {
            'REG_CODE': 0
        }
    };

    let data;
    if (deliverJson === true) {
        data = { requestJson: reqJson };
    }
    else {
        data = { requestJson: JSON.stringify(reqJson) };
    }
    return JSON.stringify(data);
}

function getGisObjectData(id, nettype, subtype, functionName, deliverJson) {
    let time = getFormattedDate();
    functionName = functionName || 'GetGisObject';

    if (!subtype) {
        subtype = 'ABLKGSN';
    }

    let reqJson = {
        'INTERFACE': 'RPI_GI',
        'REM': '',
        'VERSION': '1.0.0',
        'METADATA': {
            'OID': id,
            'SESSIONID': '',
            'ANSWER_TYPE': 'JSON'
        },
        'CATEGORY': {
            'FUNCTION': functionName,
            'TIMESTAMP': time,
            'USE_MBR': 0,
            'TIMEFILTER': {
                'TIMBEGIN': null,
                'TIMEND': null
            },
            'ROUTING': {
                'RTGBEGIN': 0,
                'RTGEND': 0,
                'RTGDIR': 0
            }
        },
        'GEODATA': {
            'COORDS': [[0, 0, 0, 0]],
            'MBR': [0, 0, 0, 0],
            'NET_TYPE': nettype,
            'SUB_TYPE': subtype,
            'ZOOM_LEVEL': 10,
            'RESOLUTION': olwrapper.resolutions[olwrapper.resolutions.length - 1],
            'ROTATION': 0
        },
        'CACHEINFO': {
            'FILE_NAME': '',
            'FILE_PATH': '',
            'PACK_DATA': 1
        },
        'METAINFOS': {
            'REG_CODE': 0
        }
    };

    let data;
    if (deliverJson === true) {
        data = { requestJson: reqJson };
    }
    else {
        data = { requestJson: JSON.stringify(reqJson) };
    }
    return JSON.stringify(data);
}


/**
 * aktiviert / deaktiviert einen Button(über dessen ID)
 * 
 * @param {any} id ID des Elements
 * @param {boolean} enabled aktiviert ja/nein
 */
function enableButton(id, enabled) {
    try {
        if (enabled) {
            $("#" + id)
                .removeAttr("disabled")
                .removeClass("disabled")
                .removeClass("clickthrough")
                .fadeTo("fast", 1);
        } else {
            $("#" + id)
                .attr("disabled", "disabled")
                .addClass("disabled")
                .addClass("clickthrough")
                .fadeTo("fast", 0.25);
        }
    }
    catch (e) {
        console.log("Der Button " + id + " existert nicht!");
    }
}

function destroyKendoObjects(container) {
    kendo.destroy(container);
}

function loadContent(elementToReplace, elementToFade, href, fadeTime, callBack, callbackParams) {
    if (fadeTime != undefined) {
        $("#" + elementToFade)
            .fadeOut(fadeTime, function () { // zu aktualisierenden Bereich ausblenden
                $("#" + elementToFade).hide();
                let toReplace = $("#" + elementToReplace);

                destroyKendoObjects(toReplace);

                toReplace.load(href, function () { // den Inhalt laden
                    $("#" + elementToReplace).fadeIn(fadeTime, function () {
                        callBack.apply(this, callbackParams);
                    });
                });
            });
    }
    else {
        $("#" + elementToReplace).load(href, function () {
            callBack.apply(this, callbackParams);
        });
    }
}

/**
 * Zur Anzeige eines Fehlers bei der Bearbeitung in der DB in der Statuszeile gedacht.
 * Kann ggf. auch zusätzlich noch einen Dialog zur Fehleranzeige öffnen.
 * Ursprünglich für Dialoge gedacht, bei denen die Statuszeile kaum sichtbar ist.
 * 
 * returns TRUE bei Fehler, FALSE bei sonstigen Meldungen
 **/

function handleErrorState(data, isShowErrorDialog, isShowNotification) {
    if (undefined == data || "" === data) {
        let message = generalErrorInternal;
        if (undefined == message) {
            message = "Fehler bei der Bearbeitung!";
            console.log("String generalErrorInternal nicht definiert!");
        }
        displayErrorInStatusInfo(message, "Vwc.Panel.Datatable");
        if (isShowErrorDialog) {
            setTimeout(function () {
                createDialogFehlerBeiDerBearbeitung(message);
            }, 0);
        }
        if (isShowNotification) {
            novaweb.notification.show({
                message: message,
                type: "data-error"
            });
        }
        return true;
    }
    if (undefined != data && undefined != data.Message) {
        displayErrorInStatusInfo(data.Message, "Vwc.Panel.Datatable");
        if (data.Message.length && data.Message.indexOf("SUCCESS") < 0) {
            if (isShowErrorDialog) {
                setTimeout(function () {
                    createDialogFehlerBeiDerBearbeitung(data.Message);
                }, 0);
            }
            if (isShowNotification) {
                novaweb.notification.show({
                    message: data.Message,
                    type: "data-error"
                });
            }
            if (data.severity != undefined && data.severity === "") {
                return false;
            }
            return true;
        }
    } else {
        console.log("Keine message in data gefunden!");
        if (undefined != data) {
            console.log(data);
        }
    }
    return false;
}

var busyStateCnt = 0;

/**
 * @param {bool} switchOn true for making the busy animation active, false for unblocking the UI.
 */
function busyState(switchOn) {
    //return;

    if (switchOn === true) {
        //console.log("lock busy state - cnt " + busyStateCnt);

        busyStateCnt++;
        //if ($("#imgOver").is(':visible')) 
        {
            $('div.k-loading-image').addClass('div-overlay');
            $('div.k-loading-image').show();
        }
    }
    else {
        //console.log("unlock busy state - cnt " + busyStateCnt);

        if (busyStateCnt > 0) {
            busyStateCnt--;
        }

        if (busyStateCnt > 0) {
            return;
        }

        console.log("unlock busy state");

        if ($('.k-loading-mask').length > 0) {
            $('.k-loading-mask').toggle(false);
        }
        $('div.k-loading-image').removeClass('div-overlay');
        $('div.k-loading-image').hide();
    }
}

function getKendoDateString(element) {
    let datePicker = $("#" + element).data("kendoDatePicker");

    if (datePicker != undefined) {
        return kendo.toString(kendo.parseDate(datePicker.value()), "yyyy-MM-dd HH:mm:ss");
    }
    return null;
}

function checkDateValues(idVon, idBis, isNullOk) {
    let von = $("#" + idVon).data("kendoDatePicker").value();
    let bis = $("#" + idBis).data("kendoDatePicker").value();

    $("#" + idBis + "_ui").find('.k-picker-wrap').removeClass("validationErrorInRequiredField");

    if ((von == null || bis == null) && isNullOk) {
        return true;
    }
    if (von > bis) {
        console.log("bad date");
        $("#" + idBis + "_ui").find('.k-picker-wrap').addClass("validationErrorInRequiredField");
        return false;
    }
    return true;
}

function checkRequiredField(field, typ) {

    let displayErrorForElement = false;

    switch (typ) {

        case "kendoTextBox":
            if ($("#" + field).val() == "") {
                $("#" + field).addClass("validationErrorInRequiredField");
                displayErrorForElement = true;
            } else {
                $("#" + field).removeClass("validationErrorInRequiredField");
            }
            break;

        case "kendoNumericTextBox":
            if ($("#" + field).data("kendoNumericTextBox").value() == null) {
                $("#" + field + "_ui").find('.k-numeric-wrap').addClass("validationErrorInRequiredField");
                displayErrorForElement = true;
            } else {
                $("#" + field + "_ui").find('.k-numeric-wrap').removeClass("validationErrorInRequiredField");
            }
            break;

        case "kendoDatePicker":
        case "kendoTimePicker":
            if (null == $("#" + field).data(typ).value()) {
                $("#" + field + "_ui").find('.k-picker-wrap').addClass("validationErrorInRequiredField");
                displayErrorForElement = true;
            } else {
                $("#" + field + "_ui").find('.k-picker-wrap').removeClass("validationErrorInRequiredField");
            }
            break;

        case "kendoDropDownList":
            if ("" == $("#" + field).data(typ).value() || $("#" + field).data(typ).value() == -1) {
                $("#" + field + "_ui").find('.k-dropdown-wrap').addClass("validationErrorInRequiredField");
                displayErrorForElement = true;
            } else {
                $("#" + field + "_ui").find('.k-dropdown-wrap').removeClass("validationErrorInRequiredField");
            }
            break;

        default:
            break;
    }

    return displayErrorForElement;

};
/* Page 50 --> Dialog "Kartenfilter" */

function openKartenFilter() {
    let idContainer = "vwcDialogKartenFilterContainer";

    createDialog(idContainer, {
        width: 850,
        modal: true,
        resizable: false,
        scrollable: true
    }, function () {
        let window = $("#" + idContainer).data("kendoWindow");
        window.bind("refresh", function () {
            this.title(titleDialogKartenFilter);
        });
        window.refresh(Vwc.actions.createDialogKartenFilter);
    });
}

function filterKartenFilterAmt() {
    let obj = {};
    return obj;
}

function filterKartenFilterKreis() {
    let obj = {};
    return obj;
}
;
// Globals
function setupVwcObject() {
    Vwc.gui = {
        grid: null,
        gridID: ""
    };

    Vwc.states = {
        activePage: 1,
        activePart: "",
        gridFilterPara: {},
        mapFilterPara: {
            mapFilter: null
        },
        pages: {
            neueAnordnung: {
                LastUmleitungsart: ""
            },
            Anordnung: {
                activePart: ""
            }
        },
        requestedDetailsViewSperrId: null
    };
}

const dateTimeFutureInfinite = '2200-01-01 00:00:00';

function initBis() {

    requireSaveChanges = false;

    setupVwcObject();

    olWrapperInit();

    $("#BisSplitter").kendoSplitter({
        panes: [
        { collapsible: true },
        { collapsible: true, min: "400px", size: "640px" }
        ],
        orientation: "horizontal",
        height:"100%"
    });

    let splitter = $('#BisSplitter').data("kendoSplitter");
    splitter.bind('resize', function () {
        setSizeOfElements();
    });

    gridSetup([1,2,3]);

    //splitter.resize(true);

    setFieldsVisibility(visibilityFieldsPage1);
    setFieldsVisibility(visibilityFieldsPage2);
    setFieldsVisibility(visibilityFieldsPage3);

    let ddl = $('#kreiseDdl_ui');
    if (ddl.length > 0) {
        ddl.data('kendoDropDownList').bind("change", onChangeKreiseDdl);
    }

    setPageState(3,"strassenklasse",'A');

    let tag = $("#Tag").bind("blur", datumTag_changed).data("kendoDatePicker");
    if (tag != undefined) {
        tag.value(kendo.toString(kendo.parseDate(new Date()), "dd.MM.yyyy"));
        tag.bind("change", datumTag_changed);
    }

    let Von = $("#Von").bind("blur", datumVon_changed).data("kendoDatePicker");
    if (Von != undefined) {
        Von.value(kendo.toString(kendo.parseDate(new Date()), "dd.MM.yyyy"));
        Von.bind("change", datumVon_changed);
    }

    let Bis = $("#Bis").bind("blur", datumVon_changed).data("kendoDatePicker");
    if (Bis != undefined) {
        //Bis.value(kendo.toString(kendo.parseDate(new Date()), "dd.MM.yyyy"));
        Bis.bind("change", datumBis_changed);
    }

    $('#Suche').data("kendoAutoComplete").bind("select", suche_selected);

    setPage1(false);

    let callbackMapReady = function() {
        setTimeout(function(){setSizeOfElements();},0);
        Vwc.gui.grid.dataSource.read();
    };

    if (Vwc.constants.firstRunWithMap) {
        let stichTag = getKendoDateString("Tag");
        let begin = getKendoDateString("Von");
        let end = getKendoDateString("Bis");

        if (stichTag != undefined) {
            mapInit(callbackMapReady, stichTag, stichTag);
        }
        else {
            mapInit(callbackMapReady, begin, end);
        }
        Vwc.constants.firstRunWithMap = false;
    } else {
        mapUpdate(callbackMapReady);
    }
    setSizeOfElements();
}

function gridInit(gridNumber) {
    let id = gridGetBaseName(gridNumber);
    let grid = $("#" + id);
    if (grid.length < 1) {
        return;
    }

    Vwc.gui.grid = grid.data("kendoGrid");

    originalColumns[id] = $.extend(true, {}, Vwc.gui.grid.columns);

    // mehrfache Eventbindung durch Neuaufrufen von gridInit verhindern
    Vwc.gui.grid.unbind("change");
    Vwc.gui.grid.dataSource.bind("requestEnd", dataSource_requestEnd);
    Vwc.gui.grid.bind("dataBound", grid_dataBound);

    switch (gridNumber) {
        case 1:
        case 2:
        case 3:
            Vwc.gui.grid.bind("change", bisGrid_change);
            break;
        default:
            break;
    }
}

function gridSetupTemplates(grid, gridNumber)
{
    if (grid !== undefined) {
        for (var i = 0; i < grid.columns.length; i++) {
            if (grid.columns[i].field === "Aktion") {
                grid.columns[i].template = function (dataItem) {
                    let encoded = dataItem.Symbol.split(";");
                    if (encoded !== undefined) {
                        if ((encoded.length > 2) && (encoded[2] === "1")) {
                            return '<span></span>';
                        }
                    }
                    return '<span><img src="../Content/Images/Vwc/action_zoomto.png" title="' + getZoomToTooltip(gridNumber) + '" style="cursor:pointer;" onclick=zoomToObject(event,"' + dataItem.Id + '")></span>';
                };
            }
            if (grid.columns[i].field == "Ort") {
                grid.columns[i].template = function (dataItem) {
                    return dataItem.get('Ort').length > 200 ? dataItem.get('Ort').substring(0, 118) + "..." : dataItem.get('Ort');
                };
            }
        }
        grid.setOptions({
            columns: grid.columns,
            selectable: true
        });
    }
}

function gridSetup(gridNumbers) {
    for (i = 0; i < gridNumbers.length; i++) {
        Vwc.gui.grid = $("#" + gridGetBaseName(gridNumbers[i])).data("kendoGrid");
        gridSetupTemplates(Vwc.gui.grid, gridNumbers[i]);
        gridInit(gridNumbers[i]);
    }
}

function gridGetBaseName(gridNumber) {
    switch (gridNumber) {
        case 1: return 'BisKarteGrid';
        case 2: return 'BisKreiseGrid';
        case 3: return 'BisStrassenklasseGrid';
    }
    return null;
}

function getZoomToTooltip(gridNumber) {
    switch (gridNumber) {
        case 1: return Vwc.zoomToTooltip.grid1;
        case 2: return Vwc.zoomToTooltip.grid2;
        case 3: return Vwc.zoomToTooltip.grid3;
    }
    return null;
}

function dataSource_requestEnd(e) {
}

function grid_dataBound(e) {
    //console.log("grid_dataBound");
    $("#" + Vwc.gui.gridID).kendoTooltip({
        filter: "td[data-field='Ort']",
        hide: function () {
                this.content.parent().css("visibility", "hidden");
        },
        show: function () {
            if (this.content.text().length > 200) {
                this.content.parent().css("visibility", "visible");
            }
        },
        width: "250px",
        content: function (e) {
            var dataItem = $("#" + Vwc.gui.gridID).data("kendoGrid").dataItem(e.target.closest("tr"));
            var content = dataItem.Ort;
            return content;
        }
    }).data("kendoTooltip");

    setTimeout(function () {
        setSizeOfElements();

        let isSelected = getPageState(Vwc.states.activePage, "isSelected") != undefined ? true : false;
        let selectedId = getPageState(Vwc.states.activePage, "selectedId");

        //console.log("grid_dataBound: isSelected " + isSelected + " selectedId " + selectedId);

        if (isSelected) {
            if (setGridSelection(null, selectedId)) {
                showDetails(selectedId);
            }
            else {
                showNoDetailsSelected();
            }
        } else {
            if (Vwc.gui.grid != undefined) {
                Vwc.gui.grid.select(null);
            }
        }
    }, 0);
}

function bisGrid_change(event)
{
    let grid = event.sender;
    let currentDataItem = grid.dataItem(this.select());
    let id;
    if (currentDataItem) {
        id = currentDataItem.Id;
        showDetails(id);
    }
    else {
        showNoDetailsSelected();
    }

    let isSelected = !jQuery.isEmptyObject(currentDataItem);
    let selectedId = isSelected ? id : null;

    setPageState(Vwc.states.activePage, "isSelected", isSelected);
    setPageState(Vwc.states.activePage, "selectedId", selectedId);

    selectGridSelectionInMap();
}

function selectGridSelectionInMap() {
    //console.log("selectGridSelectionInMap");

    let dataItem = Vwc.gui.grid.dataItem(Vwc.gui.grid.select());
    if (dataItem) {
        let sperrid = dataItem.get('Id');
        syncGridSelectionWithMap(sperrid);
    } else {
        deselectCurrentSelectionInMap();
    }
}

function syncGridSelectionWithMap(sperrid) {
    let feature = olwrapper.map.getFeaturesByProperties('SPERRUNGEN_SYMB', {
        'DOKSPERRID': sperrid
    }, true);

    if (feature) {
        olwrapper.loadDetailBeschilderungForAnordnung(sperrid);
        let old = olwrapper.getSelectedInGrid();
        if (old && old.feature) {
            olwrapper.map.deselectFeatures(old.feature, olwrapper.getLayer(old.feature));
        }

        let sel = {
            id: sperrid,
            feature: feature,
            coordinates: NovaMapUtils.getFeatureCoordinates(feature)
        };
        olwrapper.map.selectFeatures(feature, olwrapper.getLayer(feature));
        olwrapper.setSelectedInGrid(sel);
        olwrapper.selectedSymbol = sel;
    } else {
        //console.log("syncGridSelectionWithMap - no feature for ID " + sperrid);
        deselectCurrentSelectionInMap();
    }
}

function deselectCurrentSelectionInMap() {
    let old = olwrapper.getSelectedInGrid();
    if (old && old.feature) {
        olwrapper.map.deselectFeatures(old.feature, olwrapper.getLayer(old.feature));
    }
    olwrapper.setSelectedInGrid(null);
    olwrapper.map.setLayerVisible('DET_BESCH', false);
    olwrapper.clearLayer("DET_BESCH");
}

/**
 * Event-Handler des ZoomTo-Buttons im Grid
 * @param {any} event
 * @param {any} doksperrid
 */
function zoomToObject(event,doksperrid) {
    console.log("zoomToObject: ID:" + doksperrid);

    if (doksperrid) {

        deselectCurrentSelectionInMap();
        unregisterLayerEvents();

        event.stopPropagation();

        let feature = olwrapper.map.getFeaturesByProperties('SPERRUNGEN_SYMB', {
            'DOKSPERRID': doksperrid
        }, true);

        if (feature)
        {
            // im Symbollayer befindet sich ein Feature mit der entsprechenden ID (doksperrid)
            let props = feature.getProperties();
            let featureTypes = props["FEATURETYPES"];

            if (props["AO_MBR"] != undefined) {
                // der MBR der Anordnung liegt vor, es kann unmittelbar gezoomt werden
                setupLayerEvents(doksperrid, featureTypes);

                let mbr = JSON.parse(props["AO_MBR"]);
                let extent = ol.extent.createEmpty();

                ol.extent.extend(extent, mbr);

                olwrapper.map.zoomToExtent(extent, {
                    callback: function () {
                        console.log("zoom to feature done");
                        // nachfolgende Aufrufe sind nur dann erforderlich, wenn sich am Map-Viewport keine
                        // Veraenderung ergeben hat. Wenn doch: mapViewportChanged
                        gridSyncWithMapSelection(doksperrid);
                        syncGridSelectionWithMap(doksperrid);
                    }
                });
                return;
            }
        }

        // der MBR der Anordnung muss basierend auf den Geometrien der einzelnen Features bestimmt werden
        let srcFunc = olwrapper.getSourceExtractFunction();
        let features = [];

        let data = getGisObjectData(doksperrid, 'S', undefined, undefined, olwrapper.postJsonContent);
        ajaxCall(Vwc.actions.getMap, data, function (result) {
            let sperrCollection = srcFunc(result);
            features = $.merge(features, olwrapper.map.parseGeoJSONFeatures(sperrCollection));

            data = getGisObjectData(doksperrid, 'U', undefined, undefined, olwrapper.postJsonContent);
            ajaxCall(Vwc.actions.getMap, data, function (result) {
                let umlCollection = srcFunc(result);
                features = $.merge(features, olwrapper.map.parseGeoJSONFeatures(umlCollection));
                if (features.length > 0) {

                    setupLayerEvents(doksperrid);

                    olwrapper.map.zoomToFeatures(features, {
                        callback: function () {
                            console.log("zoom to feature done");

                            // nachfolgende Aufrufe sind nur dann erforderlich, wenn sich am Map-Viewport keine
                            // Veraenderung ergeben hat. Wenn doch: mapViewportChanged
                            gridSyncWithMapSelection(doksperrid);
                            syncGridSelectionWithMap(doksperrid);
                        }
                    });
                } else {
                    //console.log('Keine features gefunden für DOKSPERRID=' + (doksperrid || 'null'));
                }
                // die Detailbeschilderung wird in "syncGridSelectionWithMap" angefordert
                //olwrapper.loadDetailBeschilderungForAnordnung(doksperrid);
            });
        });
    }
}

function addLayerMonitor(layerName, doksperrid) {
    if (layerName == undefined || layerName == "editing") {
        return;
    }

    let feature = olwrapper.map.getFeaturesByProperties(layerName, {
        'DOKSPERRID': doksperrid
    }, true);

    if (feature == undefined || feature.length <= 0) {
        Vwc.states.monitorLayers.push(layerName);
        console.log("monitor layer " + layerName);
    }
}

/**
 * 
 * @param {any} doksperrid
 * @param {string} featureTypes - Auflistung der verfuegbaren Feature-Types der Anordnung
 */
function setupLayerEvents(doksperrid, featureTypes) {
    Vwc.states.monitorLayers = [];
    Vwc.states.DokSperrIdToSelect = doksperrid;

    if (featureTypes != undefined) {
        let map = olwrapper.getVectorLayerMap();

        for (let idx in map) {
            if (featureTypes.indexOf(map[idx].type) != -1) {
                addLayerMonitor(map[idx].layer, doksperrid);
            }
        }
    }
    else {
        olwrapper.map.olmap.getLayers().forEach(function (layer) {
            if (layer.type == "VECTOR") {
                if (layer.getVisible()) {
                    addLayerMonitor(layer.getProperties()['name'], doksperrid);
                }
            }
        });
    }

    olwrapper.registerDataListener("RequestStarted", onLayerProcessingStarted);
    olwrapper.registerDataListener("RequestDone", onLayerProcessingDone);
}

function unregisterLayerEvents() {
    olwrapper.removeDataListener("RequestStarted");
    olwrapper.removeDataListener("RequestDone");
}

function onLayerProcessingStarted(layerName) {
    //console.log("onLayerProcessingStarted layer " + layerName);

    if (layerName != undefined && Vwc.states.monitorLayers.indexOf(layerName) == -1) {
        Vwc.states.monitorLayers.push(layerName);
    }
}

function onLayerProcessingDone(layerName) {
    //console.log("onLayerProcessingDone layer " + layerName);

    const index = Vwc.states.monitorLayers.indexOf(layerName);
    if (index > -1) {
        Vwc.states.monitorLayers.splice(index, 1);
    }

    if (Vwc.states.monitorLayers.length == 0)
    {
        console.log("---> all layers rendered");
        setTimeout(function () {
            unregisterLayerEvents();

            //gridSyncWithMapSelection(Vwc.states.DokSperrIdToSelect);
            syncGridSelectionWithMap(Vwc.states.DokSperrIdToSelect);
        }, 0);
    }
/*
    else if (layerName == "SPERRUNGEN_SYMB") {
        setTimeout(function () {
            syncGridSelectionWithMap(Vwc.states.DokSperrIdToSelect);
        }, 10);
    }
*/
}

function getVisibleVectorLayers() {
    let layers = [];

    olwrapper.map.olmap.getLayers().forEach(function (layer) {
        if (layer.type == "VECTOR") {
            if (layer.getVisible()) {
                layers.push(layer.getProperties()['name']);
            }
        }
    });
    return layers;
}


function updateStateForPageChange(pageNr) {
    let gridId = gridGetBaseName(gridNr);
    if (gridId != null) {
        Vwc.gui.gridID = gridId;
        Vwc.gui.grid = $('#' + gridId).data("kendoGrid");
    }
}

function showNoDetailsSelected() {
    $('#detailsNoSelectionDiv').css("display", "");
    $('#detailsDiv').css("display", "none");
}

function setPage(panel, tabButton, readGridData) {
    if (Vwc.gui.gridID != null) {
        Vwc.gui.grid = $("#" + Vwc.gui.gridID).data("kendoGrid");
    }
    else {
        Vwc.gui.grid = null;
    }

    if (!Vwc.settings.isDetailsView){
        showNoDetailsSelected();
    }

    $("#panelDynamicContent").find(".button-header").removeClass("button-header-is-selected");
    $("#" + tabButton).addClass("button-header-is-selected");

    $('#panelKarteGrid').css("display","none");
    $('#panelKreiseGrid').css("display","none");
    $('#panelStrassenklasseGrid').css("display","none");
    $('#panelDetailsView').css("display","none");
    $('#'+panel).css("display","");

    setSizeOfElements();

    if (Vwc.gui.grid != undefined && readGridData !== false) {
        Vwc.gui.grid.dataSource.read();
    }
}

function setPage1(readGridData) {
    Vwc.states.activePage = 1;
    Vwc.gui.gridID = "BisKarteGrid";

    setPage("panelKarteGrid", "inKarteSichtbarBtn", readGridData);
}

function setPage2(readGridData) {
    Vwc.states.activePage = 2;
    Vwc.gui.gridID = "BisKreiseGrid";
    Vwc.gui.grid = $("#" + Vwc.gui.gridID).data("kendoGrid");

    setPage('panelKreiseGrid', "nachKreisenBtn", readGridData);
}

function setPage3(readGridData) {
    Vwc.states.activePage = 3;
    Vwc.gui.gridID = "BisStrassenklasseGrid";

    setPage('panelStrassenklasseGrid', "nachStrassenklassenBtn", readGridData);
}

function setPage4(readGridData) {
    Vwc.states.activePage = 4;
    Vwc.gui.gridID = null;

    setPage('panelDetailsView', "detailAnsichtBtn", readGridData);
}

function onChangeKreiseDdl(event) {
    showNoDetailsSelected();

    Vwc.gui.grid.dataSource.read();
}

function setStrassenklasse(klasse)
{
    $('#panelStrassenklasseButtons').find(".button-header-small").removeClass("button-header-is-selected");
    $('#' + klasse + 'Btn').addClass("button-header-is-selected");

    setPageState(3,"strassenklasse",klasse.charAt(0).toUpperCase());

    showNoDetailsSelected();

    Vwc.gui.grid.dataSource.read();
}

function openKartenlegende() {
    let idContainer = "bisLegendeDynamicContent";

    createDialog(idContainer, {
        width: 500,
        modal: true,
        resizable: false,
        scrollable: true
    }, function () {
        let window = $("#" + idContainer).data("kendoWindow");
        window.bind("refresh", function () {
            this.title(titleDialogLegende);

            let dialogWidth = $('#bisLegendeContent').outerWidth(true);
            dialogWidth += $('#bisLegendeDynamicContent').innerWidth() - $('#bisLegendeDynamicContent').width();

            this.setOptions({
                width: dialogWidth
            });
        });
        window.refresh(Vwc.actions.createDialogLegende);
    });
}

function onBisDialogLegendeSchliessen() {
    let window = $('#bisLegendeDynamicContent').data("kendoWindow");

    if (window != undefined) {
        window.close();
    }
}

function zoomToKreis() {
    let id = $('#kreiseDdl_ui').data('kendoDropDownList').value();

    if (id) {
        let obj = { id: id };

        ajaxCall(Vwc.actions.searchKreisBBOX, JSON.stringify(obj), function (result) {
            if (result.Message.indexOf("SUCCESS") < 0) {
                let errmsg = result.status != undefined ? result.status : result;
                displayErrorInStatusInfo(errmsg, "Vwc.Panel.Datatable");
            }
            else {
                try {
                    let bbox = JSON.parse(result.searchResult);
                    olwrapper.map.zoomToExtent(bbox);
                } catch (e) {
                    displayErrorInStatusInfo(Vwc.errorMessages.jsonParse, "Vwc.Panel.Datatable");
                    console.log("suche_selected: " + Vwc.errorMessages.jsonParse);
                }
            }
        });
    }
}

function exportToPDF1() {
    if (olwrapper.map != null) {
        let map = olwrapper.map;
        let bb = map.getCurrentBoundingBox();
        let boundingBox = bb[0] + ";" + bb[1] + ";" + bb[2] + ";" + bb[3] + ";";
        let zoomLevel = olwrapper.map.getCurrentZoom();
        let res = map.getCurrentViewport().resolution;
        let tag = getKendoDateString("Tag");
        let von = getKendoDateString("Von");
        let bis = getKendoDateString("Bis");
        let mapFilter = "";

        let filter = getPageState("dialogKartenFilter", "requestParameter");
        if (filter != undefined) {
            mapFilter = JSON.stringify(filter);
        }

        let mapRequest;

        if (von != undefined || bis != undefined) {
            mapRequest = olwrapper.getDataFunction('GetGISObjects', 'SUY', 'ABLKGSN', von, bis, false)(bb, res);
        }
        else {
            mapRequest = olwrapper.getDataFunction('GetGISObjects', 'SUY', 'ABLKGSN', tag, tag, false)(bb, res);
        }

        exportDataReport(
            Vwc.actions.createReportBIS1
            + "?boundingBox=" + boundingBox
            + "&zoomLevel=" + zoomLevel
            + "&mapRequest=" + JSON.parse(mapRequest).requestJson
            + "&tag=" + tag
            + "&von=" + von
            + "&bis=" + bis
            + "&mapFilter=" + mapFilter
            , null);
    }
}

function exportToPDF2() {
    let kreisID = $('#kreiseDdl_ui').data('kendoDropDownList').value();
    let kreisName = $('#panelKreiseGrid').find('.k-input').html();
    let tag = getKendoDateString("Tag");
    let von = getKendoDateString("Von");
    let bis = getKendoDateString("Bis");

    exportDataReport(
        Vwc.actions.createReportBIS2
        + "?kreisID=" + kreisID
        + "&kreisName=" + kreisName
        + "&tag=" + tag
        + "&von=" + von
        + "&bis=" + bis
        , null);
}

function exportToPDF3() {

    let strassenklasseID = getPageState(3, "strassenklasse");
    let strassenklasseName = "";
    switch (strassenklasseID) {
        case 'A':
            strassenklasseName = "Bis.Button.Autobahn";
            break;
        case "B":
            strassenklasseName = "Bis.Button.Bundesstrasse";
            break;
        case "L":
            strassenklasseName = "Bis.Button.Landstrasse";
            break;
        case "K":
            strassenklasseName = "Bis.Button.Kreisstrasse";
            break;
        case "G":
            strassenklasseName = "Bis.Button.Gemeindestrasse";
            break;
        default:
            break;
    }
    let tag = getKendoDateString("Tag");
    let von = getKendoDateString("Von");
    let bis = getKendoDateString("Bis");

    exportDataReport(
        Vwc.actions.createReportBIS3
        + "?strassenklasseID=" + strassenklasseID
        + "&strassenklasseName=" + strassenklasseName
        + "&tag=" + tag
        + "&von=" + von
        + "&bis=" + bis
        , null);
}

function getHeightWithMargin( el )
{
    return el.outerHeight(true)  + parseInt(el.css('margin-bottom')) + parseInt(el.css('margin-top'));
}

function setSizeOfElements() {

    let height_footer = $('#appFooterId').outerHeight(true);

    let height_mainFilterTable = $('#BisMainPanelFilterTable').parent().outerHeight(true);

    let height_splitter =
        $(document).height()
        - height_footer
        - 8;

    let height_mapDiv =
        height_splitter
        - height_mainFilterTable
        - 8;

    $('#bisMapDiv').height(height_mapDiv);


    let offset = 0;
    let height_header_btn = 0;
    let height_gridContent = 0;
    let height_grid_actions = 0;
    let height_grid_header = 0;
    let height_grid_pager = 0;

    let height_info = 0;

    let height_difference_complete = 0;
    let panelID = "";

    switch (Vwc.states.activePage) {
        case 1:
            panelID = "#panelKarteGrid";
            break;
        case 2:
            panelID = "#panelKreiseGrid";
            offset += 2;
            break;
        case 3:
            panelID = "#panelStrassenklasseGrid";
            break;
        case 4:
            panelID = "#panelDetailsView";
            break;

        default:
            break;
    }

    height_header_btn = getHeightWithMargin($('#panelPageSelection'));

    let panel = $(panelID);
    let item = panel.find('.panelSchalter');

    if (item.length == 1) {
        offset += item.outerHeight(true) + 2;
    }
    height_info = $("#infoDiv").outerHeight(true);

    if (Vwc.states.activePage == 4) {
        panel.height(height_splitter - height_header_btn);
        $('#detailsDiv')
    }
    else {
        height_grid_actions = getHeightWithMargin(panel.find('.gridPanelActions'));
        height_grid_header = panel.find('.k-grid-header').outerHeight(true);
        height_grid_pager = panel.find('.k-pager-wrap').outerHeight(true);

        height_difference_complete = offset + height_header_btn + height_grid_actions + height_grid_header + height_grid_pager;

        height_gridContent = height_splitter - height_difference_complete - height_info;
        $('#' + Vwc.gui.gridID + ' .k-grid-content').height(height_gridContent);
    }

    $('#BisSplitter').height(height_splitter);

    $('#BisSplitter').find('.k-pane.k-scrollable').height(height_splitter);
    $('#BisSplitter').find('.k-splitbar.k-splitbar-horizontal').height(height_splitter);


    if (olwrapper !== undefined) {
        let map = olwrapper.map;
        if (map) {
            map.updateSize();     // correct the map ratio
        }
    }
}

function filterSuche() {
    let obj = {};
    obj.suchText = $('#Suche').val();
    return obj;
}

function filterKreiseDDL()
{
    return {};
}

function GetGridFilterKarteParams() {
    Vwc.states.gridFilterPara.suche = $('#Suche').val();

    let stichTag = getKendoDateString("Tag");
    let begin;
    let end;

    if (stichTag == undefined) {
        begin = getKendoDateString("Von");
        end = getKendoDateString("Bis");
    }
    else {
        begin = stichTag;
        end = dateTimeFutureInfinite;
    }

    if (olwrapper.map != null) {
        let map = olwrapper.map;
        let bb = map.getCurrentBoundingBox();

        Vwc.states.gridFilterPara.boundingBox = bb[0] + ";" + bb[1] + ";" + bb[2] + ";" + bb[3] + ";";

        let zoom = map.getCurrentZoom();
        Vwc.states.gridFilterPara.zoomLevel = zoom.toString();
        Vwc.states.gridFilterPara.tag = stichTag;

        let res = map.getCurrentViewport().resolution;

        let rq = JSON.parse(olwrapper.getDataFunction('GetGISObjects', 'SUY', 'ABLKGSN', begin, end, false)(bb, res));
        Vwc.states.gridFilterPara.mapRequest = rq.requestJson;

        let mapFilter = getPageState("dialogKartenFilter", "requestParameter");
        if (mapFilter != undefined) {
            Vwc.states.gridFilterPara.mapFilter = JSON.stringify(mapFilter);
        }
        else {
            Vwc.states.gridFilterPara.mapFilter = "";
        }
    }

    return Vwc.states.gridFilterPara;
}


function GetGridFilterKreiseParams() {
    let param = GetGridFilterKarteParams();
    param.kreis = $('#kreiseDdl_ui').data('kendoDropDownList').value();
    return param;
}

function GetGridFilterStrassenklasseParams() {
    let param = GetGridFilterKarteParams();
    param.strassenklasse = getPageState(3,"strassenklasse");
    return param;
}

function showDetails(id) {

    //console.log("showDetails id " + id + " requestedDetailsViewSperrId " + Vwc.states.requestedDetailsViewSperrId);

    if (Vwc.states.requestedDetailsViewSperrId == id) {
        //Details nur dann laden, wenn die bereits geladenen Infos nicht aktuell sind
        $('#detailsNoSelectionDiv').css("display", "none");
        $('#detailsDiv').css("display", "");
        return;
    }
    Vwc.states.requestedDetailsViewSperrId = id;

    let fadeTime = 50;

    loadContent(
        "detailsDiv", "detailsNoSelectionDiv",
        Vwc.actions.createDialogDetails + "?id=" + id + "&page=" + (Vwc.settings.isDetailsView ? 4:1), fadeTime, loadContentDetailsCallback);
}

function loadContentDetailsCallback() {
    if (!Vwc.settings.isDetailsView) {
        $('#detailsDiv').css("height", "330px");
    }
    setSizeOfElements();
}

/****************************************************************************************************************/
/*  map  */
/****************************************************************************************************************/
function mapInitDone() {
    let map = olwrapper.map;

    map.on('select', symbolSelectEventListener);
    map.on('layeradded', function (evt) {
        mapAddTileSourceSelection(evt);

        let layerName = evt.properties.name;
        //if (layerName === 'symbols') {
        //    setLayerSymbolsMaxResolutionForCounty();
        //}
        if (layerName === 'DET_BESCH') {
            // setup Abbildungsreihenfolge hover overlays / Detailbeschilderung
            olwrapper.setLayerZindex('DET_BESCH', 1e4);
            olwrapper.setHoverOverlaysZindex(1e4 - 1);
            olwrapper.setLayersMaxResolution(['DET_BESCH'], 14 + 1); // bis zoom: 8
        }
    });
    map.on('viewportchanged', mapViewportChanged);
}

function mapInit(callback, timebegin, timeend) {
    if (olwrapper === undefined) {
        return;
    }
    ajaxCall(Vwc.actions.getConfig, getConfigRequestPayload(olwrapper.postJsonContent), function (result) {
        if (result.status.indexOf("SUCCESS") < 0) {
            //displayErrorInStatusInfo(result.status, "Vwc.Panel.Datatable");
        } else {
            try {
                Vwc.config = JSON.parse(result.json);
                olwrapper.sperrungenTooltipPrefix = '';
                olwrapper.init(Vwc.config, Vwc.layerCfg, "mapDiv", Vwc.settings.sldFileName, timebegin, timeend);
                mapInitDone();
            } catch (e) {
                setTimeout(function() {
                    olwrapper.init(Vwc.config, Vwc.layerCfg, "mapDiv", Vwc.settings.sldFileName, timebegin, timeend);
                    mapInitDone();
                }, 1000);
            }

            if (Vwc.layerCfg.initialBBOX != null && Vwc.layerCfg.initialBBOX != '' && olwrapper.map) {
                let bbox = JSON.parse(Vwc.layerCfg.initialBBOX);
                olwrapper.map.zoomToExtent(bbox);
            }
            callback.call(this);
        }
    });
}

/**
 * Eventhandler des "viewportchanged" - Events
 * @param {any} event
 */
function mapViewportChanged(event) {
    let bb = olwrapper.map.getCurrentBoundingBox();
    Vwc.states.gridFilterPara.boundingBox = bb[0] + ";" + bb[1] + ";" + bb[2] + ";" + bb[3] + ";";

    let zoom = olwrapper.map.getCurrentZoom();
    Vwc.states.gridFilterPara.zoomLevel = zoom.toString();

    // Refresh Grid für Karte
    refreshGridContents("BisKarteGrid");
}

function mapAddTileSourceSelection(evt) {
    let props = evt.properties;

    if (props.backgroundLayer) {
        let name = props.title || props.name;

        let li = document.createElement('LI');
        li.setAttribute('class', 'ui-state-default map-ddl-control');
        li.setAttribute('style', 'width: 93%;');

        let span = document.createElement('SPAN');
        span.setAttribute('style', 'width: 180px');
        span.innerHTML = name;

        let radio = document.createElement('INPUT');
        radio.setAttribute('type', 'radio');
        radio.setAttribute('name', 'vwcTileSourceRadio');
        radio.setAttribute('value', name);

        if (props.visible) {
            radio.setAttribute('checked', '');
            olwrapper.setBackgroundLayer(name);
        }
        li.appendChild(radio);
        li.appendChild(span);

        $("#map_tile_source_control").append(li);
    }
}

function mapUpdate(callback) {
    callback.call(this);
}

/****************************************************************************************************************/
/*  map. Anbindung an Grids */
/****************************************************************************************************************/

/**
 * Synchronize the object selected in the map with the grid
 * @param {number} ID - the ID of the vector data
 */
function gridSyncWithMapSelection(ID) {
    let grid = Vwc.gui.grid;

    if (grid == undefined) {
        return;
    }

    var currentStartRow = 0;
    var pageSize = grid.dataSource.pageSize();
    var SelectedRow = -1;

    if (pageSize === 0)
        return;

    var data = grid.dataSource.data();
    var idx=0;

    console.log("select grid entry with ID " + ID);

    if (data) {
        for (idx = 0; idx < data.length; idx++){
            if (data[idx].Id == ID) {
                SelectedRow = idx;
                break;
            }
        }
    }

    if (SelectedRow != -1) {
        grid.select("tr:eq(" + (SelectedRow - currentStartRow) + ")");
        console.log("gridSyncWithMapSelection: " + SelectedRow + " row: " + (SelectedRow - currentStartRow));
        gridSetGridScrollPosition(grid);
    }
}

function symbolSelectEventListener(evt) {
    if (evt.layer && evt.layer == 'SPERRUNGEN_SYMB') {
        // Array mit selektierten features
        let selected = evt.selected;
        // Array mit deselektierten features
        let deselected = evt.deselected;

        if (selected.length != 0) {
            let selection = selected[0];

            // selektiertes feature
            let feature = selection.feature;

            if (Vwc.gui.grid != undefined) {
                gridSyncWithMapSelection(feature.get('DOKSPERRID'));
            }
            else {
                showDetails(feature.get('DOKSPERRID'));
            }
            olwrapper.selectedSymbol = selection;

        } else if (deselected.length != 0) {
            let selectedSymbol = olwrapper.selectedSymbol;

            if (selectedSymbol && selectedSymbol.feature) {
                olwrapper.map.deselectFeatures(selectedSymbol.feature, 'SPERRUNGEN_SYMB');
            }

            clearGridSelection();
            showNoDetailsSelected();
        }
    }
}

/*
function zoomToFeature(id) {
    let sel = olwrapper.getSelectedFeatureById(id);
    if (sel) {
        let f = sel.feature;
        olwrapper.map.zoomToFeature(f);
    }
}
*/


/****************************************************************************************************************/
/*  Kopffilter */
/****************************************************************************************************************/

function dateChanged( elementID ) {

    $("#" + elementID + "_ui").find('.k-picker-wrap').removeClass("validationErrorInRequiredField");

    if ($("#" + elementID).val().length > 0) {
        let stichtag = kendo.parseDate($("#" + elementID).val(), "dd.MM.yyyy");

        if (null != stichtag) {
            searchFilter();
        }
        else {
            $("#" + elementID + "_ui").find('.k-picker-wrap').addClass("validationErrorInRequiredField");
        }
    }
    else {
        searchFilter();
    }
}

function datumTag_changed() {
    dateChanged("Tag");
}

function dateRangeChanged( elementID ) {

    if (false === checkDateValues("Von", "Bis", true)) {
        return;
    }
    let element = $("#" + elementID);
    let value = element.val();

    if (value.length > 0) {

        let currentDate = kendo.parseDate(value, "dd.MM.yyyy");

        if (null != currentDate) {
            searchFilter();
        } else {
            // ggf. noch Fehlertexte aus der Datenbank auslesen
            displayErrorInStatusInfo("Bitte überprüfen Sie die Eingabe '" + elementID + "'-Datum!", "Vwc.Panel.Datatable");
        }

    } else {
        searchFilter();
    }
}

function datumVon_changed() {
    dateRangeChanged("Von");
}

function datumBis_changed() {
    dateRangeChanged("Bis");
}

/**
 * im BIS aus Kompatibilitätsgründen überschrieben, da es hier keine Status-Bar gibt
 * leitet die Meldung direkt an die Konsole weiter
 * @param {any} errorText Fehlertext
 * @param {any} gridParentPanelId nicht verwendet
 */
function displayErrorInStatusInfo(errorText, gridParentPanelId) {
    console.log(errorText);
}

function searchFilter() {
    Vwc.states.gridFilterPara.suche = $('#Suche').data("kendoAutoComplete").value();
    let stichTag = getKendoDateString("Tag");
    let begin = getKendoDateString("Von");
    let end = getKendoDateString("Bis");

    Vwc.states.gridFilterPara.tag = stichTag;
    Vwc.states.gridFilterPara.vonDatum = begin;
    Vwc.states.gridFilterPara.bisDatum = end;

    Vwc.gui.grid.dataSource.page(1);

    //sync Karte
    if (Vwc.constants.isBis === true) {
        // BIS-public - Stichtag
        if (stichTag != undefined) {
            olwrapper.setDateTimeRef(Date.parse(stichTag));
        }
        else {
            olwrapper.setDateTimeRef(Date.now());
        }
        olwrapper.timeFilter(stichTag, dateTimeFutureInfinite);
    }
    else {
        // BIS-pro - Zeitraum
        olwrapper.timeFilter(begin, end);
    }
}
;
/*
  html2canvas 0.4.1 <http://html2canvas.hertzen.com>
  Copyright (c) 2013 Niklas von Hertzen

  Released under MIT License
*/

(function(window, document, undefined){

"use strict";

var _html2canvas = {},
previousElement,
computedCSS,
html2canvas;

_html2canvas.Util = {};

_html2canvas.Util.log = function(a) {
  if (_html2canvas.logging && window.console && window.console.log) {
    window.console.log(a);
  }
};

_html2canvas.Util.trimText = (function(isNative){
  return function(input) {
    return isNative ? isNative.apply(input) : ((input || '') + '').replace( /^\s+|\s+$/g , '' );
  };
})(String.prototype.trim);

_html2canvas.Util.asFloat = function(v) {
  return parseFloat(v);
};

(function() {
  // TODO: support all possible length values
  var TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
  var TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
  _html2canvas.Util.parseTextShadows = function (value) {
    if (!value || value === 'none') {
      return [];
    }

    // find multiple shadow declarations
    var shadows = value.match(TEXT_SHADOW_PROPERTY),
      results = [];
    for (var i = 0; shadows && (i < shadows.length); i++) {
      var s = shadows[i].match(TEXT_SHADOW_VALUES);
      results.push({
        color: s[0],
        offsetX: s[1] ? s[1].replace('px', '') : 0,
        offsetY: s[2] ? s[2].replace('px', '') : 0,
        blur: s[3] ? s[3].replace('px', '') : 0
      });
    }
    return results;
  };
})();


_html2canvas.Util.parseBackgroundImage = function (value) {
    var whitespace = ' \r\n\t',
        method, definition, prefix, prefix_i, block, results = [],
        c, mode = 0, numParen = 0, quote, args;

    var appendResult = function(){
        if(method) {
            if(definition.substr( 0, 1 ) === '"') {
                definition = definition.substr( 1, definition.length - 2 );
            }
            if(definition) {
                args.push(definition);
            }
            if(method.substr( 0, 1 ) === '-' &&
                    (prefix_i = method.indexOf( '-', 1 ) + 1) > 0) {
                prefix = method.substr( 0, prefix_i);
                method = method.substr( prefix_i );
            }
            results.push({
                prefix: prefix,
                method: method.toLowerCase(),
                value: block,
                args: args
            });
        }
        args = []; //for some odd reason, setting .length = 0 didn't work in safari
        method =
            prefix =
            definition =
            block = '';
    };

    appendResult();
    for(var i = 0, ii = value.length; i<ii; i++) {
        c = value[i];
        if(mode === 0 && whitespace.indexOf( c ) > -1){
            continue;
        }
        switch(c) {
            case '"':
                if(!quote) {
                    quote = c;
                }
                else if(quote === c) {
                    quote = null;
                }
                break;

            case '(':
                if(quote) { break; }
                else if(mode === 0) {
                    mode = 1;
                    block += c;
                    continue;
                } else {
                    numParen++;
                }
                break;

            case ')':
                if(quote) { break; }
                else if(mode === 1) {
                    if(numParen === 0) {
                        mode = 0;
                        block += c;
                        appendResult();
                        continue;
                    } else {
                        numParen--;
                    }
                }
                break;

            case ',':
                if(quote) { break; }
                else if(mode === 0) {
                    appendResult();
                    continue;
                }
                else if (mode === 1) {
                    if(numParen === 0 && !method.match(/^url$/i)) {
                        args.push(definition);
                        definition = '';
                        block += c;
                        continue;
                    }
                }
                break;
        }

        block += c;
        if(mode === 0) { method += c; }
        else { definition += c; }
    }
    appendResult();

    return results;
};

_html2canvas.Util.Bounds = function (element) {
  var clientRect, bounds = {};

  if (element.getBoundingClientRect){
    clientRect = element.getBoundingClientRect();

    // TODO add scroll position to bounds, so no scrolling of window necessary
    bounds.top = clientRect.top;
    bounds.bottom = clientRect.bottom || (clientRect.top + clientRect.height);
    bounds.left = clientRect.left;

    bounds.width = element.offsetWidth;
    bounds.height = element.offsetHeight;
  }

  return bounds;
};

// TODO ideally, we'd want everything to go through this function instead of Util.Bounds,
// but would require further work to calculate the correct positions for elements with offsetParents
_html2canvas.Util.OffsetBounds = function (element) {
  var parent = element.offsetParent ? _html2canvas.Util.OffsetBounds(element.offsetParent) : {top: 0, left: 0};

  return {
    top: element.offsetTop + parent.top,
    bottom: element.offsetTop + element.offsetHeight + parent.top,
    left: element.offsetLeft + parent.left,
    width: element.offsetWidth,
    height: element.offsetHeight
  };
};

function toPX(element, attribute, value ) {
    var rsLeft = element.runtimeStyle && element.runtimeStyle[attribute],
        left,
        style = element.style;

    // Check if we are not dealing with pixels, (Opera has issues with this)
    // Ported from jQuery css.js
    // From the awesome hack by Dean Edwards
    // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

    // If we're not dealing with a regular pixel number
    // but a number that has a weird ending, we need to convert it to pixels

    if ( !/^-?[0-9]+\.?[0-9]*(?:px)?$/i.test( value ) && /^-?\d/.test(value) ) {
        // Remember the original values
        left = style.left;

        // Put in the new values to get a computed value out
        if (rsLeft) {
            element.runtimeStyle.left = element.currentStyle.left;
        }
        style.left = attribute === "fontSize" ? "1em" : (value || 0);
        value = style.pixelLeft + "px";

        // Revert the changed values
        style.left = left;
        if (rsLeft) {
            element.runtimeStyle.left = rsLeft;
        }
    }

    if (!/^(thin|medium|thick)$/i.test(value)) {
        return Math.round(parseFloat(value)) + "px";
    }

    return value;
}

function asInt(val) {
    return parseInt(val, 10);
}

function parseBackgroundSizePosition(value, element, attribute, index) {
    value = (value || '').split(',');
    value = value[index || 0] || value[0] || 'auto';
    value = _html2canvas.Util.trimText(value).split(' ');

    if(attribute === 'backgroundSize' && (!value[0] || value[0].match(/cover|contain|auto/))) {
        //these values will be handled in the parent function
    } else {
        value[0] = (value[0].indexOf( "%" ) === -1) ? toPX(element, attribute + "X", value[0]) : value[0];
        if(value[1] === undefined) {
            if(attribute === 'backgroundSize') {
                value[1] = 'auto';
                return value;
            } else {
                // IE 9 doesn't return double digit always
                value[1] = value[0];
            }
        }
        value[1] = (value[1].indexOf("%") === -1) ? toPX(element, attribute + "Y", value[1]) : value[1];
    }
    return value;
}

_html2canvas.Util.getCSS = function (element, attribute, index) {
    if (previousElement !== element) {
      computedCSS = document.defaultView.getComputedStyle(element, null);
    }

    var value = computedCSS[attribute];

    if (/^background(Size|Position)$/.test(attribute)) {
        return parseBackgroundSizePosition(value, element, attribute, index);
    } else if (/border(Top|Bottom)(Left|Right)Radius/.test(attribute)) {
      var arr = value.split(" ");
      if (arr.length <= 1) {
          arr[1] = arr[0];
      }
      return arr.map(asInt);
    }

  return value;
};

_html2canvas.Util.resizeBounds = function( current_width, current_height, target_width, target_height, stretch_mode ){
  var target_ratio = target_width / target_height,
    current_ratio = current_width / current_height,
    output_width, output_height;

  if(!stretch_mode || stretch_mode === 'auto') {
    output_width = target_width;
    output_height = target_height;
  } else if(target_ratio < current_ratio ^ stretch_mode === 'contain') {
    output_height = target_height;
    output_width = target_height * current_ratio;
  } else {
    output_width = target_width;
    output_height = target_width / current_ratio;
  }

  return {
    width: output_width,
    height: output_height
  };
};

function backgroundBoundsFactory( prop, el, bounds, image, imageIndex, backgroundSize ) {
    var bgposition =  _html2canvas.Util.getCSS( el, prop, imageIndex ) ,
    topPos,
    left,
    percentage,
    val;

    if (bgposition.length === 1){
      val = bgposition[0];

      bgposition = [];

      bgposition[0] = val;
      bgposition[1] = val;
    }

    if (bgposition[0].toString().indexOf("%") !== -1){
      percentage = (parseFloat(bgposition[0])/100);
      left = bounds.width * percentage;
      if(prop !== 'backgroundSize') {
        left -= (backgroundSize || image).width*percentage;
      }
    } else {
      if(prop === 'backgroundSize') {
        if(bgposition[0] === 'auto') {
          left = image.width;
        } else {
          if (/contain|cover/.test(bgposition[0])) {
            var resized = _html2canvas.Util.resizeBounds(image.width, image.height, bounds.width, bounds.height, bgposition[0]);
            left = resized.width;
            topPos = resized.height;
          } else {
            left = parseInt(bgposition[0], 10);
          }
        }
      } else {
        left = parseInt( bgposition[0], 10);
      }
    }


    if(bgposition[1] === 'auto') {
      topPos = left / image.width * image.height;
    } else if (bgposition[1].toString().indexOf("%") !== -1){
      percentage = (parseFloat(bgposition[1])/100);
      topPos =  bounds.height * percentage;
      if(prop !== 'backgroundSize') {
        topPos -= (backgroundSize || image).height * percentage;
      }

    } else {
      topPos = parseInt(bgposition[1],10);
    }

    return [left, topPos];
}

_html2canvas.Util.BackgroundPosition = function( el, bounds, image, imageIndex, backgroundSize ) {
    var result = backgroundBoundsFactory( 'backgroundPosition', el, bounds, image, imageIndex, backgroundSize );
    return { left: result[0], top: result[1] };
};

_html2canvas.Util.BackgroundSize = function( el, bounds, image, imageIndex ) {
    var result = backgroundBoundsFactory( 'backgroundSize', el, bounds, image, imageIndex );
    return { width: result[0], height: result[1] };
};

_html2canvas.Util.Extend = function (options, defaults) {
  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      defaults[key] = options[key];
    }
  }
  return defaults;
};


/*
 * Derived from jQuery.contents()
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 */
_html2canvas.Util.Children = function( elem ) {
  var children;
  try {
    children = (elem.nodeName && elem.nodeName.toUpperCase() === "IFRAME") ? elem.contentDocument || elem.contentWindow.document : (function(array) {
      var ret = [];
      if (array !== null) {
        (function(first, second ) {
          var i = first.length,
          j = 0;

          if (typeof second.length === "number") {
            for (var l = second.length; j < l; j++) {
              first[i++] = second[j];
            }
          } else {
            while (second[j] !== undefined) {
              first[i++] = second[j++];
            }
          }

          first.length = i;

          return first;
        })(ret, array);
      }
      return ret;
    })(elem.childNodes);

  } catch (ex) {
    _html2canvas.Util.log("html2canvas.Util.Children failed with exception: " + ex.message);
    children = [];
  }
  return children;
};

_html2canvas.Util.isTransparent = function(backgroundColor) {
  return (backgroundColor === "transparent" || backgroundColor === "rgba(0, 0, 0, 0)");
};
_html2canvas.Util.Font = (function () {

  var fontData = {};

  return function(font, fontSize, doc) {
    if (fontData[font + "-" + fontSize] !== undefined) {
      return fontData[font + "-" + fontSize];
    }

    var container = doc.createElement('div'),
    img = doc.createElement('img'),
    span = doc.createElement('span'),
    sampleText = 'Hidden Text',
    baseline,
    middle,
    metricsObj;

    container.style.visibility = "hidden";
    container.style.fontFamily = font;
    container.style.fontSize = fontSize;
    container.style.margin = 0;
    container.style.padding = 0;

    doc.body.appendChild(container);

    // http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever (handtinywhite.gif)
    img.src = "data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs=";
    img.width = 1;
    img.height = 1;

    img.style.margin = 0;
    img.style.padding = 0;
    img.style.verticalAlign = "baseline";

    span.style.fontFamily = font;
    span.style.fontSize = fontSize;
    span.style.margin = 0;
    span.style.padding = 0;

    span.appendChild(doc.createTextNode(sampleText));
    container.appendChild(span);
    container.appendChild(img);
    baseline = (img.offsetTop - span.offsetTop) + 1;

    container.removeChild(span);
    container.appendChild(doc.createTextNode(sampleText));

    container.style.lineHeight = "normal";
    img.style.verticalAlign = "super";

    middle = (img.offsetTop-container.offsetTop) + 1;
    metricsObj = {
      baseline: baseline,
      lineWidth: 1,
      middle: middle
    };

    fontData[font + "-" + fontSize] = metricsObj;

    doc.body.removeChild(container);

    return metricsObj;
  };
})();

(function(){
  var Util = _html2canvas.Util,
    Generate = {};

  _html2canvas.Generate = Generate;

  var reGradients = [
  /^(-webkit-linear-gradient)\(([a-z\s]+)([\w\d\.\s,%\(\)]+)\)$/,
  /^(-o-linear-gradient)\(([a-z\s]+)([\w\d\.\s,%\(\)]+)\)$/,
  /^(-webkit-gradient)\((linear|radial),\s((?:\d{1,3}%?)\s(?:\d{1,3}%?),\s(?:\d{1,3}%?)\s(?:\d{1,3}%?))([\w\d\.\s,%\(\)\-]+)\)$/,
  /^(-moz-linear-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?))([\w\d\.\s,%\(\)]+)\)$/,
  /^(-webkit-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s([a-z\-]+)([\w\d\.\s,%\(\)]+)\)$/,
  /^(-moz-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s?([a-z\-]*)([\w\d\.\s,%\(\)]+)\)$/,
  /^(-o-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s([a-z\-]+)([\w\d\.\s,%\(\)]+)\)$/
  ];

  /*
 * TODO: Add IE10 vendor prefix (-ms) support
 * TODO: Add W3C gradient (linear-gradient) support
 * TODO: Add old Webkit -webkit-gradient(radial, ...) support
 * TODO: Maybe some RegExp optimizations are possible ;o)
 */
  Generate.parseGradient = function(css, bounds) {
    var gradient, i, len = reGradients.length, m1, stop, m2, m2Len, step, m3, tl,tr,br,bl;

    for(i = 0; i < len; i+=1){
      m1 = css.match(reGradients[i]);
      if(m1) {
        break;
      }
    }

    if(m1) {
      switch(m1[1]) {
        case '-webkit-linear-gradient':
        case '-o-linear-gradient':

          gradient = {
            type: 'linear',
            x0: null,
            y0: null,
            x1: null,
            y1: null,
            colorStops: []
          };

          // get coordinates
          m2 = m1[2].match(/\w+/g);
          if(m2){
            m2Len = m2.length;
            for(i = 0; i < m2Len; i+=1){
              switch(m2[i]) {
                case 'top':
                  gradient.y0 = 0;
                  gradient.y1 = bounds.height;
                  break;

                case 'right':
                  gradient.x0 = bounds.width;
                  gradient.x1 = 0;
                  break;

                case 'bottom':
                  gradient.y0 = bounds.height;
                  gradient.y1 = 0;
                  break;

                case 'left':
                  gradient.x0 = 0;
                  gradient.x1 = bounds.width;
                  break;
              }
            }
          }
          if(gradient.x0 === null && gradient.x1 === null){ // center
            gradient.x0 = gradient.x1 = bounds.width / 2;
          }
          if(gradient.y0 === null && gradient.y1 === null){ // center
            gradient.y0 = gradient.y1 = bounds.height / 2;
          }

          // get colors and stops
          m2 = m1[3].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}(?:%|px))?)+/g);
          if(m2){
            m2Len = m2.length;
            step = 1 / Math.max(m2Len - 1, 1);
            for(i = 0; i < m2Len; i+=1){
              m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/);
              if(m3[2]){
                stop = parseFloat(m3[2]);
                if(m3[3] === '%'){
                  stop /= 100;
                } else { // px - stupid opera
                  stop /= bounds.width;
                }
              } else {
                stop = i * step;
              }
              gradient.colorStops.push({
                color: m3[1],
                stop: stop
              });
            }
          }
          break;

        case '-webkit-gradient':

          gradient = {
            type: m1[2] === 'radial' ? 'circle' : m1[2], // TODO: Add radial gradient support for older mozilla definitions
            x0: 0,
            y0: 0,
            x1: 0,
            y1: 0,
            colorStops: []
          };

          // get coordinates
          m2 = m1[3].match(/(\d{1,3})%?\s(\d{1,3})%?,\s(\d{1,3})%?\s(\d{1,3})%?/);
          if(m2){
            gradient.x0 = (m2[1] * bounds.width) / 100;
            gradient.y0 = (m2[2] * bounds.height) / 100;
            gradient.x1 = (m2[3] * bounds.width) / 100;
            gradient.y1 = (m2[4] * bounds.height) / 100;
          }

          // get colors and stops
          m2 = m1[4].match(/((?:from|to|color-stop)\((?:[0-9\.]+,\s)?(?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)\))+/g);
          if(m2){
            m2Len = m2.length;
            for(i = 0; i < m2Len; i+=1){
              m3 = m2[i].match(/(from|to|color-stop)\(([0-9\.]+)?(?:,\s)?((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\)/);
              stop = parseFloat(m3[2]);
              if(m3[1] === 'from') {
                stop = 0.0;
              }
              if(m3[1] === 'to') {
                stop = 1.0;
              }
              gradient.colorStops.push({
                color: m3[3],
                stop: stop
              });
            }
          }
          break;

        case '-moz-linear-gradient':

          gradient = {
            type: 'linear',
            x0: 0,
            y0: 0,
            x1: 0,
            y1: 0,
            colorStops: []
          };

          // get coordinates
          m2 = m1[2].match(/(\d{1,3})%?\s(\d{1,3})%?/);

          // m2[1] == 0%   -> left
          // m2[1] == 50%  -> center
          // m2[1] == 100% -> right

          // m2[2] == 0%   -> top
          // m2[2] == 50%  -> center
          // m2[2] == 100% -> bottom

          if(m2){
            gradient.x0 = (m2[1] * bounds.width) / 100;
            gradient.y0 = (m2[2] * bounds.height) / 100;
            gradient.x1 = bounds.width - gradient.x0;
            gradient.y1 = bounds.height - gradient.y0;
          }

          // get colors and stops
          m2 = m1[3].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}%)?)+/g);
          if(m2){
            m2Len = m2.length;
            step = 1 / Math.max(m2Len - 1, 1);
            for(i = 0; i < m2Len; i+=1){
              m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%)?/);
              if(m3[2]){
                stop = parseFloat(m3[2]);
                if(m3[3]){ // percentage
                  stop /= 100;
                }
              } else {
                stop = i * step;
              }
              gradient.colorStops.push({
                color: m3[1],
                stop: stop
              });
            }
          }
          break;

        case '-webkit-radial-gradient':
        case '-moz-radial-gradient':
        case '-o-radial-gradient':

          gradient = {
            type: 'circle',
            x0: 0,
            y0: 0,
            x1: bounds.width,
            y1: bounds.height,
            cx: 0,
            cy: 0,
            rx: 0,
            ry: 0,
            colorStops: []
          };

          // center
          m2 = m1[2].match(/(\d{1,3})%?\s(\d{1,3})%?/);
          if(m2){
            gradient.cx = (m2[1] * bounds.width) / 100;
            gradient.cy = (m2[2] * bounds.height) / 100;
          }

          // size
          m2 = m1[3].match(/\w+/);
          m3 = m1[4].match(/[a-z\-]*/);
          if(m2 && m3){
            switch(m3[0]){
              case 'farthest-corner':
              case 'cover': // is equivalent to farthest-corner
              case '': // mozilla removes "cover" from definition :(
                tl = Math.sqrt(Math.pow(gradient.cx, 2) + Math.pow(gradient.cy, 2));
                tr = Math.sqrt(Math.pow(gradient.cx, 2) + Math.pow(gradient.y1 - gradient.cy, 2));
                br = Math.sqrt(Math.pow(gradient.x1 - gradient.cx, 2) + Math.pow(gradient.y1 - gradient.cy, 2));
                bl = Math.sqrt(Math.pow(gradient.x1 - gradient.cx, 2) + Math.pow(gradient.cy, 2));
                gradient.rx = gradient.ry = Math.max(tl, tr, br, bl);
                break;
              case 'closest-corner':
                tl = Math.sqrt(Math.pow(gradient.cx, 2) + Math.pow(gradient.cy, 2));
                tr = Math.sqrt(Math.pow(gradient.cx, 2) + Math.pow(gradient.y1 - gradient.cy, 2));
                br = Math.sqrt(Math.pow(gradient.x1 - gradient.cx, 2) + Math.pow(gradient.y1 - gradient.cy, 2));
                bl = Math.sqrt(Math.pow(gradient.x1 - gradient.cx, 2) + Math.pow(gradient.cy, 2));
                gradient.rx = gradient.ry = Math.min(tl, tr, br, bl);
                break;
              case 'farthest-side':
                if(m2[0] === 'circle'){
                  gradient.rx = gradient.ry = Math.max(
                    gradient.cx,
                    gradient.cy,
                    gradient.x1 - gradient.cx,
                    gradient.y1 - gradient.cy
                    );
                } else { // ellipse

                  gradient.type = m2[0];

                  gradient.rx = Math.max(
                    gradient.cx,
                    gradient.x1 - gradient.cx
                    );
                  gradient.ry = Math.max(
                    gradient.cy,
                    gradient.y1 - gradient.cy
                    );
                }
                break;
              case 'closest-side':
              case 'contain': // is equivalent to closest-side
                if(m2[0] === 'circle'){
                  gradient.rx = gradient.ry = Math.min(
                    gradient.cx,
                    gradient.cy,
                    gradient.x1 - gradient.cx,
                    gradient.y1 - gradient.cy
                    );
                } else { // ellipse

                  gradient.type = m2[0];

                  gradient.rx = Math.min(
                    gradient.cx,
                    gradient.x1 - gradient.cx
                    );
                  gradient.ry = Math.min(
                    gradient.cy,
                    gradient.y1 - gradient.cy
                    );
                }
                break;

            // TODO: add support for "30px 40px" sizes (webkit only)
            }
          }

          // color stops
          m2 = m1[5].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}(?:%|px))?)+/g);
          if(m2){
            m2Len = m2.length;
            step = 1 / Math.max(m2Len - 1, 1);
            for(i = 0; i < m2Len; i+=1){
              m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/);
              if(m3[2]){
                stop = parseFloat(m3[2]);
                if(m3[3] === '%'){
                  stop /= 100;
                } else { // px - stupid opera
                  stop /= bounds.width;
                }
              } else {
                stop = i * step;
              }
              gradient.colorStops.push({
                color: m3[1],
                stop: stop
              });
            }
          }
          break;
      }
    }

    return gradient;
  };

  function addScrollStops(grad) {
    return function(colorStop) {
      try {
        grad.addColorStop(colorStop.stop, colorStop.color);
      }
      catch(e) {
        Util.log(['failed to add color stop: ', e, '; tried to add: ', colorStop]);
      }
    };
  }

  Generate.Gradient = function(src, bounds) {
    if(bounds.width === 0 || bounds.height === 0) {
      return;
    }

    var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    gradient, grad;

    canvas.width = bounds.width;
    canvas.height = bounds.height;

    // TODO: add support for multi defined background gradients
    gradient = _html2canvas.Generate.parseGradient(src, bounds);

    if(gradient) {
      switch(gradient.type) {
        case 'linear':
          grad = ctx.createLinearGradient(gradient.x0, gradient.y0, gradient.x1, gradient.y1);
          gradient.colorStops.forEach(addScrollStops(grad));
          ctx.fillStyle = grad;
          ctx.fillRect(0, 0, bounds.width, bounds.height);
          break;

        case 'circle':
          grad = ctx.createRadialGradient(gradient.cx, gradient.cy, 0, gradient.cx, gradient.cy, gradient.rx);
          gradient.colorStops.forEach(addScrollStops(grad));
          ctx.fillStyle = grad;
          ctx.fillRect(0, 0, bounds.width, bounds.height);
          break;

        case 'ellipse':
          var canvasRadial = document.createElement('canvas'),
            ctxRadial = canvasRadial.getContext('2d'),
            ri = Math.max(gradient.rx, gradient.ry),
            di = ri * 2;

          canvasRadial.width = canvasRadial.height = di;

          grad = ctxRadial.createRadialGradient(gradient.rx, gradient.ry, 0, gradient.rx, gradient.ry, ri);
          gradient.colorStops.forEach(addScrollStops(grad));

          ctxRadial.fillStyle = grad;
          ctxRadial.fillRect(0, 0, di, di);

          ctx.fillStyle = gradient.colorStops[gradient.colorStops.length - 1].color;
          ctx.fillRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(canvasRadial, gradient.cx - gradient.rx, gradient.cy - gradient.ry, 2 * gradient.rx, 2 * gradient.ry);
          break;
      }
    }

    return canvas;
  };

  Generate.ListAlpha = function(number) {
    var tmp = "",
    modulus;

    do {
      modulus = number % 26;
      tmp = String.fromCharCode((modulus) + 64) + tmp;
      number = number / 26;
    }while((number*26) > 26);

    return tmp;
  };

  Generate.ListRoman = function(number) {
    var romanArray = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"],
    decimal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
    roman = "",
    v,
    len = romanArray.length;

    if (number <= 0 || number >= 4000) {
      return number;
    }

    for (v=0; v < len; v+=1) {
      while (number >= decimal[v]) {
        number -= decimal[v];
        roman += romanArray[v];
      }
    }

    return roman;
  };
})();
function h2cRenderContext(width, height) {
  var storage = [];
  return {
    storage: storage,
    width: width,
    height: height,
    clip: function() {
      storage.push({
        type: "function",
        name: "clip",
        'arguments': arguments
      });
    },
    translate: function() {
      storage.push({
        type: "function",
        name: "translate",
        'arguments': arguments
      });
    },
    fill: function() {
      storage.push({
        type: "function",
        name: "fill",
        'arguments': arguments
      });
    },
    save: function() {
      storage.push({
        type: "function",
        name: "save",
        'arguments': arguments
      });
    },
    restore: function() {
      storage.push({
        type: "function",
        name: "restore",
        'arguments': arguments
      });
    },
    fillRect: function () {
      storage.push({
        type: "function",
        name: "fillRect",
        'arguments': arguments
      });
    },
    createPattern: function() {
      storage.push({
        type: "function",
        name: "createPattern",
        'arguments': arguments
      });
    },
    drawShape: function() {

      var shape = [];

      storage.push({
        type: "function",
        name: "drawShape",
        'arguments': shape
      });

      return {
        moveTo: function() {
          shape.push({
            name: "moveTo",
            'arguments': arguments
          });
        },
        lineTo: function() {
          shape.push({
            name: "lineTo",
            'arguments': arguments
          });
        },
        arcTo: function() {
          shape.push({
            name: "arcTo",
            'arguments': arguments
          });
        },
        bezierCurveTo: function() {
          shape.push({
            name: "bezierCurveTo",
            'arguments': arguments
          });
        },
        quadraticCurveTo: function() {
          shape.push({
            name: "quadraticCurveTo",
            'arguments': arguments
          });
        }
      };

    },
    drawImage: function () {
      storage.push({
        type: "function",
        name: "drawImage",
        'arguments': arguments
      });
    },
    fillText: function () {
      storage.push({
        type: "function",
        name: "fillText",
        'arguments': arguments
      });
    },
    setVariable: function (variable, value) {
      storage.push({
        type: "variable",
        name: variable,
        'arguments': value
      });
      return value;
    }
  };
}
_html2canvas.Parse = function (images, options) {
  window.scroll(0,0);

  var element = (( options.elements === undefined ) ? document.body : options.elements[0]), // select body by default
  numDraws = 0,
  doc = element.ownerDocument,
  Util = _html2canvas.Util,
  support = Util.Support(options, doc),
  ignoreElementsRegExp = new RegExp("(" + options.ignoreElements + ")"),
  body = doc.body,
  getCSS = Util.getCSS,
  pseudoHide = "___html2canvas___pseudoelement",
  hidePseudoElements = doc.createElement('style');

  hidePseudoElements.innerHTML = '.' + pseudoHide + '-before:before { content: "" !important; display: none !important; }' +
  '.' + pseudoHide + '-after:after { content: "" !important; display: none !important; }';

  body.appendChild(hidePseudoElements);

  images = images || {};

  function documentWidth () {
    return Math.max(
      Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
      Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
      Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
      );
  }

  function documentHeight () {
    return Math.max(
      Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
      Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
      Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
      );
  }

  function getCSSInt(element, attribute) {
    var val = parseInt(getCSS(element, attribute), 10);
    return (isNaN(val)) ? 0 : val; // borders in old IE are throwing 'medium' for demo.html
  }

  function renderRect (ctx, x, y, w, h, bgcolor) {
    if (bgcolor !== "transparent"){
      ctx.setVariable("fillStyle", bgcolor);
      ctx.fillRect(x, y, w, h);
      numDraws+=1;
    }
  }

  function capitalize(m, p1, p2) {
    if (m.length > 0) {
      return p1 + p2.toUpperCase();
    }
  }

  function textTransform (text, transform) {
    switch(transform){
      case "lowercase":
        return text.toLowerCase();
      case "capitalize":
        return text.replace( /(^|\s|:|-|\(|\))([a-z])/g, capitalize);
      case "uppercase":
        return text.toUpperCase();
      default:
        return text;
    }
  }

  function noLetterSpacing(letter_spacing) {
    return (/^(normal|none|0px)$/.test(letter_spacing));
  }

  function drawText(currentText, x, y, ctx){
    if (currentText !== null && Util.trimText(currentText).length > 0) {
      ctx.fillText(currentText, x, y);
      numDraws+=1;
    }
  }

  function setTextVariables(ctx, el, text_decoration, color) {
    var align = false,
    bold = getCSS(el, "fontWeight"),
    family = getCSS(el, "fontFamily"),
    size = getCSS(el, "fontSize"),
    shadows = Util.parseTextShadows(getCSS(el, "textShadow"));

    switch(parseInt(bold, 10)){
      case 401:
        bold = "bold";
        break;
      case 400:
        bold = "normal";
        break;
    }

    ctx.setVariable("fillStyle", color);
    ctx.setVariable("font", [getCSS(el, "fontStyle"), getCSS(el, "fontVariant"), bold, size, family].join(" "));
    ctx.setVariable("textAlign", (align) ? "right" : "left");

    if (shadows.length) {
      // TODO: support multiple text shadows
      // apply the first text shadow
      ctx.setVariable("shadowColor", shadows[0].color);
      ctx.setVariable("shadowOffsetX", shadows[0].offsetX);
      ctx.setVariable("shadowOffsetY", shadows[0].offsetY);
      ctx.setVariable("shadowBlur", shadows[0].blur);
    }

    if (text_decoration !== "none"){
      return Util.Font(family, size, doc);
    }
  }

  function renderTextDecoration(ctx, text_decoration, bounds, metrics, color) {
    switch(text_decoration) {
      case "underline":
        // Draws a line at the baseline of the font
        // TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size
        renderRect(ctx, bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, color);
        break;
      case "overline":
        renderRect(ctx, bounds.left, Math.round(bounds.top), bounds.width, 1, color);
        break;
      case "line-through":
        // TODO try and find exact position for line-through
        renderRect(ctx, bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, color);
        break;
    }
  }

  function getTextBounds(state, text, textDecoration, isLast, transform) {
    var bounds;
    if (support.rangeBounds && !transform) {
      if (textDecoration !== "none" || Util.trimText(text).length !== 0) {
        bounds = textRangeBounds(text, state.node, state.textOffset);
      }
      state.textOffset += text.length;
    } else if (state.node && typeof state.node.nodeValue === "string" ){
      var newTextNode = (isLast) ? state.node.splitText(text.length) : null;
      bounds = textWrapperBounds(state.node, transform);
      state.node = newTextNode;
    }
    return bounds;
  }

  function textRangeBounds(text, textNode, textOffset) {
    var range = doc.createRange();
    range.setStart(textNode, textOffset);
    range.setEnd(textNode, textOffset + text.length);
    return range.getBoundingClientRect();
  }

  function textWrapperBounds(oldTextNode, transform) {
    var parent = oldTextNode.parentNode,
    wrapElement = doc.createElement('wrapper'),
    backupText = oldTextNode.cloneNode(true);

    wrapElement.appendChild(oldTextNode.cloneNode(true));
    parent.replaceChild(wrapElement, oldTextNode);

    var bounds = transform ? Util.OffsetBounds(wrapElement) : Util.Bounds(wrapElement);
    parent.replaceChild(backupText, wrapElement);
    return bounds;
  }

  function renderText(el, textNode, stack) {
    var ctx = stack.ctx,
    color = getCSS(el, "color"),
    textDecoration = getCSS(el, "textDecoration"),
    textAlign = getCSS(el, "textAlign"),
    metrics,
    textList,
    state = {
      node: textNode,
      textOffset: 0
    };

    if (Util.trimText(textNode.nodeValue).length > 0) {
      textNode.nodeValue = textTransform(textNode.nodeValue, getCSS(el, "textTransform"));
      textAlign = textAlign.replace(["-webkit-auto"],["auto"]);

      textList = (!options.letterRendering && /^(left|right|justify|auto)$/.test(textAlign) && noLetterSpacing(getCSS(el, "letterSpacing"))) ?
      textNode.nodeValue.split(/(\b| )/)
      : textNode.nodeValue.split("");

      metrics = setTextVariables(ctx, el, textDecoration, color);

      if (options.chinese) {
        textList.forEach(function(word, index) {
          if (/.*[\u4E00-\u9FA5].*$/.test(word)) {
            word = word.split("");
            word.unshift(index, 1);
            textList.splice.apply(textList, word);
          }
        });
      }

      textList.forEach(function(text, index) {
        var bounds = getTextBounds(state, text, textDecoration, (index < textList.length - 1), stack.transform.matrix);
        if (bounds) {
          drawText(text, bounds.left, bounds.bottom, ctx);
          renderTextDecoration(ctx, textDecoration, bounds, metrics, color);
        }
      });
    }
  }

  function listPosition (element, val) {
    var boundElement = doc.createElement( "boundelement" ),
    originalType,
    bounds;

    boundElement.style.display = "inline";

    originalType = element.style.listStyleType;
    element.style.listStyleType = "none";

    boundElement.appendChild(doc.createTextNode(val));

    element.insertBefore(boundElement, element.firstChild);

    bounds = Util.Bounds(boundElement);
    element.removeChild(boundElement);
    element.style.listStyleType = originalType;
    return bounds;
  }

  function elementIndex(el) {
    var i = -1,
    count = 1,
    childs = el.parentNode.childNodes;

    if (el.parentNode) {
      while(childs[++i] !== el) {
        if (childs[i].nodeType === 1) {
          count++;
        }
      }
      return count;
    } else {
      return -1;
    }
  }

  function listItemText(element, type) {
    var currentIndex = elementIndex(element), text;
    switch(type){
      case "decimal":
        text = currentIndex;
        break;
      case "decimal-leading-zero":
        text = (currentIndex.toString().length === 1) ? currentIndex = "0" + currentIndex.toString() : currentIndex.toString();
        break;
      case "upper-roman":
        text = _html2canvas.Generate.ListRoman( currentIndex );
        break;
      case "lower-roman":
        text = _html2canvas.Generate.ListRoman( currentIndex ).toLowerCase();
        break;
      case "lower-alpha":
        text = _html2canvas.Generate.ListAlpha( currentIndex ).toLowerCase();
        break;
      case "upper-alpha":
        text = _html2canvas.Generate.ListAlpha( currentIndex );
        break;
    }

    return text + ". ";
  }

  function renderListItem(element, stack, elBounds) {
    var x,
    text,
    ctx = stack.ctx,
    type = getCSS(element, "listStyleType"),
    listBounds;

    if (/^(decimal|decimal-leading-zero|upper-alpha|upper-latin|upper-roman|lower-alpha|lower-greek|lower-latin|lower-roman)$/i.test(type)) {
      text = listItemText(element, type);
      listBounds = listPosition(element, text);
      setTextVariables(ctx, element, "none", getCSS(element, "color"));

      if (getCSS(element, "listStylePosition") === "inside") {
        ctx.setVariable("textAlign", "left");
        x = elBounds.left;
      } else {
        return;
      }

      drawText(text, x, listBounds.bottom, ctx);
    }
  }

  function loadImage (src){
    var img = images[src];
    return (img && img.succeeded === true) ? img.img : false;
  }

  function clipBounds(src, dst){
    var x = Math.max(src.left, dst.left),
    y = Math.max(src.top, dst.top),
    x2 = Math.min((src.left + src.width), (dst.left + dst.width)),
    y2 = Math.min((src.top + src.height), (dst.top + dst.height));

    return {
      left:x,
      top:y,
      width:x2-x,
      height:y2-y
    };
  }

  function setZ(element, stack, parentStack){
    var newContext,
    isPositioned = stack.cssPosition !== 'static',
    zIndex = isPositioned ? getCSS(element, 'zIndex') : 'auto',
    opacity = getCSS(element, 'opacity'),
    isFloated = getCSS(element, 'cssFloat') !== 'none';

    // https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context
    // When a new stacking context should be created:
    // the root element (HTML),
    // positioned (absolutely or relatively) with a z-index value other than "auto",
    // elements with an opacity value less than 1. (See the specification for opacity),
    // on mobile WebKit and Chrome 22+, position: fixed always creates a new stacking context, even when z-index is "auto" (See this post)

    stack.zIndex = newContext = h2czContext(zIndex);
    newContext.isPositioned = isPositioned;
    newContext.isFloated = isFloated;
    newContext.opacity = opacity;
    newContext.ownStacking = (zIndex !== 'auto' || opacity < 1);

    if (parentStack) {
      parentStack.zIndex.children.push(stack);
    }
  }

  function renderImage(ctx, element, image, bounds, borders) {

    var paddingLeft = getCSSInt(element, 'paddingLeft'),
    paddingTop = getCSSInt(element, 'paddingTop'),
    paddingRight = getCSSInt(element, 'paddingRight'),
    paddingBottom = getCSSInt(element, 'paddingBottom');

    drawImage(
      ctx,
      image,
      0, //sx
      0, //sy
      image.width, //sw
      image.height, //sh
      bounds.left + paddingLeft + borders[3].width, //dx
      bounds.top + paddingTop + borders[0].width, // dy
      bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight), //dw
      bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom) //dh
      );
  }

  function getBorderData(element) {
    return ["Top", "Right", "Bottom", "Left"].map(function(side) {
      return {
        width: getCSSInt(element, 'border' + side + 'Width'),
        color: getCSS(element, 'border' + side + 'Color')
      };
    });
  }

  function getBorderRadiusData(element) {
    return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
      return getCSS(element, 'border' + side + 'Radius');
    });
  }

  var getCurvePoints = (function(kappa) {

    return function(x, y, r1, r2) {
      var ox = (r1) * kappa, // control point offset horizontal
      oy = (r2) * kappa, // control point offset vertical
      xm = x + r1, // x-middle
      ym = y + r2; // y-middle
      return {
        topLeft: bezierCurve({
          x:x,
          y:ym
        }, {
          x:x,
          y:ym - oy
        }, {
          x:xm - ox,
          y:y
        }, {
          x:xm,
          y:y
        }),
        topRight: bezierCurve({
          x:x,
          y:y
        }, {
          x:x + ox,
          y:y
        }, {
          x:xm,
          y:ym - oy
        }, {
          x:xm,
          y:ym
        }),
        bottomRight: bezierCurve({
          x:xm,
          y:y
        }, {
          x:xm,
          y:y + oy
        }, {
          x:x + ox,
          y:ym
        }, {
          x:x,
          y:ym
        }),
        bottomLeft: bezierCurve({
          x:xm,
          y:ym
        }, {
          x:xm - ox,
          y:ym
        }, {
          x:x,
          y:y + oy
        }, {
          x:x,
          y:y
        })
      };
    };
  })(4 * ((Math.sqrt(2) - 1) / 3));

  function bezierCurve(start, startControl, endControl, end) {

    var lerp = function (a, b, t) {
      return {
        x:a.x + (b.x - a.x) * t,
        y:a.y + (b.y - a.y) * t
      };
    };

    return {
      start: start,
      startControl: startControl,
      endControl: endControl,
      end: end,
      subdivide: function(t) {
        var ab = lerp(start, startControl, t),
        bc = lerp(startControl, endControl, t),
        cd = lerp(endControl, end, t),
        abbc = lerp(ab, bc, t),
        bccd = lerp(bc, cd, t),
        dest = lerp(abbc, bccd, t);
        return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
      },
      curveTo: function(borderArgs) {
        borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
      },
      curveToReversed: function(borderArgs) {
        borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
      }
    };
  }

  function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
    if (radius1[0] > 0 || radius1[1] > 0) {
      borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
      corner1[0].curveTo(borderArgs);
      corner1[1].curveTo(borderArgs);
    } else {
      borderArgs.push(["line", x, y]);
    }

    if (radius2[0] > 0 || radius2[1] > 0) {
      borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
    }
  }

  function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
    var borderArgs = [];

    if (radius1[0] > 0 || radius1[1] > 0) {
      borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
      outer1[1].curveTo(borderArgs);
    } else {
      borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
    }

    if (radius2[0] > 0 || radius2[1] > 0) {
      borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
      outer2[0].curveTo(borderArgs);
      borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
      inner2[0].curveToReversed(borderArgs);
    } else {
      borderArgs.push([ "line", borderData.c2[0], borderData.c2[1]]);
      borderArgs.push([ "line", borderData.c3[0], borderData.c3[1]]);
    }

    if (radius1[0] > 0 || radius1[1] > 0) {
      borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
      inner1[1].curveToReversed(borderArgs);
    } else {
      borderArgs.push([ "line", borderData.c4[0], borderData.c4[1]]);
    }

    return borderArgs;
  }

  function calculateCurvePoints(bounds, borderRadius, borders) {

    var x = bounds.left,
    y = bounds.top,
    width = bounds.width,
    height = bounds.height,

    tlh = borderRadius[0][0],
    tlv = borderRadius[0][1],
    trh = borderRadius[1][0],
    trv = borderRadius[1][1],
    brh = borderRadius[2][0],
    brv = borderRadius[2][1],
    blh = borderRadius[3][0],
    blv = borderRadius[3][1],

    topWidth = width - trh,
    rightHeight = height - brv,
    bottomWidth = width - brh,
    leftHeight = height - blv;

    return {
      topLeftOuter: getCurvePoints(
        x,
        y,
        tlh,
        tlv
        ).topLeft.subdivide(0.5),

      topLeftInner: getCurvePoints(
        x + borders[3].width,
        y + borders[0].width,
        Math.max(0, tlh - borders[3].width),
        Math.max(0, tlv - borders[0].width)
        ).topLeft.subdivide(0.5),

      topRightOuter: getCurvePoints(
        x + topWidth,
        y,
        trh,
        trv
        ).topRight.subdivide(0.5),

      topRightInner: getCurvePoints(
        x + Math.min(topWidth, width + borders[3].width),
        y + borders[0].width,
        (topWidth > width + borders[3].width) ? 0 :trh - borders[3].width,
        trv - borders[0].width
        ).topRight.subdivide(0.5),

      bottomRightOuter: getCurvePoints(
        x + bottomWidth,
        y + rightHeight,
        brh,
        brv
        ).bottomRight.subdivide(0.5),

      bottomRightInner: getCurvePoints(
        x + Math.min(bottomWidth, width + borders[3].width),
        y + Math.min(rightHeight, height + borders[0].width),
        Math.max(0, brh - borders[1].width),
        Math.max(0, brv - borders[2].width)
        ).bottomRight.subdivide(0.5),

      bottomLeftOuter: getCurvePoints(
        x,
        y + leftHeight,
        blh,
        blv
        ).bottomLeft.subdivide(0.5),

      bottomLeftInner: getCurvePoints(
        x + borders[3].width,
        y + leftHeight,
        Math.max(0, blh - borders[3].width),
        Math.max(0, blv - borders[2].width)
        ).bottomLeft.subdivide(0.5)
    };
  }

  function getBorderClip(element, borderPoints, borders, radius, bounds) {
    var backgroundClip = getCSS(element, 'backgroundClip'),
    borderArgs = [];

    switch(backgroundClip) {
      case "content-box":
      case "padding-box":
        parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
        parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
        parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
        parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
        break;

      default:
        parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
        parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
        parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
        parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
        break;
    }

    return borderArgs;
  }

  function parseBorders(element, bounds, borders){
    var x = bounds.left,
    y = bounds.top,
    width = bounds.width,
    height = bounds.height,
    borderSide,
    bx,
    by,
    bw,
    bh,
    borderArgs,
    // http://www.w3.org/TR/css3-background/#the-border-radius
    borderRadius = getBorderRadiusData(element),
    borderPoints = calculateCurvePoints(bounds, borderRadius, borders),
    borderData = {
      clip: getBorderClip(element, borderPoints, borders, borderRadius, bounds),
      borders: []
    };

    for (borderSide = 0; borderSide < 4; borderSide++) {

      if (borders[borderSide].width > 0) {
        bx = x;
        by = y;
        bw = width;
        bh = height - (borders[2].width);

        switch(borderSide) {
          case 0:
            // top border
            bh = borders[0].width;

            borderArgs = drawSide({
              c1: [bx, by],
              c2: [bx + bw, by],
              c3: [bx + bw - borders[1].width, by + bh],
              c4: [bx + borders[3].width, by + bh]
            }, borderRadius[0], borderRadius[1],
            borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
            break;
          case 1:
            // right border
            bx = x + width - (borders[1].width);
            bw = borders[1].width;

            borderArgs = drawSide({
              c1: [bx + bw, by],
              c2: [bx + bw, by + bh + borders[2].width],
              c3: [bx, by + bh],
              c4: [bx, by + borders[0].width]
            }, borderRadius[1], borderRadius[2],
            borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
            break;
          case 2:
            // bottom border
            by = (by + height) - (borders[2].width);
            bh = borders[2].width;

            borderArgs = drawSide({
              c1: [bx + bw, by + bh],
              c2: [bx, by + bh],
              c3: [bx + borders[3].width, by],
              c4: [bx + bw - borders[3].width, by]
            }, borderRadius[2], borderRadius[3],
            borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
            break;
          case 3:
            // left border
            bw = borders[3].width;

            borderArgs = drawSide({
              c1: [bx, by + bh + borders[2].width],
              c2: [bx, by],
              c3: [bx + bw, by + borders[0].width],
              c4: [bx + bw, by + bh]
            }, borderRadius[3], borderRadius[0],
            borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
            break;
        }

        borderData.borders.push({
          args: borderArgs,
          color: borders[borderSide].color
        });

      }
    }

    return borderData;
  }

  function createShape(ctx, args) {
    var shape = ctx.drawShape();
    args.forEach(function(border, index) {
      shape[(index === 0) ? "moveTo" : border[0] + "To" ].apply(null, border.slice(1));
    });
    return shape;
  }

  function renderBorders(ctx, borderArgs, color) {
    if (color !== "transparent") {
      ctx.setVariable( "fillStyle", color);
      createShape(ctx, borderArgs);
      ctx.fill();
      numDraws+=1;
    }
  }

  function renderFormValue (el, bounds, stack){

    var valueWrap = doc.createElement('valuewrap'),
    cssPropertyArray = ['lineHeight','textAlign','fontFamily','color','fontSize','paddingLeft','paddingTop','width','height','border','borderLeftWidth','borderTopWidth'],
    textValue,
    textNode;

    cssPropertyArray.forEach(function(property) {
      try {
        valueWrap.style[property] = getCSS(el, property);
      } catch(e) {
        // Older IE has issues with "border"
        Util.log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
      }
    });

    valueWrap.style.borderColor = "black";
    valueWrap.style.borderStyle = "solid";
    valueWrap.style.display = "block";
    valueWrap.style.position = "absolute";

    if (/^(submit|reset|button|text|password)$/.test(el.type) || el.nodeName === "SELECT"){
      valueWrap.style.lineHeight = getCSS(el, "height");
    }

    valueWrap.style.top = bounds.top + "px";
    valueWrap.style.left = bounds.left + "px";

    textValue = (el.nodeName === "SELECT") ? (el.options[el.selectedIndex] || 0).text : el.value;
    if(!textValue) {
      textValue = el.placeholder;
    }

    textNode = doc.createTextNode(textValue);

    valueWrap.appendChild(textNode);
    body.appendChild(valueWrap);

    renderText(el, textNode, stack);
    body.removeChild(valueWrap);
  }

  function drawImage (ctx) {
    ctx.drawImage.apply(ctx, Array.prototype.slice.call(arguments, 1));
    numDraws+=1;
  }

  function getPseudoElement(el, which) {
    var elStyle = window.getComputedStyle(el, which);
    if(!elStyle || !elStyle.content || elStyle.content === "none" || elStyle.content === "-moz-alt-content" || elStyle.display === "none") {
      return;
    }
    var content = elStyle.content + '',
    first = content.substr( 0, 1 );
    //strips quotes
    if(first === content.substr( content.length - 1 ) && first.match(/'|"/)) {
      content = content.substr( 1, content.length - 2 );
    }

    var isImage = content.substr( 0, 3 ) === 'url',
    elps = document.createElement( isImage ? 'img' : 'span' );

    elps.className = pseudoHide + "-before " + pseudoHide + "-after";

    Object.keys(elStyle).filter(indexedProperty).forEach(function(prop) {
      // Prevent assigning of read only CSS Rules, ex. length, parentRule
      try {
        elps.style[prop] = elStyle[prop];
      } catch (e) {
        Util.log(['Tried to assign readonly property ', prop, 'Error:', e]);
      }
    });

    if(isImage) {
      elps.src = Util.parseBackgroundImage(content)[0].args[0];
    } else {
      elps.innerHTML = content;
    }
    return elps;
  }

  function indexedProperty(property) {
    return (isNaN(window.parseInt(property, 10)));
  }

  function injectPseudoElements(el, stack) {
    var before = getPseudoElement(el, ':before'),
    after = getPseudoElement(el, ':after');
    if(!before && !after) {
      return;
    }

    if(before) {
      el.className += " " + pseudoHide + "-before";
      el.parentNode.insertBefore(before, el);
      parseElement(before, stack, true);
      el.parentNode.removeChild(before);
      el.className = el.className.replace(pseudoHide + "-before", "").trim();
    }

    if (after) {
      el.className += " " + pseudoHide + "-after";
      el.appendChild(after);
      parseElement(after, stack, true);
      el.removeChild(after);
      el.className = el.className.replace(pseudoHide + "-after", "").trim();
    }

  }

  function renderBackgroundRepeat(ctx, image, backgroundPosition, bounds) {
    var offsetX = Math.round(bounds.left + backgroundPosition.left),
    offsetY = Math.round(bounds.top + backgroundPosition.top);

    ctx.createPattern(image);
    ctx.translate(offsetX, offsetY);
    ctx.fill();
    ctx.translate(-offsetX, -offsetY);
  }

  function backgroundRepeatShape(ctx, image, backgroundPosition, bounds, left, top, width, height) {
    var args = [];
    args.push(["line", Math.round(left), Math.round(top)]);
    args.push(["line", Math.round(left + width), Math.round(top)]);
    args.push(["line", Math.round(left + width), Math.round(height + top)]);
    args.push(["line", Math.round(left), Math.round(height + top)]);
    createShape(ctx, args);
    ctx.save();
    ctx.clip();
    renderBackgroundRepeat(ctx, image, backgroundPosition, bounds);
    ctx.restore();
  }

  function renderBackgroundColor(ctx, backgroundBounds, bgcolor) {
    renderRect(
      ctx,
      backgroundBounds.left,
      backgroundBounds.top,
      backgroundBounds.width,
      backgroundBounds.height,
      bgcolor
      );
  }

  function renderBackgroundRepeating(el, bounds, ctx, image, imageIndex) {
    var backgroundSize = Util.BackgroundSize(el, bounds, image, imageIndex),
    backgroundPosition = Util.BackgroundPosition(el, bounds, image, imageIndex, backgroundSize),
    backgroundRepeat = getCSS(el, "backgroundRepeat").split(",").map(Util.trimText);

    image = resizeImage(image, backgroundSize);

    backgroundRepeat = backgroundRepeat[imageIndex] || backgroundRepeat[0];

    switch (backgroundRepeat) {
      case "repeat-x":
        backgroundRepeatShape(ctx, image, backgroundPosition, bounds,
          bounds.left, bounds.top + backgroundPosition.top, 99999, image.height);
        break;

      case "repeat-y":
        backgroundRepeatShape(ctx, image, backgroundPosition, bounds,
          bounds.left + backgroundPosition.left, bounds.top, image.width, 99999);
        break;

      case "no-repeat":
        backgroundRepeatShape(ctx, image, backgroundPosition, bounds,
          bounds.left + backgroundPosition.left, bounds.top + backgroundPosition.top, image.width, image.height);
        break;

      default:
        renderBackgroundRepeat(ctx, image, backgroundPosition, {
          top: bounds.top,
          left: bounds.left,
          width: image.width,
          height: image.height
        });
        break;
    }
  }

  function renderBackgroundImage(element, bounds, ctx) {
    var backgroundImage = getCSS(element, "backgroundImage"),
    backgroundImages = Util.parseBackgroundImage(backgroundImage),
    image,
    imageIndex = backgroundImages.length;

    while(imageIndex--) {
      backgroundImage = backgroundImages[imageIndex];

      if (!backgroundImage.args || backgroundImage.args.length === 0) {
        continue;
      }

      var key = backgroundImage.method === 'url' ?
      backgroundImage.args[0] :
      backgroundImage.value;

      image = loadImage(key);

      // TODO add support for background-origin
      if (image) {
        renderBackgroundRepeating(element, bounds, ctx, image, imageIndex);
      } else {
        Util.log("html2canvas: Error loading background:", backgroundImage);
      }
    }
  }

  function resizeImage(image, bounds) {
    if(image.width === bounds.width && image.height === bounds.height) {
      return image;
    }

    var ctx, canvas = doc.createElement('canvas');
    canvas.width = bounds.width;
    canvas.height = bounds.height;
    ctx = canvas.getContext("2d");
    drawImage(ctx, image, 0, 0, image.width, image.height, 0, 0, bounds.width, bounds.height );
    return canvas;
  }

  function setOpacity(ctx, element, parentStack) {
    return ctx.setVariable("globalAlpha", getCSS(element, "opacity") * ((parentStack) ? parentStack.opacity : 1));
  }

  function removePx(str) {
    return str.replace("px", "");
  }

  var transformRegExp = /(matrix)\((.+)\)/;

  function getTransform(element, parentStack) {
    var transform = getCSS(element, "transform") || getCSS(element, "-webkit-transform") || getCSS(element, "-moz-transform") || getCSS(element, "-ms-transform") || getCSS(element, "-o-transform");
    var transformOrigin = getCSS(element, "transform-origin") || getCSS(element, "-webkit-transform-origin") || getCSS(element, "-moz-transform-origin") || getCSS(element, "-ms-transform-origin") || getCSS(element, "-o-transform-origin") || "0px 0px";

    transformOrigin = transformOrigin.split(" ").map(removePx).map(Util.asFloat);

    var matrix;
    if (transform && transform !== "none") {
      var match = transform.match(transformRegExp);
      if (match) {
        switch(match[1]) {
          case "matrix":
            matrix = match[2].split(",").map(Util.trimText).map(Util.asFloat);
            break;
        }
      }
    }

    return {
      origin: transformOrigin,
      matrix: matrix
    };
  }

  function createStack(element, parentStack, bounds, transform) {
    var ctx = h2cRenderContext((!parentStack) ? documentWidth() : bounds.width , (!parentStack) ? documentHeight() : bounds.height),
    stack = {
      ctx: ctx,
      opacity: setOpacity(ctx, element, parentStack),
      cssPosition: getCSS(element, "position"),
      borders: getBorderData(element),
      transform: transform,
      clip: (parentStack && parentStack.clip) ? Util.Extend( {}, parentStack.clip ) : null
    };

    setZ(element, stack, parentStack);

    // TODO correct overflow for absolute content residing under a static position
    if (options.useOverflow === true && /(hidden|scroll|auto)/.test(getCSS(element, "overflow")) === true && /(BODY)/i.test(element.nodeName) === false){
      stack.clip = (stack.clip) ? clipBounds(stack.clip, bounds) : bounds;
    }

    return stack;
  }

  function getBackgroundBounds(borders, bounds, clip) {
    var backgroundBounds = {
      left: bounds.left + borders[3].width,
      top: bounds.top + borders[0].width,
      width: bounds.width - (borders[1].width + borders[3].width),
      height: bounds.height - (borders[0].width + borders[2].width)
    };

    if (clip) {
      backgroundBounds = clipBounds(backgroundBounds, clip);
    }

    return backgroundBounds;
  }

  function getBounds(element, transform) {
    var bounds = (transform.matrix) ? Util.OffsetBounds(element) : Util.Bounds(element);
    transform.origin[0] += bounds.left;
    transform.origin[1] += bounds.top;
    return bounds;
  }

  function renderElement(element, parentStack, pseudoElement, ignoreBackground) {
    var transform = getTransform(element, parentStack),
    bounds = getBounds(element, transform),
    image,
    stack = createStack(element, parentStack, bounds, transform),
    borders = stack.borders,
    ctx = stack.ctx,
    backgroundBounds = getBackgroundBounds(borders, bounds, stack.clip),
    borderData = parseBorders(element, bounds, borders),
    backgroundColor = (ignoreElementsRegExp.test(element.nodeName)) ? "#efefef" : getCSS(element, "backgroundColor");


    createShape(ctx, borderData.clip);

    ctx.save();
    ctx.clip();

    if (backgroundBounds.height > 0 && backgroundBounds.width > 0 && !ignoreBackground) {
      renderBackgroundColor(ctx, bounds, backgroundColor);
      renderBackgroundImage(element, backgroundBounds, ctx);
    } else if (ignoreBackground) {
      stack.backgroundColor =  backgroundColor;
    }

    ctx.restore();

    borderData.borders.forEach(function(border) {
      renderBorders(ctx, border.args, border.color);
    });

    if (!pseudoElement) {
      injectPseudoElements(element, stack);
    }

    switch(element.nodeName){
      case "IMG":
        if ((image = loadImage(element.getAttribute('src')))) {
          renderImage(ctx, element, image, bounds, borders);
        } else {
          Util.log("html2canvas: Error loading <img>:" + element.getAttribute('src'));
        }
        break;
      case "INPUT":
        // TODO add all relevant type's, i.e. HTML5 new stuff
        // todo add support for placeholder attribute for browsers which support it
        if (/^(text|url|email|submit|button|reset)$/.test(element.type) && (element.value || element.placeholder || "").length > 0){
          renderFormValue(element, bounds, stack);
        }
        break;
      case "TEXTAREA":
        if ((element.value || element.placeholder || "").length > 0){
          renderFormValue(element, bounds, stack);
        }
        break;
      case "SELECT":
        if ((element.options||element.placeholder || "").length > 0){
          renderFormValue(element, bounds, stack);
        }
        break;
      case "LI":
        renderListItem(element, stack, backgroundBounds);
        break;
      case "CANVAS":
        renderImage(ctx, element, element, bounds, borders);
        break;
    }

    return stack;
  }

  function isElementVisible(element) {
    return (getCSS(element, 'display') !== "none" && getCSS(element, 'visibility') !== "hidden" && !element.hasAttribute("data-html2canvas-ignore"));
  }

  function parseElement (element, stack, pseudoElement) {
    if (isElementVisible(element)) {
      stack = renderElement(element, stack, pseudoElement, false) || stack;
      if (!ignoreElementsRegExp.test(element.nodeName)) {
        parseChildren(element, stack, pseudoElement);
      }
    }
  }

  function parseChildren(element, stack, pseudoElement) {
    Util.Children(element).forEach(function(node) {
      if (node.nodeType === node.ELEMENT_NODE) {
        parseElement(node, stack, pseudoElement);
      } else if (node.nodeType === node.TEXT_NODE) {
        renderText(element, node, stack);
      }
    });
  }

  function init() {
    var background = getCSS(document.documentElement, "backgroundColor"),
      transparentBackground = (Util.isTransparent(background) && element === document.body),
      stack = renderElement(element, null, false, transparentBackground);
    parseChildren(element, stack);

    if (transparentBackground) {
      background = stack.backgroundColor;
    }

    body.removeChild(hidePseudoElements);
    return {
      backgroundColor: background,
      stack: stack
    };
  }

  return init();
};

function h2czContext(zindex) {
  return {
    zindex: zindex,
    children: []
  };
}

_html2canvas.Preload = function( options ) {

  var images = {
    numLoaded: 0,   // also failed are counted here
    numFailed: 0,
    numTotal: 0,
    cleanupDone: false
  },
  pageOrigin,
  Util = _html2canvas.Util,
  methods,
  i,
  count = 0,
  element = options.elements[0] || document.body,
  doc = element.ownerDocument,
  domImages = element.getElementsByTagName('img'), // Fetch images of the present element only
  imgLen = domImages.length,
  link = doc.createElement("a"),
  supportCORS = (function( img ){
    return (img.crossOrigin !== undefined);
  })(new Image()),
  timeoutTimer;

  link.href = window.location.href;
  pageOrigin  = link.protocol + link.host;

  function isSameOrigin(url){
    link.href = url;
    link.href = link.href; // YES, BELIEVE IT OR NOT, that is required for IE9 - http://jsfiddle.net/niklasvh/2e48b/
    var origin = link.protocol + link.host;
    return (origin === pageOrigin);
  }

  function start(){
    Util.log("html2canvas: start: images: " + images.numLoaded + " / " + images.numTotal + " (failed: " + images.numFailed + ")");
    if (!images.firstRun && images.numLoaded >= images.numTotal){
      Util.log("Finished loading images: # " + images.numTotal + " (failed: " + images.numFailed + ")");

      if (typeof options.complete === "function"){
        options.complete(images);
      }

    }
  }

  // TODO modify proxy to serve images with CORS enabled, where available
  function proxyGetImage(url, img, imageObj){
    var callback_name,
    scriptUrl = options.proxy,
    script;

    link.href = url;
    url = link.href; // work around for pages with base href="" set - WARNING: this may change the url

    callback_name = 'html2canvas_' + (count++);
    imageObj.callbackname = callback_name;

    if (scriptUrl.indexOf("?") > -1) {
      scriptUrl += "&";
    } else {
      scriptUrl += "?";
    }
    scriptUrl += 'url=' + encodeURIComponent(url) + '&callback=' + callback_name;
    script = doc.createElement("script");

    window[callback_name] = function(a){
      if (a.substring(0,6) === "error:"){
        imageObj.succeeded = false;
        images.numLoaded++;
        images.numFailed++;
        start();
      } else {
        setImageLoadHandlers(img, imageObj);
        img.src = a;
      }
      window[callback_name] = undefined; // to work with IE<9  // NOTE: that the undefined callback property-name still exists on the window object (for IE<9)
      try {
        delete window[callback_name];  // for all browser that support this
      } catch(ex) {}
      script.parentNode.removeChild(script);
      script = null;
      delete imageObj.script;
      delete imageObj.callbackname;
    };

    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", scriptUrl);
    imageObj.script = script;
    window.document.body.appendChild(script);

  }

  function loadPseudoElement(element, type) {
    var style = window.getComputedStyle(element, type),
    content = style.content;
    if (content.substr(0, 3) === 'url') {
      methods.loadImage(_html2canvas.Util.parseBackgroundImage(content)[0].args[0]);
    }
    loadBackgroundImages(style.backgroundImage, element);
  }

  function loadPseudoElementImages(element) {
    loadPseudoElement(element, ":before");
    loadPseudoElement(element, ":after");
  }

  function loadGradientImage(backgroundImage, bounds) {
    var img = _html2canvas.Generate.Gradient(backgroundImage, bounds);

    if (img !== undefined){
      images[backgroundImage] = {
        img: img,
        succeeded: true
      };
      images.numTotal++;
      images.numLoaded++;
      start();
    }
  }

  function invalidBackgrounds(background_image) {
    return (background_image && background_image.method && background_image.args && background_image.args.length > 0 );
  }

  function loadBackgroundImages(background_image, el) {
    var bounds;

    _html2canvas.Util.parseBackgroundImage(background_image).filter(invalidBackgrounds).forEach(function(background_image) {
      if (background_image.method === 'url') {
        methods.loadImage(background_image.args[0]);
      } else if(background_image.method.match(/\-?gradient$/)) {
        if(bounds === undefined) {
          bounds = _html2canvas.Util.Bounds(el);
        }
        loadGradientImage(background_image.value, bounds);
      }
    });
  }

  function getImages (el) {
    var elNodeType = false;

    // Firefox fails with permission denied on pages with iframes
    try {
      Util.Children(el).forEach(getImages);
    }
    catch( e ) {}

    try {
      elNodeType = el.nodeType;
    } catch (ex) {
      elNodeType = false;
      Util.log("html2canvas: failed to access some element's nodeType - Exception: " + ex.message);
    }

    if (elNodeType === 1 || elNodeType === undefined) {
      loadPseudoElementImages(el);
      try {
        loadBackgroundImages(Util.getCSS(el, 'backgroundImage'), el);
      } catch(e) {
        Util.log("html2canvas: failed to get background-image - Exception: " + e.message);
      }
      loadBackgroundImages(el);
    }
  }

  function setImageLoadHandlers(img, imageObj) {
    img.onload = function() {
      if ( imageObj.timer !== undefined ) {
        // CORS succeeded
        window.clearTimeout( imageObj.timer );
      }

      images.numLoaded++;
      imageObj.succeeded = true;
      img.onerror = img.onload = null;
      start();
    };
    img.onerror = function() {
      if (img.crossOrigin === "anonymous") {
        // CORS failed
        window.clearTimeout( imageObj.timer );

        // let's try with proxy instead
        if ( options.proxy ) {
          var src = img.src;
          img = new Image();
          imageObj.img = img;
          img.src = src;

          proxyGetImage( img.src, img, imageObj );
          return;
        }
      }

      images.numLoaded++;
      images.numFailed++;
      imageObj.succeeded = false;
      img.onerror = img.onload = null;
      start();
    };
  }

  methods = {
    loadImage: function( src ) {
      var img, imageObj;
      if ( src && images[src] === undefined ) {
        img = new Image();
        if ( src.match(/data:image\/.*;base64,/i) ) {
          img.src = src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, '');
          imageObj = images[src] = {
            img: img
          };
          images.numTotal++;
          setImageLoadHandlers(img, imageObj);
        } else if ( isSameOrigin( src ) || options.allowTaint ===  true ) {
          imageObj = images[src] = {
            img: img
          };
          images.numTotal++;
          setImageLoadHandlers(img, imageObj);
          img.src = src;
        } else if ( supportCORS && !options.allowTaint && options.useCORS ) {
          // attempt to load with CORS

          img.crossOrigin = "anonymous";
          imageObj = images[src] = {
            img: img
          };
          images.numTotal++;
          setImageLoadHandlers(img, imageObj);
          img.src = src;
        } else if ( options.proxy ) {
          imageObj = images[src] = {
            img: img
          };
          images.numTotal++;
          proxyGetImage( src, img, imageObj );
        }
      }

    },
    cleanupDOM: function(cause) {
      var img, src;
      if (!images.cleanupDone) {
        if (cause && typeof cause === "string") {
          Util.log("html2canvas: Cleanup because: " + cause);
        } else {
          Util.log("html2canvas: Cleanup after timeout: " + options.timeout + " ms.");
        }

        for (src in images) {
          if (images.hasOwnProperty(src)) {
            img = images[src];
            if (typeof img === "object" && img.callbackname && img.succeeded === undefined) {
              // cancel proxy image request
              window[img.callbackname] = undefined; // to work with IE<9  // NOTE: that the undefined callback property-name still exists on the window object (for IE<9)
              try {
                delete window[img.callbackname];  // for all browser that support this
              } catch(ex) {}
              if (img.script && img.script.parentNode) {
                img.script.setAttribute("src", "about:blank");  // try to cancel running request
                img.script.parentNode.removeChild(img.script);
              }
              images.numLoaded++;
              images.numFailed++;
              Util.log("html2canvas: Cleaned up failed img: '" + src + "' Steps: " + images.numLoaded + " / " + images.numTotal);
            }
          }
        }

        // cancel any pending requests
        if(window.stop !== undefined) {
          window.stop();
        } else if(document.execCommand !== undefined) {
          document.execCommand("Stop", false);
        }
        if (document.close !== undefined) {
          document.close();
        }
        images.cleanupDone = true;
        if (!(cause && typeof cause === "string")) {
          start();
        }
      }
    },

    renderingDone: function() {
      if (timeoutTimer) {
        window.clearTimeout(timeoutTimer);
      }
    }
  };

  if (options.timeout > 0) {
    timeoutTimer = window.setTimeout(methods.cleanupDOM, options.timeout);
  }

  Util.log('html2canvas: Preload starts: finding background-images');
  images.firstRun = true;

  getImages(element);

  Util.log('html2canvas: Preload: Finding images');
  // load <img> images
  for (i = 0; i < imgLen; i+=1){
    methods.loadImage( domImages[i].getAttribute( "src" ) );
  }

  images.firstRun = false;
  Util.log('html2canvas: Preload: Done.');
  if (images.numTotal === images.numLoaded) {
    start();
  }

  return methods;
};

_html2canvas.Renderer = function(parseQueue, options){

  // http://www.w3.org/TR/CSS21/zindex.html
  function createRenderQueue(parseQueue) {
    var queue = [],
    rootContext;

    rootContext = (function buildStackingContext(rootNode) {
      var rootContext = {};
      function insert(context, node, specialParent) {
        var zi = (node.zIndex.zindex === 'auto') ? 0 : Number(node.zIndex.zindex),
        contextForChildren = context, // the stacking context for children
        isPositioned = node.zIndex.isPositioned,
        isFloated = node.zIndex.isFloated,
        stub = {node: node},
        childrenDest = specialParent; // where children without z-index should be pushed into

        if (node.zIndex.ownStacking) {
          // '!' comes before numbers in sorted array
          contextForChildren = stub.context = { '!': [{node:node, children: []}]};
          childrenDest = undefined;
        } else if (isPositioned || isFloated) {
          childrenDest = stub.children = [];
        }

        if (zi === 0 && specialParent) {
          specialParent.push(stub);
        } else {
          if (!context[zi]) { context[zi] = []; }
          context[zi].push(stub);
        }

        node.zIndex.children.forEach(function(childNode) {
          insert(contextForChildren, childNode, childrenDest);
        });
      }
      insert(rootContext, rootNode);
      return rootContext;
    })(parseQueue);

    function sortZ(context) {
      Object.keys(context).sort().forEach(function(zi) {
        var nonPositioned = [],
        floated = [],
        positioned = [],
        list = [];

        // positioned after static
        context[zi].forEach(function(v) {
          if (v.node.zIndex.isPositioned || v.node.zIndex.opacity < 1) {
            // http://www.w3.org/TR/css3-color/#transparency
            // non-positioned element with opactiy < 1 should be stacked as if it were a positioned element with ‘z-index: 0’ and ‘opacity: 1’.
            positioned.push(v);
          } else if (v.node.zIndex.isFloated) {
            floated.push(v);
          } else {
            nonPositioned.push(v);
          }
        });

        (function walk(arr) {
          arr.forEach(function(v) {
            list.push(v);
            if (v.children) { walk(v.children); }
          });
        })(nonPositioned.concat(floated, positioned));

        list.forEach(function(v) {
          if (v.context) {
            sortZ(v.context);
          } else {
            queue.push(v.node);
          }
        });
      });
    }

    sortZ(rootContext);

    return queue;
  }

  function getRenderer(rendererName) {
    var renderer;

    if (typeof options.renderer === "string" && _html2canvas.Renderer[rendererName] !== undefined) {
      renderer = _html2canvas.Renderer[rendererName](options);
    } else if (typeof rendererName === "function") {
      renderer = rendererName(options);
    } else {
      throw new Error("Unknown renderer");
    }

    if ( typeof renderer !== "function" ) {
      throw new Error("Invalid renderer defined");
    }
    return renderer;
  }

  return getRenderer(options.renderer)(parseQueue, options, document, createRenderQueue(parseQueue.stack), _html2canvas);
};

_html2canvas.Util.Support = function (options, doc) {

  function supportSVGRendering() {
    var img = new Image(),
    canvas = doc.createElement("canvas"),
    ctx = (canvas.getContext === undefined) ? false : canvas.getContext("2d");
    if (ctx === false) {
      return false;
    }
    canvas.width = canvas.height = 10;
    img.src = [
    "data:image/svg+xml,",
    "<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'>",
    "<foreignObject width='10' height='10'>",
    "<div xmlns='http://www.w3.org/1999/xhtml' style='width:10;height:10;'>",
    "sup",
    "</div>",
    "</foreignObject>",
    "</svg>"
    ].join("");
    try {
      ctx.drawImage(img, 0, 0);
      canvas.toDataURL();
    } catch(e) {
      return false;
    }
    _html2canvas.Util.log('html2canvas: Parse: SVG powered rendering available');
    return true;
  }

  // Test whether we can use ranges to measure bounding boxes
  // Opera doesn't provide valid bounds.height/bottom even though it supports the method.

  function supportRangeBounds() {
    var r, testElement, rangeBounds, rangeHeight, support = false;

    if (doc.createRange) {
      r = doc.createRange();
      if (r.getBoundingClientRect) {
        testElement = doc.createElement('boundtest');
        testElement.style.height = "123px";
        testElement.style.display = "block";
        doc.body.appendChild(testElement);

        r.selectNode(testElement);
        rangeBounds = r.getBoundingClientRect();
        rangeHeight = rangeBounds.height;

        if (rangeHeight === 123) {
          support = true;
        }
        doc.body.removeChild(testElement);
      }
    }

    return support;
  }

  return {
    rangeBounds: supportRangeBounds(),
    svgRendering: options.svgRendering && supportSVGRendering()
  };
};
window.html2canvas = function(elements, opts) {
  elements = (elements.length) ? elements : [elements];
  var queue,
  canvas,
  options = {
    // general
    logging: false,
    elements: elements,
    background: "#fff",

    // preload options
    proxy: null,
    timeout: 0,    // no timeout
    useCORS: false, // try to load images as CORS (where available), before falling back to proxy
    allowTaint: false, // whether to allow images to taint the canvas, won't need proxy if set to true

    // parse options
    svgRendering: false, // use svg powered rendering where available (FF11+)
    ignoreElements: "IFRAME|OBJECT|PARAM",
    useOverflow: true,
    letterRendering: false,
    chinese: false,

    // render options

    width: null,
    height: null,
    taintTest: true, // do a taint test with all images before applying to canvas
    renderer: "Canvas"
  };

  options = _html2canvas.Util.Extend(opts, options);

  _html2canvas.logging = options.logging;
  options.complete = function( images ) {

    if (typeof options.onpreloaded === "function") {
      if ( options.onpreloaded( images ) === false ) {
        return;
      }
    }
    queue = _html2canvas.Parse( images, options );

    if (typeof options.onparsed === "function") {
      if ( options.onparsed( queue ) === false ) {
        return;
      }
    }

    canvas = _html2canvas.Renderer( queue, options );

    if (typeof options.onrendered === "function") {
      options.onrendered( canvas );
    }


  };

  // for pages without images, we still want this to be async, i.e. return methods before executing
  window.setTimeout( function(){
    _html2canvas.Preload( options );
  }, 0 );

  return {
    render: function( queue, opts ) {
      return _html2canvas.Renderer( queue, _html2canvas.Util.Extend(opts, options) );
    },
    parse: function( images, opts ) {
      return _html2canvas.Parse( images, _html2canvas.Util.Extend(opts, options) );
    },
    preload: function( opts ) {
      return _html2canvas.Preload( _html2canvas.Util.Extend(opts, options) );
    },
    log: _html2canvas.Util.log
  };
};

window.html2canvas.log = _html2canvas.Util.log; // for renderers
window.html2canvas.Renderer = {
  Canvas: undefined // We are assuming this will be used
};
_html2canvas.Renderer.Canvas = function(options) {
  options = options || {};

  var doc = document,
  safeImages = [],
  testCanvas = document.createElement("canvas"),
  testctx = testCanvas.getContext("2d"),
  Util = _html2canvas.Util,
  canvas = options.canvas || doc.createElement('canvas');

  function createShape(ctx, args) {
    ctx.beginPath();
    args.forEach(function(arg) {
      ctx[arg.name].apply(ctx, arg['arguments']);
    });
    ctx.closePath();
  }

  function safeImage(item) {
    if (safeImages.indexOf(item['arguments'][0].src ) === -1) {
      testctx.drawImage(item['arguments'][0], 0, 0);
      try {
        testctx.getImageData(0, 0, 1, 1);
      } catch(e) {
        testCanvas = doc.createElement("canvas");
        testctx = testCanvas.getContext("2d");
        return false;
      }
      safeImages.push(item['arguments'][0].src);
    }
    return true;
  }

  function renderItem(ctx, item) {
    switch(item.type){
      case "variable":
        ctx[item.name] = item['arguments'];
        break;
      case "function":
        switch(item.name) {
          case "createPattern":
            if (item['arguments'][0].width > 0 && item['arguments'][0].height > 0) {
              try {
                ctx.fillStyle = ctx.createPattern(item['arguments'][0], "repeat");
              }
              catch(e) {
                Util.log("html2canvas: Renderer: Error creating pattern", e.message);
              }
            }
            break;
          case "drawShape":
            createShape(ctx, item['arguments']);
            break;
          case "drawImage":
            if (item['arguments'][8] > 0 && item['arguments'][7] > 0) {
              if (!options.taintTest || (options.taintTest && safeImage(item))) {
                ctx.drawImage.apply( ctx, item['arguments'] );
              }
            }
            break;
          default:
            ctx[item.name].apply(ctx, item['arguments']);
        }
        break;
    }
  }

  return function(parsedData, options, document, queue, _html2canvas) {
    var ctx = canvas.getContext("2d"),
    newCanvas,
    bounds,
    fstyle,
    zStack = parsedData.stack;

    canvas.width = canvas.style.width =  options.width || zStack.ctx.width;
    canvas.height = canvas.style.height = options.height || zStack.ctx.height;

    fstyle = ctx.fillStyle;
    ctx.fillStyle = (Util.isTransparent(zStack.backgroundColor) && options.background !== undefined) ? options.background : parsedData.backgroundColor;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = fstyle;

    queue.forEach(function(storageContext) {
      // set common settings for canvas
      ctx.textBaseline = "bottom";
      ctx.save();

      if (storageContext.transform.matrix) {
        ctx.translate(storageContext.transform.origin[0], storageContext.transform.origin[1]);
        ctx.transform.apply(ctx, storageContext.transform.matrix);
        ctx.translate(-storageContext.transform.origin[0], -storageContext.transform.origin[1]);
      }

      if (storageContext.clip){
        ctx.beginPath();
        ctx.rect(storageContext.clip.left, storageContext.clip.top, storageContext.clip.width, storageContext.clip.height);
        ctx.clip();
      }

      if (storageContext.ctx.storage) {
        storageContext.ctx.storage.forEach(function(item) {
          renderItem(ctx, item);
        });
      }

      ctx.restore();
    });

    Util.log("html2canvas: Renderer: Canvas renderer done - returning canvas obj");

    if (options.elements.length === 1) {
      if (typeof options.elements[0] === "object" && options.elements[0].nodeName !== "BODY") {
        // crop image to the bounds of selected (single) element
        bounds = _html2canvas.Util.Bounds(options.elements[0]);
        newCanvas = document.createElement('canvas');
        newCanvas.width = Math.ceil(bounds.width);
        newCanvas.height = Math.ceil(bounds.height);
        ctx = newCanvas.getContext("2d");
        var imgData = canvas.getContext("2d").getImageData(bounds.left, bounds.top, bounds.width, bounds.height);
        ctx.putImageData(imgData, 0, 0);
        //ctx.drawImage(canvas, bounds.left, bounds.top, bounds.width, bounds.height, 0, 0, bounds.width, bounds.height);
        canvas = null;
        return newCanvas;
      }
    }

    return canvas;
  };
};
})(window,document);;
var showDownloadStartMessage = false;
var showDownloadEndMessage = false;

//not used anymore
function createUUID() {
    // http://www.ietf.org/rfc/rfc4122.txt
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr(s[19] & 0x3 | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "";

    var uuid = s.join("");
    return uuid;
}


function nothing() {
}


//get outer html
$.fn.outerHTML = function () {
    // IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
    return !this.length ? this : this[0].outerHTML || (
      function (el) {
          var div = document.createElement('div');
          div.appendChild(el.cloneNode(true));
          var contents = div.innerHTML;
          div = null;
          return contents;
      })(this[0]);
};

//get messages from db
function getMessages(componentId, allIds, nonAlert) {
    var ids = "";
    if (allIds) {
        if (allIds.length == 0) {
            return;
        }

        for (var i = 0; i < allIds.length; i++) {
            ids = ids + allIds[i].Id + ";";
        }
    }
    else {
        ids = null;
    }
    log("getMessages(" + componentId + ", " + ids + ")");
    if (componentId)
        ajaxCall((isIframeApp? "/":"") + 'Desktop/GetMessages/' + componentId, null, getMessagesCallback, componentId, allIds);
    else
        ajaxCall((isIframeApp? "/":"") + 'Desktop/GetMessages/', null, getMessagesCallback, componentId, allIds);
}

////logout
//function logout() {
//    $('#logouta')[0].click()
//}

//var messagesAlreadySended = [];
//receive messsages and if interval 0 show them in the bottom part or alert if interval > 0
function getMessagesCallback(data, compId, allIds) {
    var winId = compId;
    if (allIds && allIds.length > 0) {
        winId = allIds[0].Id;
    }

    var messagesArray = [];
    for (var i = 0; i < data.length; i++) {
        if (data[i].IntervalDB > 0) {
            messagesArray.push({ id: data[i].Id, text: data[i].MessageText });
        }
    }

    if (messagesArray.length > 0)
        showInstantMessages(messagesArray, winId);

    if (allIds) {
        for (var j = 0; j < allIds.length; j++) {
            winId = allIds[j].Id;
            var text = "";
            let i = 0;
            for ( i = 0; i < data.length; i++) {
                if (data[i].IntervalDB == 0) {
                    if (data[i].MessageText == "LOGOUT_USER") {
                        setTimeout("logout()", parseInt(timeOutUntilLogout) * 60 * 1000);
                        confirmPrompt(logoutMessageText, function () { });
                        ajaxCall((isIframeApp ? "/" : "") + 'Desktop/ConfirmMessage/' + data[i].Id + "?onlyLastSendDate=false", null, confirmMessageCallback);
                    }
                    else
                        if (data[i].MessageText == "RELOAD_START_MENU") {
                            getStartMenu();
                            ajaxCall((isIframeApp ? "/" : "") + 'Desktop/ConfirmMessage/' + data[i].Id + "?onlyLastSendDate=false", null, confirmMessageCallback);
                        }
                        else {
                            if (text.length > 0) {
                                text += '</br>' + data[i].MessageText;
                            }
                            else {
                                text += data[i].MessageText;
                            }
                        }
                }
            }

            appendMesagesDiv(winId, text);
        }
    }
}

//alert from messages
function showInstantMessages(messagesArray, componentId) {
    var yes = function () {
        ajaxCall((isIframeApp ? "/" : "") + 'Desktop/ConfirmMessage/' + messagesArray[0].id + "?onlyLastSendDate=false", null, confirmMessageCallback);
        messagesArray.splice(0, 1);
        if (messagesArray.length > 0) {
            showInstantMessages(messagesArray);
        }
    };

    var noEmpty = function () {
        messagesArray.splice(0, 1);
        if (messagesArray.length > 0) {
            showInstantMessages(messagesArray);
        }
    };

    var no = function () {
        ajaxCall((isIframeApp ? "/" : "") + 'Desktop/ConfirmMessage/' + messagesArray[0].id + "?onlyLastSendDate=true", null, confirmMessageCallback);
        messagesArray.splice(0, 1);
        if (messagesArray.length > 0) {
            showInstantMessages(messagesArray);
        }
    };
    if (!desktopInitilizing) {
        ajaxCall((isIframeApp ? "/" : "") + 'Desktop/ConfirmMessage/' + messagesArray[0].id + "?onlyLastSendDate=true", null, confirmMessageCallback);
        confirmPrompt(messagesArray[0].text, yes, noEmpty);
    }
    else
        if (componentId == null) {
            confirmPrompt(messagesArray[0].text, yes, no);
        }
}

function confirmMessageCallback(data) {
    log("Message confirmed successfully");
}

var initialExportButtonTitle = '';
function changeExportButton(btnClass, setCancel) {
    $('.' + btnClass).removeClass('cancelExportGrid');
    $('.' + btnClass).attr('title', initialExportButtonTitle);
    if (setCancel) {
        $('.' + btnClass).attr('title', cancelDownloadText);
        $('.' + btnClass).addClass('cancelExportGrid');
    }
}

//export data (for now only in sms)
function exportData(urlSession, url, gridName, btnExportClass) {
    var obj = null;
    if (getFilterObjForSession)
        obj = getFilterObjForSession(gridName);
    if (showDownloadStartMessage) {
        confirmPrompt(downloadStartedtext, function () { });
    }

    //send information on server and store in SESSION
    ajaxCall(urlSession, JSON.stringify(obj), exportDataCallback, url, gridName, btnExportClass);
}

function exportDataCallback(data, url, gridName, btnExportClass) {
    var obj = null;

    var download = function () {
        if (btnExportClass) {
            initialExportButtonTitle = $('.' + btnExportClass).attr('title');
            changeExportButton(btnExportClass, true);
        }
        $.fileDownload(url,
                {
                    successCallback: function () {
                        if (showDownloadEndMessage) {
                            confirmPrompt(downloadFinishtext, function () { });
                        }
                        if (btnExportClass) {
                            changeExportButton(btnExportClass, false);
                        }
                    },
                    failCallback: function () {
                        if (downloadCancelByUser) {
                            downloadCancelByUser = null;
                            confirmPrompt(downloadStoppedtext, function () { });
                        }
                        else {
                            confirmPrompt(downloadFailedtext, function () { });
                        }

                        if (btnExportClass) {
                            changeExportButton(btnExportClass, false);
                        }
                    },
                    httpMethod: "GET",
                    data: obj
                }
                );
    };

    //if (url.indexOf("PDFExportFormatter") > 0 && obj.verifyMaxColumns) {
    //    var columns = obj.columnNames.split("~");
    //    if (columns.length > maxColumnsInExport)
    //        confirmPrompt(exportMultipleColumns, download, null);
    //    else
    //        download();
    //}
    //else
    download();
}

function exportDataReport(url, getObj) {
    var obj = null;
    if (getObj)
        obj = getObj();
    var download = function () {
        $.fileDownload(url,
                {
                    successCallback: function () {
                        confirmPrompt(downloadFinishtext, function () { });
                    },
                    failCallback: function () {
                        confirmPrompt(downloadFailedtext, function () { });
                    },
                    httpMethod: "GET",
                    data: obj
                }
                );
    };
    download();

}

function exportDataReportCallback(data) {
    log("data exported with report succesfully");
}

function DateFmt(fstr) {
    this.formatString = fstr;

    var mthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    var zeroPad = function (number) {
        return ("0" + number).substr(-2, 2);
    };

    var dateMarkers = {
        d: ['getDate', function(v) { return zeroPad(v); }],
        m: ['getMonth', function(v) { return zeroPad(v + 1); }],
        n: ['getMonth', function (v) { return mthNames[v]; }],
        w: ['getDay', function (v) { return dayNames[v]; }],
        y: ['getFullYear'],
        H: ['getHours', function(v) { return zeroPad(v); }],
        M: ['getMinutes', function(v) { return zeroPad(v); }],
        S: ['getSeconds', function(v) { return zeroPad(v); }],
        i: ['toISOString']
    };

    this.format = function (date) {
        var dateTxt = this.formatString.replace(/%(.)/g, function (m, p) {
            var rv = date[dateMarkers[p][0]]();

            if (dateMarkers[p][1] != null){
                rv = dateMarkers[p][1](rv);
            }
            return rv;

        });
        return dateTxt;
    };
}

function dateTimePicker(control) {
    $(control).kendoDateTimePicker({
        format: "dd/MM/yyyy HH:mm:ss",
        timeFormat: "HH:mm:ss"
    });
}

function timePicker(control) {
    $(control).kendoTimePicker({
        format: "HH:mm:ss",
        type: "time"
    });
}


//do not delete the following function
function emptyFilter() {
    return { filterId: "" };
}

// formatiert aktuelles Datum + Zeit für Rapid-Interface 
function getFormattedDate(date) {
    date = date || new Date();

    let year = date.getFullYear();
    let month = formatDateNumber(date.getMonth() + 1);
    let day = formatDateNumber(date.getDate());

    let hours = formatDateNumber(date.getHours() + 1);
    let min = formatDateNumber(date.getMinutes());
    let sec = formatDateNumber(date.getSeconds());

    return year + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec;
}

function formatDateNumber(number) {
    if (!number && number !== 0) {
        return '';
    }

    let str = number;
    if (typeof number === 'number') {
        str = number.toString();
    }

    while (str.length < 2) {
        str = '0' + str;
    }

    return str;
}

/**
 * @param {number} val Number to be rounded.
 * @param {number} fracDig Number of fractional digits after rounding.
 * @return {number} The rounded number, with fracDig fractional digits
 */
function round(val, fracDig) {
    fracDig = fracDig || 0;
    if (fracDig === 0) {
        return Math.round(val);
    }

    let pow = Math.pow(10, fracDig);

    return Math.round(val * pow) / pow;
}

// Stringify, das 'circular references' beachtet
function saveStringify(o) {
    let ret = '';
    if (o) {
        let cache = [];
        ret = JSON.stringify(o, function(key, value) {
            if (typeof value === 'object' && value !== null) {
                if (cache.indexOf(value) !== -1) {
                    // Circular reference found, discard key;
                    return;
                }
                // Store value
                cache.push(value);
            }
            return value;
        });
        cache = null;
    }
    return ret;
}

// TODO bessere art den fehler mitzuteilen
function checkForSoapFault(node) {
    if (typeof node == 'string') {
        node = parseXml(node);
    }

    if (node) {
        let fcarr = node.getElementsByTagName('faultcode');
        let fsarr = node.getElementsByTagName('faultstring');

        if (fcarr.length > 0 && fsarr.length > 0) {
            let fc, fs;
            if (fcarr[0]) {
                fc = fcarr[0].nodeValue || fcarr[0].textContent;
            }

            if (fsarr[0]) {
                fs = fsarr[0].nodeValue || fsarr[0].textContent;
            }

            if (fs || fc) {
                let err = (fc + ' - ' || '') + (fs || 'Fehler im Soap-Request');
                console.log(err);
                displayErrorInStatusInfo(err, "Vwc.Panel.Datatable");
                return true;
            }
        }
    }

    return false;
}

function degToRad(angle) {
    return angle / 180 * Math.PI;
}

function radToDeg(rad) {
    return rad * 180 / Math.PI;
}

function getAvailableFonts() {
    /**
     * JavaScript code to detect available availability of a
     * particular font in a browser using JavaScript and CSS.
     *
     * Author : Lalit Patel
     * Website: http://www.lalit.org/lab/javascript-css-font-detect/
     * License: Apache Software License 2.0
     *          http://www.apache.org/licenses/LICENSE-2.0
     * Version: 0.15 (21 Sep 2009)
     *          Changed comparision font to default from sans-default-default,
     *          as in FF3.0 font of child element didn't fallback
     *          to parent element if the font is missing.
     * Version: 0.2 (04 Mar 2012)
     *          Comparing font against all the 3 generic font families ie,
     *          'monospace', 'sans-serif' and 'sans'. If it doesn't match all 3
     *          then that font is 100% not available in the system
     * Version: 0.3 (24 Mar 2012)
     *          Replaced sans with serif in the list of baseFonts
     */
    let Detector = function() {
        // a font will be compared against all the three default fonts.
        // and if it doesn't match all 3 then that font is not available.
        let baseFonts = ['monospace', 'sans-serif', 'serif'];

        //we use m or w because these two characters take up the maximum width.
        // And we use a LLi so that the same matching fonts can get separated
        let testString = "mmmmmmmmmmlli";

        //we test using 72px font size, we may use any size. I guess larger the better.
        let testSize = '72px';

        let h = document.getElementsByTagName("body")[0];

        // create a SPAN in the document to get the width of the text we use to test
        let s = document.createElement("span");
        s.style.fontSize = testSize;
        s.innerHTML = testString;
        let defaultWidth = {};
        let defaultHeight = {};
        for (let index in baseFonts) {
            //get the default width for the three base fonts
            s.style.fontFamily = baseFonts[index];
            h.appendChild(s);
            defaultWidth[baseFonts[index]] = s.offsetWidth; //width for the default font
            defaultHeight[baseFonts[index]] = s.offsetHeight; //height for the defualt font
            h.removeChild(s);
        }

        function detect(font) {
            let detected = false;
            for (let index in baseFonts) {
                s.style.fontFamily = font + ',' + baseFonts[index]; // name of the font along with the base font for fallback.
                h.appendChild(s);
                let matched = s.offsetWidth != defaultWidth[baseFonts[index]] || s.offsetHeight != defaultHeight[baseFonts[index]];
                h.removeChild(s);
                detected = detected || matched;
            }
            return detected;
        }

        this.detect = detect;
    };

    let ret = [];
    // from https://www.w3schools.com/cssref/css_websafe_fonts.asp
    let fontFamilies = [
        // serif fonts
        'Georgia',
        'Palatino Linotype',
        'Book Antiqua',
        'Palatino',
        'Times New Roman',
        'Times',
        // sans-serif fonts
        'Arial',
        'Helvetica',
        'Arial Black',
        'Gadget',
        'Comic Sans MS',
        'Impact',
        'Charcoal',
        'Lucida Sans Unicode',
        'Lucida Grande',
        'Tahoma',
        'Geneva',
        'Trebuchet MS',
        'Verdana',
        // monospace fonts
        'Courier New',
        'Courier',
        'Lucida Console',
        'Monaco'
    ];
    let detector = new Detector();
    for (let i = 0; i < fontFamilies.length; ++i) {
        let ff = fontFamilies[i];
        let detected = detector.detect(ff);
        if (detected) {
            ret.push(ff);
        }
    }
    detector = null;
    return ret;
}

function parseXml(obj) {
    return new DOMParser().parseFromString(obj, 'application/xml');
}

function parseKilometerToStationResponse(xml, hasBlockNr) {
    return parseKilometrierungResponse(xml, hasBlockNr ? 'station' : 'stationen'); 
}

function parseKilometrierungResponse(xml, tagName) {
    let ret = {};
    if (xml) {
        if (typeof xml === 'string') {
            xml = parseXml(xml);
        }
        if (checkForSoapFault(xml)) {
            // fehler im soap-request
            return null;
        }
                   
        let elements = xml.getElementsByTagName(tagName);
        if (elements && elements.length > 0) {
            let stationElement = elements[0];
            if (stationElement && stationElement.hasChildNodes()) {
                let children = stationElement.childNodes;
                for (let i = 0; i < children.length; ++i) {
                    let child = children[i];
                    let ln = child.localName;
                    let val = child.nodeValue || child.textContent;
                    switch (ln) {
                        case 'VST':
                        case 'BST': {
                            if (typeof val === 'string') {
                                val = Number.parseInt(val);
                            }
                            ret.station = val;
                            break;
                        }
                        case 'LEN': {
                            ret.len = val;
                            break;
                        }
                        case 'vonKartenblatt': {
                            ret.vonKartenblatt = val;
                            break;
                        }
                        case 'vonNkLfd': {
                            ret.vonNkLfd = val;
                            break;
                        }
                        case 'vonZusatz': {
                            ret.vonZusatz = val === 'O' ? '' : val;
                            break;
                        }
                        case 'nachKartenblatt': {
                            ret.nachKartenblatt = val;
                            break;
                        }
                        case 'nachNkLfd': {
                            ret.nachNkLfd = val;
                            break;
                        }
                        case 'nachZusatz': {
                            ret.nachZusatz = val === 'O' ? '' : val;
                            break;
                        }
                        case 'inStatRi': {
                            ret.inRichtung = val == 'true';
                            break;
                        }
                        case 'kilometer': {
                            if (typeof val === 'string') {
                                val = parseFloat(val);
                            }
                            ret.kilometer = val;
                        }
                    }
                }
            }
        }
    }
    ret.vnk = getNk(ret.vonKartenblatt, ret.vonNkLfd, ret.vonZusatz);
    ret.nnk = getNk(ret.nachKartenblatt, ret.nachNkLfd, ret.nachZusatz);

    return ret;
}

function parseStationToKilometerResponse(xml) {
    let ret = {};
    if (xml) {
        if (typeof xml === 'string') {
            xml = parseXml(xml);
        }
        if (checkForSoapFault(xml)) {
            // fehler im soap-request
            return null;
        }
                   
        let elements = xml.getElementsByTagName('kilometer');
        if (elements && elements.length > 0) {
            let kilometerElement = elements[0];
            ret = kilometerElement.nodeValue || kilometerElement.textContent;
        }
    }

    return ret;
}

function getNk(kartenblatt, lfd, zusatz) {
    kartenblatt = typeof kartenblatt === 'number' ? kartenblatt.toString() : kartenblatt;
    lfd = typeof lfd === 'number' ? lfd.toString() : lfd;
    zusatz = typeof zusatz === 'number' ? zusatz.toString() : zusatz;

    let nk = kartenblatt;

    while (lfd.length < 3) {
        lfd = '0' + lfd;
    }
    nk += lfd;

    if (zusatz || zusatz == '0') {
        nk += zusatz;
    }

    return nk;
}

function getPartsFromNk(nk) {
    let ret = {};

    ret.kartenblatt = nk.substring(0, 4);
    if (ret.kartenblatt) {
        ret.kartenblatt = Number.parseInt(ret.kartenblatt);
    }
    ret.lfd = nk.substring(4, 7);
    if (ret.lfd) {
        ret.lfd = Number.parseInt(ret.lfd);
    }
    ret.zusatz = nk.substring(7, 8);

    return ret;
}

function enterWaitState() {
    Vwc.temp.cursor = $('html, body').css('cursor');
    $('html, body').css('cursor', 'wait');
}

function leaveWaitState() {
    $('html, body').css('cursor', Vwc.temp.cursor || 'default');
};
/*
* jQuery File Download Plugin v1.4.2 
*
* http://www.johnculviner.com
*
* Copyright (c) 2013 - John Culviner
*
* Licensed under the MIT license:
*   http://www.opensource.org/licenses/mit-license.php
*/

(function ($, window) {
    // i'll just put them here to get evaluated on script load
    var htmlSpecialCharsRegEx = /[<>&\r\n"']/gm;
    var htmlSpecialCharsPlaceHolders = {
        '<': 'lt;',
        '>': 'gt;',
        '&': 'amp;',
        '\r': "#13;",
        '\n': "#10;",
        '"': 'quot;',
        "'": 'apos;' /*single quotes just to be safe*/
    };

    $.extend({
        //
        //$.fileDownload('/path/to/url/', options)
        //  see directly below for possible 'options'
        fileDownload: function (fileUrl, options) {

            //provide some reasonable defaults to any unspecified options below
            var settings = $.extend({

                //
                //Requires jQuery UI: provide a message to display to the user when the file download is being prepared before the browser's dialog appears
                //
                preparingMessageHtml: null,

                //
                //Requires jQuery UI: provide a message to display to the user when a file download fails
                //
                failMessageHtml: null,

                //
                //the stock android browser straight up doesn't support file downloads initiated by a non GET: http://code.google.com/p/android/issues/detail?id=1780
                //specify a message here to display if a user tries with an android browser
                //if jQuery UI is installed this will be a dialog, otherwise it will be an alert
                //
                androidPostUnsupportedMessageHtml: "Unfortunately your Android browser doesn't support this type of file download. Please try again with a different browser.",

                //
                //Requires jQuery UI: options to pass into jQuery UI Dialog
                //
                dialogOptions: { modal: true },

                //
                //a function to call while the dowload is being prepared before the browser's dialog appears
                //Args:
                //  url - the original url attempted
                //
                prepareCallback: function (url) { },

                //
                //a function to call after a file download dialog/ribbon has appeared
                //Args:
                //  url - the original url attempted
                //
                successCallback: function (url) { },

                //
                //a function to call after a file download dialog/ribbon has appeared
                //Args:
                //  responseHtml    - the html that came back in response to the file download. this won't necessarily come back depending on the browser.
                //                      in less than IE9 a cross domain error occurs because 500+ errors cause a cross domain issue due to IE subbing out the
                //                      server's error message with a "helpful" IE built in message
                //  url             - the original url attempted
                //
                failCallback: function (responseHtml, url) { },

                //
                // the HTTP method to use. Defaults to "GET".
                //
                httpMethod: "GET",

                //
                // if specified will perform a "httpMethod" request to the specified 'fileUrl' using the specified data.
                // data must be an object (which will be $.param serialized) or already a key=value param string
                //
                data: null,

                //
                //a period in milliseconds to poll to determine if a successful file download has occured or not
                //
                checkInterval: 100,

                //
                //the cookie name to indicate if a file download has occured
                //
                cookieName: "fileDownload",

                //
                //the cookie value for the above name to indicate that a file download has occured
                //
                cookieValue: "true",

                //
                //the cookie path for above name value pair
                //
                cookiePath: "/",

                //
                //the title for the popup second window as a download is processing in the case of a mobile browser
                //
                popupWindowTitle: "Initiating file download...",

                //
                //Functionality to encode HTML entities for a POST, need this if data is an object with properties whose values contains strings with quotation marks.
                //HTML entity encoding is done by replacing all &,<,>,',",\r,\n characters.
                //Note that some browsers will POST the string htmlentity-encoded whilst others will decode it before POSTing.
                //It is recommended that on the server, htmlentity decoding is done irrespective.
                //
                encodeHTMLEntities: true

            }, options);

            var deferred = new $.Deferred();

            //Setup mobile browser detection: Partial credit: http://detectmobilebrowser.com/
            var userAgent = (navigator.userAgent || navigator.vendor || window.opera).toLowerCase();

            var isIos;                  //has full support of features in iOS 4.0+, uses a new window to accomplish this.
            var isAndroid;              //has full support of GET features in 4.0+ by using a new window. Non-GET is completely unsupported by the browser. See above for specifying a message.
            var isOtherMobileBrowser;   //there is no way to reliably guess here so all other mobile devices will GET and POST to the current window.

            if (/ip(ad|hone|od)/.test(userAgent)) {

                isIos = true;

            } else if (userAgent.indexOf('android') !== -1) {

                isAndroid = true;

            } else {

                isOtherMobileBrowser = /avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|playbook|silk|iemobile|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(userAgent.substr(0, 4));

            }

            var httpMethodUpper = settings.httpMethod.toUpperCase();

            if (isAndroid && httpMethodUpper !== "GET") {
                //the stock android browser straight up doesn't support file downloads initiated by non GET requests: http://code.google.com/p/android/issues/detail?id=1780

                if ($().dialog) {
                    $("<div>").html(settings.androidPostUnsupportedMessageHtml).dialog(settings.dialogOptions);
                } else {
                    alert(settings.androidPostUnsupportedMessageHtml);
                }

                return deferred.reject();
            }

            var $preparingDialog = null;

            var internalCallbacks = {

                onPrepare: function (url) {

                    //wire up a jquery dialog to display the preparing message if specified
                    if (settings.preparingMessageHtml) {

                        $preparingDialog = $("<div>").html(settings.preparingMessageHtml).dialog(settings.dialogOptions);

                    } else if (settings.prepareCallback) {

                        settings.prepareCallback(url);

                    }

                },

                onSuccess: function (url) {

                    //remove the perparing message if it was specified
                    if ($preparingDialog) {
                        $preparingDialog.dialog('close');
                    };

                    settings.successCallback(url);

                    deferred.resolve(url);
                },

                onFail: function (responseHtml, url) {

                    //remove the perparing message if it was specified
                    if ($preparingDialog) {
                        $preparingDialog.dialog('close');
                    };

                    //wire up a jquery dialog to display the fail message if specified
                    if (settings.failMessageHtml) {
                        $("<div>").html(settings.failMessageHtml).dialog(settings.dialogOptions);
                    }

                    settings.failCallback(responseHtml, url);

                    deferred.reject(responseHtml, url);
                }
            };

            internalCallbacks.onPrepare(fileUrl);

            //make settings.data a param string if it exists and isn't already
            if (settings.data !== null && typeof settings.data !== "string") {
                settings.data = $.param(settings.data);
            }


            var $iframe,
            downloadWindow,
            formDoc,
            $form;

            if (httpMethodUpper === "GET") {

                if (settings.data !== null) {
                    //need to merge any fileUrl params with the data object

                    var qsStart = fileUrl.indexOf('?');

                    if (qsStart !== -1) {
                        //we have a querystring in the url

                        if (fileUrl.substring(fileUrl.length - 1) !== "&") {
                            fileUrl = fileUrl + "&";
                        }
                    } else {

                        fileUrl = fileUrl + "?";
                    }

                    fileUrl = fileUrl + settings.data;
                }

                if (isIos || isAndroid) {

                    downloadWindow = window.open(fileUrl);
                    downloadWindow.document.title = settings.popupWindowTitle;
                    window.focus();

                } else if (isOtherMobileBrowser) {

                    window.location(fileUrl);

                } else {

                    //create a temporary iframe that is used to request the fileUrl as a GET request
                    $iframe = $("<iframe class='iframeForDownload'>")
                    .hide()
                    .prop("src", fileUrl)
                    .appendTo("body");
                }

            } else {

                var formInnerHtml = "";

                if (settings.data !== null) {

                    $.each(settings.data.replace(/\+/g, ' ').split("&"), function () {

                        var kvp = this.split("=");

                        var key = settings.encodeHTMLEntities ? htmlSpecialCharsEntityEncode(decodeURIComponent(kvp[0])) : decodeURIComponent(kvp[0]);
                        if (key) {
                            var value = settings.encodeHTMLEntities ? htmlSpecialCharsEntityEncode(decodeURIComponent(kvp[1])) : decodeURIComponent(kvp[1]);
                            formInnerHtml += '<input type="hidden" name="' + key + '" value="' + value + '" />';
                        }
                    });
                }

                if (isOtherMobileBrowser) {

                    $form = $("<form>").appendTo("body");
                    $form.hide()
                    .prop('method', settings.httpMethod)
                    .prop('action', fileUrl)
                    .html(formInnerHtml);

                } else {

                    if (isIos) {

                        downloadWindow = window.open("about:blank");
                        downloadWindow.document.title = settings.popupWindowTitle;
                        formDoc = downloadWindow.document;
                        window.focus();

                    } else {

                        $iframe = $("<iframe style='display: none' src='about:blank'></iframe>").appendTo("body");
                        formDoc = getiframeDocument($iframe);
                    }

                    formDoc.write("<html><head></head><body><form method='" + settings.httpMethod + "' action='" + fileUrl + "'>" + formInnerHtml + "</form>" + settings.popupWindowTitle + "</body></html>");
                    $form = $(formDoc).find('form');
                }

                $form.submit();
            }


            //check if the file download has completed every checkInterval ms
            setTimeout(checkFileDownloadComplete, settings.checkInterval);


            function checkFileDownloadComplete() {

                //has the cookie been written due to a file download occuring?
                if (document.cookie.indexOf(settings.cookieName + "=" + settings.cookieValue) != -1) {

                    //execute specified callback
                    internalCallbacks.onSuccess(fileUrl);

                    //remove the cookie and iframe
                    document.cookie = settings.cookieName + "=; expires=" + new Date(1000).toUTCString() + "; path=" + settings.cookiePath;

                    cleanUp(false);

                    return;
                }

                //has an error occured?
                //if neither containers exist below then the file download is occuring on the current window
                if (downloadWindow || $iframe) {

                    //has an error occured?
                    try {

                        var formDoc = downloadWindow ? downloadWindow.document : getiframeDocument($iframe);

                        if (formDoc && formDoc.body != null && formDoc.body.innerHTML.length) {

                            var isFailure = true;

                            if ($form && $form.length) {
                                var $contents = $(formDoc.body).contents().first();

                                if ($contents.length && $contents[0] === $form[0]) {
                                    isFailure = false;
                                }
                            }

                            if (isFailure) {
                                internalCallbacks.onFail(formDoc.body.innerHTML, fileUrl);

                                cleanUp(true);

                                return;
                            }
                        }
                    }
                    catch (err) {

                        //500 error less than IE9
                        internalCallbacks.onFail('', fileUrl);

                        cleanUp(true);

                        return;
                    }
                }


                //keep checking...
                setTimeout(checkFileDownloadComplete, settings.checkInterval);
            }

            //gets an iframes document in a cross browser compatible manner
            function getiframeDocument($iframe) {
                var iframeDoc = $iframe[0].contentWindow || $iframe[0].contentDocument;
                if (iframeDoc.document) {
                    iframeDoc = iframeDoc.document;
                }
                return iframeDoc;
            }

            function cleanUp(isFailure) {

                setTimeout(function () {

                    if (downloadWindow) {

                        if (isAndroid) {
                            downloadWindow.close();
                        }

                        if (isIos) {
                            downloadWindow.focus(); //ios safari bug doesn't allow a window to be closed unless it is focused
                            if (isFailure) {
                                downloadWindow.close();
                            }
                        }
                    }

                    //iframe cleanup appears to randomly cause the download to fail
                    //not doing it seems better than failure...
                    //if ($iframe) {
                    //    $iframe.remove();
                    //}

                }, 0);
            }


            function htmlSpecialCharsEntityEncode(str) {
                return str.replace(htmlSpecialCharsRegEx, function (match) {
                    return '&' + htmlSpecialCharsPlaceHolders[match];
                });
            }

            return deferred.promise();
        }
    });

})(jQuery, this);;
