xref: /plugin/openlayersmap/script.js (revision 617626162a281aec305b51ea2b8498956fe64cee)
1/*
2 * Copyright (c) 2008-2018 Mark C. Prins <mprins@users.sf.net>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17/**
18 * @fileoverview Javascript voor OpenLayers plugin.
19 *
20 * @requires {lib/OpenLayers.js} or a full openlayers build
21 * @author Mark C. Prins <mprins@users.sf.net>
22 *
23 */
24
25/**
26 * Openlayers selectcontrol.
27 *
28 * @type {OpenLayers.Control.SelectFeature}
29 * @private
30 */
31var selectControl;
32
33/**
34 * handle feature select event.
35 *
36 * @param {OpenLayers.Feature.Vector}
37 *            selFeature the selected feature
38 */
39function onFeatureSelect(selFeature) {
40	// 'this' is selectFeature control
41	var pPos = selFeature.geometry.getBounds().getCenterLonLat();
42	// != OpenLayers.Geometry.Point
43	if (selFeature.geometry.CLASS_NAME === "OpenLayers.Geometry.LineString") {
44		try {
45			// for lines make the popup show at the cursor position
46			pPos = selFeature.layer.map.getLonLatFromViewPortPx(this.handlers.feature.evt.xy);
47		} catch (anErr) {
48			OpenLayers.Console.warn("unable to get event position; reverting to boundingbox center.");
49			pPos = selFeature.geometry.getBounds().getCenterLonLat();
50		}
51	}
52
53	var pContent = '<div class="spacer">&nbsp;</div>';
54	var locDesc = '';
55	if (selFeature.data.rowId !== undefined) {
56		pContent += '<span class="rowId">' + selFeature.data.rowId + ': </span>';
57	}
58	if (selFeature.data.name !== undefined) {
59		pContent += '<span class="txt">' + selFeature.data.name + '</span>';
60		locDesc = selFeature.data.name;
61		// locDesc = selFeature.data.name.split(/\s+/).slice(0,2).join('+');
62	}
63	if (selFeature.data.ele !== undefined) {
64		pContent += '<div class="ele">elevation: ' + selFeature.data.ele + '</div>';
65	}
66	if (selFeature.data.type !== undefined) {
67		pContent += '<div>' + selFeature.data.type + '</div>';
68	}
69	if (selFeature.data.time !== undefined) {
70		pContent += '<div class="time">time: ' + selFeature.data.time + '</div>';
71	}
72	if (selFeature.data.description !== undefined) {
73		pContent += '<div class="desc">' + selFeature.data.description + '</div>';
74	}
75	// mapillary layer
76	if (selFeature.attributes.location !== undefined) {
77		pContent += '<div class="desc">' + selFeature.data.location + '</div>';
78	}
79	// mapillary layer
80	if (selFeature.attributes.image !== undefined) {
81		pContent += '<img class="img" src=' + selFeature.data.image + ' width="320" />';
82	}
83	// mapillary layer
84	if (selFeature.attributes.ca !== undefined) {
85		var angle = Math.floor(selFeature.data.ca);
86		pContent += '<div class="coord"><img src="' + DOKU_BASE + 'lib/plugins/openlayersmapoverlays/icons/arrow-up-20.png'
87				+ '" width="16" height="16" style="transform:rotate(' + angle + 'deg)" alt="' + angle + 'º"/> '+OpenLayers.i18n("compass") + angle + 'º</div>';
88	}
89
90	if (selFeature.attributes.img !== undefined) {
91		pContent += '<div class="coord" title="lat;lon"><img src="' + selFeature.attributes.img
92				+ '" width="16" height="16" style="transform:rotate(' + selFeature.attributes.angle + 'deg)" />&nbsp;'
93				+ '<a href="geo:'+ selFeature.data.lat + ',' + selFeature.data.lon
94				+ '?q=' + selFeature.data.lat + ',' + selFeature.data.lon + '(' + locDesc + ')" title="' + OpenLayers.i18n("navi") + '">'
95				+ selFeature.data.latlon + '</a></div>';
96	}
97	if (pContent.length > 0) {
98		// only show when there is something to show...
99		var popup = new OpenLayersMap.Popup.FramedCloud("olPopup", pPos, null, pContent, null, true, function() {
100			selectControl.unselect(selFeature);
101			jQuery('#' + selectControl.layer.map.div.id).focus();
102		});
103		selFeature.popup = popup;
104		selFeature.layer.map.addPopup(popup);
105		jQuery('#olPopup').attr("tabindex", -1).focus();
106	}
107}
108
109/**
110 * handle feature unselect event. remove & destroy the popup.
111 *
112 * @param {OpenLayers.Feature.Vector}
113 *            selFeature the un-selected feature
114 */
115function onFeatureUnselect(selFeature) {
116	if (selFeature.popup !== null) {
117		selFeature.layer.map.removePopup(selFeature.popup);
118		selFeature.popup.destroy();
119		selFeature.popup = null;
120	}
121}
122/**
123 * Test for css support in the browser by sniffing for a css class we added
124 * using javascript added by the action plugin; this is an edge case because
125 * browsers that support javascript generally support css as well.
126 *
127 * @returns {Boolean} true when the browser supports css (and implicitly
128 *          javascript)
129 */
130function olTestCSSsupport() {
131	return (jQuery('.olCSSsupported').length > 0);
132}
133
134/**
135 * Creates a DocumentFragment to insert into the dom.
136 *
137 * @param mapid
138 *            id for the map div
139 * @param width
140 *            width for the map div
141 * @param height
142 *            height for the map div
143 * @returns a {DocumentFragment} element that can be injected into the dom
144 */
145function olCreateMaptag(mapid, width, height) {
146	var mEl = '<div id="' + mapid + '-olContainer" class="olContainer olWebOnly">'
147	// map
148	+ '<div id="' + mapid + '" tabindex="0" style="width:' + width + ';height:' + height + ';" class="olMap"></div>'
149	// statusbar
150	+ '<div id="' + mapid + '-olStatusBar" style="width:' + width + ';" class="olStatusBarContainer">' + '  <div id="'
151			+ mapid + '-statusbar-scale" class="olStatusBar olStatusBarScale">scale</div>' + '  <div id="' + mapid
152			+ '-statusbar-mouseposition" class="olStatusBar olStatusBarMouseposition"></div>' + '  <div id="' + mapid
153			+ '-statusbar-projection" class="olStatusBar olStatusBarProjection">proj</div>' + '  <div id="' + mapid
154			+ '-statusbar-text" class="olStatusBar olStatusBarText">txt</div>' + '</div>'
155			//
156			+ '</div>',
157	// fragment
158	frag = document.createDocumentFragment(),
159	// temp node
160	temp = document.createElement('div');
161	temp.innerHTML = mEl;
162	while (temp.firstChild) {
163		frag.appendChild(temp.firstChild);
164	}
165	return frag;
166}
167
168/**
169 * Create the map based on the params given.
170 *
171 * @param {Object}
172 *            mapOpts MapOptions hash {id:'olmap', width:500px, height:500px,
173 *            lat:6710200, lon:506500, zoom:13, statusbar:1, controls:1,
174 *            poihoverstyle:1, baselyr:'', kmlfile:'', gpxfile:'', geojsonfile,
175 *            summary:''}
176 * @param {Array}
177 *            OLmapPOI array with POI's [ {lat:6710300,lon:506000,txt:'instap
178 *            punt',angle:180,opacity:.9,img:'', rowId:n},... ]);
179 *
180 * @return {OpenLayers.Map} the created map
181 */
182function createMap(mapOpts, OLmapPOI) {
183	if (!olEnable) {
184		return;
185	}
186	if (!olTestCSSsupport()) {
187		olEnable = false;
188		return;
189	}
190	OpenLayers.ImgPath = DOKU_BASE + 'lib/plugins/openlayersmap/lib/img/';
191	OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
192
193	// find map element location
194	var cleartag = document.getElementById(mapOpts.id + '-clearer');
195	if (cleartag === null) {
196		return;
197	}
198	// create map element and add to document
199	var fragment = olCreateMaptag(mapOpts.id, mapOpts.width, mapOpts.height);
200	cleartag.parentNode.insertBefore(fragment, cleartag);
201
202	/** dynamic map extent. */
203	var extent = new OpenLayers.Bounds(),
204
205	/** map. */
206	m = new OpenLayers.Map({
207		div : mapOpts.id,
208		projection : 'EPSG:3857',
209		displayProjection : new OpenLayers.Projection("EPSG:4326"),
210		numZoomLevels : 22,
211		controls : [],
212		theme : null
213	});
214
215	if (osmEnable) {
216		/* add OSM map layers */
217		m.addLayer(new OpenLayers.Layer.OSM());
218
219		/* open cycle map */
220		m.addLayer(new OpenLayersMap.Layer.OCM("cycle map",[
221				'//a.tile.thunderforest.com/cycle/${z}/${x}/${y}.png?apikey='+tfApiKey,
222				'//b.tile.thunderforest.com/cycle/${z}/${x}/${y}.png?apikey='+tfApiKey,
223				'//c.tile.thunderforest.com/cycle/${z}/${x}/${y}.png?apikey='+tfApiKey ], {
224			visibility : mapOpts.baselyr === "transport",
225			apikey : tfApiKey
226		}));
227		m.addLayer(new OpenLayersMap.Layer.OCM("transport", [
228				"http://a.tile.thunderforest.com/transport/${z}/${x}/${y}.png?apikey="+tfApiKey,
229				"http://b.tile.thunderforest.com/transport/${z}/${x}/${y}.png?apikey="+tfApiKey,
230				"http://c.tile.thunderforest.com/transport/${z}/${x}/${y}.png?apikey="+tfApiKey ], {
231			visibility : mapOpts.baselyr === "transport",
232			apikey : tfApiKey
233		}));
234		m.addLayer(new OpenLayersMap.Layer.OCM("landscape", [
235				"http://a.tile.thunderforest.com/landscape/${z}/${x}/${y}.png?apikey="+tfApiKey,
236				"http://b.tile.thunderforest.com/landscape/${z}/${x}/${y}.png?apikey="+tfApiKey,
237				"http://c.tile.thunderforest.com/landscape/${z}/${x}/${y}.png?apikey="+tfApiKey ], {
238			visibility : mapOpts.baselyr === "landscape",
239			apikey : tfApiKey
240		}));
241		m.addLayer(new OpenLayersMap.Layer.OCM("outdoors", [
242				"http://a.tile.thunderforest.com/outdoors/${z}/${x}/${y}.png?apikey="+tfApiKey,
243				"http://b.tile.thunderforest.com/outdoors/${z}/${x}/${y}.png?apikey="+tfApiKey,
244				"http://c.tile.thunderforest.com/outdoors/${z}/${x}/${y}.png?apikey="+tfApiKey ], {
245			visibility : mapOpts.baselyr === "outdoors",
246			apikey : tfApiKey
247		}));
248
249		m.addLayer(new OpenLayers.Layer.OSM(
250				"hike and bike map", "http://toolserver.org/tiles/hikebike/${z}/${x}/${y}.png", {
251					visibility : mapOpts.baselyr === "hike and bike map",
252					tileOptions : {
253						crossOriginKeyword : null
254					}
255		}));
256	}
257	/*
258	 * add Stamen map layers, see: http://maps.stamen.com/
259	 */
260	if (stamenEnable) {
261		m.addLayer(new OpenLayersMap.Layer.StamenTerrain());
262		m.addLayer(new OpenLayersMap.Layer.StamenToner());
263	}
264
265	if (gEnable) {
266		/* load google maps */
267		try {
268			m.addLayer(new OpenLayers.Layer.Google("google relief", {
269				type : google.maps.MapTypeId.TERRAIN,
270				numZoomLevels : 16,
271				animationEnabled : true,
272				visibility : mapOpts.baselyr === "google relief"
273			}));
274			m.addLayer(new OpenLayers.Layer.Google("google sat", {
275				type : google.maps.MapTypeId.SATELLITE,
276				animationEnabled : true,
277				visibility : mapOpts.baselyr === "google sat"
278			}));
279			m.addLayer(new OpenLayers.Layer.Google("google hybrid", {
280				type : google.maps.MapTypeId.HYBRID,
281				animationEnabled : true,
282				visibility : mapOpts.baselyr === "google hybrid"
283			}));
284			m.addLayer(new OpenLayers.Layer.Google("google road", {
285				animationEnabled : true,
286				visibility : mapOpts.baselyr === "google road"
287			}));
288		} catch (ol_err1) {
289			Openlayers.Console.userError('Error loading Google maps' + ol_err1);
290		}
291	}
292
293	if (bEnable && bApiKey !== '') {
294		try {
295			/* add Bing tiles */
296			m.addLayer(new OpenLayers.Layer.Bing({
297				key : bApiKey,
298				type : "Road",
299				name : "bing road",
300				visibility : mapOpts.baselyr === "bing road",
301				wrapDateLine : true,
302				attributionTemplate : '<a target="_blank" href="http://www.bing.com/maps/">'
303						+ 'Bing™</a><img src="//www.bing.com/favicon.ico" alt="Bing logo"/> ${copyrights}'
304						+ '<a target="_blank" href="http://www.microsoft.com/maps/product/terms.html">Terms of Use</a>'
305			}));
306			m.addLayer(new OpenLayers.Layer.Bing({
307				key : bApiKey,
308				type : "Aerial",
309				name : "bing sat",
310				visibility : mapOpts.baselyr === "bing sat",
311				wrapDateLine : true,
312				attributionTemplate : '<a target="_blank" href="http://www.bing.com/maps/">'
313						+ 'Bing™</a><img src="//www.bing.com/favicon.ico" alt="Bing logo"/> ${copyrights}'
314						+ '<a target="_blank" href="http://www.microsoft.com/maps/product/terms.html">Terms of Use</a>'
315			}));
316			m.addLayer(new OpenLayers.Layer.Bing({
317				key : bApiKey,
318				type : "AerialWithLabels",
319				name : "bing hybrid",
320				visibility : mapOpts.baselyr === "bing hybrid",
321				wrapDateLine : true,
322				attributionTemplate : '<a target="_blank" href="http://www.bing.com/maps/">'
323						+ 'Bing™</a><img src="//www.bing.com/favicon.ico" alt="Bing logo"/> ${copyrights}'
324						+ '<a target="_blank" href="http://www.microsoft.com/maps/product/terms.html">Terms of Use</a>'
325			}));
326		} catch (ol_errBing) {
327			Openlayers.Console.userError('Error loading Bing maps: ' + ol_errBing);
328		}
329	}
330
331	m.setCenter(new OpenLayers.LonLat(mapOpts.lon, mapOpts.lat).transform(m.displayProjection, m.projection),
332			mapOpts.zoom);
333	extent.extend(m.getExtent());
334
335	// change/set alternative baselyr
336	try {
337		m.setBaseLayer(((m.getLayersByName(mapOpts.baselyr))[0]));
338	} catch (ol_err4) {
339		m.setBaseLayer(m.layers[0]);
340	}
341
342	m.addControls([ new OpenLayers.Control.ScaleLine({
343		geodesic : true
344	}), new OpenLayers.Control.KeyboardDefaults({
345		observeElement : mapOpts.id
346	}), new OpenLayers.Control.Navigation() ]);
347
348	if (mapOpts.statusbar === 1) {
349		// statusbar control: mouse pos.
350		m.addControl(new OpenLayers.Control.MousePosition({
351			'div' : OpenLayers.Util.getElement(mapOpts.id + '-statusbar-mouseposition')
352		}));
353		// statusbar control: scale
354		m.addControl(new OpenLayers.Control.Scale(mapOpts.id + '-statusbar-scale'));
355		// statusbar control: attribution
356		m.addControl(new OpenLayers.Control.Attribution({
357			'div' : OpenLayers.Util.getElement(mapOpts.id + '-statusbar-text')
358		}));
359		// statusbar control: projection
360		OpenLayers.Util.getElement(mapOpts.id + '-statusbar-projection').innerHTML = m.displayProjection;
361	} else {
362		OpenLayers.Util.getElement(mapOpts.id + '-olStatusBar').display = 'none';
363	}
364
365	if (OLmapPOI.length > 0) {
366		var markers = new OpenLayers.Layer.Vector("POI", {
367			styleMap : new OpenLayers.StyleMap({
368				"default" : {
369					cursor : "help",
370					externalGraphic : "${img}",
371					graphicHeight : 16,
372					graphicWidth : 16,
373					// graphicXOffset : 0,
374					// graphicYOffset : -8,
375					graphicOpacity : "${opacity}",
376					rotation : "${angle}",
377					backgroundGraphic : DOKU_BASE + "lib/plugins/openlayersmap/icons/marker_shadow.png",
378					// backgroundXOffset : 0,
379					// backgroundYOffset : -4,
380					backgroundRotation : "${angle}",
381					pointRadius : 10,
382					labelXOffset : 8,
383					labelYOffset : 8,
384					labelAlign : "lb",
385					label : "${label}",
386					// fontColor : "",
387					fontFamily : "monospace",
388					fontSize : "12px",
389					fontWeight : "bold"
390				},
391				"select" : {
392					cursor : "help",
393					externalGraphic : DOKU_BASE + "lib/plugins/openlayersmap/icons/marker-red.png",
394					graphicHeight : 16,
395					graphicWidth : 16,
396					// graphicXOffset : 0,
397					// graphicYOffset : -8,
398					graphicOpacity : 1.0,
399					rotation : "${angle}"
400				}
401			}),
402			isBaseLayer : false,
403			rendererOptions : {
404				yOrdering : true
405			}
406		});
407		m.addLayer(markers);
408		var features = [];
409		for (var j = 0; j < OLmapPOI.length; j++) {
410			var feat = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(OLmapPOI[j].lon, OLmapPOI[j].lat)
411					.transform(m.displayProjection, m.projection), {
412				angle : OLmapPOI[j].angle,
413				opacity : OLmapPOI[j].opacity,
414				img : DOKU_BASE + "lib/plugins/openlayersmap/icons/" + OLmapPOI[j].img,
415				label : OLmapPOI[j].rowId
416			});
417			var _latlon = OLmapPOI[j].lat + 'º;' + OLmapPOI[j].lon + 'º';
418			if (mapOpts.displayformat === 'DMS') {
419				_latlon = OpenLayers.Util.getFormattedLonLat(OLmapPOI[j].lat, 'lat') + ';'
420						+ OpenLayers.Util.getFormattedLonLat(OLmapPOI[j].lon, 'lon');
421			}
422			feat.data = {
423				name : OLmapPOI[j].txt,
424				rowId : OLmapPOI[j].rowId,
425				latlon : _latlon,
426				lat: OLmapPOI[j].lat,
427				lon: OLmapPOI[j].lon
428			};
429			features.push(feat);
430		}
431		markers.addFeatures(features);
432		extent.extend(markers.getDataExtent());
433		m.zoomToExtent(extent);
434	}
435
436	/* GPX layer */
437	if (mapOpts.gpxfile.length > 0) {
438		var layerGPX = new OpenLayers.Layer.Vector("GPS route", {
439			protocol : new OpenLayers.Protocol.HTTP({
440				url : DOKU_BASE + "lib/exe/fetch.php?media=" + mapOpts.gpxfile,
441				format : new OpenLayers.Format.GPX({
442					extractWaypoints : true,
443					extractTracks : true,
444					extractStyles : true,
445					extractAttributes : true,
446					handleHeight : true,
447					maxDepth : 3
448				})
449			}),
450			style : {
451				strokeColor : "#0000FF",
452				strokeWidth : 3,
453				strokeOpacity : 0.7,
454				pointRadius : 4,
455				fillColor : "#0099FF",
456				fillOpacity : 0.7
457			// , label:"${name}"
458			},
459			projection : new OpenLayers.Projection("EPSG:4326"),
460			strategies : [ new OpenLayers.Strategy.Fixed() ]
461		});
462		m.addLayer(layerGPX);
463		layerGPX.events.register('loadend', m, function() {
464			extent.extend(layerGPX.getDataExtent());
465			m.zoomToExtent(extent);
466		});
467	}
468
469	/* GeoJSON layer */
470	if (mapOpts.geojsonfile.length > 0) {
471		var layerGJS = new OpenLayers.Layer.Vector("json data", {
472			protocol : new OpenLayers.Protocol.HTTP({
473				url : DOKU_BASE + "lib/exe/fetch.php?media=" + mapOpts.geojsonfile,
474				format : new OpenLayers.Format.GeoJSON({
475					ignoreExtraDims : true
476				})
477			}),
478			style : {
479				strokeColor : "#FF00FF",
480				strokeWidth : 3,
481				strokeOpacity : 0.7,
482				pointRadius : 4,
483				fillColor : "#FF99FF",
484				fillOpacity : 0.7
485			// , label:"${name}"
486			},
487			projection : new OpenLayers.Projection("EPSG:4326"),
488			strategies : [ new OpenLayers.Strategy.Fixed() ]
489		});
490		m.addLayer(layerGJS);
491		layerGJS.events.register('loadend', m, function() {
492			extent.extend(layerGJS.getDataExtent());
493			m.zoomToExtent(extent);
494		});
495	}
496
497	/* KML layer */
498	if (mapOpts.kmlfile.length > 0) {
499		var layerKML = new OpenLayers.Layer.Vector("KML file", {
500			protocol : new OpenLayers.Protocol.HTTP({
501				url : DOKU_BASE + "lib/exe/fetch.php?media=" + mapOpts.kmlfile,
502				format : new OpenLayers.Format.KML({
503					extractStyles : true,
504					extractAttributes : true,
505					maxDepth : 3
506				})
507			}),
508			style : {
509				label : "${name}"
510			},
511			projection : new OpenLayers.Projection("EPSG:4326"),
512			strategies : [ new OpenLayers.Strategy.Fixed() ]
513		});
514		m.addLayer(layerKML);
515		layerKML.events.register('loadend', m, function() {
516			extent.extend(layerKML.getDataExtent());
517			m.zoomToExtent(extent);
518		});
519	}
520
521	// selectcontrol for layers
522	if ((m.getLayersByClass('OpenLayers.Layer.GML').length > 0)
523			|| m.getLayersByClass('OpenLayers.Layer.Vector').length > 0) {
524		selectControl = new OpenLayers.Control.SelectFeature((m.getLayersByClass('OpenLayers.Layer.Vector')).concat(m
525				.getLayersByClass('OpenLayers.Layer.GML')), {
526			hover : mapOpts.poihoverstyle,
527			onSelect : onFeatureSelect,
528			onUnselect : onFeatureUnselect
529		});
530		m.addControl(selectControl);
531		selectControl.activate();
532
533		// keyboard select control
534		var iControl = new OpenLayersMap.Control.KeyboardClick({
535			observeElement : mapOpts.id,
536			selectControl : selectControl
537		});
538		m.addControl(iControl);
539	}
540
541	if (mapOpts.controls === 1) {
542		/* add base controls to map */
543		m.addControls([ new OpenLayersMap.Control.LayerSwitcher(), new OpenLayers.Control.Graticule({
544			visible : false
545		}), new OpenLayersMap.Control.OverviewMap({
546			mapOptions : {
547				theme : null
548			}
549		}), new OpenLayersMap.Control.Zoom(), new OpenLayersMap.Control.Fullscreen() ]);
550
551		// add hillshade, since this is off by default only add when we have a
552		// layerswitcher
553		/*
554		m.addLayer(new OpenLayers.Layer.OSM("Hillshade", "http://toolserver.org/~cmarqu/hill/${z}/${x}/${y}.png", {
555			isBaseLayer : false,
556			transparent : true,
557			visibility : false,
558			displayOutsideMaxExtent : true,
559			attribution : '',
560			tileOptions : {
561				crossOriginKeyword : null
562			}
563		}));
564		*/
565	}
566
567	return m;
568}
569
570/** init. */
571function olInit() {
572	if (olEnable) {
573		var _i = 0;
574		// create the maps in the page
575		for (_i = 0; _i < olMapData.length; _i++) {
576			var _id = olMapData[_i].mapOpts.id;
577			olMaps[_id] = createMap(olMapData[_i].mapOpts, olMapData[_i].poi);
578
579			// set max-width on help pop-over
580			jQuery('#' + _id).parent().parent().find('.olMapHelp').css('max-width', olMapData[_i].mapOpts.width);
581
582			// shrink the map width to fit inside page container
583			//TODO also do this when window is resized
584			var _w = jQuery('#' + _id + '-olContainer').parent().innerWidth();
585			if (parseInt(olMapData[_i].mapOpts.width) > _w) {
586				jQuery('#' + _id).width(_w);
587				jQuery('#' + _id + '-olStatusBar').width(_w);
588				jQuery('#' + _id).parent().parent().find('.olMapHelp').width(_w);
589				olMaps[_id].updateSize();
590			}
591		}
592
593		// hide the table(s) with POI by giving it a print-only style
594		jQuery('.olPOItableSpan').addClass('olPrintOnly');
595		// hide the static map image(s) by giving it a print only style
596		jQuery('.olStaticMap').addClass('olPrintOnly');
597		// add help button with toggle.
598		jQuery('.olWebOnly > .olMap')
599				.prepend(
600						'<div class="olMapHelpButtonDiv">'
601								+ '<button onclick="jQuery(\'.olMapHelp\').toggle(500);" class="olMapHelpButton olHasTooltip"><span>'
602								+ OpenLayers.i18n("toggle_help") + '</span>?</button></div>');
603		// toggle to switch dynamic vs. static map
604		jQuery('.olMapHelp').before(
605				'<div class="a11y"><button onclick="jQuery(\'.olPrintOnly\').toggle();jQuery(\'.olWebOnly\').toggle();">'
606						+ OpenLayers.i18n("toggle_dynamic_map") + '</button></div>');
607	}
608}
609
610/**
611 * ol api flag.
612 *
613 * @type {Boolean}
614 */
615var olEnable = false,
616/**
617 * An array with data for each map in the page.
618 *
619 * @type {Array}
620 */
621olMapData = [],
622/**
623 * Holds a reference to all of the maps on this page with the map's id as key.
624 * Can be used as an extension point.
625 *
626 * @type {Object}
627 */
628olMaps = new Object(),
629/**
630 * Stamen tiles flag.
631 *
632 * @type {Boolean}
633 */
634stamenEnable = false,
635/**
636 * google map api flag.
637 *
638 * @type {Boolean}
639 */
640gEnable = false,
641/**
642 * Bing tiles flag.
643 *
644 * @type {Boolean}
645 */
646bEnable = false,
647/**
648 * Bing API key.
649 *
650 * @type {String}
651 */
652bApiKey = '',
653/**
654 * Google API key.
655 *
656 * @type {String}
657 */
658gApiKey = '',
659/**
660 * Thunderforest API key.
661 *
662 * @type {String}
663 */
664tfApiKey = '',
665/**
666 * OSM tiles flag.
667 *
668 * @type {Boolean}
669 */
670osmEnable = true,
671/**
672 * CSS support flag.
673 *
674 * @type {Boolean}
675 */
676olCSSEnable = true;
677
678/* register olInit to run with onload event. */
679jQuery(olInit);
680