xref: /plugin/openlayersmap/syntax/olmap.php (revision 8a442ab1a002c46ffc63f3f5a9910e281edd55f0)
1<?php
2/*
3 * Copyright (c) 2008-2013 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'))define('DOKU_INC', realpath(dirname(__FILE__) . '/../../') . '/');
18if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
19require_once (DOKU_PLUGIN . 'syntax.php');
20
21/**
22 * DokuWiki Plugin openlayersmap (Syntax Component).
23 * Provides for display of an OpenLayers based map in a wiki page.
24 *
25 * @author Mark Prins
26 */
27class syntax_plugin_openlayersmap_olmap extends DokuWiki_Syntax_Plugin {
28
29	/** defaults of the known attributes of the olmap tag. */
30	private $dflt = array (
31			'id'		=> 'olmap',
32			'width'		=> '550px',
33			'height'	=> '450px',
34			'lat'		=> 50.0,
35			'lon'		=> 5.1,
36			'zoom'		=> 12,
37			'statusbar'	=> true,
38			'controls'	=> true,
39			'poihoverstyle'	=> false,
40			'baselyr'	=> 'OpenStreetMap',
41			'gpxfile'	=> '',
42			'kmlfile'	=> '',
43			'geojsonfile'=> '',
44			'summary'	=> ''
45	);
46
47	/**
48	 * @see DokuWiki_Syntax_Plugin::getType()
49	 */
50	function getType() {
51		return 'substition';
52	}
53
54	/**
55	 * @see DokuWiki_Syntax_Plugin::getPType()
56	 */
57	function getPType() {
58		return 'block';
59	}
60
61	/**
62	 * @see Doku_Parser_Mode::getSort()
63	 */
64	function getSort() {
65		return 901;
66	}
67
68	/**
69	 * @see Doku_Parser_Mode::connectTo()
70	 */
71	function connectTo($mode) {
72		$this->Lexer->addSpecialPattern('<olmap ?[^>\n]*>.*?</olmap>', $mode, 'plugin_openlayersmap_olmap');
73	}
74
75	/**
76	 * @see DokuWiki_Syntax_Plugin::handle()
77	 */
78	function handle($match, $state, $pos, &$handler) {
79		// break matched cdata into its components
80		list ($str_params, $str_points) = explode('>', substr($match, 7, -9), 2);
81		// get the lat/lon for adding them to the metadata (used by geotag)
82		preg_match('(lat[:|=]\"-?\d*\.\d*\")',$match,$mainLat);
83		preg_match('(lon[:|=]\"-?\d*\.\d*\")',$match,$mainLon);
84		$mainLat=substr($mainLat[0],5,-1);
85		$mainLon=substr($mainLon[0],5,-1);
86
87		$gmap = $this->_extract_params($str_params);
88		$overlay = $this->_extract_points($str_points);
89		$_firstimageID ='';
90
91		// choose maptype based on tag
92		$imgUrl = "{{";
93		if (stripos($gmap['baselyr'],'google') !== false){
94			// use google
95			$imgUrl .= $this->_getGoogle($gmap, $overlay);
96			$imgUrl .="&.png";
97		} elseif (stripos($gmap['baselyr'],'ve') !== false){
98			// use bing
99			$imgUrl .= $this->_getBing($gmap, $overlay);
100			$imgUrl .="&.png";
101		} elseif (stripos($gmap['baselyr'],'bing') !== false){
102			// use bing
103			$imgUrl .= $this->_getBing($gmap, $overlay);
104			$imgUrl .="&.png";
105		} elseif (stripos($gmap['baselyr'],'mapquest') !== false){
106			if($this->getConf('optionStaticMapGenerator')=='remote'){
107				// use mapquest remote
108				$imgUrl .=$this->_getMapQuest($gmap,$overlay);
109				$imgUrl .="&.png";
110			} else{
111				$_firstimageID = $this->_getStaticOSM($gmap,$overlay);
112				$imgUrl .= $_firstimageID;
113			}
114		} else {
115			$_firstimageID = $this->_getStaticOSM($gmap,$overlay);
116			$imgUrl .= $_firstimageID;
117			if($this->getConf('optionStaticMapGenerator')=='remote'){
118				$imgUrl .="&.png";
119			}
120		}
121
122		// append dw p_render specific params and render
123		$imgUrl .="?".str_replace("px", "",$gmap['width'])."x".str_replace("px", "",$gmap['height']);
124		$imgUrl .= "&nolink";
125		$imgUrl .= " |".$gmap['summary']." }}";
126
127		$mapid = $gmap['id'];
128		// create a javascript parameter string for the map
129		$param = '';
130		foreach ($gmap as $key => $val) {
131			$param .= is_numeric($val) ? "$key: $val, " : "$key: '" . hsc($val) . "', ";
132		}
133		if (!empty ($param)) {
134			$param = substr($param, 0, -2);
135		}
136		unset ($gmap['id']);
137
138		// create a javascript serialisation of the point data
139		$poi = '';
140		$poitable='';
141		$rowId=0;
142		if (!empty ($overlay)) {
143			foreach ($overlay as $data) {
144				list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
145				$rowId++;
146				$poi .= ", {lat: $lat, lon: $lon, txt: '$text', angle: $angle, opacity: $opacity, img: '$img', rowId: $rowId}";
147				$poitable .='
148						<tr>
149						<td class="rowId">'.$rowId.'</td>
150								<td class="icon"><img src="'.DOKU_BASE.'lib/plugins/openlayersmap/icons/'.$img.'" alt="icon" /></td>
151										<td class="lat" title="'.$this->getLang('olmapPOIlatTitle').'">'.$lat.'</td>
152												<td class="lon" title="'.$this->getLang('olmapPOIlonTitle').'">'.$lon.'</td>
153														<td class="txt">'.$text.'</td>
154																</tr>';
155			}
156			$poi = substr($poi, 2);
157		}
158		if (!empty ($gmap['kmlfile'])) {
159			$poitable .='
160					<tr>
161					<td class="rowId"><img src="'.DOKU_BASE.'lib/plugins/openlayersmap/toolbar/kml_file.png" alt="KML icon" /></td>
162							<td class="icon"><img src="'.DOKU_BASE.'lib/plugins/openlayersmap/toolbar/kml_line.png" alt="icon" /></td>
163									<td class="txt" colspan="3">KML track: '.$this->getFileName($gmap['kmlfile']).'</td>
164											</tr>';
165		}
166		if (!empty ($gmap['gpxfile'])) {
167			$poitable .='
168					<tr>
169					<td class="rowId"><img src="'.DOKU_BASE.'lib/plugins/openlayersmap/toolbar/gpx_file.png" alt="GPX icon" /></td>
170							<td class="icon"><img src="'.DOKU_BASE.'lib/plugins/openlayersmap/toolbar/gpx_line.png" alt="icon" /></td>
171									<td class="txt" colspan="3">GPX track: '.$this->getFileName($gmap['gpxfile']).'</td>
172											</tr>';
173		}
174		if (!empty ($gmap['geojsonfile'])) {
175			$poitable .='
176					<tr>
177					<td class="rowId"><img src="'.DOKU_BASE.'lib/plugins/openlayersmap/toolbar/geojson_file.png" alt="KML icon" /></td>
178							<td class="icon"><img src="'.DOKU_BASE.'lib/plugins/openlayersmap/toolbar/geojson_line.png" alt="icon" /></td>
179									<td class="txt" colspan="3">GeoJSON track: '.$this->getFileName($gmap['geojsonfile']).'</td>
180											</tr>';
181		}
182
183		$js .= "{mapOpts:{" . $param . " },poi:[$poi]};";
184		// unescape the json
185		$poitable = stripslashes($poitable);
186
187		return array($mapid,$js,$mainLat,$mainLon,$poitable,$gmap['summary'],$imgUrl,$_firstimageID);
188	}
189
190	/**
191	 * @see DokuWiki_Syntax_Plugin::render()
192	 */
193	function render($mode, &$renderer, $data) {
194		// set to true after external scripts tags are written
195		static $initialised = false;
196		// incremented for each map tag in the page source so we can keep track of each map in a page
197		static $mapnumber = 0;
198
199		// dbglog($data, 'olmap::render() data.');
200		list ($mapid, $param, $mainLat, $mainLon, $poitable, $poitabledesc, $staticImgUrl, $_firstimage) = $data;
201
202		if ($mode == 'xhtml') {
203			$olscript = '';
204			$olEnable = false;
205			$gscript = '';
206			$gEnable = $this->getConf('enableGoogle');
207			$mqEnable = $this->getConf('enableMapQuest');
208			$osmEnable = $this->getConf('enableOSM');
209			$enableBing = $this->getConf('enableBing');
210
211			$scriptEnable = '';
212
213			if (!$initialised) {
214				$initialised = true;
215				// render necessary script tags
216				if($gEnable){
217					$gscript ='<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.11&amp;sensor=false"></script>';
218				}
219				$olscript = $this->getConf('olScriptUrl');
220				$olscript = $olscript ? '<script type="text/javascript" src="' . $olscript . '"></script>' : "";
221				$olscript = str_replace('DOKU_BASE/', DOKU_BASE, $olscript);
222
223				$scriptEnable = '<script type="text/javascript" charset="utf-8">/*<![CDATA[*/';
224				$scriptEnable .= $olscript ? 'olEnable = true;' : 'olEnable = false;';
225				$scriptEnable .= 'gEnable = '.($gEnable ? 'true' : 'false').';';
226				$scriptEnable .= 'osmEnable = '.($osmEnable ? 'true' : 'false').';';
227				$scriptEnable .= 'mqEnable = '.($mqEnable ? 'true' : 'false').';';
228				$scriptEnable .= 'bEnable = '.($enableBing ? 'true' : 'false').';';
229				$scriptEnable .= 'bApiKey="'.$this->getConf('bingAPIKey').'";';
230				$scriptEnable .= 'OpenLayers.ImgPath = "'.DOKU_BASE.'lib/plugins/openlayersmap/lib/'.$this->getConf('olMapStyle').'/";';
231				$scriptEnable .= '/*!]]>*/</script>';
232			}
233			$renderer->doc .= "
234			$gscript
235			$olscript
236			$scriptEnable";
237
238			if ($this->getConf('enableA11y')){
239				$renderer->doc .= '<div id="'.$mapid.'-static" class="olStaticMap">'.p_render($mode, p_get_instructions($staticImgUrl), $info).'</div>';
240			}
241			$renderer->doc .= '<div id="'.$mapid.'-clearer" class="clearer"><p>&nbsp;</p></div>';
242			if ($this->getConf('enableA11y')){
243				// render a (initially hidden) table of the POI for the print and a11y presentation
244				$renderer->doc .= '<div class="olPOItableSpan" id="'.$mapid.'-table-span"><table class="olPOItable" id="'.$mapid.'-table" summary="'.$poitabledesc.'" title="'.$this->getLang('olmapPOItitle').'">
245<caption class="olPOITblCaption">'.$this->getLang('olmapPOItitle').'</caption>
246<thead class="olPOITblHeader">
247<tr>
248<th class="rowId" scope="col">id</th>
249<th class="icon" scope="col">'.$this->getLang('olmapPOIicon').'</th>
250<th class="lat" scope="col" title="'.$this->getLang('olmapPOIlatTitle').'">'.$this->getLang('olmapPOIlat').'</th>
251<th class="lon" scope="col" title="'.$this->getLang('olmapPOIlonTitle').'">'.$this->getLang('olmapPOIlon').'</th>
252<th class="txt" scope="col">'.$this->getLang('olmapPOItxt').'</th>
253</tr>
254</thead>';
255				if ($poitabledesc !=''){
256					$renderer->doc .='<tfoot class="olPOITblFooter"><tr><td colspan="5">'.$poitabledesc.'</td></tr></tfoot>';
257				}
258				$renderer->doc .='<tbody class="olPOITblBody">'.$poitable.'</tbody>
259</table></div>';
260			}
261			// render inline mapscript parts
262			$renderer->doc .='<script type="text/javascript" charset="utf-8">/*<![CDATA[*/';
263			$renderer->doc .=" olMapData[$mapnumber] = $param /*!]]>*/</script>";
264			$mapnumber++;
265			return true;
266		} elseif ($mode == 'metadata') {
267			if (!(($this->dflt['lat']==$mainLat) && ($thisdflt['lon']==$mainLon))){
268				// render geo metadata, unless they are the default
269				$renderer->meta['geo']['lat'] = $mainLat;
270				$renderer->meta['geo']['lon'] = $mainLon;
271				if ($geophp = &plugin_load('helper', 'geophp')){
272					// if we have the geoPHP helper, add the geohash
273					// fails with older php versions.. $renderer->meta['geo']['geohash'] = (new Point($mainLon,$mainLat))->out('geohash');
274					$p = new Point($mainLon,$mainLat);
275					$renderer->meta['geo']['geohash'] = $p->out('geohash');
276				}
277			}
278
279			if(($this->getConf('enableA11y')) && (!empty($_firstimage))){
280				// add map local image into relation/firstimage if not already filled and when it is a local image
281
282				global $ID;
283				$rel = p_get_metadata($ID, 'relation', METADATA_RENDER_USING_CACHE);
284				$img = $rel['firstimage'];
285				if(empty($img) /* || $img == $_firstimage*/){
286					dbglog($_firstimage,'olmap::render#rendering image relation metadata for _firstimage as $img was empty or the same.');
287					// This seems to never work; the firstimage entry in the .meta file is empty
288					// $renderer->meta['relation']['firstimage'] = $_firstimage;
289
290					// ... and neither does this; the firstimage entry in the .meta file is empty
291					// $relation = array('relation'=>array('firstimage'=>$_firstimage));
292					// p_set_metadata($ID, $relation, false, false);
293
294					// ... this works
295					$renderer->internalmedia($_firstimage, $poitabledesc);
296				}
297			}
298			return true;
299		}
300		return false;
301	}
302
303	/**
304	 * extract parameters for the map from the parameter string
305	 *
306	 * @param   string    $str_params   string of key="value" pairs
307	 * @return  array                   associative array of parameters key=>value
308	 */
309	private function _extract_params($str_params) {
310		$param = array ();
311		preg_match_all('/(\w*)="(.*?)"/us', $str_params, $param, PREG_SET_ORDER);
312		// parse match for instructions, break into key value pairs
313		$gmap = $this->dflt;
314		foreach ($param as $kvpair) {
315			list ($match, $key, $val) = $kvpair;
316			$key = strtolower($key);
317			if (isset ($gmap[$key])){
318				if ($key == 'summary'){
319					// preserve case for summary field
320					$gmap[$key] = $val;
321				}else {
322					$gmap[$key] = strtolower($val);
323				}
324			}
325		}
326		return $gmap;
327	}
328
329	/**
330	 * extract overlay points for the map from the wiki syntax data
331	 *
332	 * @param   string    $str_points   multi-line string of lat,lon,text triplets
333	 * @return  array                   multi-dimensional array of lat,lon,text triplets
334	 */
335	private function _extract_points($str_points) {
336		$point = array ();
337		//preg_match_all('/^([+-]?[0-9].*?),\s*([+-]?[0-9].*?),(.*?),(.*?),(.*?),(.*)$/um', $str_points, $point, PREG_SET_ORDER);
338		/*
339		group 1: ([+-]?[0-9]+(?:\.[0-9]*)?)
340		group 2: ([+-]?[0-9]+(?:\.[0-9]*)?)
341		group 3: (.*?)
342		group 4: (.*?)
343		group 5: (.*?)
344		group 6: (.*)
345		*/
346		preg_match_all('/^([+-]?[0-9]+(?:\.[0-9]*)?),\s*([+-]?[0-9]+(?:\.[0-9]*)?),(.*?),(.*?),(.*?),(.*)$/um', $str_points, $point, PREG_SET_ORDER);
347		// create poi array
348		$overlay = array ();
349		foreach ($point as $pt) {
350			list ($match, $lat, $lon, $angle, $opacity, $img, $text) = $pt;
351			$lat = is_numeric($lat) ? $lat : 0;
352			$lon = is_numeric($lon) ? $lon : 0;
353			$angle = is_numeric($angle) ? $angle : 0;
354			$opacity = is_numeric($opacity) ? $opacity : 0.8;
355			$img = trim($img);
356			// TODO validate using exist & set up default img?
357			$text = addslashes(str_replace("\n", "", p_render("xhtml", p_get_instructions($text), $info)));
358			$overlay[] = array($lat, $lon, $text, $angle, $opacity, $img);
359		}
360		return $overlay;
361	}
362
363	/**
364	 * Create a MapQuest static map API image url.
365	 * @param array $gmap
366	 * @param array $overlay
367	 */
368	private function _getMapQuest($gmap,$overlay) {
369		$sUrl=$this->getConf('iconUrlOverload');
370		if (!$sUrl){
371			$sUrl=DOKU_URL;
372		}
373		switch ($gmap['baselyr']){
374			case 'mapquest hybrid':
375				$maptype='hyb';
376				break;
377			case 'mapquest sat':
378				// because sat coverage is very limited use 'hyb' instead of 'sat' so we don't get a blank map
379				$maptype='hyb';
380				break;
381			case 'mapquest road':
382			default:
383				$maptype='map';
384				break;
385		}
386		$imgUrl = "http://open.mapquestapi.com/staticmap/v4/getmap?declutter=true&";
387		if (count($overlay)< 1){
388			$imgUrl .= "?center=".$gmap['lat'].",".$gmap['lon'];
389			//max level for mapquest is 16
390			if ($gmap['zoom']>16) {
391				$imgUrl .= "&zoom=16";
392			} else			{
393				$imgUrl .= "&zoom=".$gmap['zoom'];
394			}
395		}
396		// use bestfit instead of center/zoom, needs upperleft/lowerright corners
397		//$bbox=$this->_calcBBOX($overlay, $gmap['lat'], $gmap['lon']);
398		//$imgUrl .= "bestfit=".$bbox['minlat'].",".$bbox['maxlon'].",".$bbox['maxlat'].",".$bbox['minlon'];
399
400		// TODO declutter option works well for square maps but not for rectangular, maybe compensate for that or compensate the mbr..
401		$imgUrl .= "&size=".str_replace("px", "",$gmap['width']).",".str_replace("px", "",$gmap['height']);
402
403		// TODO mapquest allows using one image url with a multiplier $NUMBER eg:
404		// $NUMBER = 2
405		// $imgUrl .= DOKU_URL."/".DOKU_PLUGIN."/".getPluginName()."/icons/".$img.",$NUMBER,C,".$lat1.",".$lon1.",0,0,0,0,C,".$lat2.",".$lon2.",0,0,0,0";
406		if (!empty ($overlay)) {
407			$imgUrl .= "&xis=";
408			foreach ($overlay as $data) {
409				list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
410				//$imgUrl .= $sUrl."lib/plugins/openlayersmap/icons/".$img.",1,C,".$lat.",".$lon.",0,0,0,0,";
411				$imgUrl .= $sUrl."lib/plugins/openlayersmap/icons/".$img.",1,C,".$lat.",".$lon.",";
412			}
413			$imgUrl = substr($imgUrl,0,-1);
414		}
415		$imgUrl .= "&imageType=png&type=".$maptype;
416		//dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getMapQuest: MapQuest image url is:');
417		return $imgUrl;
418	}
419
420	/**
421	 * Create a Google maps static image url w/ the poi.
422	 * @param array $gmap
423	 * @param array $overlay
424	 */
425	private function _getGoogle($gmap, $overlay){
426		$sUrl=$this->getConf('iconUrlOverload');
427		if (!$sUrl){
428			$sUrl=DOKU_URL;
429		}
430		switch ($gmap['baselyr']){
431			case 'google hybrid':
432				$maptype='hybrid';
433				break;
434			case 'google sat':
435				$maptype='satellite';
436				break;
437			case 'google relief':
438				$maptype='terrain';
439				break;
440			case 'google road':
441			default:
442				$maptype='roadmap';
443				break;
444		}
445		// TODO maybe use viewport / visible instead of center/zoom,
446		//		see: https://code.google.com/intl/nl/apis/maps/documentation/staticmaps/#ImplicitPositioning
447		//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
448		$imgUrl = "http://maps.google.com/maps/api/staticmap?sensor=false";
449		$imgUrl .= "&size=".str_replace("px", "",$gmap['width'])."x".str_replace("px", "",$gmap['height']);
450		$imgUrl .= "&center=".$gmap['lat'].",".$gmap['lon'];
451		// max is 21 (== building scale), but that's overkill..
452		if ($gmap['zoom']>17) {
453			$imgUrl .= "&zoom=17";
454		} else			{
455			$imgUrl .= "&zoom=".$gmap['zoom'];
456		}
457
458		if (!empty ($overlay)) {
459			$rowId=0;
460			foreach ($overlay as $data) {
461				list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
462				$imgUrl .= "&markers=icon%3a".$sUrl."lib/plugins/openlayersmap/icons/".$img."%7c".$lat.",".$lon."%7clabel%3a".++$rowId;
463			}
464		}
465		$imgUrl .= "&format=png&maptype=".$maptype;
466		global $conf;
467		$imgUrl .= "&language=".$conf['lang'];
468		//dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getGoogle: Google image url is:');
469		return $imgUrl;
470	}
471
472	/**
473	 * Create a Bing maps static image url w/ the poi.
474	 * @param array $gmap
475	 * @param array $overlay
476	 */
477	private function _getBing($gmap, $overlay){
478		if(!$this->getConf('bingAPIKey')){
479			// in case there is no Bing api key we'll use OSM
480			$this->_getStaticOSM($gmap, $overlay);
481		}
482		switch ($gmap['baselyr']){
483			case 've hybrid':
484			case 'bing hybrid':
485				$maptype='AerialWithLabels';
486				break;
487			case 've sat':
488			case 'bing sat':
489				$maptype='Aerial';
490				break;
491			case 've normal':
492			case 've road':
493			case 've':
494			case 'bing road':
495			default:
496				$maptype='Road';
497				break;
498		}
499		$imgUrl = "http://dev.virtualearth.net/REST/v1/Imagery/Map/".$maptype."/";
500		if (!$this->getConf('autoZoomMap')){
501			$bbox=$this->_calcBBOX($overlay, $gmap['lat'], $gmap['lon']);
502			$imgUrl .= "?mapArea=".$bbox['minlat'].",".$bbox['minlon'].",".$bbox['maxlat'].",".$bbox['maxlon'];
503			$imgUrl .= "&declutter=1";
504			// or
505			//$imgUrl .= $gmap['lat'].",".$gmap['lon']."/".$gmap['zoom']."?";
506		}
507		if (strpos($imgUrl, "?") === false) $imgUrl .= "?";
508
509		$imgUrl .= "&ms=".str_replace("px", "",$gmap['width']).",".str_replace("px", "",$gmap['height']);
510		$imgUrl .= "&key=".$this->getConf('bingAPIKey');
511		if (!empty ($overlay)) {
512			$rowId=0;
513			foreach ($overlay as $data) {
514				list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
515				// TODO icon style lookup, see: http://msdn.microsoft.com/en-us/library/ff701719.aspx for iconStyle
516				$iconStyle=32;
517				$rowId++;
518				// NOTE: the max number of pushpins is 18! or we have tuo use POST (http://msdn.microsoft.com/en-us/library/ff701724.aspx)
519				if ($rowId==18) {
520					break;
521				}
522				$imgUrl .= "&pp=$lat,$lon;$iconStyle;$rowId";
523			}
524		}
525		//dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getBing: bing image url is:');
526		return $imgUrl;
527	}
528
529	/**
530	 * Create a static OSM map image url w/ the poi from http://staticmap.openstreetmap.de (staticMapLite)
531	 * use http://staticmap.openstreetmap.de "staticMapLite" or a local version
532	 * @param array $gmap
533	 * @param array $overlay
534	 *
535	 * @todo implementation for http://ojw.dev.openstreetmap.org/StaticMapDev/
536	 */
537	private function _getStaticOSM($gmap, $overlay){
538		//http://staticmap.openstreetmap.de/staticmap.php?center=47.000622235634,10.117187497601&zoom=5&size=500x350
539		// &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
540		global $conf;
541
542		if ($this->getConf('optionStaticMapGenerator')=='local') {
543			if (!$my = &plugin_load('helper', 'openlayersmap_staticmap')){
544				dbglog($my,'syntax_plugin_openlayersmap_olmap::_getStaticOSM: openlayersmap_staticmap plugin is not available.');
545			}
546			if (!$geophp = &plugin_load('helper', 'geophp')){
547				dbglog($geophp,'syntax_plugin_openlayersmap_olmap::_getStaticOSM: geophp plugin is not available.');
548			}
549			$size = str_replace("px", "",$gmap['width'])."x".str_replace("px", "",$gmap['height']);
550
551			$markers='';
552			if (!empty ($overlay)) {
553				foreach ($overlay as $data) {
554					list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
555					$iconStyle = substr($img, 0, strlen($img)-4);
556					$markers[] = array(
557							'lat'=>$lat,
558							'lon'=>$lon,
559							'type'=>$iconStyle);
560				}
561			}
562
563			$result = $my->getMap($gmap['lat'], $gmap['lon'], $gmap['zoom'],
564					$size, $maptype, $markers, $gmap['gpxfile'], $gmap['kmlfile'], $gmap['geojsonfile']);
565		} else {
566			// default to external provider
567			$imgUrl = "http://staticmap.openstreetmap.de/staticmap.php";
568			$imgUrl .= "?center=".$gmap['lat'].",".$gmap['lon'];
569			$imgUrl .= "&size=".str_replace("px", "",$gmap['width'])."x".str_replace("px", "",$gmap['height']);
570
571
572			if ($gmap['zoom']>16) {
573				// actually this could even be 18, but that seems overkill
574				$imgUrl .= "&zoom=16";
575			} else {
576				$imgUrl .= "&zoom=".$gmap['zoom'];
577			}
578
579			switch ($gmap['baselyr']){
580				case 'mapnik':
581				case 'openstreetmap':
582					$maptype='openstreetmap';
583					break;
584				case 'transport':
585					$maptype='transport';
586					break;
587				case 'landscape':
588					$maptype='landscape';
589					break;
590				case 'cycle map':
591					$maptype='cycle';
592					break;
593				case 'cloudmade':
594					$maptype='cloudmade';
595					break;
596				case 'cloudmade fresh':
597					$maptype='fresh';
598					break;
599				case 'hike and bike map':
600					$maptype='hikeandbike';
601					break;
602				case 'mapquest hybrid':
603				case 'mapquest road':
604				case 'mapquest sat':
605					$maptype='mapquest';
606					break;
607				default:
608					$maptype='';
609					break;
610			}
611			$imgUrl .= "&maptype=".$maptype;
612
613			if (!empty ($overlay)) {
614				$rowId=0;
615				$imgUrl .= "&markers=";
616				foreach ($overlay as $data) {
617					list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
618					$rowId++;
619					$iconStyle = "lightblue$rowId";
620					$imgUrl .= "$lat,$lon,$iconStyle%7c";
621				}
622				$imgUrl = substr($imgUrl,0,-3);
623			}
624
625			$result = $imgUrl;
626		}
627
628		//dbglog($result,'syntax_plugin_openlayersmap_olmap::_getStaticOSM: osm image url is:');
629		return $result;
630	}
631
632	/**
633	 * Calculate the minimum bbox for a start location + poi.
634	 *
635	 * @param array $overlay  multi-dimensional array of array($lat, $lon, $text, $angle, $opacity, $img)
636	 * @param float $lat latitude for map center
637	 * @param float $lon longitude for map center
638	 * @return multitype:float array describing the mbr and center point
639	 */
640	private function _calcBBOX($overlay, $lat, $lon){
641		$lats[] = $lat;
642		$lons[] = $lon;
643		foreach ($overlay as $data) {
644			list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
645			$lats[] = $lat;
646			$lons[] = $lon;
647		}
648		sort($lats);
649		sort($lons);
650		// TODO: make edge/wrap around cases work
651		$centerlat = $lats[0]+($lats[count($lats)-1]-$lats[0]);
652		$centerlon = $lons[0]+($lons[count($lats)-1]-$lons[0]);
653		return array('minlat'=>$lats[0], 'minlon'=>$lons[0],
654				'maxlat'=>$lats[count($lats)-1], 'maxlon'=>$lons[count($lats)-1],
655				'centerlat'=>$centerlat,'centerlon'=>$centerlon);
656	}
657
658	/**
659	 * Figures out the base filename of a media path.
660	 * @param String $mediaLink
661	 */
662	private function getFileName($mediaLink){
663		$mediaLink=str_replace('[[','',$mediaLink);
664		$mediaLink=str_replace(']]','',$mediaLink);
665		$mediaLink = substr($mediaLink, 0, -4);
666		$parts=explode(':',$mediaLink);
667		$mediaLink = end($parts);
668		return str_replace('_',' ',$mediaLink);
669	}
670}