torque/dist/torque.js
2014-01-09 16:56:06 +01:00

2 lines
55 KiB
JavaScript

(function(e){function r(e,t){if(!t.steps)throw new Error("steps option missing");this.options=t,this.running=!1,this._tick=this._tick.bind(this),this._t0=+(new Date),this.callback=e,this._time=0,_.defaults(this.options,{animationDelay:0,maxDelta:.2,loop:!0}),this.rescale()}e.torque=e.torque||{};var t=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||function(e){setTimeout(e,16)},n=window.requestAnimationFrame||window.mozCancelAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||function(e){};r.prototype={start:function(){this.running=!0,t(this._tick)},isRunning:function(){return this.running},stop:function(){this.pause(),this.time(0)},time:function(e){if(!arguments.length)return this._time;this._time=e;var t=this.range(this.domain(this._time));this.callback(t)},toggle:function(){this.running?this.pause():this.start()},rescale:function(){return this.domainInv=torque.math.linear(this.options.animationDelay,this.options.animationDelay+this.options.animationDuration),this.domain=this.domainInv.invert(),this.range=torque.math.linear(0,this.options.steps),this.rangeInv=this.range.invert(),this.time(this._time),this},duration:function(e){return arguments.length?(this.options.animationDuration=e,this.time()>e&&this.time(0),this.rescale(),this):this.options.animationDuration},steps:function(e){return this.options.steps=e,this.rescale()},step:function(e){if(arguments.length===0)return this.range(this.domain(this._time));this._time=this.domainInv(this.rangeInv(e))},pause:function(){this.running=!1,n(this._tick)},_tick:function(){var e=+(new Date),n=(e-this._t0)*.001;n=Math.min(this.options.maxDelta,n),this._t0=e,this._time+=n,this.time(this._time),this.step()>=this.options.steps&&(this._time=0),this.running&&t(this._tick)}},e.torque.Animator=r})(typeof exports=="undefined"?this:exports),function(e){e.torque=e.torque||{};var t={version:"1.0.0",style:{"comp-op":{css:"comp-op","default-value":"src-over","default-meaning":"add the current layer on top of other layers",doc:"Composite operation. This defines how this layer should behave relative to layers atop or below it.",type:["src","src-over","dst-over","src-in","dst-in","src-out","dst-out","src-atop","dst-atop","xor","darken","lighten"]}},layer:{"buffer-size":{"default-value":"0",type:"float","default-meaning":"No buffer will be used",doc:"Extra tolerance around the Layer extent (in pixels) used to when querying and (potentially) clipping the layer data during rendering"},"-torque-frame-count":{"default-value":"128",type:"number","default-meaning":"the data is broken into 128 time frames",doc:"Number of animation steps/frames used in the animation. If the data contains a fewere number of total frames, the lesser value will be used."},"-torque-resolution":{"default-value":"2",type:"number","default-meaning":"",doc:"Spatial resolution in pixels. A resolution of 1 means no spatial aggregation of the data. Any other resolution of N results in spatial aggregation into cells of NxN pixels. The value N must be power of 2"},"-torque-animation-duration":{"default-value":"30",type:"number","default-meaning":"the animation lasts 30 seconds",doc:"Animation duration in seconds"},"-torque-aggregation-function":{"default-value":"count(cartodb_id)",type:"string","default-meaning":"the value for each cell is the count of points in that cell",doc:"A function used to calculate a value from the aggregate data for each cell. See -torque-resolution"},"-torque-time-attribute":{"default-value":"time",type:"string","default-meaning":"the data column in your table that is of a time based type",doc:"The table column that contains the time information used create the animation"},"-torque-data-aggregation":{"default-value":"linear",type:["cumulative"],"default-meaning":"previous values are discarded",doc:"A linear animation will discard previous values while a cumulative animation will accumulate them until it restarts"}},symbolizers:{"*":{"comp-op":{css:"comp-op","default-value":"src-over","default-meaning":"add the current layer on top of other layers",doc:"Composite operation. This defines how this layer should behave relative to layers atop or below it.",type:["src","src-over","dst-over","src-in","dst-in","src-out","dst-out","src-atop","dst-atop","xor","darken","lighten"]},opacity:{css:"opacity",type:"float",doc:"An alpha value for the style (which means an alpha applied to all features in separate buffer and then composited back to main buffer)","default-value":1,"default-meaning":"no separate buffer will be used and no alpha will be applied to the style after rendering"}},trail:{steps:{css:"trail-steps",type:"float","default-value":1,"default-meaning":"no trail steps",doc:"How many steps of trails are going to be rendered"}},polygon:{fill:{css:"polygon-fill",type:"color","default-value":"rgba(128,128,128,1)","default-meaning":"gray and fully opaque (alpha = 1), same as rgb(128,128,128)",doc:"Fill color to assign to a polygon"},"fill-opacity":{css:"polygon-opacity",type:"float",doc:"The opacity of the polygon","default-value":1,"default-meaning":"opaque"}},line:{stroke:{css:"line-color","default-value":"rgba(0,0,0,1)",type:"color","default-meaning":"black and fully opaque (alpha = 1), same as rgb(0,0,0)",doc:"The color of a drawn line"},"stroke-width":{css:"line-width","default-value":1,type:"float",doc:"The width of a line in pixels"},"stroke-opacity":{css:"line-opacity","default-value":1,type:"float","default-meaning":"opaque",doc:"The opacity of a line"},"stroke-linejoin":{css:"line-join","default-value":"miter",type:["miter","round","bevel"],doc:"The behavior of lines when joining"},"stroke-linecap":{css:"line-cap","default-value":"butt",type:["butt","round","square"],doc:"The display of line endings"}},markers:{file:{css:"marker-file",doc:"An SVG file that this marker shows at each placement. If no file is given, the marker will show an ellipse.","default-value":"","default-meaning":"An ellipse or circle, if width equals height",type:"uri"},opacity:{css:"marker-opacity",doc:"The overall opacity of the marker, if set, overrides both the opacity of both the fill and stroke","default-value":1,"default-meaning":"The stroke-opacity and fill-opacity will be used",type:"float"},"fill-opacity":{css:"marker-fill-opacity",doc:"The fill opacity of the marker","default-value":1,"default-meaning":"opaque",type:"float"},stroke:{css:"marker-line-color",doc:"The color of the stroke around a marker shape.","default-value":"black",type:"color"},"stroke-width":{css:"marker-line-width",doc:"The width of the stroke around a marker shape, in pixels. This is positioned on the boundary, so high values can cover the area itself.",type:"float"},"stroke-opacity":{css:"marker-line-opacity","default-value":1,"default-meaning":"opaque",doc:"The opacity of a line",type:"float"},fill:{css:"marker-fill","default-value":"blue",doc:"The color of the area of the marker.",type:"color"},"marker-type":{css:"marker-type",type:["rectangle","ellipse"],"default-value":"ellipse",doc:"The default marker-type. If a SVG file is not given as the marker-file parameter, the renderer provides either an rectangle or an ellipse (a circle if height is equal to width)"}},point:{file:{css:"point-file",type:"uri",required:!1,"default-value":"none",doc:"Image file to represent a point"},opacity:{css:"point-opacity",type:"float","default-value":1,"default-meaning":"Fully opaque",doc:"A value from 0 to 1 to control the opacity of the point"}}},colors:{aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50],transparent:[0,0,0,0]}};e.torque["torque-reference"]={version:{latest:t,"1.0.0":t}}}(typeof exports=="undefined"?this:exports),function(e){function t(){}t.prototype={},t.optionsFromLayer=function(e){var t={};if(!e)return t;var n={"buffer-size":"buffer-size","-torque-frame-count":"steps","-torque-resolution":"resolution","-torque-animation-duration":"animationDuration","-torque-aggregation-function":"countby","-torque-time-attribute":"column","-torque-data-aggregation":"data_aggregation"};for(var r in n){var i=e.eval(r);if(i!==undefined){var s=n[r];t[s]=i}}return t},t.optionsFromCartoCSS=function(e){var n=(new carto.RendererJS).render(e),r=n.findLayer({name:"Map"});return t.optionsFromLayer(r)},e.torque.common=torque.common||{},e.torque.common.TorqueLayer=t}(typeof exports=="undefined"?this:exports),function(e){e.torque=e.torque||{};var t={};t.on=function(e,t){var n=this._evt_callbacks=this._evt_callbacks||{},r=n[e]||(n[e]=[]);r.push(t)},t.trigger=function(e){var t=this._evt_callbacks&&this._evt_callbacks[e];for(var n=0;t&&n<t.length;++n)t[n].apply(this,Array.prototype.slice.call(arguments,1))},t.fire=t.trigger,t.off=function(e,t){var n=this._evt_callbacks&&this._evt_callbacks[e];if(n&&!t)return delete this._evt_callbacks[e],this;var r=[];for(var i=0;n&&i<n.length;++i)n[i]===t&&r.push(i);while((i=r.pop())!==undefined)n.splice(i,1)},t.callbacks=function(e){return this._evt_callbacks&&this._evt_callbacks[e]||[]},e.torque.Event=t,e.torque.types={Uint8Array:typeof window.Uint8Array!="undefined"?window.Uint8Array:Array,Uint32Array:typeof window.Uint32Array!="undefined"?window.Uint32Array:Array,Int32Array:typeof window.Int32Array!="undefined"?window.Int32Array:Array},e.torque.isBrowserSupported=function(){return!!document.createElement("canvas")}}(typeof exports=="undefined"?this:exports),function(e){function t(e,t){return function(n){return Math.max(Math.min(n,t),e)}}function n(e,n){var r=t(0,1);return function(t){return r((t-e)/(n-e))}}function r(e,r){function s(t){return i(e*(1-t)+t*r)}var i=t(e,r);return s.invert=function(){return n(e,r)},s}e.torque=e.torque||{},e.torque.math={clamp:t,linear:r,invLinear:n}}(typeof exports=="undefined"?this:exports),function(e){function n(){}function r(e){this.t0=null,this.name=e,this.count=0}var t=1024;n.metrics={},n.get=function(e){return n.metrics[e]||{max:0,min:Number.MAX_VALUE,avg:0,total:0,count:0,history:typeof Float32Array!="undefined"?new Float32Array(t):[]}},n.new_value=function(e,r){var i=n.metrics[e]=n.get(e);i.max=Math.max(i.max,r),i.min=Math.min(i.min,r),i.total+=r,++i.count,i.avg=i.total/i.count,i.history[i.count%t]=r},n.print_stats=function(){for(k in n.metrics){var e=n.metrics[k];console.log(" === "+k+" === "),console.log(" max: "+e.max),console.log(" min: "+e.min),console.log(" avg: "+e.avg),console.log(" count: "+e.count),console.log(" total: "+e.total)}},r.prototype={start:function(){return this.t0=+(new Date),this},_elapsed:function(){return+(new Date)-this.t0},end:function(){this.t0!==null&&(n.new_value(this.name,this._elapsed()),this.t0=null)},inc:function(e){e=e===undefined?1:e,n.new_value(this.name,n.get(this.name).count+(e?e:0))},dec:function(e){e=e===undefined?1:e,this.inc(-e)},mark:function(){++this.count;if(this.t0===null){this.start();return}var e=this._elapsed();e>1&&(n.new_value(this.name,this.count),this.count=0,this.start())}},n.metric=function(e){return new r(e)},e.Profiler=n}(typeof exports=="undefined"?this:exports),function(e){function o(e){for(var t=1;t<arguments.length;++t){var n=arguments[t];for(var r in n)e=e.replace(RegExp("\\{"+r+"\\}","g"),n[r])}return e}var t=e.torque=e.torque||{},n=e.torque.providers=e.torque.providers||{},r=t.types.Uint8Array,i=t.types.Int32Array,s=t.types.Uint32Array,u=function(e){this._ready=!1,this._tileQueue=[],this.options=e,this.options.is_time=this.options.is_time===undefined?!0:this.options.is_time,this.options.tiler_protocol=e.tiler_protocol||"http",this.options.tiler_domain=e.tiler_domain||"cartodb.com",this.options.tiler_port=e.tiler_port||80,this.options.data_aggregation&&(this.options.cumulative=this.options.data_aggregation==="cumulative");if(e.resolution===undefined)throw new Error("resolution should be provided");if(e.steps===undefined)throw new Error("steps should be provided");e.start===undefined?this._fetchKeySpan():this._setReady(!0)};u.prototype={proccessTile:function(e,t,n){var o,u=new r(e.length),a=new r(e.length),f=Profiler.metric("ProviderJSON:mem"),l=Profiler.metric("ProviderJSON:point_count"),c=Profiler.metric("ProviderJSON:process_time").start(),h=0,p=-1;for(o=0;o<e.length;++o){var d=e[o];h+=d.dates__uint16.length;for(var v=0;v<d.dates__uint16.length;++v)p=Math.max(p,d.dates__uint16[v])}this.options.cumulative&&(h=(1+p)*e.length);var m=this.options.cumulative?s:r,g=new i(p+1),y=new i(p+1),b=new(this.options.valueDataType||m)(h),w=new s(h);f.inc(4*p+4*p+h+h*4),l.inc(e.length);var E={};for(var o=0;o<e.length;++o){var d=e[o];u[o]=d.x__uint8*this.options.resolution,d.y__uint8===-1?a[o]=0:a[o]=d.y__uint8*this.options.resolution;var h=d.dates__uint16,S=d.vals__uint8;if(!this.options.cumulative)for(var x=0,T=h.length;x<T;++x){var N=E[h[x]]||(E[h[x]]=[]);this.options.cumulative&&(S[x]+=prev_val),prev_val=S[x],N.push([o,S[x]])}else{var C={};for(var x=0,T=h.length;x<T;++x)C[h[x]]=S[x];var k=0;for(var x=h[0];x<=p;++x){var N=E[x]||(E[x]=[]),L=C[x];L&&(k+=L),N.push([o,k])}}}var A=0,O=0,M=0;for(var M=0;M<=p;++M){var _=0,D=E[M];if(D)for(var o=0;o<D.length;++o){var N=D[o];++_,w[A]=N[0],b[A]=N[1],++A}g[M]=O,y[M]=_,O+=_}return c.end(),{x:u,y:a,z:n,coord:{x:t.x,y:t.y,z:n},timeCount:y,timeIndex:g,renderDataPos:w,renderData:b,maxDate:p}},_host:function(){var e=this.options,t=e.sql_api_port,n=(e.user_name||e.user)+"."+(e.sql_api_domain||"cartodb.com")+(t?":"+t:""),r=e.sql_api_protocol||"http";return this.options.url||r+"://"+n+"/api/v2/sql"},url:function(e){var t=this.options,n=t.sql_api_protocol||"http";if(!this.options.cdn_url)return this._host();var r=n+"://";e&&(r+=e+".");var i=t.cdn_url;if(!i.http&&!i.https)throw new Error("cdn_host should contain http and/or https entries");return r+=i[n]+"/"+(t.user_name||t.user)+"/api/v2/sql",r},_hash:function(e){var t=0;if(!e||e.length==0)return t;for(var n=0,r=e.length;n<r;++n)t=(t<<5)-t+e.charCodeAt(n)|0;return t},_extraParams:function(){if(this.options.extra_params){var e=[];for(var t in this.options.extra_params){var n=this.options.extra_params[t];n&&e.push(t+"="+encodeURIComponent(n))}return e.join("&")}return null},isHttps:function(){return this.options.sql_api_protocol&&this.options.sql_api_protocol==="https"},sql:function(e,n,r){r=r||{};var i=this.options.subdomains||"0123";this.isHttps()&&(i=[null]);var s;r.no_cdn?s=this._host():s=this.url(i[Math.abs(this._hash(e))%i.length]);var o=this._extraParams();t.net.get(s+"?q="+encodeURIComponent(e)+(o?"&"+o:""),function(e){r.parseJSON&&(e=JSON.parse(e&&e.responseText)),n&&n(e)})},getTileData:function(e,t,n){this._ready?this._getTileData(e,t,n):this._tileQueue.push([e,t,n])},_setReady:function(e){this._ready=!0,this._processQueue(),this.options.ready&&this.options.ready()},_processQueue:function(){var e;while(e=this._tileQueue.pop())this._getTileData.apply(this,e)},_getTileData:function(e,t,n){var r=Profiler.metric("ProviderJSON:tile_fetch_time").start();this.table=this.options.table;var i=1<<t,s=this.options.column;this.options.is_time&&(s=o("date_part('epoch', {column})",this.options));var u="WITH par AS ( SELECT CDB_XYZ_Resolution({zoom})*{resolution} as res, 256/{resolution} as tile_size, CDB_XYZ_Extent({x}, {y}, {zoom}) as ext ),cte AS ( SELECT ST_SnapToGrid(i.the_geom_webmercator, p.res) g, {countby} c, floor(({column_conv} - {start})/{step}) d FROM ({_sql}) i, par p WHERE i.the_geom_webmercator && p.ext GROUP BY g, d) SELECT (st_x(g)-st_xmin(p.ext))/p.res x__uint8, (st_y(g)-st_ymin(p.ext))/p.res y__uint8, array_agg(c) vals__uint8, array_agg(d) dates__uint16 FROM cte, par p where (st_y(g)-st_ymin(p.ext))/p.res < tile_size and (st_x(g)-st_xmin(p.ext))/p.res < tile_size GROUP BY x__uint8, y__uint8",a=o(u,this.options,{zoom:t,x:e.x,y:e.y,column_conv:s,_sql:this.getSQL()}),f=this;this.sql(a,function(i){if(i){var s=JSON.parse(i.responseText).rows;n(f.proccessTile(s,e,t))}else n(null);r.end()})},getKeySpan:function(){return{start:this.options.start*1e3,end:this.options.end*1e3,step:this.options.step,steps:this.options.steps,columnType:this.options.is_time?"date":"number"}},setColumn:function(e,t){this.options.column=e,this.options.is_time=t===undefined?!0:!1,this.reload()},setResolution:function(e){this.options.resolution=e},setOptions:function(e){var t=!1;e.resolution!==undefined&&e.resolution!==this.options.resolution&&(this.options.resolution=e.resolution,t=!0),e.steps!==undefined&&e.steps!==this.options.steps&&(this.setSteps(e.steps,{silent:!0}),t=!0),e.column!==undefined&&e.column!==this.options.column&&(this.options.column=e.column,t=!0),e.countby!==undefined&&e.countby!==this.options.countby&&(this.options.countby=e.countby,t=!0);if(e.data_aggregation!==undefined){var n=e.data_aggregation==="cumulative";this.options.cumulative!==n&&(this.options.cumulative=n,t=!0)}return t&&this.reload(),t},reload:function(){this._ready=!1,this._fetchKeySpan()},setSQL:function(e){this.options.sql!=e&&(this.options.sql=e,this.reload())},getSteps:function(){return Math.min(this.options.steps,this.options.data_steps)},setSteps:function(e,t){t=t||{},this.options.steps!==e&&(this.options.steps=e,this.options.step=(this.options.end-this.options.start)/this.getSteps(),this.options.step=this.options.step||1,t.silent||this.reload())},getBounds:function(){return this.options.bounds},getSQL:function(){return this.options.sql||"select * from "+this.options.table},_tilerHost:function(){var e=this.options,t=e.user_name||e.user;return e.tiler_protocol+"://"+(t?t+".":"")+e.tiler_domain+(e.tiler_port!=""?":"+e.tiler_port:"")},_fetchUpdateAt:function(e){var n=this,r={version:"1.0.1",stat_tag:this.options.stat_tag||"torque",layers:[{type:"cartodb",options:{cartocss_version:"2.1.1",cartocss:"#layer {}",sql:this.getSQL()}}]},i=this._tilerHost()+"/tiles/layergroup",s=this._extraParams();s&&(s=s.replace("api_key=","map_key=")),i=i+"?config="+encodeURIComponent(JSON.stringify(r))+"&callback=?"+(s?"&"+s:""),t.net.jsonp(i,function(t){var r=o("select * from ({sql}) __torque_wrap_sql limit 0",{sql:n.getSQL()});n.sql(r,function(n){t&&e({updated_at:t.last_updated,fields:n.fields})},{parseJSON:!0})})},_fetchKeySpan:function(){var e=this,t,n,r,i;this._fetchUpdateAt(function(s){if(!s)return;e.options.extra_params=e.options.extra_params||{},e.options.extra_params.last_updated=s.updated_at||0,e.options.extra_params.cache_policy="persist",e.options.is_time=s.fields[e.options.column].type==="date";var u=e.options.column;e.options.is_time?(r="date_part('epoch', max({column}))",i="date_part('epoch', min({column}))",u=o("date_part('epoch', {column})",e.options)):(r="max({column})",i="min({column})"),t=o(r,{column:e.options.column}),n=o(i,{column:e.options.column});var a=" SELECT st_xmax(st_envelope(st_collect(the_geom))) xmax, st_ymax(st_envelope(st_collect(the_geom))) ymax, st_xmin(st_envelope(st_collect(the_geom))) xmin, st_ymin(st_envelope(st_collect(the_geom))) ymin, count(*) as num_steps, {max_col} max_date, {min_col} min_date FROM ({sql}) __torque_wrap_sql ",f=o(a,{max_col:t,min_col:n,column:u,sql:e.getSQL()});e.sql(f,function(t){t=t.rows[0],e.options.start=t.min_date,e.options.end=t.max_date,e.options.step=(t.max_date-t.min_date)/Math.min(e.options.steps,t.num_steps>>0),e.options.data_steps=t.num_steps>>0,e.options.step=e.options.step||1,e.options.bounds=[[t.ymin,t.xmin],[t.ymax,t.xmax]],e._setReady(!0)},{parseJSON:!0,no_cdn:!0})},{parseJSON:!0,no_cdn:!0})}},t.providers.json=u}(typeof exports=="undefined"?this:exports),function(e){function u(e,t){for(var n=1;n<arguments.length;++n){var t=arguments[n];for(var r in t)e=e.replace(RegExp("\\{"+r+"\\}","g"),t[r])}return e}var t=e.torque=e.torque||{},n=e.torque.providers=e.torque.providers||{},i=t.types.Uint8Array,s=t.types.Int32Array,o=t.types.Uint32Array,a=function(e){this.options=e};a.prototype={aggregateByKey:function(e){function t(e){var t=3,n=e.data[2],r={};for(var i=0;i<n;++i)r[e.data[t+i]]=e.data[t+n+i];return r}var n={};for(r=0;r<e.length;++r){var i=t(e[r]);for(var s in i)n[s]=n[s]||0,n[s]+=i[s]}return n},proccessTile:function(e,t,n){function l(e){var t=3,n={x:e.data[0]*f.options.resolution,y:e.data[1]*f.options.resolution,valuesCount:e.data[2],times:[],values:[]};for(var r=0;r<n.valuesCount;++r)n.times.push(e.data[t+r]),n.values.push(e.data[t+n.valuesCount+r]);if(f.options.cumulative)for(var r=1;r<n.valuesCount;++r)n.values[r]+=n.values[r-1];return n}var r,u=new i(e.length),a=new i(e.length),f=this;for(r=0;r<e.length;++r)e[r]=l(e[r]);var c=0,h=0;for(r=0;r<e.length;++r){var p=e[r];c+=p.times.length;for(var d=0;d<p.times.length;++d)h=Math.max(h,p.times[d])}var v=new s(h+1),m=new s(h+1),g=new(this.options.valueDataType||i)(c),y=new o(c),b={};for(var r=0;r<e.length;++r){var p=e[r];u[r]=p.x,a[r]=p.y;var c=p.times,w=p.values;for(var E=0,S=c.length;E<S;++E){var x=b[c[E]]||(b[c[E]]=[]);x.push([r,w[E]])}}var T=0,N=0,C=0;for(var C=0;C<=h;++C){var k=0,L=b[C];if(L)for(var r=0;r<L.length;++r){var x=L[r];++k,y[T]=x[0],g[T]=x[1],++T}v[C]=N,m[C]=k,N+=k}return{x:u,y:a,coord:{x:t.x,y:t.y,z:n},timeCount:m,timeIndex:v,renderDataPos:y,renderData:g}},url:function(){return this.options.url},tileUrl:function(e,t){var n=this.url(),r=(this.options.subdomains||"abcd")[(e.x+e.y+t)%4];return n.replace("{x}",e.x).replace("{y}",e.y).replace("{z}",t).replace("{s}",r)},getTile:function(e,n,r){var i=this.tileUrl(e,n),s=this,o=Profiler.metric("jsonarray:fetch time");o.start(),t.net.get(i,function(e){o.end(),e&&(e=JSON.parse(e.responseText)),r(e)})},getTileData:function(e,n,r){var i=this.tileUrl(e,n),s=this,o=Profiler.metric("jsonarray:fetch time");o.start(),t.net.get(i,function(t){o.end();var i=null,u=Profiler.metric("jsonarray:processing time"),a=Profiler.metric("jsonarray:parsing time");try{u.start(),a.start();var f=JSON.parse(t.responseText||t.response).rows;a.end(),i=s.proccessTile(f,e,n),u.end()}catch(l){console.error("problem parsing JSON on ",e,n)}r(i)})}},t.providers.JsonArray=a}(typeof exports=="undefined"?this:exports),function(e){function r(e,t,n){function o(){r.removeChild(i),clearTimeout(u),delete window[s]}n=n||{timeout:1e4};var r=document.getElementsByTagName("head")[0],i=document.createElement("script"),s="torque_"+Date.now();window[s]=function(){o(),t.apply(window,arguments)};var u=setTimeout(function(){o(),t.call(window,null)},n.timeout);e=e.replace("callback=?","callback="+s),i.type="text/javascript",i.src=e,i.async=!0,setTimeout(function(){r.appendChild(i)},0)}function i(e,t,r){function o(){var e=s.status,n;!e&&s.responseText||e>=200&&e<300||e===304?t(s):t(null)}r=r||{method:"GET",data:null},n={url:e,callback:t};var i=XMLHttpRequest;window.XDomainRequest&&!("withCredentials"in i)&&/^(http(s)?:)?\/\//.test(e)&&(i=XDomainRequest);var s=new i;return s.open(r.method,e,!0),"onload"in s?s.onload=s.onerror=o:s.onreadystatechange=function(){s.readyState>3&&o()},s.onprogress=function(){},r.data&&(s.setRequestHeader("Content-type","application/json"),s.setRequestHeader("Accept","*")),s.send(r.data),s}function s(e,t,n){return i(e,n,{data:t,method:"POST"})}var t=e.torque=e.torque||{};t.net=t.net||{};var n=null;t.net={get:i,post:s,jsonp:r,lastCall:function(){return n}}}(typeof exports=="undefined"?this:exports),function(e){function n(e,n){e.fillStyle=n.fillStyle,e.strokStyle=n.strokStyle;var r=n["point-radius"];e.beginPath(),e.arc(0,0,r,0,t,!0,!0),e.closePath(),n.fillStyle&&(n.fillOpacity&&(e.globalAlpha=n.fillOpacity),e.fill()),e.globalAlpha=1,n.strokeStyle&&n.lineWidth&&(n.strokeOpacity&&(e.globalAlpha=n.strokeOpacity),n.lineWidth&&(e.lineWidth=n.lineWidth),e.strokeStyle=n.strokeStyle,e.globalAlpha>0&&e.stroke())}function r(e,t){e.fillStyle=t.fillStyle,e.strokStyle=t.strokStyle;var n=t["point-radius"];t.fillStyle&&t.fillOpacity&&(e.globalAlpha=t.fillOpacity),e.fillRect(0,0,n,n),e.globalAlpha=1,t.strokeStyle&&t.lineWidth&&(t.strokeOpacity&&(e.globalAlpha=t.strokeOpacity),t.lineWidth&&(e.lineWidth=t.lineWidth),e.strokeStyle=t.strokeStyle,e.globalAlpha>0&&e.strokeRect(0,0,n,n))}function i(e,t){var n=t["point-file"]||t["marker-file"],r=n.height/n.width,i=t["point-radius"]||n.width,s=t["point-radius"]||t["marker-height"]||i*r;e.drawImage(n,0,0,i,s)}e.torque=e.torque||{};var t=Math.PI*2;e.torque.cartocss=e.torque.cartocss||{},e.torque.cartocss={renderPoint:n,renderSprite:i,renderRectangle:r}}(typeof exports=="undefined"?this:exports),function(e){function r(e,t){if(!e)throw new Error("canvas can't be undefined");this.options=t,this._canvas=e,this._ctx=e.getContext("2d"),this._sprites=[],this._shader=null,this.setCartoCSS(this.options.cartocss||n)}e.torque=e.torque||{},e.torque.renderer=e.torque.renderer||{};var t=Math.PI*2,n=["#layer {"," marker-fill: #662506;"," marker-width: 4;"," [value > 1] { marker-fill: #FEE391; }"," [value > 2] { marker-fill: #FEC44F; }"," [value > 3] { marker-fill: #FE9929; }"," [value > 4] { marker-fill: #EC7014; }"," [value > 5] { marker-fill: #CC4C02; }"," [value > 6] { marker-fill: #993404; }"," [value > 7] { marker-fill: #662506; }","}"].join("\n");r.prototype={setCanvas:function(e){this._canvas=e,this._ctx=e.getContext("2d")},setCartoCSS:function(e){this.setShader((new carto.RendererJS).render(e))},setShader:function(e){this._sprites=[],this._shader=e},clearSpriteCache:function(){this._sprites=[]},generateSprite:function(e,t,n){console.log("generate sprite",n);var r=Profiler.metric("PointRenderer:generateSprite").start(),i=e.getStyle("canvas-2d",{value:t},n),s=i["point-radius"];if(!s)throw new Error("marker-width property should be set");var o=(i.lineWidth||0)+s*2,u=document.createElement("canvas"),a=u.getContext("2d");a.width=u.width=Math.ceil(o),a.height=u.height=Math.ceil(o),a.translate(o/2,o/2);if(i["point-file"]||i["marker-file"])torque.cartocss.renderSprite(a,i);else{var f=i["marker-type"];f&&f==="rectangle"?torque.cartocss.renderRectangle(a,i):torque.cartocss.renderPoint(a,i)}return r.end(),u},renderTile:function(e,t){var n=this._shader.getLayers();for(var r=0,i=n.length;r<i;++r){var s=n[r];if(s.name()!=="Map"){var o=this._sprites[r]||(this._sprites[r]={});for(var u=0;u<s.frames().length;++u){var a=s.frames()[u],f=o[a]||(o[a]=[]);this._renderTile(e,t-a,a,f,s)}}}},_renderTile:function(e,t,n,r,i,s){if(!this._canvas)return;var o=Profiler.metric("PointRenderer:renderTile").start(),u=this._ctx,a=i.eval("comp-op")||this.options.blendmode;a&&(u.globalCompositeOperation=a),this.options.cumulative&&t>e.maxDate&&(t=e.maxDate);var f=this.options.resolution*(256/this.options.resolution-1),l=e.timeCount[t];if(l){var c=e.timeIndex[t];for(var h=0;h<l;++h){var p=e.renderDataPos[c+h],d=e.renderData[c+h];if(d){var v=r[d];v||(v=r[d]=this.generateSprite(i,d,_.extend({zoom:e.z,"frame-offset":n},s)));var m=e.x[p]-(v.width>>1),g=f-e.y[p];u.drawImage(v,m,g-(v.height>>1))}}}o.end()},setBlendMode:function(e){this.options.blendmode=e}},e.torque.renderer.Point=r}(typeof exports=="undefined"?this:exports),function(e){function r(e,n){this.options=n,carto.tree.Reference.set(torque["torque-reference"]),this.setCanvas(e),this.setCartoCSS(this.options.cartocss||t)}e.torque=e.torque||{},e.torque.renderer=e.torque.renderer||{};var t=["#layer {"," polygon-fill: #FFFF00;"," [value > 10] { polygon-fill: #FFFF00; }"," [value > 100] { polygon-fill: #FFCC00; }"," [value > 1000] { polygon-fill: #FE9929; }"," [value > 10000] { polygon-fill: #FF6600; }"," [value > 100000] { polygon-fill: #FF3300; }","}"].join("\n"),n=Math.PI*2;r.prototype={setCartoCSS:function(e){this._cartoCssStyle=(new carto.RendererJS).render(e);if(this._cartoCssStyle.getLayers().length>1)throw new Error("only one CartoCSS layer is supported");this._shader=this._cartoCssStyle.getLayers()[0].shader},setCanvas:function(e){if(!e)return;this._canvas=e,this._ctx=e.getContext("2d")},accumulate:function(e,t){var n=Profiler.metric("RectangleRender:accumulate").start(),r,i,s,o,u,a,f,l,c=this.options.resolution,h=256/c,p=new Float32Array(h*h);typeof t!="object"&&(t=[t]);for(u=0;u<t.length;++u){a=t[u],f=e.timeCount[a];if(f){l=e.timeIndex[a];for(o=0;o<f;++o)s=e.renderDataPos[l+o],r=e.x[s]/c,i=e.y[s]/c,p[r*h+i]+=e.renderData[l+o]}}return n.end(),p},renderTileAccum:function(e,t,n){var r=Profiler.metric("RectangleRender:renderTileAccum").start(),i,s,o,u,a=this.options.resolution,f=this._ctx,l=256/a|0,c=l*l,h=this._colors;this.options.blendmode&&(f.globalCompositeOperation=this.options.blendmode);var p=this._shader["polygon-opacity"]||function(){return 1};for(var d=0;d<c;++d){var v=d,m=e[d];m&&(s=v/l|0,o=v%l,i=this._shader["polygon-fill"]({value:m},{zoom:0}),f.fillStyle=i,u=p({value:m},{zoom:0}),u===null&&(u=1),f.globalAlpha=u,f.fillRect(s*a,256-a-o*a,a,a))}r.end()},renderTile:function(e,t,n,r){if(!this._canvas)return;var i=this.options.resolution,s=this._ctx,o=this._colors,u=e.timeCount[t];if(u){var a=this._canvas.width,f=this._canvas.height,l=e.timeIndex[t];for(var c=0;c<activePixels;++c){var h=e.renderDataPos[l+c],p=e.renderData[l+c];if(p){var d=o[Math.min(p,o.length-1)],v=e.x[h],m=e.y[h];s.fillStyle=d,s.fillRect(v,m,i,i)}}}}},e.torque.renderer.Rectangle=r}(typeof exports=="undefined"?this:exports);if(typeof google!="undefined"&&typeof google.maps!="undefined"){function CanvasLayer(e){function n(e,t){return function(){t.apply(e)}}this.isAdded_=!1,this.isAnimated_=!1,this.paneName_=CanvasLayer.DEFAULT_PANE_NAME_,this.updateHandler_=null,this.resizeHandler_=null,this.topLeft_=null,this.centerListener_=null,this.resizeListener_=null,this.needsResize_=!0,this.requestAnimationFrameId_=null;var t=document.createElement("canvas");t.style.position="absolute",t.style.top=0,t.style.left=0,t.style
.pointerEvents="none",this.canvas=t,this.repositionFunction_=n(this,this.repositionCanvas_),this.resizeFunction_=n(this,this.resize_),this.requestUpdateFunction_=n(this,this.update_),e&&this.setOptions(e)}CanvasLayer.prototype=new google.maps.OverlayView,CanvasLayer.DEFAULT_PANE_NAME_="overlayLayer",CanvasLayer.CSS_TRANSFORM_=function(){var e=document.createElement("div"),t=["transform","WebkitTransform","MozTransform","OTransform","msTransform"];for(var n=0;n<t.length;n++){var r=t[n];if(e.style[r]!==undefined)return r}return t[0]}(),CanvasLayer.prototype.requestAnimFrame_=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(e){return window.setTimeout(e,1e3/60)},CanvasLayer.prototype.cancelAnimFrame_=window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame||function(e){},CanvasLayer.prototype.setOptions=function(e){e.animate!==undefined&&this.setAnimate(e.animate),e.paneName!==undefined&&this.setPane(e.paneName),e.updateHandler!==undefined&&this.setUpdateHandler(e.updateHandler),e.resizeHandler!==undefined&&this.setResizeHandler(e.resizeHandler),e.readyHandler&&(this.readyHandler=e.readyHandler)},CanvasLayer.prototype.setAnimate=function(e){this.isAnimated_=!!e,this.isAnimated_&&this.scheduleUpdate()},CanvasLayer.prototype.isAnimated=function(){return this.isAnimated_},CanvasLayer.prototype.setPaneName=function(e){this.paneName_=e,this.setPane_()},CanvasLayer.prototype.getPaneName=function(){return this.paneName_},CanvasLayer.prototype.setPane_=function(){if(!this.isAdded_)return;var e=this.getPanes();if(!e[this.paneName_])throw new Error('"'+this.paneName_+'" is not a valid MapPane name.');e[this.paneName_].appendChild(this.canvas)},CanvasLayer.prototype.setResizeHandler=function(e){this.resizeHandler_=e},CanvasLayer.prototype.setUpdateHandler=function(e){this.updateHandler_=e},CanvasLayer.prototype.onAdd=function(){if(this.isAdded_)return;this.isAdded_=!0,this.setPane_(),this.resizeListener_=google.maps.event.addListener(this.getMap(),"resize",this.resizeFunction_),this.centerListener_=google.maps.event.addListener(this.getMap(),"center_changed",this.repositionFunction_),this.resize_(),this.repositionCanvas_(),this.readyHandler&&this.readyHandler()},CanvasLayer.prototype.onRemove=function(){if(!this.isAdded_)return;this.isAdded_=!1,this.topLeft_=null,this.canvas.parentElement.removeChild(this.canvas),this.centerListener_&&(google.maps.event.removeListener(this.centerListener_),this.centerListener_=null),this.resizeListener_&&(google.maps.event.removeListener(this.resizeListener_),this.resizeListener_=null),this.requestAnimationFrameId_&&(this.cancelAnimFrame_.call(window,this.requestAnimationFrameId_),this.requestAnimationFrameId_=null)},CanvasLayer.prototype.resize_=function(){if(!this.isAdded_)return;var e=this.getMap(),t=e.getDiv().offsetWidth,n=e.getDiv().offsetHeight,r=this.canvas.width,i=this.canvas.height;if(r!==t||i!==n)this.canvas.width=t,this.canvas.height=n,this.canvas.style.width=t+"px",this.canvas.style.height=n+"px",this.needsResize_=!0,this.scheduleUpdate()},CanvasLayer.prototype.draw=function(){this.repositionCanvas_()},CanvasLayer.prototype.repositionCanvas_=function(){var e=this.getMap().getBounds();this.topLeft_=new google.maps.LatLng(e.getNorthEast().lat(),e.getSouthWest().lng());var t=this.getProjection(),n=t.fromLatLngToDivPixel(this.topLeft_),r=(1<<this.getMap().getZoom())*256;Math.abs(n.x)>r&&(n.x-=r),this.canvas.style[CanvasLayer.CSS_TRANSFORM_]="translate("+Math.round(n.x)+"px,"+Math.round(n.y)+"px)",this.scheduleUpdate()},CanvasLayer.prototype.update_=function(){this.requestAnimationFrameId_=null;if(!this.isAdded_)return;this.isAnimated_&&this.scheduleUpdate(),this.needsResize_&&this.resizeHandler_&&(this.needsResize_=!1,this.resizeHandler_()),this.updateHandler_&&this.updateHandler_()},CanvasLayer.prototype.getTopLeft=function(){return this.topLeft_},CanvasLayer.prototype.scheduleUpdate=function(){this.isAdded_&&!this.requestAnimationFrameId_&&(this.requestAnimationFrameId_=this.requestAnimFrame_.call(window,this.requestUpdateFunction_))}}if(typeof google!="undefined"&&typeof google.maps!="undefined"){function CanvasTileLayer(e,t){this.tileSize=new google.maps.Size(256,256),this.maxZoom=19,this.name="Tile #s",this.alt="Canvas tile layer",this.tiles={},this.canvas_setup=e,this.render=t,t||(this.render=e)}CanvasTileLayer.prototype.create_tile_canvas=function(e,t,n){var r=n.createElement("canvas"),i=n.createElement("canvas");r.style.border=i.style.border="none",r.style.margin=i.style.margin="0",r.style.padding=i.style.padding="0";var s=r.getContext("2d");s.width=r.width=this.tileSize.width,s.height=r.height=this.tileSize.height;var o=i.getContext("2d");i.width=o.width=this.tileSize.width,i.height=o.height=this.tileSize.height;var u=e.x+"_"+e.y+"_"+t;return r.setAttribute("id",u),i.setAttribute("id",u),u in this.tiles&&delete this.tiles[u],this.tiles[u]={canvas:r,ctx:s,hit_canvas:i,hit_ctx:o,coord:e,zoom:t,primitives:null},this.canvas_setup&&this.canvas_setup(this.tiles[u],e,t),r},CanvasTileLayer.prototype.each=function(e){for(var t in this.tiles){var n=this.tiles[t];e(n)}},CanvasTileLayer.prototype.recreate=function(){for(var e in this.tiles){var t=this.tiles[e];this.canvas_setup(t,t.coord,t.zoom)}},CanvasTileLayer.prototype.redraw_tile=function(e){this.render(e,e.coord,e.zoom)},CanvasTileLayer.prototype.redraw=function(){for(var e in this.tiles){var t=this.tiles[e];this.render(t,t.coord,t.zoom)}},CanvasTileLayer.prototype.getTile=function(e,t,n){return this.create_tile_canvas(e,t,n)},CanvasTileLayer.prototype.releaseTile=function(e){var t=e.getAttribute("id");delete this.tiles[t]}}(function(e){function t(){}if(typeof google=="undefined"||typeof google.maps=="undefined")return;t.prototype={_initTileLoader:function(e,t){this._map=e,this._projection=t,this._tiles={},this._tilesToLoad=0,this._updateTiles=this._updateTiles.bind(this),this._listeners=[],this._listeners.push(google.maps.event.addListener(this._map,"dragend",this._updateTiles),google.maps.event.addListener(this._map,"zoom_changed",this._updateTiles)),this.tileSize=256,this._updateTiles()},_removeTileLoader:function(){for(var e in this._listeners)google.maps.event.removeListener(this._listeners[e]);this._removeTiles()},_removeTiles:function(){for(var e in this._tiles)this._removeTile(e)},_reloadTiles:function(){this._removeTiles(),this._updateTiles()},_updateTiles:function(){if(!this._map)return;var e=this._map.getBounds(),t=this._map.getZoom(),n=this.tileSize,r=1<<t,i=new google.maps.LatLng(e.getNorthEast().lat(),e.getSouthWest().lng()),s=new google.maps.LatLng(e.getSouthWest().lat(),e.getNorthEast().lng());this._projection=this._map.getProjection();var o=this._projection.fromLatLngToPoint(i),u=this._projection.fromLatLngToPoint(s),a=new google.maps.Point(Math.floor(o.x*r/n),Math.floor(o.y*r/n)),f=new google.maps.Point(Math.floor(u.x*r/n),Math.floor(u.y*r/n));this._addTilesFromCenterOut(a,f),this._removeOtherTiles(a,f)},_removeOtherTiles:function(e,t){var n,r,i,s,o=this._map.getZoom();for(s in this._tiles)this._tiles.hasOwnProperty(s)&&(n=s.split(":"),r=parseInt(n[0],10),i=parseInt(n[1],10),z=parseInt(n[2],10),(z!==o||r<e.x||r>t.x||i<e.y||i>t.y)&&this._removeTile(s))},_removeTile:function(e){this.onTileRemoved&&this.onTileRemoved(this._tiles[e]),delete this._tiles[e]},_tileShouldBeLoaded:function(e){return!(e.x+":"+e.y+":"+e.zoom in this._tiles)},_tileLoaded:function(e,t){this._tilesToLoad--,this._tiles[e.x+":"+e.y+":"+e.zoom]=t,this._tilesToLoad===0&&this.onTilesLoaded&&this.onTilesLoaded()},getTilePos:function(e){var t=1<<this._map.getZoom();e={x:(e.x%t+t)%t,y:e.y},e=new google.maps.Point(e.x*this.tileSize,e.y*this.tileSize);var n=this._map.getBounds(),r=new google.maps.LatLng(n.getNorthEast().lat(),n.getSouthWest().lng()),i=this._map.getProjection().fromLatLngToPoint(r);return zoom=1<<this._map.getZoom(),i.x=i.x*zoom,i.y=i.y*zoom,new google.maps.Point(e.x-i.x,e.y-i.y)},_addTilesFromCenterOut:function(e,t){function f(e){var t=e.x-r.x,n=e.y-r.y;return t*t+n*n}var n=[],r=new google.maps.Point((e.x+t.x)*.5,(e.y+t.y)*.5),i=this._map.getZoom(),s,o,u;for(s=e.y;s<=t.y;s++)for(o=e.x;o<=t.x;o++)u=new google.maps.Point(o,s),u.zoom=i,this._tileShouldBeLoaded(u)&&n.push(u);var a=n.length;if(a===0)return;n.sort(function(e,t){return f(e)-f(t)}),this._tilesToLoad+=a;if(this.onTileAdded)for(o=0;o<a;o++)this.onTileAdded(n[o])}},torque.GMapsTileLoader=t})(typeof exports=="undefined"?this:exports),function(e){function t(e){var t=this;if(!torque.isBrowserSupported())throw new Error("browser is not supported by torque");this.key=0,this.shader=null,this.ready=!1,this.options=_.extend({},e),_.defaults(this.options,{provider:"sql_api",renderer:"point",resolution:2,steps:100,visible:!0}),e.cartocss&&_.extend(this.options,torque.common.TorqueLayer.optionsFromCartoCSS(e.cartocss)),this.hidden=!this.options.visible,this.animator=new torque.Animator(function(e){var n=e|0;t.key!==n&&t.setKey(n)},this.options),this.play=this.animator.start.bind(this.animator),this.stop=this.animator.stop.bind(this.animator),this.pause=this.animator.pause.bind(this.animator),this.toggle=this.animator.toggle.bind(this.animator),this.setDuration=this.animator.duration.bind(this.animator),this.isRunning=this.animator.isRunning.bind(this.animator),CanvasLayer.call(this,{map:this.options.map,animate:!1,updateHandler:this.render,readyHandler:this.initialize})}function n(e){this.options=_.extend({},e),CanvasTileLayer.call(this,this._loadTile.bind(this),this.drawTile.bind(this)),this.initialize(e)}if(typeof google=="undefined"||typeof google.maps=="undefined")return;t.prototype=_.extend({},CanvasLayer.prototype,torque.GMapsTileLoader.prototype,torque.Event,{providers:{sql_api:torque.providers.json,url_template:torque.providers.jsonarray},renderers:{point:torque.renderer.Point,pixel:torque.renderer.Rectangle},initialize:function(){var e=this;this.onTileAdded=this.onTileAdded.bind(this),this.options.ready=function(){e.fire("change:bounds",{bounds:e.provider.getBounds()}),e.animator.steps(e.provider.getSteps()),e.animator.rescale(),e.fire("change:steps",{steps:e.provider.getSteps()}),e.setKey(e.key)},this.provider=new this.providers[this.options.provider](this.options),this.renderer=new this.renderers[this.options.renderer](this.getCanvas(),this.options),this._cacheListener=google.maps.event.addListener(this.options.map,"zoom_changed",function(){e.renderer&&e.renderer.clearSpriteCache()}),this._initTileLoader(this.options.map,this.getProjection()),this.shader&&this.renderer.setShader(this.shader)},hide:function(){return this.hidden?this:(this.pause(),this.clear(),this.hidden=!0,this)},show:function(){return this.hidden?(this.hidden=!1,this.play(),this):this},setSQL:function(e){if(!this.provider||!this.provider.setSQL)throw new Error("this provider does not support SQL");return this.provider.setSQL(e),this._reloadTiles(),this},setBlendMode:function(e){this.renderer&&this.renderer.setBlendMode(e),this.redraw()},setSteps:function(e){this.provider&&this.provider.setSteps(e),this.animator&&this.animator.steps(e),this._reloadTiles()},setColumn:function(e,t){this.provider&&this.provider.setColumn(e,t),this._reloadTiles()},getTimeBounds:function(){return this.provider&&this.provider.getKeySpan()},getCanvas:function(){return this.canvas},onTileAdded:function(e){var t=this;this.provider.getTileData(e,e.zoom,function(n){if(e.zoom!==t.options.map.getZoom())return;t._tileLoaded(e,n),n&&t.redraw()})},clear:function(){var e=this.canvas;e.width=e.width},render:function(){if(this.hidden)return;var e,t,n,r=this.canvas;r.width=r.width;var i=r.getContext("2d");for(e in this._tiles)t=this._tiles[e],t&&(n=this.getTilePos(t.coord),i.setTransform(1,0,0,1,n.x,n.y),this.renderer.renderTile(t,this.key,n.x,n.y))},setKey:function(e){this.key=e,this.animator.step(e),this.redraw(),this.fire("change:time",{time:this.getTime(),step:this.key})},setStep:function(e){if(e===undefined||e.length!==undefined)throw new Error("setTime only accept scalars");this.setKey(e)},stepToTime:function(e){if(!this.provider)return 0;var t=this.provider.getKeySpan(),n=t.start+(t.end-t.start)*(e/this.provider.getSteps());return new Date(n)},getStep:function(){return this.key},getTime:function(){return this.stepToTime(this.key)},setCartoCSS:function(e){var t=(new carto.RendererJS).render(e);this.shader=t,this.renderer&&this.renderer.setShader(t);var n=torque.common.TorqueLayer.optionsFromLayer(t.findLayer({name:"Map"}));return this.provider&&this.provider.setOptions(n)&&this._reloadTiles(),_.extend(this.options,n),n.animationDuration&&this.animator.duration(n.animationDuration),this.redraw(),this},redraw:function(){this.scheduleUpdate()},onRemove:function(){CanvasLayer.prototype.onRemove.call(this),this.animator.stop(),this._removeTileLoader(),google.maps.event.removeListener(this._cacheListener)}}),n.prototype=_.extend({},CanvasTileLayer.prototype,{providers:{sql_api:torque.providers.json,url_template:torque.providers.JsonArray},renderers:{point:torque.renderer.Point,pixel:torque.renderer.Rectangle},initialize:function(e){var t=this;this.key=0,this.options.renderer=this.options.renderer||"pixel",this.options.provider=this.options.provider||"sql_api",this.provider=new this.providers[this.options.provider](e),this.renderer=new this.renderers[this.options.renderer](null,e)},_tileLoaded:function(e,t){e.data=t,this.drawTile(e)},_loadTile:function(e,t,n){var r=this,i=1<<n,s={x:(t.x%i+i)%i,y:t.y};this.provider.getTileData(s,n,function(t){r._tileLoaded(e,t)})},drawTile:function(e){var t=e.canvas;if(!e.data)return;t.width=t.width,this.renderer.setCanvas(t);var n=this.renderer.accumulate(e.data,this.key);this.renderer.renderTileAccum(n,0,0)},setKey:function(e){this.key=e,this.redraw()},setCartoCSS:function(e){if(!this.renderer)throw new Error("renderer is not valid");return this.renderer.setCartoCSS(e)}}),e.torque.GMapsTiledTorqueLayer=n,e.torque.GMapsTorqueLayer=t}(typeof exports=="undefined"?this:exports),typeof L!="undefined"&&(L.Mixin.TileLoader={_initTileLoader:function(){this._tiles={},this._tilesToLoad=0,this._map.on({moveend:this._updateTiles},this),this._updateTiles()},_removeTileLoader:function(){this._map.off({moveend:this._updateTiles},this),this._removeTiles()},_updateTiles:function(){if(!this._map)return;var e=this._map.getPixelBounds(),t=this._map.getZoom(),n=this.options.tileSize;if(t>this.options.maxZoom||t<this.options.minZoom)return;var r=new L.Point(Math.floor(e.min.x/n),Math.floor(e.min.y/n)),i=new L.Point(Math.floor(e.max.x/n),Math.floor(e.max.y/n)),s=new L.Bounds(r,i);this._addTilesFromCenterOut(s),this._removeOtherTiles(s)},_removeTiles:function(e){for(var t in this._tiles)this._removeTile(t)},_reloadTiles:function(){this._removeTiles(),this._updateTiles()},_removeOtherTiles:function(e){var t,n,r,i,s,o=this._map.getZoom();for(s in this._tiles)this._tiles.hasOwnProperty(s)&&(t=s.split(":"),n=parseInt(t[0],10),r=parseInt(t[1],10),i=parseInt(t[2],10),(o!==i||n<e.min.x||n>e.max.x||r<e.min.y||r>e.max.y)&&this._removeTile(s))},_removeTile:function(e){this.fire("tileRemoved",this._tiles[e]),delete this._tiles[e]},_tileShouldBeLoaded:function(e){return!(e.x+":"+e.y+":"+e.zoom in this._tiles)},_tileLoaded:function(e,t){this._tilesToLoad--,this._tiles[e.x+":"+e.y+":"+e.zoom]=t,this._tilesToLoad===0&&this.fire("tilesLoaded")},getTilePos:function(e){e=new L.Point(e.x,e.y);var t=this._map._getNewTopLeftPoint(this._map.getCenter()),n=this.options.tileSize;return e.multiplyBy(n).subtract(t)},_addTilesFromCenterOut:function(e){var t=[],n=e.getCenter(),r=this._map.getZoom(),i,s,o;for(i=e.min.y;i<=e.max.y;i++)for(s=e.min.x;s<=e.max.x;s++)o=new L.Point(s,i),o.zoom=r,this._tileShouldBeLoaded(o)&&t.push(o);var u=t.length;if(u===0)return;t.sort(function(e,t){return e.distanceTo(n)-t.distanceTo(n)}),this._tilesToLoad+=u;for(s=0;s<u;s++)this.fire("tileAdded",t[s])}}),typeof L!="undefined"&&(L.CanvasLayer=L.Class.extend({includes:[L.Mixin.Events,L.Mixin.TileLoader],options:{minZoom:0,maxZoom:28,tileSize:256,subdomains:"abc",errorTileUrl:"",attribution:"",zoomOffset:0,opacity:1,unloadInvisibleTiles:L.Browser.mobile,updateWhenIdle:L.Browser.mobile,tileLoader:!1},initialize:function(e){var t=this;e=e||{},this.render=this.render.bind(this),L.Util.setOptions(this,e),this._canvas=document.createElement("canvas"),this._canvas.style.position="absolute",this._canvas.style.top=0,this._canvas.style.left=0,this._canvas.style.zIndex=e.zIndex||0,this._ctx=this._canvas.getContext("2d");var n=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||function(e){return window.setTimeout(e,1e3/60)};this.requestAnimationFrame=n},onAdd:function(e){this._map=e,e._panes.staticPane||(e._panes.staticPane=e._createPane("leaflet-tile-pane",e._container)),this._staticPane=e._panes.staticPane,this._staticPane.appendChild(this._canvas),e.on({viewreset:this._reset},this),e.on("move",this._render,this),e.on("resize",this._reset,this),this.options.tileLoader&&this._initTileLoader(),this._reset()},getCanvas:function(){return this._canvas},getAttribution:function(){return this.options.attribution},draw:function(){return this._reset()},onRemove:function(e){e._container.removeChild(this._staticPane),e.off({viewreset:this._reset,move:this._render,resize:this._reset},this)},addTo:function(e){return e.addLayer(this),this},setOpacity:function(e){return this.options.opacity=e,this._updateOpacity(),this},setZIndex:function(e){this._canvas.style.zIndex=e},bringToFront:function(){return this},bringToBack:function(){return this},_reset:function(){var e=this._map.getSize();this._canvas.width=e.x,this._canvas.height=e.y,this.onResize(),this._render()},_updateOpacity:function(){},_render:function(){this.requestAnimationFrame.call(window,this.render)},redraw:function(){this._render()},onResize:function(){},render:function(){throw new Error("render function should be implemented")}})),typeof L!="undefined"&&(L.TorqueLayer=L.CanvasLayer.extend({providers:{sql_api:torque.providers.json,url_template:torque.providers.jsonarray},renderers:{point:torque.renderer.Point,pixel:torque.renderer.Rectangle},initialize:function(e){var t=this;if(!torque.isBrowserSupported())throw new Error("browser is not supported by torque");e.tileLoader=!0,this.key=0,e.cartocss&&_.extend(e,torque.common.TorqueLayer.optionsFromCartoCSS(e.cartocss)),e.resolution=e.resolution||2,e.steps=e.steps||100,e.visible=e.visible===undefined?!0:e.visible,this.hidden=!e.visible,this.animator=new torque.Animator(function(e){var n=e|0;t.key!==n&&t.setKey(n)},e),this.play=this.animator.start.bind(this.animator),this.stop=this.animator.stop.bind(this.animator),this.pause=this.animator.pause.bind(this.animator),this.toggle=this.animator.toggle.bind(this.animator),this.setDuration=this.animator.duration.bind(this.animator),this.isRunning=this.animator.isRunning.bind(this.animator),L.CanvasLayer.prototype.initialize.call(this,e),this.options.renderer=this.options.renderer||"point",this.options.provider=this.options.provider||"sql_api",e.ready=function(){t.fire("change:bounds",{bounds:t.provider.getBounds()}),t.animator.steps(t.provider.getSteps()),t.animator.rescale(),t.fire("change:steps",{steps:t.provider.getSteps()}),t.setKey(t.key)},this.provider=new this.providers[this.options.provider](e),this.renderer=new this.renderers[this.options.renderer](this.getCanvas(),e),this.on("tileAdded",function(e){var n=this.provider.getTileData(e,e.zoom,function(n){if(e.zoom!==t._map.getZoom())return;t._tileLoaded(e,n),n&&t.redraw()})},this)},_clearCaches:function(){this.renderer&&this.renderer.clearSpriteCache()},onAdd:function(e){e.on({zoomend:this._clearCaches},this),L.CanvasLayer.prototype.onAdd.call(this,e)},onRemove:function(e){this._removeTileLoader(),e.off({zoomend:this._clearCaches},this),L.CanvasLayer.prototype.onRemove.call(this,e)},hide:function(){return this.hidden?this:(this.pause(),this.clear(),this.hidden=!0,this)},show:function(){return this.hidden?(this.hidden=!1,this.play(),this):this},setSQL:function(e){if(!this.provider||!this.provider.setSQL)throw new Error("this provider does not support SQL");return this.provider.setSQL(e),this._reloadTiles(),this},setBlendMode:function(e){this.renderer.setBlendMode(e),this.redraw()},setSteps:function(e){this.provider.setSteps(e),this._reloadTiles()},setColumn:function(e,t){this.provider.setColumn(e,t),this._reloadTiles()},getTimeBounds:function(){return this.provider&&this.provider.getKeySpan()},clear:function(){var e=this.getCanvas();e.width=e.width},render:function(){if(this.hidden)return;var e,t,n,r=this.getCanvas();r.width=r.width;var i=r.getContext("2d");for(e in this._tiles)t=this._tiles[e],t&&(n=this.getTilePos(t.coord),i.setTransform(1,0,0,1,n.x,n.y),this.renderer.renderTile(t,this.key,n.x,n.y))},setKey:function(e){this.key=e,this.animator.step(e),this.redraw(),this.fire("change:time",{time:this.getTime(),step:this.key})},setStep:function(e){if(e===undefined||e.length!==undefined)throw new Error("setTime only accept scalars");this.setKey(e)},stepToTime:function(e){var t=this.provider.getKeySpan(),n=t.start+(t.end-t.start)*(e/this.provider.getSteps());return new Date(n)},getStep:function(){return this.key},getTime:function(){return this.stepToTime(this.key)},getTimeSpan:function(){var e=this.provider.getKeySpan()},setCartoCSS:function(e){if(!this.renderer)throw new Error("renderer is not valid");var t=(new carto.RendererJS).render(e);this.renderer.setShader(t);var n=torque.common.TorqueLayer.optionsFromLayer(t.findLayer({name:"Map"}));return this.provider.setOptions(n)&&this._reloadTiles(),_.extend(this.options,n),n.animationDuration&&this.animator.duration(n.animationDuration),this.redraw(),this}}),L.TiledTorqueLayer=L.TileLayer.Canvas.extend({providers:{sql_api:torque.providers.json,url_template:torque.providers.JsonArray},renderers:{point:torque.renderer.Point,pixel:torque.renderer.Rectangle},initialize:function(e){var t=this;this.key=0,e.async=!0,L.TileLayer.Canvas.prototype.initialize.call(this,e),this.options.renderer=this.options.renderer||"pixel",this.options.provider=this.options.provider||"sql_api",this.provider=new this.providers[this.options.provider](e),this.renderer=new this.renderers[this.options.renderer](null,e)},_tileLoaded:function(e,t,n){this._tiles[t.x+":"+t.y]!==undefined&&(this._tiles[t.x+":"+t.y].data=n,this.drawTile(e)),L.TileLayer.Canvas.prototype._tileLoaded.call(this)},redraw:function(){for(var e in this._tiles)this._redrawTile(this._tiles[e])},_loadTile:function(e,t){var n=this;L.TileLayer.Canvas.prototype._loadTile.apply(this,arguments);var r=t.clone();this._adjustTilePoint(r),this.provider.getTileData(r,this._map.getZoom(),function(r){n._tileLoaded(e,t,r),L.DomUtil.addClass(e,"leaflet-tile-loaded")})},drawTile:function(e){var t=e;if(!e.data)return;t.width=t.width,this.renderer.setCanvas(t);var n=this.renderer.accumulate(e.data,this.key);this.renderer.renderTileAccum(n,0,0)},setKey:function(e){this.key=e,this.redraw()},setCartoCSS:function(e){if(!this.renderer)throw new Error("renderer is not valid");return this.renderer.setCartoCSS(e)}}));