492b57ed873c982bdd1ee53759b923dc0a0136ac
[potlatch2.git] / net / systemeD / halcyon / Map.as
1 package net.systemeD.halcyon {
2
3         import flash.text.TextField;
4         import flash.geom.Rectangle;
5         import flash.display.DisplayObjectContainer;
6         import flash.display.Loader;
7         import flash.display.Sprite;
8         import flash.display.Shape;
9         import flash.display.Stage;
10         import flash.display.BitmapData;
11         import flash.display.LoaderInfo;
12         import flash.text.Font;
13         import flash.utils.ByteArray;
14         import flash.events.*;
15         import flash.net.*;
16     import flash.external.ExternalInterface;
17
18     import net.systemeD.halcyon.connection.*;
19     import net.systemeD.halcyon.connection.EntityEvent;
20         import net.systemeD.halcyon.styleparser.*;
21         import net.systemeD.halcyon.Globals;
22         import flash.ui.Keyboard;
23
24 //      for experimental export function:
25 //      import flash.net.FileReference;
26 //      import com.adobe.images.JPGEncoder;
27
28     /** The representation of part of the map on the screen, including information about coordinates, background imagery, paint properties etc. */
29     public class Map extends Sprite {
30
31                 /** master map scale - how many Flash pixels in 1 degree longitude (for Landsat, 5120) */
32                 public const MASTERSCALE:Number=5825.4222222222; 
33                                                                                                 
34                 /** don't zoom out past this */
35                 public const MINSCALE:uint=13; 
36                 /** don't zoom in past this */
37                 public const MAXSCALE:uint=23; 
38
39                 /** sprite for ways and (POI/tagged) nodes in core layer */
40                 public var paint:MapPaint;                                               
41                 /** sprite for vector background layers */
42                 public var vectorbg:Sprite;
43
44                 /** map scale */
45                 public var scale:uint=14;                                                
46                 /** current scaling factor for lon/latp */
47                 public var scalefactor:Number=MASTERSCALE;
48                 public var bigedge_l:Number= 999999;                    // area of largest whichways
49                 public var bigedge_r:Number=-999999;                    //  |
50                 public var bigedge_b:Number= 999999;                    //  |
51                 public var bigedge_t:Number=-999999;                    //  |
52
53                 public var edge_l:Number;                                               // current bounding box
54                 public var edge_r:Number;                                               //  |
55                 public var edge_t:Number;                                               //  |
56                 public var edge_b:Number;                                               //  |
57                 public var centre_lat:Number;                                   // centre lat/lon
58                 public var centre_lon:Number;                                   //  |
59
60                 /** urllon-xradius/masterscale; */ 
61                 public var baselon:Number;
62                 /** lat2lat2p(urllat)+yradius/masterscale; */
63                 public var basey:Number; 
64                 /** width (Flash pixels) */
65                 public var mapwidth:uint; 
66                 /** height (Flash pixels) */
67                 public var mapheight:uint; 
68
69                 /** Is the map being panned */
70                 public var dragstate:uint=NOT_DRAGGING;                 // dragging map (panning)
71                 /** Can the map be panned */
72                 private var _draggable:Boolean=true;                    //  |
73                 private var lastxmouse:Number;                                  //  |
74                 private var lastymouse:Number;                                  //  |
75                 private var downX:Number;                                               //  |
76                 private var downY:Number;                                               //  |
77                 private var downTime:Number;                                    //  |
78                 public const NOT_DRAGGING:uint=0;                               //  |
79                 public const NOT_MOVED:uint=1;                                  //  |
80                 public const DRAGGING:uint=2;                                   //  |
81                 /** How far the map can be dragged without actually triggering a pan. */
82                 public const TOLERANCE:uint=7;                                  //  |
83                 
84                 /** object containing HTML page parameters */
85                 public var initparams:Object; 
86
87                 /** reference to backdrop sprite */
88                 public var backdrop:Object; 
89                 /** background tile object */
90                 public var tileset:TileSet; 
91                 /** background tile URL, name and scheme */
92                 private var tileparams:Object={ url:'' }; 
93                 /** internal style URL */
94                 private var styleurl:String=''; 
95                 /** show all objects, even if unstyled? */
96                 public var showall:Boolean=true; 
97                 
98                 /** server connection */
99                 public var connection:Connection; 
100                 /** VectorLayer objects */
101                 public var vectorlayers:Object={};  
102                 
103                 /** Should the position of mouse cursor be shown to the user? */
104                 private var showingLatLon:Boolean=false;  
105                 
106                 // ------------------------------------------------------------------------------------------
107                 /** Map constructor function */
108         public function Map(initparams:Object) {
109
110                         this.initparams=initparams;
111                         connection = Connection.getConnection(initparams);
112             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
113             connection.addEventListener(Connection.NEW_POI, newPOICreated);
114             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumbered);
115             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumbered);
116                         gotEnvironment(null);
117
118                         addEventListener(Event.ENTER_FRAME, everyFrame);
119                         scrollRect=new Rectangle(0,0,800,600);
120         }
121
122                 public function gotEnvironment(r:Object):void {
123                         var loader:Loader = new Loader();
124                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotFont);
125                         loader.load(new URLRequest("FontLibrary.swf"));
126                 }
127                 
128                 public function gotFont(r:Event):void {
129                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
130                         Font.registerFont(FontLibrary.DejaVu);
131
132                         if (initparams['lat'] != null) {
133                                 // parameters sent from HTML
134                                 init(initparams['lat'],
135                                          initparams['lon'],
136                                          initparams['zoom']);
137
138                         } else {
139                                 // somewhere innocuous
140                                 init(53.09465,-2.56495,17);
141                         }
142                 }
143
144                 // ------------------------------------------------------------------------------------------
145                 /** Initialise map at a given lat/lon */
146         public function init(startlat:Number, startlon:Number, startscale:uint=0):void {
147                         while (numChildren) { removeChildAt(0); }
148
149                         tileset=new TileSet(this);                                      // 0 - 900913 background
150                         if (initparams['tileblocks']) {                         //   | option to block dodgy tile sources
151                                 tileset.blocks=initparams['tileblocks'];//   |
152                         }                                                                                       //   |
153                         addChild(tileset);                                                      //   |
154                         tileset.init(tileparams, false, 
155                                      initparams['background_dim']    ==null ? true  : initparams['background_dim'],
156                                      initparams['background_sharpen']==null ? false : initparams['background_sharpen']);
157
158                         vectorbg = new Sprite();                                        // 1 - vector background layers
159                         addChild(vectorbg);                                                     //   |
160
161                         paint = new MapPaint(this,-5,5);                        // 2 - core paint object
162                         addChild(paint);                                                        //   |
163                         paint.isBackground=false;                                       //   |
164
165                         if (styleurl) {                                                         // if we've only just set up paint, then setStyle won't have created the RuleSet
166                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
167                                 paint.ruleset.loadFromCSS(styleurl);
168                         }
169                         if (startscale>0) {
170                                 scale=startscale;
171                                 this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
172                         }
173
174                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
175                         baselon    =startlon          -(mapwidth /2)/scalefactor;
176                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
177                         addDebug("Baselon "+baselon+", basey "+basey);
178                         updateCoords(0,0);
179             this.dispatchEvent(new Event(MapEvent.INITIALISED));
180                         download();
181
182             if (ExternalInterface.available) {
183               ExternalInterface.addCallback("setPosition", function (lat:Number,lon:Number,zoom:uint):void {
184                   updateCoordsFromLatLon(lat, lon);
185                   changeScale(zoom);
186               });
187             }
188         }
189
190                 // ------------------------------------------------------------------------------------------
191                 /** Recalculate co-ordinates from new Flash origin */
192
193                 public function updateCoords(tx:Number,ty:Number):void {
194                         setScrollRectXY(tx,ty);
195
196                         edge_t=coord2lat(-ty          );
197                         edge_b=coord2lat(-ty+mapheight);
198                         edge_l=coord2lon(-tx          );
199                         edge_r=coord2lon(-tx+mapwidth );
200                         setCentre();
201
202                         tileset.update();
203                 }
204                 
205                 /** Move the map to centre on a given latitude/longitude. */
206                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
207                         var cy:Number=-(lat2coord(lat)-mapheight/2);
208                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
209                         updateCoords(cx,cy);
210                 }
211                 
212                 private function setScrollRectXY(tx:Number,ty:Number):void {
213                         var w:Number=scrollRect.width;
214                         var h:Number=scrollRect.height;
215                         scrollRect=new Rectangle(-tx,-ty,w,h);
216                 }
217                 private function setScrollRectSize(width:Number,height:Number):void {
218                         var sx:Number=scrollRect.x ? scrollRect.x : 0;
219                         var sy:Number=scrollRect.y ? scrollRect.y : 0;
220                         scrollRect=new Rectangle(sx,sy,width,height);
221                 }
222                 
223                 private function getX():Number { return -scrollRect.x; }
224                 private function getY():Number { return -scrollRect.y; }
225                 
226                 private function setCentre():void {
227                         centre_lat=coord2lat(-getY()+mapheight/2);
228                         centre_lon=coord2lon(-getX()+mapwidth/2);
229                         this.dispatchEvent(new MapEvent(MapEvent.MOVE, {lat:centre_lat, lon:centre_lon, scale:scale, minlon:edge_l, maxlon:edge_r, minlat:edge_b, maxlat:edge_t}));
230                 }
231                 
232                 /** Sets the offset between the background imagery and the map. */
233                 public function nudgeBackground(x:Number,y:Number):void {
234                         this.dispatchEvent(new MapEvent(MapEvent.NUDGE_BACKGROUND, { x: x, y: y }));
235                 }
236
237                 private function moveMap(dx:Number,dy:Number):void {
238                         updateCoords(getX()+dx,getY()+dy);
239                         updateEntityUIs(false, false);
240                         download();
241                 }
242                 
243                 /** Recentre map at given lat/lon, updating the UI and downloading entities. */
244                 public function moveMapFromLatLon(lat:Number,lon:Number):void {
245                         updateCoordsFromLatLon(lat,lon);
246                         updateEntityUIs(false,false);
247                         download();
248                 }
249
250                 // Co-ordinate conversion functions
251
252                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
253                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
254                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
255                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
256
257                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
258                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
259
260                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
261                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
262
263
264                 // ------------------------------------------------------------------------------------------
265                 /** Resize map size based on current stage and height */
266
267                 public function updateSize(w:uint, h:uint):void {
268                         mapwidth = w; centre_lon=coord2lon(-getX()+w/2);
269                         mapheight= h; centre_lat=coord2lat(-getY()+h/2);
270                         setScrollRectSize(w,h);
271
272                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
273                         
274             if ( backdrop != null ) {
275                 backdrop.width=mapwidth;
276                 backdrop.height=mapheight;
277             }
278             if ( mask != null ) {
279                 mask.width=mapwidth;
280                 mask.height=mapheight;
281             }
282                 }
283
284         /** Download map data. Data is downloaded for the connection and the vector layers, where supported.
285         * The bounding box for the download is taken from the current map edges.
286         */
287                 public function download():void {
288                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
289                         
290                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
291                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
292                         bigedge_l=edge_l; bigedge_r=edge_r;
293                         bigedge_b=edge_b; bigedge_t=edge_t;
294                         if (connection.waycount>1000) {
295                                 connection.purgeOutside(edge_l,edge_r,edge_t,edge_b);
296                         }
297                         addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
298                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
299
300             // Do the same for vector layers
301             for each (var layer:VectorLayer in vectorlayers) {
302               layer.loadBbox(edge_l,edge_r,edge_t,edge_b);
303             }
304                 }
305
306         private function newWayCreated(event:EntityEvent):void {
307             var way:Way = event.entity as Way;
308                         if (!way.loaded || !way.within(edge_l,edge_r,edge_t,edge_b)) { return; }
309                         paint.createWayUI(way);
310         }
311
312         private function newPOICreated(event:EntityEvent):void {
313             var node:Node = event.entity as Node;
314                         if (!node.within(edge_l,edge_r,edge_t,edge_b)) { return; }
315                         paint.createNodeUI(node);
316         }
317
318                 private function wayRenumbered(event:EntityRenumberedEvent):void {
319             var way:Way = event.entity as Way;
320                         paint.renumberWayUI(way,event.oldID);
321                 }
322
323                 private function nodeRenumbered(event:EntityRenumberedEvent):void {
324             var node:Node = event.entity as Node;
325                         paint.renumberNodeUI(node,event.oldID);
326                 }
327
328         /** Visually mark an entity as highlighted. */
329         public function setHighlight(entity:Entity, settings:Object):void {
330                         if      ( entity is Way  && paint.wayuis[entity.id] ) { paint.wayuis[entity.id].setHighlight(settings);  }
331                         else if ( entity is Node && paint.nodeuis[entity.id]) { paint.nodeuis[entity.id].setHighlight(settings); }
332         }
333
334         public function setHighlightOnNodes(way:Way, settings:Object):void {
335                         if (paint.wayuis[way.id]) paint.wayuis[way.id].setHighlightOnNodes(settings);
336         }
337
338                 public function protectWay(way:Way):void {
339                         if (paint.wayuis[way.id]) paint.wayuis[way.id].protectSprites();
340                 }
341
342                 public function unprotectWay(way:Way):void {
343                         if (paint.wayuis[way.id]) paint.wayuis[way.id].unprotectSprites();
344                 }
345                 
346                 public function limitWayDrawing(way:Way,except:Number=NaN,only:Number=NaN):void {
347                         if (!paint.wayuis[way.id]) return;
348                         paint.wayuis[way.id].drawExcept=except;
349                         paint.wayuis[way.id].drawOnly  =only;
350                         paint.wayuis[way.id].redraw();
351                 }
352
353                 /** Protect Entities and EntityUIs against purging. This prevents the currently selected items
354                    from being purged even though they're off-screen. */
355
356                 public function setPurgable(entities:Array, purgable:Boolean):void {
357                         for each (var entity:Entity in entities) {
358                                 entity.locked=!purgable;
359                                 if ( entity is Way  ) {
360                                         var way:Way=entity as Way;
361                                         if (paint.wayuis[way.id]) { paint.wayuis[way.id].purgable=purgable; }
362                                         for (var i:uint=0; i<way.length; i++) {
363                                                 var node:Node=way.getNode(i)
364                                                 node.locked=!purgable;
365                                                 if (paint.nodeuis[node.id]) { paint.nodeuis[node.id].purgable=purgable; }
366                                         }
367                                 } else if ( entity is Node && paint.nodeuis[entity.id]) { 
368                                         paint.nodeuis[entity.id].purgable=purgable;
369                                 }
370                         }
371                 }
372
373         // Handle mouse events on ways/nodes
374         private var mapController:MapController = null;
375
376         /** Assign map controller. */
377         public function setController(controller:MapController):void {
378             this.mapController = controller;
379         }
380
381         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
382             if ( mapController != null )
383                 mapController.entityMouseEvent(event, entity);
384                                 
385         }
386
387                 // ------------------------------------------------------------------------------------------
388                 // Add vector layer
389                 
390                 public function addVectorLayer(layer:VectorLayer):void {
391                         vectorlayers[layer.name]=layer;
392                         vectorbg.addChild(layer.paint);
393                 }
394
395                 // ------------------------------------------------------------------------------------------
396                 // Redraw all items, zoom in and out
397                 
398                 public function updateEntityUIs(redraw:Boolean,remove:Boolean):void {
399                         paint.updateEntityUIs(connection.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
400                         for each (var v:VectorLayer in vectorlayers) {
401                                 v.paint.updateEntityUIs(v.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
402                         }
403                 }
404                 /** Redraw everything, including in every vector layer. */
405                 public function redraw():void {
406                         paint.redraw();
407                         for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
408                 }
409                 /** Redraw POI's, including in every vector layer. */
410                 public function redrawPOIs():void { 
411                         paint.redrawPOIs();
412                         for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
413                 }
414                 
415                 /** Increase scale. */
416                 public function zoomIn():void {
417                         if (scale==MAXSCALE) { return; }
418                         changeScale(scale+1);
419                 }
420
421                 /** Decrease scale. */
422                 public function zoomOut():void {
423                         if (scale==MINSCALE) { return; }
424                         changeScale(scale-1);
425                 }
426
427                 private function changeScale(newscale:uint):void {
428                         addDebug("new scale "+newscale);
429                         scale=newscale;
430                         this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
431                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
432                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
433                         tileset.changeScale(scale);
434                         updateEntityUIs(true,true);
435                         download();
436                 }
437
438                 private function reportPosition():void {
439                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
440                 }
441
442         private function toggleReportPosition():void {
443             showingLatLon = !showingLatLon;
444             this.dispatchEvent(new MapEvent(MapEvent.TOGGLE_LATLON, {latlon: showingLatLon}));
445         }
446                 
447                 /** Switch to new MapCSS. */
448                 public function setStyle(url:String):void {
449                         styleurl=url;
450                         if (paint) { 
451                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
452                                 paint.ruleset.loadFromCSS(url);
453                         }
454         }
455
456                 /** Select a new background imagery. */
457                 public function setBackground(bg:Object):void {
458                         tileparams=bg;
459                         if (tileset) { tileset.init(bg, bg.url!=''); }
460                 }
461
462                 /** Set background dimming on/off. */
463                 public function setDimming(dim:Boolean):void {
464                         if (tileset) { tileset.setDimming(dim); }
465                 }
466                 
467                 /** Return background dimming. */
468                 public function getDimming():Boolean {
469                         if (tileset) { return tileset.getDimming(); }
470                         return true;
471                 }
472
473                 /** Set background sharpening on/off. */
474                 public function setSharpen(sharpen:Boolean):void {
475                         if (tileset) { tileset.setSharpen(sharpen); }
476                 }
477                 /** Return background sharpening. */
478                 public function getSharpen():Boolean {
479                         if (tileset) { return tileset.getSharpen(); }
480                         return false;
481                 }
482
483                 // ------------------------------------------------------------------------------------------
484                 // Export (experimental)
485                 // ** just a bit of fun for now!
486                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
487                 // to that area (will probably require creating a new DisplayObject with a different origin
488                 // and mask)
489 /*              
490                 public function export():void {
491                         addDebug("size is "+this.width+","+this.height);
492                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
493                         jpgSource.draw(this);
494                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
495                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
496                         var fileRef:FileReference = new FileReference();
497 //                      fileRef.save(jpgStream,'map.jpeg');
498                 }
499
500 */
501
502                 // ==========================================================================================
503                 // Events
504                 
505                 // ------------------------------------------------------------------------------------------
506                 // Mouse events
507                 
508                 /** Should map be allowed to pan? */
509                 public function set draggable(draggable:Boolean):void {
510                         _draggable=draggable;
511                         dragstate=NOT_DRAGGING;
512                 }
513
514                 /** Prepare for being dragged by recording start time and location of mouse. */
515                 public function mouseDownHandler(event:MouseEvent):void {
516                         if (!_draggable) { return; }
517                         dragstate=NOT_MOVED;
518                         lastxmouse=stage.mouseX; downX=stage.mouseX;
519                         lastymouse=stage.mouseY; downY=stage.mouseY;
520                         downTime=new Date().getTime();
521                 }
522         
523                 /** Respond to mouse up by possibly moving map. */
524                 public function mouseUpHandler(event:MouseEvent=null):void {
525                         if (dragstate==DRAGGING) { moveMap(x,y); }
526                         dragstate=NOT_DRAGGING;
527                 }
528         
529                 /** Respond to mouse movement, dragging the map if tolerance threshold met. */
530                 public function mouseMoveHandler(event:MouseEvent):void {
531                         if (!_draggable) { return; }
532                         if (dragstate==NOT_DRAGGING) { 
533                            this.dispatchEvent(new MapEvent(MapEvent.MOUSEOVER, { x: coord2lon(mouseX), y: coord2lat(mouseY) }));
534                return; 
535             }
536                         
537                         if (dragstate==NOT_MOVED) {
538                                 if (new Date().getTime()-downTime<300) {
539                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE   && Math.abs(downY-stage.mouseY)<=TOLERANCE  ) return;
540                                 } else {
541                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE/2 && Math.abs(downY-stage.mouseY)<=TOLERANCE/2) return;
542                                 }
543                                 dragstate=DRAGGING;
544                         }
545                         
546                         setScrollRectXY(getX()+stage.mouseX-lastxmouse,getY()+stage.mouseY-lastymouse);
547                         lastxmouse=stage.mouseX; lastymouse=stage.mouseY;
548                         setCentre();
549                 }
550         
551                 // ------------------------------------------------------------------------------------------
552                 // Do every frame
553
554                 private function everyFrame(event:Event):void {
555                         if (tileset) { tileset.serviceQueue(); }
556                 }
557
558                 // ------------------------------------------------------------------------------------------
559                 // Miscellaneous events
560                 
561                 /** Respond to cursor movements and zoom in/out.*/
562                 public function keyUpHandler(event:KeyboardEvent):void {
563                         if (event.target is TextField) return;                          // not meant for us
564                         switch (event.keyCode) {
565                                 case Keyboard.PAGE_UP:  zoomIn(); break;                 // Page Up - zoom in
566                                 case Keyboard.PAGE_DOWN:        zoomOut(); break;            // Page Down - zoom out
567                                 case Keyboard.LEFT:     moveMap(mapwidth/2,0); break;        // left cursor
568                                 case Keyboard.UP:       moveMap(0,mapheight/2); break;           // up cursor
569                                 case Keyboard.RIGHT:    moveMap(-mapwidth/2,0); break;   // right cursor
570                                 case Keyboard.DOWN:     moveMap(0,-mapheight/2); break;      // down cursor
571                                 case 76:        toggleReportPosition(); break;                  // L - report lat/long
572                         }
573                 }
574
575                 /** What to do if an error with the network connection happens. */
576                 public function connectionError(err:Object=null): void {
577                         addDebug("got error"); 
578                 }
579
580                 // ------------------------------------------------------------------------------------------
581                 // Debugging
582                 
583                 public function clearDebug():void {
584                         if (!Globals.vars.hasOwnProperty('debug')) return;
585                         Globals.vars.debug.text='';
586                 }
587                         
588                 public function addDebug(text:String):void {
589                         trace(text);
590                         if (!Globals.vars.hasOwnProperty('debug')) return;
591                         if (!Globals.vars.debug.visible) return;
592                         Globals.vars.debug.appendText(text+"\n");
593                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
594                 }
595
596         }
597 }