-
Notifications
You must be signed in to change notification settings - Fork 9
/
mapstraction.js
5171 lines (4721 loc) · 160 KB
/
mapstraction.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2006-8, Tom Carden, Steve Coast, Mikel Maron, Andrew Turner, Henri Bergius, Rob Moran
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Mapstraction nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Revision: $Revision: 194 $
// Use http://jsdoc.sourceforge.net/ to generate documentation
/** @mapstraction */
(function(){
////////////////////////////
//
// utility to functions, TODO namespace or remove before release
//
///////////////////////////
/**
* $m, the dollar function, elegantising getElementById()
* @return An HTML element or array of HTML elements
*/
function $m() {
var elements = [];
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof(element) == 'string') {
element = document.getElementById(element);
}
if (arguments.length == 1) {
return element;
}
elements.push(element);
}
return elements;
}
/**
* loadScript is a JSON data fetcher
* @param {String} src URL to JSON file
* @param {Function} callback Callback function
*/
function loadScript(src, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
if (callback) {
var evl = {};
evl.handleEvent = function(e) {
callback();
};
script.addEventListener('load' ,evl ,true);
}
document.getElementsByTagName('head')[0].appendChild(script);
return;
}
/**
*
* @param {Object} point
* @param {Object} level
*/
function convertLatLonXY_Yahoo(point, level) { //Mercator
var size = 1 << (26 - level);
var pixel_per_degree = size / 360.0;
var pixel_per_radian = size / (2 * Math.PI);
var origin = new YCoordPoint(size / 2 , size / 2);
var answer = new YCoordPoint();
answer.x = Math.floor(origin.x + point.lon * pixel_per_degree);
var sin = Math.sin(point.lat * Math.PI / 180.0);
answer.y = Math.floor(origin.y + 0.5 * Math.log((1 + sin) / (1 - sin)) * -pixel_per_radian);
return answer;
}
/**
* Load a stylesheet from a remote file.
* @param {String} href URL to the CSS file
*/
function loadStyle(href) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = href;
document.getElementsByTagName('head')[0].appendChild(link);
return;
}
/**
* getStyle provides cross-browser access to css
* @param {Object} el HTML Element
* @param {String} prop Style property name
*/
function getStyle(el, prop) {
var y;
if (el.currentStyle) {
y = el.currentStyle[prop];
}
else if (window.getComputedStyle) {
y = window.getComputedStyle( el, '').getPropertyValue(prop);
}
return y;
}
/**
* Convert longitude to metres
* http://www.uwgb.edu/dutchs/UsefulData/UTMFormulas.HTM
* "A degree of longitude at the equator is 111.2km... For other latitudes,
* multiply by cos(lat)"
* assumes the earth is a sphere but good enough for our purposes
* @param {Float} lon
* @param {Float} lat
*/
function lonToMetres(lon, lat) {
return lon * (111200 * Math.cos(lat * (Math.PI / 180)));
}
/**
* Convert metres to longitude
* @param {Object} m
* @param {Object} lat
*/
function metresToLon(m, lat) {
return m / (111200 * Math.cos(lat * (Math.PI / 180)));
}
/**
* Convert kilometres to miles
* @param {Float} km
* @returns {Float} miles
*/
function KMToMiles(km) {
return km / 1.609344;
}
/**
* Convert miles to kilometres
* @param {Float} miles
* @returns {Float} km
*/
function milesToKM(miles) {
return miles * 1.609344;
}
// stuff to convert google zoom levels to/from degrees
// assumes zoom 0 = 256 pixels = 360 degrees
// zoom 1 = 256 pixels = 180 degrees
// etc.
/**
*
* @param {Object} pixels
* @param {Object} zoom
*/
function getDegreesFromGoogleZoomLevel(pixels, zoom) {
return (360 * pixels) / (Math.pow(2, zoom + 8));
}
/**
*
* @param {Object} pixels
* @param {Object} degrees
*/
function getGoogleZoomLevelFromDegrees(pixels, degrees) {
return logN((360 * pixels) / degrees, 2) - 8;
}
/**
*
* @param {Object} number
* @param {Object} base
*/
function logN(number, base) {
return Math.log(number) / Math.log(base);
}
/////////////////////////////
//
// Mapstraction proper begins here
//
/////////////////////////////
/**
* Mapstraction instantiates a map with some API choice into the HTML element given
* @param {String} element The HTML element to replace with a map
* @param {String} api The API to use, one of 'google', 'yahoo', 'microsoft', 'openstreetmap', 'multimap', 'map24', 'openlayers', 'mapquest'
* @param {Bool} debug optional parameter to turn on debug support - this uses alert panels for unsupported actions
* @constructor
*/
function Mapstraction(element,api,debug) {
this.api = api; // could detect this from imported scripts?
this.maps = {};
this.currentElement = $m(element);
this.eventListeners = [];
this.markers = [];
this.layers = [];
this.polylines = [];
this.images = [];
this.loaded = {};
this.onload = {};
// Mapstraction.writeInclude(api, "nothing");
// optional debug support
if (debug === true) {
this.debug = true;
}
else {
this.debug = false;
}
// This is so that it is easy to tell which revision of this file
// has been copied into other projects.
this.svn_revision_string = '$Revision: 194 $';
this.addControlsArgs = {};
// if (this.currentElement) {
this.addAPI($m(element), api);
// }
}
/**
* Change the current api on the fly
* @param {String} api The API to swap to
* @param element
*/
Mapstraction.prototype.swap = function(element,api) {
if (this.api == api) {
return;
}
var center = this.getCenter();
var zoom = this.getZoom();
this.currentElement.style.visibility = 'hidden';
this.currentElement.style.display = 'none';
this.currentElement = $m(element);
this.currentElement.style.visibility = 'visible';
this.currentElement.style.display = 'block';
this.api = api;
if (this.maps[this.api] === undefined) {
this.addAPI($m(element),api);
this.setCenterAndZoom(center,zoom);
for (var i = 0; i < this.markers.length; i++) {
this.addMarker(this.markers[i], true);
}
for (var j = 0; j < this.polylines.length; j++) {
this.addPolyline( this.polylines[j], true);
}
}
else {
//sync the view
this.setCenterAndZoom(center,zoom);
//TODO synchronize the markers and polylines too
// (any overlays created after api instantiation are not sync'd)
}
this.addControls(this.addControlsArgs);
};
/**
*
* @param {Object} element
* @param {String} api
*/
Mapstraction.prototype.addAPI = function(element,api) {
this.loaded[api] = false;
this.onload[api] = [];
var me = this;
switch (api) {
case 'yahoo':
if (YMap) {
this.maps[api] = new YMap(element);
YEvent.Capture(this.maps[api], EventsList.MouseClick, function(event,location) {
me.clickHandler(location.Lat, location.Lon, location, me);
});
YEvent.Capture(this.maps[api], EventsList.changeZoom, function() {
me.moveendHandler(me);
});
YEvent.Capture(this.maps[api], EventsList.endPan, function() {
me.moveendHandler(me);
});
this.loaded[api] = true;
}
else {
alert(api + ' map script not imported');
}
break;
case 'google':
if (GMap2) {
if (GBrowserIsCompatible()) {
this.maps[api] = new GMap2(element);
GEvent.addListener(this.maps[api], 'click', function(marker,location) {
// If the user puts their own Google markers directly on the map
// then there is no location and this event should not fire.
if ( location ) {
me.clickHandler(location.y,location.x,location,me);
}
});
GEvent.addListener(this.maps[api], 'moveend', function() {
me.moveendHandler(me);
});
this.loaded[api] = true;
}
else {
alert('browser not compatible with Google Maps');
}
}
else {
alert(api + ' map script not imported');
}
break;
case 'microsoft':
if (VEMap) {
element.style.position='relative';
var msft_width = parseFloat(getStyle($m(element),'width'));
var msft_height = parseFloat(getStyle($m(element),'height'));
/* Hack so the VE works with FF2 */
var ffv = 0;
var ffn = "Firefox/";
var ffp = navigator.userAgent.indexOf(ffn);
if (ffp != -1) {
ffv = parseFloat(navigator.userAgent.substring(ffp+ffn.length));
}
if (ffv >= 1.5) {
Msn.Drawing.Graphic.CreateGraphic = function(f,b) {
return new Msn.Drawing.SVGGraphic(f, b);
};
}
this.maps[api] = new VEMap(element.id);
this.maps[api].LoadMap();
this.maps[api].AttachEvent("onclick", function(e) {
me.clickHandler(e.view.LatLong.Latitude, e.view.LatLong.Longitude, me);
});
this.maps[api].AttachEvent("onchangeview", function(e) {
me.moveendHandler(me);
});
//Source of our trouble with Mapufacture?
this.resizeTo(msft_width, msft_height);
this.loaded[api] = true;
}
else {
alert(api + ' map script not imported');
}
break;
case 'openlayers':
this.maps[api] = new OpenLayers.Map(
element.id,
{
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
maxResolution:156543,
numZoomLevels:18,
units:'meters',
projection: "EPSG:41001"
}
);
this.layers['osmmapnik'] = new OpenLayers.Layer.TMS(
'OSM Mapnik',
[
"http://a.tile.openstreetmap.org/",
"http://b.tile.openstreetmap.org/",
"http://c.tile.openstreetmap.org/"
],
{
type:'png',
getURL: function (bounds) {
var res = this.map.getResolution();
var x = Math.round ((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
var y = Math.round ((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
var z = this.map.getZoom();
var limit = Math.pow(2, z);
if (y < 0 || y >= limit) {
return null;
} else {
x = ((x % limit) + limit) % limit;
var path = z + "/" + x + "/" + y + "." + this.type;
var url = this.url;
if (url instanceof Array) {
url = this.selectUrl(path, url);
}
return url + path;
}
},
displayOutsideMaxExtent: true
}
);
this.layers['osm'] = new OpenLayers.Layer.TMS(
'OSM',
[
"http://a.tah.openstreetmap.org/Tiles/tile.php/",
"http://b.tah.openstreetmap.org/Tiles/tile.php/",
"http://c.tah.openstreetmap.org/Tiles/tile.php/"
],
{
type:'png',
getURL: function (bounds) {
var res = this.map.getResolution();
var x = Math.round ((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
var y = Math.round ((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
var z = this.map.getZoom();
var limit = Math.pow(2, z);
if (y < 0 || y >= limit) {
return null;
} else {
x = ((x % limit) + limit) % limit;
var path = z + "/" + x + "/" + y + "." + this.type;
var url = this.url;
if (url instanceof Array) {
url = this.selectUrl(path, url);
}
return url + path;
}
},
displayOutsideMaxExtent: true
}
);
this.maps[api].addLayer(this.layers['osmmapnik']);
this.maps[api].addLayer(this.layers['osm']);
this.loaded[api] = true;
break;
case 'openstreetmap':
// for now, osm is a hack on top of google
if (GMap2) {
if (GBrowserIsCompatible()) {
this.maps[api] = new GMap2(element);
GEvent.addListener(this.maps[api], 'click', function(marker,location) {
// If the user puts their own Google markers directly on the map
// then there is no location and this event should not fire.
if ( location ) {
me.clickHandler(location.y,location.x,location,me);
}
});
GEvent.addListener(this.maps[api], 'moveend', function() {
me.moveendHandler(me);
});
// Add OSM tiles
var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0, "copyleft");
var copyrightCollection = new GCopyrightCollection('OSM');
copyrightCollection.addCopyright(copyright);
var tilelayers = [];
tilelayers[0] = new GTileLayer(copyrightCollection, 1, 18);
tilelayers[0].getTileUrl = function (a, b) {
return "http://tile.openstreetmap.org/"+b+"/"+a.x+"/"+a.y+".png";
};
tilelayers[0].isPng = function() {
return true;
};
tilelayers[0].getOpacity = function() {
return 1.0;
};
var custommap = new GMapType(tilelayers, new GMercatorProjection(19), "OSM", {
errorMessage:"More OSM coming soon"
});
this.maps[api].addMapType(custommap);
// Have to tell Mapstraction that we're good so the
// setCenterAndZoom call below initializes the map
this.loaded[api] = true;
var myPoint = new LatLonPoint(50.6805,-1.4062505);
this.setCenterAndZoom(myPoint, 11);
this.maps[api].setMapType(custommap);
}
else {
alert('browser not compatible with Google Maps');
}
}
else {
alert(api + ' map script not imported');
}
break;
case 'multimap':
if (MultimapViewer) {
if(this.debug){
// multimap calls this print_debug function to output debug info
window.print_debug = function(strMessage){
var dbg = document.getElementById('debug');
if(dbg){
dbg.innerHTML += '<p>MUlTIMAP: ' + strMessage + '</p>';
}
else {
alert(strMessage);
}
};
}
this.maps[api] = new MultimapViewer(element);
this.maps[api].addEventHandler('click', function(eventType, eventTarget, arg1, arg2, arg3){
if (arg1) {
me.clickHandler(arg1.lat, arg1.lon, me);
}
});
this.maps[api].addEventHandler('changeZoom', function(eventType, eventTarget, arg1, arg2, arg3){
me.moveendHandler(me);
});
this.maps[api].addEventHandler('endPan', function(eventType, eventTarget, arg1, arg2, arg3){
me.moveendHandler(me);
});
this.loaded[api] = true;
}
else {
alert(api + ' map script not imported');
}
break;
case 'map24':
// Copied from Google and modified
if (Map24) {
Map24.loadApi(["core_api","wrapper_api"] , function() {
Map24.MapApplication.init
( {
NodeName: element.id,
MapType: "Static"
} );
me.maps[api] = Map24.MapApplication.Map;
Map24.MapApplication.Map.addListener('Map24.Event.MapClick',
function(e) {
me.clickHandler(e.Coordinate.Latitude/60,
e.Coordinate.Longitude/60,
me);
e.stop();
}
);
Map24.MapApplication.Map.addListener("MapPanStop",
function(e) {
me.moveendHandler(me);
}
);
/**/
var client=Map24.MapApplication.Map.MapClient['Static'];
/*
These *will* cause the specified listener to run when we stop
panning the map, but the default pan stop handler will be
cancelled. The result of this will be that when we have stopped
panning, we will permanently be in 'pan' mode and unable to do
anything else (e.g. click on the map to create a new marker).
var defaultOnPanStop = client.onPanStop;
var defaultOnZoomInStop = client.onZoomInStop;
var defaultOnZoomOutStop = client.onZoomOutStop;
client.onPanStop = function(e)
{ me.moveendHandler(me); defaultOnPanStop(e);
status('DEFAULTONPANSTOP DONE');}
// Handle zoom events - these also fire moveendHandler for the
// other APIs in Mapstraction
client.onZoomInStop = function(e)
{ me.moveendHandler(me); defaultOnZoomInStop(e); }
client.onZoomOutStop = function(e)
{ me.moveendHandler(me); defaultOnZoomOutStop(e); }
*/
me.loaded[api] = true;
for (var i = 0; i < me.onload[api].length; i++) {
me.onload[api][i]();
}
}, "2.0.1247" );
} else {
alert(api + ' api not loaded');
}
break;
case 'mapquest':
if (MQA.TileMap) {
this.maps[api] = new MQA.TileMap(element);
this.loaded[api] = true;
MQA.EventManager.addListener(this.maps[api],"click",function(eventType, eventTarget, arg1, arg2, arg3){
if (arg1) {
me.clickHandler(arg1.lat, arg1.lon, me);
}
});
MQA.EventManager.addListener(this.maps[api],"zoomend",function() {
me.moveendHandler(me)
});
MQA.EventManager.addListener(this.maps[api],"moveend",function() {
me.moveendHandler(me)
});
}
else {
alert(api + ' map script not imported');
}
break;
case 'freeearth':
this.maps[api] = new FE.Map($m(element));
this.maps[api].onLoad = function() {
me.freeEarthLoaded = true;
me.loaded[api] = true;
for (var i = 0; i < me.onload[api].length; i++) {
me.onload[api][i]();
}
};
this.maps[api].load();
break;
case 'openspace':
// create the map with no controls and don't centre popup info window
this.maps[api] = new OpenSpace.Map(element,{
controls: [],
centreInfoWindow: false
});
// note that these three controls are always there and the fact that there
// are three resident controls is used in addControls()
// enable map drag with mouse and keyboard
this.maps[api].addControl(new OpenLayers.Control.Navigation());
this.maps[api].addControl(new OpenLayers.Control.KeyboardDefaults());
// include copyright statement
this.maps[api].addControl(new OpenSpace.Control.CopyrightCollection());
this.maps[api].events.register("click", this.maps[api], function(evt) {
var point = this.getLonLatFromViewPortPx( evt.xy );
// convert to LatLonPoint
var llPoint = new LatLonPoint;
llPoint.fromOpenSpace(point);
me.clickHandler( llPoint.lat, llPoint.lon );
return false;
});
this.loaded[api] = true;
break;
case 'viamichelin':
if (VMMap) {
this.maps[api] = new VMMap(element);
this.maps[api].addEventHandler('onClick', function(eventType, eventTarget, arg1, arg2, arg3){
if (arg1) {
me.clickHandler(arg1.lat, arg1.lon, me);
}
});
this.maps[api].addEventHandler('onZoomIn', function(eventType, eventTarget, arg1, arg2, arg3){
me.moveendHandler(me);
});
this.maps[api].addEventHandler('onZoomOut', function(eventType, eventTarget, arg1, arg2, arg3){
me.moveendHandler(me);
});
this.maps[api].addEventHandler('onStopPan', function(eventType, eventTarget, arg1, arg2, arg3){
me.moveendHandler(me);
});
this.loaded[api] = true;
}
else {
alert(api + ' map script not imported');
}
break;
default:
if(this.debug) {
alert(api + ' not supported by mapstraction');
}
}
// this.resizeTo(getStyle($m(element),'width'), getStyle($m(element),'height'));
// the above line was called on all APIs but MSFT alters with the div size when it loads
// so you have to find the dimensions and set them again (see msft constructor).
// FIXME: test if google/yahoo etc need this resize called. Also - getStyle returns
// CSS size ('200px') not an integer, and resizeTo seems to expect ints
};
Mapstraction._getScriptLocation = function() {
var scriptLocation = '';
var SCRIPT_NAME = 'mapstraction.js';
var scripts = document.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++) {
var src = scripts[i].getAttribute('src');
if(src) {
var index = src.lastIndexOf(SCRIPT_NAME);
if((index > -1) && (index + SCRIPT_NAME.length == src.length)) {
scriptLocation=src.slice(0, -SCRIPT_NAME.length);
break;
}
}
}
return scriptLocation;
};
Mapstraction.writeInclude = function(api, key, version) {
var jsfiles = [];
var allScriptTags = '';
var host = Mapstraction._getScriptLocation() + 'lib/';
switch(api) {
case 'google':
if(version === null) {
version = '2';
}
jsfiles.push('http://maps.google.com/maps?file=api&v=' + version + '&key=' + key);
break;
case 'microsoft':
if(version === null) {
version = 'v3';
}
jsfiles.push('http://dev.virtualearth.net/mapcontrol/' + version + '/mapcontrol.js');
break;
case 'yahoo':
if(version === null) {
version = '3.8';
}
jsfiles.push('http://api.maps.yahoo.com/ajaxymap?v='+ version + '&appid=' + key);
break;
case 'openlayers':
jsfiles.push('http://openlayers.org/api/OpenLayers.js');
break;
case 'multimap':
if(version === null) {
version = '1.2';
}
jsfiles.push('http://developer.multimap.com/API/maps/' + version + '/' + key);
break;
case 'map24':
jsfiles.push('http://api.maptp.map24.com/ajax?appkey=' + key);
break;
case 'mapquest':
// Many changes between 5.2 and 5.3
// http://developer.mapquest.com/content/documentation/ApiDocumentation/53/JavaScript/JS_DeveloperGuide_v5.3.0.1.htm
if(version === null) {
version = "5.3";
}
jsfiles.push('http://btilelog.access.mapquest.com/tilelog/transaction?transaction=script&key=' + key + '&ipr=true&itk=true&ipkg=controls1&v=' + version);
jsfiles.push('mapquest-js/mqcommon.js');
jsfiles.push('mapquest-js/mqutils.js');
jsfiles.push('mapquest-js/mqobjects.js');
jsfiles.push('mapquest-js/mqexec.js');
break;
case 'freeearth':
jsfiles.push('http://freeearth.poly9.com/api.js');
break;
case 'openspace':
jsfiles.push('http://openspace.ordnancesurvey.co.uk/osmapapi/openspace.js?key=' + key);
jsfiles.push('mapstraction-js/mapstraction-openspace.js');
break;
case 'viamichelin':
jsfiles.push('http://api.viamichelin.com/apijs/js/api.js');
//document.write('VMAPI.registerKey("' + key + '")'); // FIXME
break;
}
for(var i=0; i<jsfiles.length; i++) {
if(/MSIE/.test(navigator.userAgent) || /Safari/.test(navigator.userAgent)) {
// var currentScriptTag="<script src='"+host+jsfiles[i]+"'></script>";
var currentScriptTag = jsfiles[i];
allScriptTags += currentScriptTag;
}
else {
var s = document.createElement('script');
s.src = jsfiles[i];
s.type = 'text/javascript';
var h = document.getElementsByTagName('head').length ? document.getElementsByTagName('head')[0] : document.body;
h.appendChild(s);
}
}
if(allScriptTags) {
document.write(allScriptTags);
}
};
/**
* Returns the loaded state of a Map Provider
* @param {String} api Optional API to query for. If not specified, returns state of the originally created API
* @type {Boolean} The state of the map loading
*/
Mapstraction.prototype.isLoaded = function(api){
if (api === null) {
api = this.api;
}
return this.loaded[api];
};
/**
* Set the debugging on or off - shows alert panels for functions that don't exist in Mapstraction
* @param {Boolean} debug true to turn on debugging, false to turn it off
* @type {Boolean} The state of debugging
*/
Mapstraction.prototype.setDebug = function(debug){
if(debug !== null) {
this.debug = debug;
}
return this.debug;
};
/**
* Resize the current map to the specified width and height
* (since it is actually on a child div of the mapElement passed
* as argument to the Mapstraction constructor, the resizing of this
* mapElement may have no effect on the size of the actual map)
* @param {Integer} width The width the map should be.
* @param {Integer} height The width the map should be.
*/
Mapstraction.prototype.resizeTo = function(width,height){
if(this.loaded[this.api] === false) {
var me = this;
this.onload[this.api].push( function() {
me.resizeTo(width,height);
} );
return;
}
switch (this.api) {
case 'yahoo':
this.maps[this.api].resizeTo(new YSize(width,height));
break;
case 'google':
case 'openstreetmap':
this.currentElement.style.width = width;
this.currentElement.style.height = height;
this.maps[this.api].checkResize();
break;
case 'openspace' :
this.currentElement.style.width = width;
this.currentElement.style.height = height;
this.maps[this.api].updateSize();
break;
case 'openlayers':
this.currentElement.style.width = width;
this.currentElement.style.height = height;
this.maps[this.api].updateSize();
break;
case 'microsoft':
this.maps[this.api].Resize(width, height);
break;
case 'multimap':
this.currentElement.style.width = width;
this.currentElement.style.height = height;
this.maps[this.api].resize();
break;
case 'mapquest':
this.currentElement.style.width = width;
this.currentElement.style.height = height;
this.maps[this.api].setSize(new MQA.Size(width, height));
break;
case 'map24':
Map24.MapApplication.Map.Canvas['c'].resizeTo(width,height);
break;
case 'viamichelin':
this.maps[this.api].resizeTo(width, height);
break;
}
};
/////////////////////////
//
// Event Handling
//
// FIXME need to consolidate some of these handlers...
//
///////////////////////////
// Click handler attached to native API
Mapstraction.prototype.clickHandler = function(lat, lon, me) {
this.callEventListeners('click', {
location: new LatLonPoint(lat, lon)
});
};
// Move and zoom handler attached to native API
Mapstraction.prototype.moveendHandler = function(me) {
this.callEventListeners('moveend', {});
};
/**
* Add a listener for an event.
* @param {String} type Event type to attach listener to
* @param {Function} func Callback function
* @param {Object} caller Callback object
*/
Mapstraction.prototype.addEventListener = function() {
var listener = {};
listener.event_type = arguments[0];
listener.callback_function = arguments[1];
// added the calling object so we can retain scope of callback function
if(arguments.length == 3) {
listener.back_compat_mode = false;
listener.callback_object = arguments[2];
}
else {
listener.back_compat_mode = true;
listener.callback_object = null;
}
this.eventListeners.push(listener);
};
/**
* Call listeners for a particular event.
* @param {String} sEventType Call listeners of this event type
* @param {Object} oEventArgs Event args object to pass back to the callback
*/
Mapstraction.prototype.callEventListeners = function(sEventType, oEventArgs) {
oEventArgs.source = this;
for(var i = 0; i < this.eventListeners.length; i++) {
var evLi = this.eventListeners[i];
if(evLi.event_type == sEventType) {
// only two cases for this, click and move
if(evLi.back_compat_mode) {
if(evLi.event_type == 'click') {
evLi.callback_function(oEventArgs.location);
}
else {
evLi.callback_function();
}
}
else {
var scope = evLi.callback_object || this;
evLi.callback_function.call(scope, oEventArgs);
}
}
}
};
////////////////////
//
// map manipulation
//
/////////////////////
/**
* addControls adds controls to the map. You specify which controls to add in
* the associative array that is the only argument.
* addControls can be called multiple time, with different args, to dynamically change controls.
*
* args = {
* pan: true,
* zoom: 'large' || 'small',
* overview: true,
* scale: true,
* map_type: true,
* }
*
* @param {array} args Which controls to switch on
*/
Mapstraction.prototype.addControls = function( args ) {
if(this.loaded[this.api] === false) {
var me = this;
this.onload[this.api].push( function() {
me.addControls(args);
} );
return;
}
var map = this.maps[this.api];
this.addControlsArgs = args;
switch (this.api) {