xref: /plugin/openlayersmap/syntax/olmap.php (revision ee4229967c4c5c3c5631bc91c13dbad6db1e2f19)
1<?php
2/*
3 * Copyright (c) 2008-2015 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, &$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, &$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			$mqEnable = $this->getConf ( 'enableMapQuest' );
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.22&amp;sensor=false&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 .= 'mqEnable = ' . ($mqEnable ? 'true' : 'false') . ';';
273				$scriptEnable .= 'bEnable = ' . ($enableBing ? 'true' : 'false') . ';';
274				$scriptEnable .= 'bApiKey="' . $this->getConf ( 'bingAPIKey' ) . '";';
275				$scriptEnable .= 'mqApiKey="' . $this->getConf ( 'mapquestAPIKey' ) . '";';
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	private function _getMapQuest($gmap, $overlay) {
425		$sUrl = $this->getConf ( 'iconUrlOverload' );
426		if (! $sUrl) {
427			$sUrl = DOKU_URL;
428		}
429		switch ($gmap ['baselyr']) {
430			case 'mapquest hybrid' :
431				$maptype = 'hyb';
432				break;
433			case 'mapquest sat' :
434				// because sat coverage is very limited use 'hyb' instead of 'sat' so we don't get a blank map
435				$maptype = 'hyb';
436				break;
437			case 'mapquest road' :
438			default :
439				$maptype = 'map';
440				break;
441		}
442		$imgUrl = "http://open.mapquestapi.com/staticmap/v4/getmap?declutter=true&";
443		if (count ( $overlay ) < 1) {
444			$imgUrl .= "?center=" . $gmap ['lat'] . "," . $gmap ['lon'];
445			// max level for mapquest is 16
446			if ($gmap ['zoom'] > 16) {
447				$imgUrl .= "&zoom=16";
448			} else {
449				$imgUrl .= "&zoom=" . $gmap ['zoom'];
450			}
451		}
452		// use bestfit instead of center/zoom, needs upperleft/lowerright corners
453		// $bbox=$this->_calcBBOX($overlay, $gmap['lat'], $gmap['lon']);
454		// $imgUrl .= "bestfit=".$bbox['minlat'].",".$bbox['maxlon'].",".$bbox['maxlat'].",".$bbox['minlon'];
455
456		// TODO declutter option works well for square maps but not for rectangular, maybe compensate for that or compensate the mbr..
457		$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "," . str_replace ( "px", "", $gmap ['height'] );
458
459		// TODO mapquest allows using one image url with a multiplier $NUMBER eg:
460		// $NUMBER = 2
461		// $imgUrl .= DOKU_URL."/".DOKU_PLUGIN."/".getPluginName()."/icons/".$img.",$NUMBER,C,".$lat1.",".$lon1.",0,0,0,0,C,".$lat2.",".$lon2.",0,0,0,0";
462		if (! empty ( $overlay )) {
463			$imgUrl .= "&xis=";
464			foreach ( $overlay as $data ) {
465				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
466				// $imgUrl .= $sUrl."lib/plugins/openlayersmap/icons/".$img.",1,C,".$lat.",".$lon.",0,0,0,0,";
467				$imgUrl .= $sUrl . "lib/plugins/openlayersmap/icons/" . $img . ",1,C," . $lat . "," . $lon . ",";
468			}
469			$imgUrl = substr ( $imgUrl, 0, - 1 );
470		}
471		$imgUrl .= "&imageType=png&type=" . $maptype;
472		$imgUrl .= "&key=".$this->getConf ( 'mapquestAPIKey' );
473		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getMapQuest: MapQuest image url is:');
474		return $imgUrl;
475	}
476
477	/**
478	 * Create a Google maps static image url w/ the poi.
479	 *
480	 * @param array $gmap
481	 * @param array $overlay
482	 */
483	private function _getGoogle($gmap, $overlay) {
484		$sUrl = $this->getConf ( 'iconUrlOverload' );
485		if (! $sUrl) {
486			$sUrl = DOKU_URL;
487		}
488		switch ($gmap ['baselyr']) {
489			case 'google hybrid' :
490				$maptype = 'hybrid';
491				break;
492			case 'google sat' :
493				$maptype = 'satellite';
494				break;
495			case 'terrain' :
496			case 'google relief' :
497				$maptype = 'terrain';
498				break;
499			case 'google road' :
500			default :
501				$maptype = 'roadmap';
502				break;
503		}
504		// TODO maybe use viewport / visible instead of center/zoom,
505		// see: https://developers.google.com/maps/documentation/staticmaps/index#Viewports
506		// 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
507		$imgUrl = "http://maps.googleapis.com/maps/api/staticmap?sensor=false";
508		$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
509		//if (!$this->getConf( 'autoZoomMap')) { // no need for center & zoom params }
510		$imgUrl .= "&center=" . $gmap ['lat'] . "," . $gmap ['lon'];
511		// max is 21 (== building scale), but that's overkill..
512		if ($gmap ['zoom'] > 17) {
513			$imgUrl .= "&zoom=17";
514		} else {
515			$imgUrl .= "&zoom=" . $gmap ['zoom'];
516		}
517		if (! empty ( $overlay )) {
518			$rowId = 0;
519			foreach ( $overlay as $data ) {
520				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
521				$imgUrl .= "&markers=icon%3a" . $sUrl . "lib/plugins/openlayersmap/icons/" . $img . "%7c" . $lat . "," . $lon . "%7clabel%3a" . ++ $rowId;
522			}
523		}
524		$imgUrl .= "&format=png&maptype=" . $maptype;
525		global $conf;
526		$imgUrl .= "&language=" . $conf ['lang'];
527		if ($this->getConf( 'googleAPIkey' )) {
528			$imgUrl .= "&key=" . $this->getConf( 'googleAPIkey' );
529		}
530		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getGoogle: Google image url is:');
531		return $imgUrl;
532	}
533
534	/**
535	 * Create a Bing maps static image url w/ the poi.
536	 *
537	 * @param array $gmap
538	 * @param array $overlay
539	 */
540	private function _getBing($gmap, $overlay) {
541		switch ($gmap ['baselyr']) {
542			case 've hybrid' :
543			case 'bing hybrid' :
544				$maptype = 'AerialWithLabels';
545				break;
546			case 've sat' :
547			case 'bing sat' :
548				$maptype = 'Aerial';
549				break;
550			case 've normal' :
551			case 've road' :
552			case 've' :
553			case 'bing road' :
554			default :
555				$maptype = 'Road';
556				break;
557		}
558		$imgUrl = "http://dev.virtualearth.net/REST/v1/Imagery/Map/" . $maptype;// . "/";
559		if ($this->getConf ( 'autoZoomMap' )) {
560			$bbox = $this->_calcBBOX ( $overlay, $gmap ['lat'], $gmap ['lon'] );
561			//$imgUrl .= "?ma=" . $bbox ['minlat'] . "," . $bbox ['minlon'] . "," . $bbox ['maxlat'] . "," . $bbox ['maxlon'];
562			$imgUrl .= "?ma=" . $bbox ['minlat'] . "%2C" . $bbox ['minlon'] . "%2C" . $bbox ['maxlat'] . "%2C" . $bbox ['maxlon'];
563			$imgUrl .= "&dcl=1";
564		}
565		if (strpos ( $imgUrl, "?" ) === false)
566			$imgUrl .= "?";
567
568		//$imgUrl .= "&ms=" . str_replace ( "px", "", $gmap ['width'] ) . "," . str_replace ( "px", "", $gmap ['height'] );
569		$imgUrl .= "&ms=" . str_replace ( "px", "", $gmap ['width'] ) . "%2C" . str_replace ( "px", "", $gmap ['height'] );
570		$imgUrl .= "&key=" . $this->getConf ( 'bingAPIKey' );
571		if (! empty ( $overlay )) {
572			$rowId = 0;
573			foreach ( $overlay as $data ) {
574				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
575				// TODO icon style lookup, see: http://msdn.microsoft.com/en-us/library/ff701719.aspx for iconStyle
576				$iconStyle = 32;
577				$rowId ++;
578				// NOTE: the max number of pushpins is 18! or we have to use POST (http://msdn.microsoft.com/en-us/library/ff701724.aspx)
579				if ($rowId == 18) {
580					break;
581				}
582				//$imgUrl .= "&pp=$lat,$lon;$iconStyle;$rowId";
583				$imgUrl .= "&pp=$lat%2C$lon%3B$iconStyle%3B$rowId";
584
585			}
586		}
587		global $conf;
588		$imgUrl .= "&fmt=png";
589		$imgUrl .= "&c=" . $conf ['lang'];
590		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getBing: bing image url is:');
591		return $imgUrl;
592	}
593
594	/**
595	 * Create a static OSM map image url w/ the poi from http://staticmap.openstreetmap.de (staticMapLite)
596	 * use http://staticmap.openstreetmap.de "staticMapLite" or a local version
597	 *
598	 * @param array $gmap
599	 * @param array $overlay
600	 *
601	 * @todo implementation for http://ojw.dev.openstreetmap.org/StaticMapDev/
602	 */
603	private function _getStaticOSM($gmap, $overlay) {
604		global $conf;
605
606		if ($this->getConf ( 'optionStaticMapGenerator' ) == 'local') {
607			// using local basemap composer
608			if (! $myMap = &plugin_load ( 'helper', 'openlayersmap_staticmap' )) {
609				dbglog ( $myMap, 'syntax_plugin_openlayersmap_olmap::_getStaticOSM: openlayersmap_staticmap plugin is not available.' );
610			}
611			if (! $geophp = &plugin_load ( 'helper', 'geophp' )) {
612				dbglog ( $geophp, 'syntax_plugin_openlayersmap_olmap::_getStaticOSM: geophp plugin is not available.' );
613			}
614			$size = str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
615
616			$markers = '';
617			if (! empty ( $overlay )) {
618				foreach ( $overlay as $data ) {
619					list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
620					$iconStyle = substr ( $img, 0, strlen ( $img ) - 4 );
621					$markers [] = array (
622							'lat' => $lat,
623							'lon' => $lon,
624							'type' => $iconStyle
625					);
626				}
627			}
628
629			switch ($gmap ['baselyr']) {
630				case 'mapnik' :
631				case 'openstreetmap' :
632					$maptype = 'openstreetmap';
633					break;
634				case 'transport' :
635					$maptype = 'transport';
636					break;
637				case 'landscape' :
638					$maptype = 'landscape';
639					break;
640				case 'cycle map' :
641					$maptype = 'cycle';
642					break;
643				case 'hike and bike map' :
644					$maptype = 'hikeandbike';
645					break;
646				case 'mapquest hybrid' :
647				case 'mapquest road' :
648				case 'mapquest sat' :
649					$maptype = 'mapquest';
650					break;
651				default :
652					$maptype = '';
653					break;
654			}
655
656			$result = $myMap->getMap ( $gmap ['lat'], $gmap ['lon'], $gmap ['zoom'], $size, $maptype, $markers, $gmap ['gpxfile'], $gmap ['kmlfile'], $gmap ['geojsonfile'] );
657		} else {
658			// using external basemap composer
659
660			// http://staticmap.openstreetmap.de/staticmap.php?center=47.000622235634,10.117187497601&zoom=5&size=500x350
661			// &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
662			$imgUrl = "http://staticmap.openstreetmap.de/staticmap.php";
663			$imgUrl .= "?center=" . $gmap ['lat'] . "," . $gmap ['lon'];
664			$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
665
666			if ($gmap ['zoom'] > 16) {
667				// actually this could even be 18, but that seems overkill
668				$imgUrl .= "&zoom=16";
669			} else {
670				$imgUrl .= "&zoom=" . $gmap ['zoom'];
671			}
672
673			if (! empty ( $overlay )) {
674				$rowId = 0;
675				$imgUrl .= "&markers=";
676				foreach ( $overlay as $data ) {
677					list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
678					$rowId ++;
679					$iconStyle = "lightblue$rowId";
680					$imgUrl .= "$lat,$lon,$iconStyle%7c";
681				}
682				$imgUrl = substr ( $imgUrl, 0, - 3 );
683			}
684
685			$result = $imgUrl;
686		}
687		// dbglog ( $result, 'syntax_plugin_openlayersmap_olmap::_getStaticOSM: osm image url is:' );
688		return $result;
689	}
690
691	/**
692	 * Calculate the minimum bbox for a start location + poi.
693	 *
694	 * @param array $overlay
695	 *        	multi-dimensional array of array($lat, $lon, $text, $angle, $opacity, $img)
696	 * @param float $lat
697	 *        	latitude for map center
698	 * @param float $lon
699	 *        	longitude for map center
700	 * @return multitype:float array describing the mbr and center point
701	 */
702	private function _calcBBOX($overlay, $lat, $lon) {
703		$lats [] = $lat;
704		$lons [] = $lon;
705		foreach ( $overlay as $data ) {
706			list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
707			$lats [] = $lat;
708			$lons [] = $lon;
709		}
710		sort ( $lats );
711		sort ( $lons );
712		// TODO: make edge/wrap around cases work
713		$centerlat = $lats [0] + ($lats [count ( $lats ) - 1] - $lats [0]);
714		$centerlon = $lons [0] + ($lons [count ( $lats ) - 1] - $lons [0]);
715		return array (
716				'minlat' => $lats [0],
717				'minlon' => $lons [0],
718				'maxlat' => $lats [count ( $lats ) - 1],
719				'maxlon' => $lons [count ( $lats ) - 1],
720				'centerlat' => $centerlat,
721				'centerlon' => $centerlon
722		);
723	}
724
725	/**
726	 * Figures out the base filename of a media path.
727	 *
728	 * @param String $mediaLink
729	 */
730	private function getFileName($mediaLink) {
731		$mediaLink = str_replace ( '[[', '', $mediaLink );
732		$mediaLink = str_replace ( ']]', '', $mediaLink );
733		$mediaLink = substr ( $mediaLink, 0, - 4 );
734		$parts = explode ( ':', $mediaLink );
735		$mediaLink = end ( $parts );
736		return str_replace ( '_', ' ', $mediaLink );
737	}
738
739	/**
740	 * Convert decimal degrees to degrees, minutes, seconds format
741	 *
742	 * @todo move this into a shared library
743	 * @param float $decimaldegrees
744	 * @return string dms
745	 */
746	private function _convertDDtoDMS($decimaldegrees) {
747		$dms = floor ( $decimaldegrees );
748		$secs = ($decimaldegrees - $dms) * 3600;
749		$min = floor ( $secs / 60 );
750		$sec = round ( $secs - ($min * 60), 3 );
751		$dms .= 'º' . $min . '\'' . $sec . '"';
752		return $dms;
753	}
754
755	/**
756	 * convert latitude in decimal degrees to DMS+hemisphere.
757	 *
758	 * @todo move this into a shared library
759	 * @param float $decimaldegrees
760	 * @return string
761	 */
762	private function convertLat($decimaldegrees) {
763		if (strpos ( $decimaldegrees, '-' ) !== false) {
764			$latPos = "S";
765		} else {
766			$latPos = "N";
767		}
768		$dms = $this->_convertDDtoDMS ( abs ( floatval ( $decimaldegrees ) ) );
769		return hsc ( $dms . $latPos );
770	}
771
772	/**
773	 * convert longitude in decimal degrees to DMS+hemisphere.
774	 *
775	 * @todo move this into a shared library
776	 * @param float $decimaldegrees
777	 * @return string
778	 */
779	private function convertLon($decimaldegrees) {
780		if (strpos ( $decimaldegrees, '-' ) !== false) {
781			$lonPos = "W";
782		} else {
783			$lonPos = "E";
784		}
785		$dms = $this->_convertDDtoDMS ( abs ( floatval ( $decimaldegrees ) ) );
786		return hsc ( $dms . $lonPos );
787	}
788}
789