xref: /plugin/openlayersmap/syntax/olmap.php (revision 5c60353226181d17ae0b77a986abbd77423da42d)
1<?php
2/*
3 * Copyright (c) 2008-2016 Mark C. Prins <mprins@users.sf.net>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17if (! defined ( 'DOKU_INC' ))
18	define ( 'DOKU_INC', realpath ( dirname ( __FILE__ ) . '/../../' ) . '/' );
19if (! defined ( 'DOKU_PLUGIN' ))
20	define ( 'DOKU_PLUGIN', DOKU_INC . 'lib/plugins/' );
21require_once (DOKU_PLUGIN . 'syntax.php');
22
23/**
24 * DokuWiki Plugin openlayersmap (Syntax Component).
25 * Provides for display of an OpenLayers based map in a wiki page.
26 *
27 * @author Mark Prins
28 */
29class syntax_plugin_openlayersmap_olmap extends DokuWiki_Syntax_Plugin {
30
31	/**
32	 * defaults of the known attributes of the olmap tag.
33	 */
34	private $dflt = array (
35			'id' => 'olmap',
36			'width' => '550px',
37			'height' => '450px',
38			'lat' => 50.0,
39			'lon' => 5.1,
40			'zoom' => 12,
41			'statusbar' => true,
42			'controls' => true,
43			'poihoverstyle' => false,
44			'baselyr' => 'OpenStreetMap',
45			'gpxfile' => '',
46			'kmlfile' => '',
47			'geojsonfile' => '',
48			'summary' => ''
49	);
50
51	/**
52	 *
53	 * @see DokuWiki_Syntax_Plugin::getType()
54	 */
55	function getType() {
56		return 'substition';
57	}
58
59	/**
60	 *
61	 * @see DokuWiki_Syntax_Plugin::getPType()
62	 */
63	function getPType() {
64		return 'block';
65	}
66
67	/**
68	 *
69	 * @see Doku_Parser_Mode::getSort()
70	 */
71	function getSort() {
72		return 901;
73	}
74
75	/**
76	 *
77	 * @see Doku_Parser_Mode::connectTo()
78	 */
79	function connectTo($mode) {
80		$this->Lexer->addSpecialPattern ( '<olmap ?[^>\n]*>.*?</olmap>', $mode, 'plugin_openlayersmap_olmap' );
81	}
82
83	/**
84	 *
85	 * @see DokuWiki_Syntax_Plugin::handle()
86	 */
87	function handle($match, $state, $pos, Doku_Handler $handler) {
88		// break matched cdata into its components
89		list ( $str_params, $str_points ) = explode ( '>', substr ( $match, 7, - 9 ), 2 );
90		// get the lat/lon for adding them to the metadata (used by geotag)
91		preg_match ( '(lat[:|=]\"-?\d*\.\d*\")', $match, $mainLat );
92		preg_match ( '(lon[:|=]\"-?\d*\.\d*\")', $match, $mainLon );
93		$mainLat = substr ( $mainLat [0], 5, - 1 );
94		$mainLon = substr ( $mainLon [0], 5, - 1 );
95
96		$gmap = $this->_extract_params ( $str_params );
97		$overlay = $this->_extract_points ( $str_points );
98		$_firstimageID = '';
99
100		$_nocache = false;
101		// choose maptype based on the specified tag
102		$imgUrl = "{{";
103		if (stripos ( $gmap ['baselyr'], 'google' ) !== false) {
104			// Google
105			$imgUrl .= $this->_getGoogle ( $gmap, $overlay );
106			$imgUrl .= "&.png";
107		} elseif (stripos ( $gmap ['baselyr'], 'bing' ) !== false) {
108			// Bing
109			if (! $this->getConf ( 'bingAPIKey' )) {
110				// in case there is no Bing api key we'll use OSM
111				$_firstimageID = $this->_getStaticOSM ( $gmap, $overlay );
112				$imgUrl .= $_firstimageID;
113				if ($this->getConf ( 'optionStaticMapGenerator' ) == 'remote') {
114					$imgUrl .= "&.png";
115				}
116			} else {
117				// seems that Bing doesn't like the DW client, turn off caching
118				$_nocache = true;
119				$imgUrl .= $this->_getBing ( $gmap, $overlay ) . "&.png";
120			}
121		} /* elseif (stripos ( $gmap ['baselyr'], 'mapquest' ) !== false) {
122			// MapQuest
123			if (! $this->getConf ( 'mapquestAPIKey' )) {
124				// no API key for MapQuest, use OSM
125				$_firstimageID = $this->_getStaticOSM ( $gmap, $overlay );
126				$imgUrl .= $_firstimageID;
127				if ($this->getConf ( 'optionStaticMapGenerator' ) == 'remote') {
128					$imgUrl .= "&.png";
129				}
130			} else {
131				$imgUrl .= $this->_getMapQuest ( $gmap, $overlay );
132				$imgUrl .= "&.png";
133			}
134		} */ else {
135			// default OSM
136			$_firstimageID = $this->_getStaticOSM ( $gmap, $overlay );
137			$imgUrl .= $_firstimageID;
138			if ($this->getConf ( 'optionStaticMapGenerator' ) == 'remote') {
139				$imgUrl .= "&.png";
140			}
141		}
142
143		// append dw p_render specific params and render
144		$imgUrl .= "?" . str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
145		$imgUrl .= "&nolink";
146
147		// add nocache option for selected services
148		if ($_nocache) {
149			$imgUrl .= "&nocache";
150		}
151
152		$imgUrl .= " |".$gmap ['summary'] . " }}";
153
154		// dbglog($imgUrl,"complete image tags is:");
155
156		$mapid = $gmap ['id'];
157		// create a javascript parameter string for the map
158		$param = '';
159		foreach ( $gmap as $key => $val ) {
160			$param .= is_numeric ( $val ) ? "$key: $val, " : "$key: '" . hsc ( $val ) . "', ";
161		}
162		if (! empty ( $param )) {
163			$param = substr ( $param, 0, - 2 );
164		}
165		unset ( $gmap ['id'] );
166
167		// create a javascript serialisation of the point data
168		$poi = '';
169		$poitable = '';
170		$rowId = 0;
171		if (! empty ( $overlay )) {
172			foreach ( $overlay as $data ) {
173				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
174				$rowId ++;
175				$poi .= ", {lat: $lat, lon: $lon, txt: '$text', angle: $angle, opacity: $opacity, img: '$img', rowId: $rowId}";
176
177				if ($this->getConf ( 'displayformat' ) === 'DMS') {
178					$lat = $this->convertLat ( $lat );
179					$lon = $this->convertLon ( $lon );
180				} else {
181					$lat .= 'º';
182					$lon .= 'º';
183				}
184
185				$poitable .= '
186					<tr>
187					<td class="rowId">' . $rowId . '</td>
188					<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/icons/' . $img . '" alt="'. substr($img, 0, -4) . $this->getlang('alt_legend_poi').' " /></td>
189					<td class="lat" title="' . $this->getLang ( 'olmapPOIlatTitle' ) . '">' . $lat . '</td>
190					<td class="lon" title="' . $this->getLang ( 'olmapPOIlonTitle' ) . '">' . $lon . '</td>
191					<td class="txt">' . $text . '</td>
192					</tr>';
193			}
194			$poi = substr ( $poi, 2 );
195		}
196		if (! empty ( $gmap ['kmlfile'] )) {
197			$poitable .= '
198					<tr>
199					<td class="rowId"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/kml_file.png" alt="KML file" /></td>
200					<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/kml_line.png" alt="' . $this->getlang('alt_legend_kml') .'" /></td>
201					<td class="txt" colspan="3">KML track: ' . $this->getFileName ( $gmap ['kmlfile'] ) . '</td>
202					</tr>';
203		}
204		if (! empty ( $gmap ['gpxfile'] )) {
205			$poitable .= '
206					<tr>
207					<td class="rowId"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/gpx_file.png" alt="GPX file" /></td>
208					<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/gpx_line.png" alt="' . $this->getlang('alt_legend_gpx') .'" /></td>
209					<td class="txt" colspan="3">GPX track: ' . $this->getFileName ( $gmap ['gpxfile'] ) . '</td>
210					</tr>';
211		}
212		if (! empty ( $gmap ['geojsonfile'] )) {
213			$poitable .= '
214					<tr>
215					<td class="rowId"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/geojson_file.png" alt="GeoJSON file" /></td>
216					<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/geojson_line.png" alt="' . $this->getlang('alt_legend_geojson') .'" /></td>
217					<td class="txt" colspan="3">GeoJSON track: ' . $this->getFileName ( $gmap ['geojsonfile'] ) . '</td>
218					</tr>';
219		}
220
221		$js .= "{mapOpts:{" . $param . ",displayformat:'" . $this->getConf ( 'displayformat' ) . "'},poi:[$poi]};";
222		// unescape the json
223		$poitable = stripslashes ( $poitable );
224
225		return array (
226				$mapid,
227				$js,
228				$mainLat,
229				$mainLon,
230				$poitable,
231				$gmap ['summary'],
232				$imgUrl,
233				$_firstimageID
234		);
235	}
236
237	/**
238	 *
239	 * @see DokuWiki_Syntax_Plugin::render()
240	 */
241	function render($mode, Doku_Renderer $renderer, $data) {
242		// set to true after external scripts tags are written
243		static $initialised = false;
244		// incremented for each map tag in the page source so we can keep track of each map in this page
245		static $mapnumber = 0;
246
247		// dbglog($data, 'olmap::render() data.');
248		list ( $mapid, $param, $mainLat, $mainLon, $poitable, $poitabledesc, $staticImgUrl, $_firstimage ) = $data;
249
250		if ($mode == 'xhtml') {
251			$olscript = '';
252			$olEnable = false;
253			$gscript = '';
254			$gEnable = $this->getConf ( 'enableGoogle' );
255			$stamenEnable = $this->getConf ( 'enableStamen' );
256			$osmEnable = $this->getConf ( 'enableOSM' );
257			$enableBing = $this->getConf ( 'enableBing' );
258
259			$scriptEnable = '';
260			if (! $initialised) {
261				$initialised = true;
262				// render necessary script tags
263				if ($gEnable) {
264					$gscript = '<script type="text/javascript" src="//maps.google.com/maps/api/js?v=3.29&amp;key='.$this->getConf ( 'googleAPIkey' ).'"></script>';
265				}
266				$olscript = '<script type="text/javascript" src="' . DOKU_BASE . 'lib/plugins/openlayersmap/lib/OpenLayers.js"></script>';
267
268				$scriptEnable = '<script type="text/javascript">/*<![CDATA[*/';
269				$scriptEnable .= $olscript ? 'olEnable = true;' : 'olEnable = false;';
270				$scriptEnable .= 'gEnable = ' . ($gEnable ? 'true' : 'false') . ';';
271				$scriptEnable .= 'osmEnable = ' . ($osmEnable ? 'true' : 'false') . ';';
272				$scriptEnable .= 'stamenEnable = ' . ($stamenEnable ? 'true' : 'false') . ';';
273				$scriptEnable .= 'bEnable = ' . ($enableBing ? 'true' : 'false') . ';';
274				$scriptEnable .= 'bApiKey="' . $this->getConf ( 'bingAPIKey' ) . '";';
275				$scriptEnable .= 'tfApiKey="' . $this->getConf ( 'tfApiKey' ) . '";';
276				$scriptEnable .= 'gApiKey="' . $this->getConf ( 'googleAPIkey' ) . '";';
277				$scriptEnable .= '/*!]]>*/</script>';
278			}
279			$renderer->doc .= "$gscript\n$olscript\n$scriptEnable";
280			$renderer->doc .= '<div class="olMapHelp">' . $this->locale_xhtml ( "help" ) . '</div>';
281			if ($this->getConf ( 'enableA11y' )) {
282				$renderer->doc .= '<div id="' . $mapid . '-static" class="olStaticMap">' . p_render ( $mode, p_get_instructions ( $staticImgUrl ), $info ) . '</div>';
283			}
284			$renderer->doc .= '<div id="' . $mapid . '-clearer" class="clearer"><p>&nbsp;</p></div>';
285			if ($this->getConf ( 'enableA11y' )) {
286				// render a table of the POI for the print and a11y presentation, it is hidden using javascript
287				$renderer->doc .= '<div class="olPOItableSpan" id="' . $mapid . '-table-span">
288					<table class="olPOItable" id="' . $mapid . '-table">
289					<caption class="olPOITblCaption">' . $this->getLang ( 'olmapPOItitle' ) . '</caption>
290					<thead class="olPOITblHeader">
291					<tr>
292					<th class="rowId" scope="col">id</th>
293					<th class="icon" scope="col">' . $this->getLang ( 'olmapPOIicon' ) . '</th>
294					<th class="lat" scope="col" title="' . $this->getLang ( 'olmapPOIlatTitle' ) . '">' . $this->getLang ( 'olmapPOIlat' ) . '</th>
295					<th class="lon" scope="col" title="' . $this->getLang ( 'olmapPOIlonTitle' ) . '">' . $this->getLang ( 'olmapPOIlon' ) . '</th>
296					<th class="txt" scope="col">' . $this->getLang ( 'olmapPOItxt' ) . '</th>
297					</tr>
298					</thead>';
299				if ($poitabledesc != '') {
300					$renderer->doc .= '<tfoot class="olPOITblFooter"><tr><td colspan="5">' . $poitabledesc . '</td></tr></tfoot>';
301				}
302				$renderer->doc .= '<tbody class="olPOITblBody">' . $poitable . '</tbody>
303					</table></div>';
304			}
305			// render inline mapscript parts
306			$renderer->doc .= '<script type="text/javascript">/*<![CDATA[*/';
307			$renderer->doc .= " olMapData[$mapnumber] = $param /*!]]>*/</script>";
308			$mapnumber ++;
309			return true;
310		} elseif ($mode == 'metadata') {
311			if (! (($this->dflt ['lat'] == $mainLat) && ($thisdflt ['lon'] == $mainLon))) {
312				// render geo metadata, unless they are the default
313				$renderer->meta ['geo'] ['lat'] = $mainLat;
314				$renderer->meta ['geo'] ['lon'] = $mainLon;
315				if ($geophp = &plugin_load ( 'helper', 'geophp' )) {
316					// if we have the geoPHP helper, add the geohash
317					// fails with older php versions.. $renderer->meta['geo']['geohash'] = (new Point($mainLon,$mainLat))->out('geohash');
318					$p = new Point ( $mainLon, $mainLat );
319					$renderer->meta ['geo'] ['geohash'] = $p->out ( 'geohash' );
320				}
321			}
322
323			if (($this->getConf ( 'enableA11y' )) && (! empty ( $_firstimage ))) {
324				// add map local image into relation/firstimage if not already filled and when it is a local image
325
326				global $ID;
327				$rel = p_get_metadata ( $ID, 'relation', METADATA_RENDER_USING_CACHE );
328				$img = $rel ['firstimage'];
329				if (empty ( $img ) /* || $img == $_firstimage*/){
330					//dbglog ( $_firstimage, 'olmap::render#rendering image relation metadata for _firstimage as $img was empty or the same.' );
331					// This seems to never work; the firstimage entry in the .meta file is empty
332					// $renderer->meta['relation']['firstimage'] = $_firstimage;
333
334					// ... and neither does this; the firstimage entry in the .meta file is empty
335					// $relation = array('relation'=>array('firstimage'=>$_firstimage));
336					// p_set_metadata($ID, $relation, false, false);
337
338					// ... this works
339					$renderer->internalmedia ( $_firstimage, $poitabledesc );
340				}
341			}
342			return true;
343		}
344		return false;
345	}
346
347	/**
348	 * extract parameters for the map from the parameter string
349	 *
350	 * @param string $str_params
351	 *        	string of key="value" pairs
352	 * @return array associative array of parameters key=>value
353	 */
354	private function _extract_params($str_params) {
355		$param = array ();
356		preg_match_all ( '/(\w*)="(.*?)"/us', $str_params, $param, PREG_SET_ORDER );
357		// parse match for instructions, break into key value pairs
358		$gmap = $this->dflt;
359		foreach ( $param as $kvpair ) {
360			list ( $match, $key, $val ) = $kvpair;
361			$key = strtolower ( $key );
362			if (isset ( $gmap [$key] )) {
363				if ($key == 'summary') {
364					// preserve case for summary field
365					$gmap [$key] = $val;
366				} elseif ($key == 'id') {
367					// preserve case for id field
368					$gmap [$key] = $val;
369				} else {
370					$gmap [$key] = strtolower ( $val );
371				}
372			}
373		}
374		return $gmap;
375	}
376
377	/**
378	 * extract overlay points for the map from the wiki syntax data
379	 *
380	 * @param string $str_points
381	 *        	multi-line string of lat,lon,text triplets
382	 * @return array multi-dimensional array of lat,lon,text triplets
383	 */
384	private function _extract_points($str_points) {
385		$point = array ();
386		// preg_match_all('/^([+-]?[0-9].*?),\s*([+-]?[0-9].*?),(.*?),(.*?),(.*?),(.*)$/um', $str_points, $point, PREG_SET_ORDER);
387		/*
388		 * group 1: ([+-]?[0-9]+(?:\.[0-9]*)?) group 2: ([+-]?[0-9]+(?:\.[0-9]*)?) group 3: (.*?) group 4: (.*?) group 5: (.*?) group 6: (.*)
389		 */
390		preg_match_all ( '/^([+-]?[0-9]+(?:\.[0-9]*)?),\s*([+-]?[0-9]+(?:\.[0-9]*)?),(.*?),(.*?),(.*?),(.*)$/um', $str_points, $point, PREG_SET_ORDER );
391		// create poi array
392		$overlay = array ();
393		foreach ( $point as $pt ) {
394			list ( $match, $lat, $lon, $angle, $opacity, $img, $text ) = $pt;
395			$lat = is_numeric ( $lat ) ? $lat : 0;
396			$lon = is_numeric ( $lon ) ? $lon : 0;
397			$angle = is_numeric ( $angle ) ? $angle : 0;
398			$opacity = is_numeric ( $opacity ) ? $opacity : 0.8;
399			// TODO validate using exist & set up default img?
400			$img = trim ( $img );
401			$text = p_get_instructions ( $text );
402			// dbg ( $text );
403			$text = p_render ( "xhtml", $text, $info );
404			// dbg ( $text );
405			$text = addslashes ( str_replace ( "\n", "", $text ) );
406			$overlay [] = array (
407					$lat,
408					$lon,
409					$text,
410					$angle,
411					$opacity,
412					$img
413			);
414		}
415		return $overlay;
416	}
417
418	/**
419	 * Create a MapQuest static map API image url.
420	 *
421	 * @param array $gmap
422	 * @param array $overlay
423	 */
424	 /*
425	private function _getMapQuest($gmap, $overlay) {
426		$sUrl = $this->getConf ( 'iconUrlOverload' );
427		if (! $sUrl) {
428			$sUrl = DOKU_URL;
429		}
430		switch ($gmap ['baselyr']) {
431			case 'mapquest hybrid' :
432				$maptype = 'hyb';
433				break;
434			case 'mapquest sat' :
435				// because sat coverage is very limited use 'hyb' instead of 'sat' so we don't get a blank map
436				$maptype = 'hyb';
437				break;
438			case 'mapquest road' :
439			default :
440				$maptype = 'map';
441				break;
442		}
443		$imgUrl = "http://open.mapquestapi.com/staticmap/v4/getmap?declutter=true&";
444		if (count ( $overlay ) < 1) {
445			$imgUrl .= "?center=" . $gmap ['lat'] . "," . $gmap ['lon'];
446			// max level for mapquest is 16
447			if ($gmap ['zoom'] > 16) {
448				$imgUrl .= "&zoom=16";
449			} else {
450				$imgUrl .= "&zoom=" . $gmap ['zoom'];
451			}
452		}
453		// use bestfit instead of center/zoom, needs upperleft/lowerright corners
454		// $bbox=$this->_calcBBOX($overlay, $gmap['lat'], $gmap['lon']);
455		// $imgUrl .= "bestfit=".$bbox['minlat'].",".$bbox['maxlon'].",".$bbox['maxlat'].",".$bbox['minlon'];
456
457		// TODO declutter option works well for square maps but not for rectangular, maybe compensate for that or compensate the mbr..
458		$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "," . str_replace ( "px", "", $gmap ['height'] );
459
460		// TODO mapquest allows using one image url with a multiplier $NUMBER eg:
461		// $NUMBER = 2
462		// $imgUrl .= DOKU_URL."/".DOKU_PLUGIN."/".getPluginName()."/icons/".$img.",$NUMBER,C,".$lat1.",".$lon1.",0,0,0,0,C,".$lat2.",".$lon2.",0,0,0,0";
463		if (! empty ( $overlay )) {
464			$imgUrl .= "&xis=";
465			foreach ( $overlay as $data ) {
466				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
467				// $imgUrl .= $sUrl."lib/plugins/openlayersmap/icons/".$img.",1,C,".$lat.",".$lon.",0,0,0,0,";
468				$imgUrl .= $sUrl . "lib/plugins/openlayersmap/icons/" . $img . ",1,C," . $lat . "," . $lon . ",";
469			}
470			$imgUrl = substr ( $imgUrl, 0, - 1 );
471		}
472		$imgUrl .= "&imageType=png&type=" . $maptype;
473		$imgUrl .= "&key=".$this->getConf ( 'mapquestAPIKey' );
474		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getMapQuest: MapQuest image url is:');
475		return $imgUrl;
476	}
477	*/
478
479	/**
480	 * Create a Google maps static image url w/ the poi.
481	 *
482	 * @param array $gmap
483	 * @param array $overlay
484	 */
485	private function _getGoogle($gmap, $overlay) {
486		$sUrl = $this->getConf ( 'iconUrlOverload' );
487		if (! $sUrl) {
488			$sUrl = DOKU_URL;
489		}
490		switch ($gmap ['baselyr']) {
491			case 'google hybrid' :
492				$maptype = 'hybrid';
493				break;
494			case 'google sat' :
495				$maptype = 'satellite';
496				break;
497			case 'terrain' :
498			case 'google relief' :
499				$maptype = 'terrain';
500				break;
501			case 'google road' :
502			default :
503				$maptype = 'roadmap';
504				break;
505		}
506		// TODO maybe use viewport / visible instead of center/zoom,
507		// see: https://developers.google.com/maps/documentation/staticmaps/index#Viewports
508		// http://maps.google.com/maps/api/staticmap?center=51.565690,5.456756&zoom=16&size=600x400&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/marker.png|label:1|51.565690,5.456756&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/marker-blue.png|51.566197,5.458966|label:2&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/parking.png|51.567177,5.457909|label:3&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/parking.png|51.566283,5.457330|label:4&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/parking.png|51.565630,5.457695|label:5&sensor=false&format=png&maptype=roadmap
509		$imgUrl = "http://maps.googleapis.com/maps/api/staticmap?";
510		$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
511		//if (!$this->getConf( 'autoZoomMap')) { // no need for center & zoom params }
512		$imgUrl .= "&center=" . $gmap ['lat'] . "," . $gmap ['lon'];
513		// max is 21 (== building scale), but that's overkill..
514		if ($gmap ['zoom'] > 17) {
515			$imgUrl .= "&zoom=17";
516		} else {
517			$imgUrl .= "&zoom=" . $gmap ['zoom'];
518		}
519		if (! empty ( $overlay )) {
520			$rowId = 0;
521			foreach ( $overlay as $data ) {
522				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
523				$imgUrl .= "&markers=icon%3a" . $sUrl . "lib/plugins/openlayersmap/icons/" . $img . "%7c" . $lat . "," . $lon . "%7clabel%3a" . ++ $rowId;
524			}
525		}
526		$imgUrl .= "&format=png&maptype=" . $maptype;
527		global $conf;
528		$imgUrl .= "&language=" . $conf ['lang'];
529		if ($this->getConf( 'googleAPIkey' )) {
530			$imgUrl .= "&key=" . $this->getConf( 'googleAPIkey' );
531		}
532		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getGoogle: Google image url is:');
533		return $imgUrl;
534	}
535
536	/**
537	 * Create a Bing maps static image url w/ the poi.
538	 *
539	 * @param array $gmap
540	 * @param array $overlay
541	 */
542	private function _getBing($gmap, $overlay) {
543		switch ($gmap ['baselyr']) {
544			case 've hybrid' :
545			case 'bing hybrid' :
546				$maptype = 'AerialWithLabels';
547				break;
548			case 've sat' :
549			case 'bing sat' :
550				$maptype = 'Aerial';
551				break;
552			case 've normal' :
553			case 've road' :
554			case 've' :
555			case 'bing road' :
556			default :
557				$maptype = 'Road';
558				break;
559		}
560		$imgUrl = "http://dev.virtualearth.net/REST/v1/Imagery/Map/" . $maptype;// . "/";
561		if ($this->getConf ( 'autoZoomMap' )) {
562			$bbox = $this->_calcBBOX ( $overlay, $gmap ['lat'], $gmap ['lon'] );
563			//$imgUrl .= "?ma=" . $bbox ['minlat'] . "," . $bbox ['minlon'] . "," . $bbox ['maxlat'] . "," . $bbox ['maxlon'];
564			$imgUrl .= "?ma=" . $bbox ['minlat'] . "%2C" . $bbox ['minlon'] . "%2C" . $bbox ['maxlat'] . "%2C" . $bbox ['maxlon'];
565			$imgUrl .= "&dcl=1";
566		}
567		if (strpos ( $imgUrl, "?" ) === false)
568			$imgUrl .= "?";
569
570		//$imgUrl .= "&ms=" . str_replace ( "px", "", $gmap ['width'] ) . "," . str_replace ( "px", "", $gmap ['height'] );
571		$imgUrl .= "&ms=" . str_replace ( "px", "", $gmap ['width'] ) . "%2C" . str_replace ( "px", "", $gmap ['height'] );
572		$imgUrl .= "&key=" . $this->getConf ( 'bingAPIKey' );
573		if (! empty ( $overlay )) {
574			$rowId = 0;
575			foreach ( $overlay as $data ) {
576				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
577				// TODO icon style lookup, see: http://msdn.microsoft.com/en-us/library/ff701719.aspx for iconStyle
578				$iconStyle = 32;
579				$rowId ++;
580				// NOTE: the max number of pushpins is 18! or we have to use POST (http://msdn.microsoft.com/en-us/library/ff701724.aspx)
581				if ($rowId == 18) {
582					break;
583				}
584				//$imgUrl .= "&pp=$lat,$lon;$iconStyle;$rowId";
585				$imgUrl .= "&pp=$lat%2C$lon%3B$iconStyle%3B$rowId";
586
587			}
588		}
589		global $conf;
590		$imgUrl .= "&fmt=png";
591		$imgUrl .= "&c=" . $conf ['lang'];
592		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getBing: bing image url is:');
593		return $imgUrl;
594	}
595
596	/**
597	 * Create a static OSM map image url w/ the poi from http://staticmap.openstreetmap.de (staticMapLite)
598	 * use http://staticmap.openstreetmap.de "staticMapLite" or a local version
599	 *
600	 * @param array $gmap
601	 * @param array $overlay
602	 *
603	 * @todo implementation for http://ojw.dev.openstreetmap.org/StaticMapDev/
604	 */
605	private function _getStaticOSM($gmap, $overlay) {
606		global $conf;
607
608		if ($this->getConf ( 'optionStaticMapGenerator' ) == 'local') {
609			// using local basemap composer
610			if (! $myMap = &plugin_load ( 'helper', 'openlayersmap_staticmap' )) {
611				dbglog ( $myMap, 'syntax_plugin_openlayersmap_olmap::_getStaticOSM: openlayersmap_staticmap plugin is not available.' );
612			}
613			if (! $geophp = &plugin_load ( 'helper', 'geophp' )) {
614				dbglog ( $geophp, 'syntax_plugin_openlayersmap_olmap::_getStaticOSM: geophp plugin is not available.' );
615			}
616			$size = str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
617
618			$markers = '';
619			if (! empty ( $overlay )) {
620				foreach ( $overlay as $data ) {
621					list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
622					$iconStyle = substr ( $img, 0, strlen ( $img ) - 4 );
623					$markers [] = array (
624							'lat' => $lat,
625							'lon' => $lon,
626							'type' => $iconStyle
627					);
628				}
629			}
630
631			switch ($gmap ['baselyr']) {
632				case 'mapnik' :
633				case 'openstreetmap' :
634					$maptype = 'openstreetmap';
635					break;
636				case 'transport' :
637					$maptype = 'transport';
638					break;
639				case 'landscape' :
640					$maptype = 'landscape';
641					break;
642				case 'cycle map' :
643					$maptype = 'cycle';
644					break;
645				case 'hike and bike map' :
646					$maptype = 'hikeandbike';
647					break;
648				case 'mapquest hybrid' :
649				case 'mapquest road' :
650				case 'mapquest sat' :
651					$maptype = 'mapquest';
652					break;
653				default :
654					$maptype = '';
655					break;
656			}
657
658			$result = $myMap->getMap ( $gmap ['lat'], $gmap ['lon'], $gmap ['zoom'], $size, $maptype, $markers, $gmap ['gpxfile'], $gmap ['kmlfile'], $gmap ['geojsonfile'] );
659		} else {
660			// using external basemap composer
661
662			// http://staticmap.openstreetmap.de/staticmap.php?center=47.000622235634,10.117187497601&zoom=5&size=500x350
663			// &markers=48.999812532766,8.3593749976708,lightblue1|43.154850037315,17.499999997306,lightblue1|49.487527053077,10.820312497573,ltblu-pushpin|47.951071133739,15.917968747369,ol-marker|47.921629720114,18.027343747285,ol-marker-gold|47.951071133739,19.257812497236,ol-marker-blue|47.180141361692,19.257812497236,ol-marker-green
664			$imgUrl = "http://staticmap.openstreetmap.de/staticmap.php";
665			$imgUrl .= "?center=" . $gmap ['lat'] . "," . $gmap ['lon'];
666			$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
667
668			if ($gmap ['zoom'] > 16) {
669				// actually this could even be 18, but that seems overkill
670				$imgUrl .= "&zoom=16";
671			} else {
672				$imgUrl .= "&zoom=" . $gmap ['zoom'];
673			}
674
675			if (! empty ( $overlay )) {
676				$rowId = 0;
677				$imgUrl .= "&markers=";
678				foreach ( $overlay as $data ) {
679					list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
680					$rowId ++;
681					$iconStyle = "lightblue$rowId";
682					$imgUrl .= "$lat,$lon,$iconStyle%7c";
683				}
684				$imgUrl = substr ( $imgUrl, 0, - 3 );
685			}
686
687			$result = $imgUrl;
688		}
689		// dbglog ( $result, 'syntax_plugin_openlayersmap_olmap::_getStaticOSM: osm image url is:' );
690		return $result;
691	}
692
693	/**
694	 * Calculate the minimum bbox for a start location + poi.
695	 *
696	 * @param array $overlay
697	 *        	multi-dimensional array of array($lat, $lon, $text, $angle, $opacity, $img)
698	 * @param float $lat
699	 *        	latitude for map center
700	 * @param float $lon
701	 *        	longitude for map center
702	 * @return multitype:float array describing the mbr and center point
703	 */
704	private function _calcBBOX($overlay, $lat, $lon) {
705		$lats [] = $lat;
706		$lons [] = $lon;
707		foreach ( $overlay as $data ) {
708			list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
709			$lats [] = $lat;
710			$lons [] = $lon;
711		}
712		sort ( $lats );
713		sort ( $lons );
714		// TODO: make edge/wrap around cases work
715		$centerlat = $lats [0] + ($lats [count ( $lats ) - 1] - $lats [0]);
716		$centerlon = $lons [0] + ($lons [count ( $lats ) - 1] - $lons [0]);
717		return array (
718				'minlat' => $lats [0],
719				'minlon' => $lons [0],
720				'maxlat' => $lats [count ( $lats ) - 1],
721				'maxlon' => $lons [count ( $lats ) - 1],
722				'centerlat' => $centerlat,
723				'centerlon' => $centerlon
724		);
725	}
726
727	/**
728	 * Figures out the base filename of a media path.
729	 *
730	 * @param String $mediaLink
731	 */
732	private function getFileName($mediaLink) {
733		$mediaLink = str_replace ( '[[', '', $mediaLink );
734		$mediaLink = str_replace ( ']]', '', $mediaLink );
735		$mediaLink = substr ( $mediaLink, 0, - 4 );
736		$parts = explode ( ':', $mediaLink );
737		$mediaLink = end ( $parts );
738		return str_replace ( '_', ' ', $mediaLink );
739	}
740
741	/**
742	 * Convert decimal degrees to degrees, minutes, seconds format
743	 *
744	 * @todo move this into a shared library
745	 * @param float $decimaldegrees
746	 * @return string dms
747	 */
748	private function _convertDDtoDMS($decimaldegrees) {
749		$dms = floor ( $decimaldegrees );
750		$secs = ($decimaldegrees - $dms) * 3600;
751		$min = floor ( $secs / 60 );
752		$sec = round ( $secs - ($min * 60), 3 );
753		$dms .= 'º' . $min . '\'' . $sec . '"';
754		return $dms;
755	}
756
757	/**
758	 * convert latitude in decimal degrees to DMS+hemisphere.
759	 *
760	 * @todo move this into a shared library
761	 * @param float $decimaldegrees
762	 * @return string
763	 */
764	private function convertLat($decimaldegrees) {
765		if (strpos ( $decimaldegrees, '-' ) !== false) {
766			$latPos = "S";
767		} else {
768			$latPos = "N";
769		}
770		$dms = $this->_convertDDtoDMS ( abs ( floatval ( $decimaldegrees ) ) );
771		return hsc ( $dms . $latPos );
772	}
773
774	/**
775	 * convert longitude in decimal degrees to DMS+hemisphere.
776	 *
777	 * @todo move this into a shared library
778	 * @param float $decimaldegrees
779	 * @return string
780	 */
781	private function convertLon($decimaldegrees) {
782		if (strpos ( $decimaldegrees, '-' ) !== false) {
783			$lonPos = "W";
784		} else {
785			$lonPos = "E";
786		}
787		$dms = $this->_convertDDtoDMS ( abs ( floatval ( $decimaldegrees ) ) );
788		return hsc ( $dms . $lonPos );
789	}
790}
791