You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

577 lines
18 KiB

  1. <?php
  2. namespace p3k\geo\StaticMap;
  3. use p3k\geo\WebMercator;
  4. use Imagick, ImagickPixel, ImagickDraw;
  5. function generate($params, $filename, $assetPath) {
  6. $bounds = array(
  7. 'minLat' => 90,
  8. 'maxLat' => -90,
  9. 'minLng' => 180,
  10. 'maxLng' => -180
  11. );
  12. // If any markers are specified, choose a default lat/lng as the center of all the markers
  13. $markers = array();
  14. if($markersTemp=k($params,'marker')) {
  15. if(!is_array($markersTemp))
  16. $markersTemp = array($markersTemp);
  17. // If no latitude is set, use the center of all the markers
  18. foreach($markersTemp as $i=>$m) {
  19. if(preg_match_all('/(?P<k>[a-z]+):(?P<v>[^;]+)/', $m, $matches)) {
  20. $properties = array();
  21. foreach($matches['k'] as $j=>$key) {
  22. $properties[$key] = $matches['v'][$j];
  23. }
  24. // Skip invalid marker definitions, show error in a header
  25. if(array_key_exists('icon', $properties) && (
  26. (array_key_exists('lat', $properties) && array_key_exists('lng', $properties))
  27. || array_key_exists('location', $properties)
  28. )
  29. ) {
  30. // Geocode the provided location and return lat/lng
  31. if(array_key_exists('location', $properties)) {
  32. $result = ArcGISGeocoder::geocode($properties['location']);
  33. if(!$result->success) {
  34. #header('X-Marker-' . ($i+1) . ': error geocoding location "' . $properties['location'] . '"');
  35. continue;
  36. }
  37. $properties['lat'] = $result->latitude;
  38. $properties['lng'] = $result->longitude;
  39. }
  40. if(preg_match('/https?:\/\/(.+)/', $properties['icon'], $match)) {
  41. // Looks like an external image, attempt to download it
  42. $ch = curl_init($properties['icon']);
  43. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  44. $img = curl_exec($ch);
  45. $properties['iconImg'] = @imagecreatefromstring($img);
  46. if(!$properties['iconImg']) {
  47. $properties['iconImg'] = false;
  48. }
  49. } else {
  50. $properties['iconImg'] = imagecreatefrompng($assetPath . '/' . $properties['icon'] . '.png');
  51. }
  52. if($properties['iconImg']) {
  53. $markers[] = $properties;
  54. }
  55. if($properties['lat'] < $bounds['minLat'])
  56. $bounds['minLat'] = $properties['lat'];
  57. if($properties['lat'] > $bounds['maxLat'])
  58. $bounds['maxLat'] = $properties['lat'];
  59. if($properties['lng'] < $bounds['minLng'])
  60. $bounds['minLng'] = $properties['lng'];
  61. if($properties['lng'] > $bounds['maxLng'])
  62. $bounds['maxLng'] = $properties['lng'];
  63. } else {
  64. #header('X-Marker-' . ($i+1) . ': missing icon, or lat/lng/location parameters');
  65. }
  66. }
  67. }
  68. }
  69. $paths = array();
  70. if($pathsTemp=k($params,'path')) {
  71. if(!is_array($pathsTemp))
  72. $pathsTemp = array($pathsTemp);
  73. foreach($pathsTemp as $i=>$path) {
  74. $properties = array();
  75. if(preg_match_all('/(?P<k>[a-z]+):(?P<v>[^;]+)/', $path, $matches)) {
  76. foreach($matches['k'] as $j=>$key) {
  77. $properties[$key] = $matches['v'][$j];
  78. }
  79. }
  80. // Set default color and weight if none specified
  81. if(!array_key_exists('color', $properties))
  82. $properties['color'] = '333333';
  83. if(!array_key_exists('weight', $properties))
  84. $properties['weight'] = 3;
  85. // Now parse the points into an array
  86. if(preg_match_all('/(?P<point>\[[0-9\.-]+,[0-9\.-]+\])/', $path, $matches)) {
  87. $properties['path'] = json_decode('[' . implode(',', $matches['point']) . ']');
  88. // Adjust the bounds to fit the path
  89. foreach($properties['path'] as $point) {
  90. if($point[1] < $bounds['minLat'])
  91. $bounds['minLat'] = $point[1];
  92. if($point[1] > $bounds['maxLat'])
  93. $bounds['maxLat'] = $point[1];
  94. if($point[0] < $bounds['minLng'])
  95. $bounds['minLng'] = $point[0];
  96. if($point[0] > $bounds['maxLng'])
  97. $bounds['maxLng'] = $point[0];
  98. }
  99. }
  100. if(array_key_exists('path', $properties))
  101. $paths[] = $properties;
  102. }
  103. }
  104. $defaultLatitude = $bounds['minLat'] + (($bounds['maxLat'] - $bounds['minLat']) / 2);
  105. $defaultLongitude = $bounds['minLng'] + (($bounds['maxLng'] - $bounds['minLng']) / 2);
  106. if(k($params,'latitude') !== false) {
  107. $latitude = k($params,'latitude');
  108. $longitude = k($params,'longitude');
  109. } elseif(k($params,'location') !== false) {
  110. $result = ArcGISGeocoder::geocode(k($params,'location'));
  111. if(!$result->success) {
  112. $latitude = $defaultLatitude;
  113. $longitude = $defaultLongitude;
  114. #header('X-Geocode: error');
  115. #header('X-Geocode-Result: ' . $result->raw);
  116. } else {
  117. $latitude = $result->latitude;
  118. $longitude = $result->longitude;
  119. #header('X-Geocode: success');
  120. #header('X-Geocode-Result: ' . $latitude . ', ' . $longitude);
  121. }
  122. } else {
  123. $latitude = $defaultLatitude;
  124. $longitude = $defaultLongitude;
  125. }
  126. $width = k($params, 'width', 300);
  127. $height = k($params, 'height', 300);
  128. // If no zoom is specified, choose a zoom level that will fit all the markers and the path
  129. if(k($params,'zoom')) {
  130. $zoom = k($params,'zoom');
  131. } else {
  132. // start at max zoom level (20)
  133. $fitZoom = 21;
  134. $doesNotFit = true;
  135. while($fitZoom > 1 && $doesNotFit) {
  136. $fitZoom--;
  137. $center = webmercator\latLngToPixels($latitude, $longitude, $fitZoom);
  138. $leftEdge = $center['x'] - $width/2;
  139. $topEdge = $center['y'] - $height/2;
  140. // check if the bounding rectangle fits within width/height
  141. $sw = webmercator\latLngToPixels($bounds['minLat'], $bounds['minLng'], $fitZoom);
  142. $ne = webmercator\latLngToPixels($bounds['maxLat'], $bounds['maxLng'], $fitZoom);
  143. // leave some padding around the objects
  144. $fitHeight = abs($ne['y'] - $sw['y']) + (0.1 * $height);
  145. $fitWidth = abs($ne['x'] - $sw['x']) + (0.1 * $width);
  146. if($fitHeight <= $height && $fitWidth <= $width) {
  147. $doesNotFit = false;
  148. }
  149. }
  150. $zoom = $fitZoom;
  151. }
  152. if(k($params,'maxzoom') && k($params,'maxzoom') < $zoom) {
  153. $zoom = k($params,'maxzoom');
  154. }
  155. $minZoom = 2;
  156. if($zoom < $minZoom)
  157. $zoom = $minZoom;
  158. $tileServices = array(
  159. 'streets' => array(
  160. 'http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{Z}/{Y}/{X}'
  161. ),
  162. 'satellite' => array(
  163. 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}'
  164. ),
  165. 'hybrid' => array(
  166. 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}',
  167. 'http://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{Z}/{Y}/{X}'
  168. ),
  169. 'topo' => array(
  170. 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{Z}/{Y}/{X}'
  171. ),
  172. 'gray' => array(
  173. 'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{Z}/{Y}/{X}',
  174. 'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer/tile/{Z}/{Y}/{X}'
  175. ),
  176. 'gray-background' => array(
  177. 'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{Z}/{Y}/{X}',
  178. ),
  179. 'oceans' => array(
  180. 'http://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{Z}/{Y}/{X}'
  181. ),
  182. 'national-geographic' => array(
  183. 'http://server.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{Z}/{Y}/{X}'
  184. ),
  185. 'osm' => array(
  186. 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'
  187. ),
  188. 'stamen-toner' => array(
  189. 'http://tile.stamen.com/toner/{Z}/{X}/{Y}.png'
  190. ),
  191. 'stamen-toner-background' => array(
  192. 'http://tile.stamen.com/toner-background/{Z}/{X}/{Y}.png'
  193. ),
  194. 'stamen-toner-lite' => array(
  195. 'http://tile.stamen.com/toner-lite/{Z}/{X}/{Y}.png'
  196. ),
  197. 'stamen-terrain' => array(
  198. 'http://tile.stamen.com/terrain/{Z}/{X}/{Y}.png'
  199. ),
  200. 'stamen-terrain-background' => array(
  201. 'http://tile.stamen.com/terrain-background/{Z}/{X}/{Y}.png'
  202. ),
  203. 'stamen-watercolor' => array(
  204. 'http://tile.stamen.com/watercolor/{Z}/{X}/{Y}.png'
  205. )
  206. );
  207. if(k($params,'basemap') && k($tileServices, k($params,'basemap'))) {
  208. $tileURL = $tileServices[k($params,'basemap')][0];
  209. if(array_key_exists(1, $tileServices[k($params,'basemap')]))
  210. $overlayURL = $tileServices[k($params,'basemap')][1];
  211. else
  212. $overlayURL = 0;
  213. } else {
  214. $tileURL = $tileServices['gray'][0];
  215. $overlayURL = false;
  216. }
  217. function urlForTile($x, $y, $z, $tileURL) {
  218. return str_replace(array(
  219. '{X}', '{Y}', '{Z}'
  220. ), array(
  221. $x, $y, $z
  222. ), $tileURL);
  223. }
  224. $im = imagecreatetruecolor($width, $height);
  225. // Find the pixel coordinate of the center of the map
  226. $center = webmercator\latLngToPixels($latitude, $longitude, $zoom);
  227. $leftEdge = $center['x'] - $width/2;
  228. $topEdge = $center['y'] - $height/2;
  229. $tilePos = webmercator\pixelsToTile($center['x'], $center['y']);
  230. // print_r($tilePos);
  231. // echo '<br />';
  232. $pos = webmercator\positionInTile($center['x'], $center['y']);
  233. // print_r($pos);
  234. // echo '<br />';
  235. // For the given number of pixels, determine how many tiles are needed in each direction
  236. $neTile = webmercator\pixelsToTile($center['x'] + $width/2, $center['y'] + $height/2);
  237. // print_r($neTile);
  238. // echo '<br />';
  239. $swTile = webmercator\pixelsToTile($center['x'] - $width/2, $center['y'] - $height/2);
  240. // print_r($swTile);
  241. // echo '<br />';
  242. // Now download all the tiles
  243. $tiles = array();
  244. $overlays = array();
  245. $chs = array();
  246. $mh = curl_multi_init();
  247. $numTiles = 0;
  248. for($x = $swTile['x']; $x <= $neTile['x']; $x++) {
  249. if(!array_key_exists("$x", $tiles)) {
  250. $tiles["$x"] = array();
  251. $overlays["$x"] = array();
  252. $chs["$x"] = array();
  253. $ochs["$x"] = array();
  254. }
  255. for($y = $swTile['y']; $y <= $neTile['y']; $y++) {
  256. $url = urlForTile($x, $y, $zoom, $tileURL);
  257. $tiles["$x"]["$y"] = false;
  258. $chs["$x"]["$y"] = curl_init($url);
  259. curl_setopt($chs["$x"]["$y"], CURLOPT_RETURNTRANSFER, TRUE);
  260. curl_multi_add_handle($mh, $chs["$x"]["$y"]);
  261. if($overlayURL) {
  262. $url = urlForTile($x, $y, $zoom, $overlayURL);
  263. $overlays["$x"]["$y"] = false;
  264. $ochs["$x"]["$y"] = curl_init($url);
  265. curl_setopt($ochs["$x"]["$y"], CURLOPT_RETURNTRANSFER, TRUE);
  266. curl_multi_add_handle($mh, $ochs["$x"]["$y"]);
  267. }
  268. $numTiles++;
  269. }
  270. }
  271. $running = null;
  272. // Execute the handles. Blocks until all are finished.
  273. do {
  274. $mrc = curl_multi_exec($mh, $running);
  275. } while($running > 0);
  276. // In case any of the tiles fail, they will be grey instead of throwing an error
  277. $blank = imagecreatetruecolor(256, 256);
  278. $grey = imagecolorallocate($im, 224, 224, 224);
  279. imagefill($blank, 0,0, $grey);
  280. foreach($chs as $x=>$yTiles) {
  281. foreach($yTiles as $y=>$ch) {
  282. $content = curl_multi_getcontent($ch);
  283. if($content)
  284. $tiles["$x"]["$y"] = @imagecreatefromstring($content);
  285. else
  286. $tiles["$x"]["$y"] = $blank;
  287. }
  288. }
  289. if($overlayURL) {
  290. foreach($ochs as $x=>$yTiles) {
  291. foreach($yTiles as $y=>$ch) {
  292. $content = curl_multi_getcontent($ch);
  293. if($content)
  294. $overlays["$x"]["$y"] = @imagecreatefromstring($content);
  295. else
  296. $overlays["$x"]["$y"] = $blank;
  297. }
  298. }
  299. }
  300. // Assemble all the tiles into a new image positioned as appropriate
  301. foreach($tiles as $x=>$yTiles) {
  302. foreach($yTiles as $y=>$tile) {
  303. $x = intval($x);
  304. $y = intval($y);
  305. $ox = (($x - $tilePos['x']) * TILE_SIZE) - $pos['x'] + ($width/2);
  306. $oy = (($y - $tilePos['y']) * TILE_SIZE) - $pos['y'] + ($height/2);
  307. imagecopy($im, $tile, $ox,$oy, 0,0, imagesx($tile),imagesy($tile));
  308. }
  309. }
  310. if($overlayURL) {
  311. foreach($overlays as $x=>$yTiles) {
  312. foreach($yTiles as $y=>$tile) {
  313. $x = intval($x);
  314. $y = intval($y);
  315. $ox = (($x - $tilePos['x']) * TILE_SIZE) - $pos['x'] + ($width/2);
  316. $oy = (($y - $tilePos['y']) * TILE_SIZE) - $pos['y'] + ($height/2);
  317. imagecopy($im, $tile, $ox,$oy, 0,0, imagesx($tile),imagesy($tile));
  318. }
  319. }
  320. }
  321. if(count($paths)) {
  322. // Draw the path with ImageMagick because GD sucks as anti-aliased lines
  323. $mg = new Imagick();
  324. $mg->newImage($width, $height, new ImagickPixel('none'));
  325. $draw = new ImagickDraw();
  326. $colors = array();
  327. foreach($paths as $path) {
  328. $draw->setStrokeColor(new ImagickPixel('#'.$path['color']));
  329. $draw->setStrokeWidth($path['weight']);
  330. $draw->setFillOpacity(0);
  331. $draw->setStrokeLineCap(Imagick::LINECAP_ROUND);
  332. $draw->setStrokeLineJoin(Imagick::LINEJOIN_ROUND);
  333. $previous = false;
  334. foreach($path['path'] as $point) {
  335. if($previous) {
  336. $from = webmercator\latLngToPixels($previous[1], $previous[0], $zoom);
  337. $to = webmercator\latLngToPixels($point[1], $point[0], $zoom);
  338. if(k($params, 'bezier')) {
  339. $x_dist = abs($from['x'] - $to['x']);
  340. $y_dist = abs($from['y'] - $to['y']);
  341. // If the X distance is longer than Y distance, draw from left to right
  342. if($x_dist > $y_dist) {
  343. // Draw from left to right
  344. if($from['x'] > $to['x']) {
  345. $tmpFrom = $from;
  346. $tmpTo = $to;
  347. $from = $tmpTo;
  348. $to = $tmpFrom;
  349. unset($tmp);
  350. }
  351. } else {
  352. // Draw from top to bottom
  353. if($from['y'] > $to['y']) {
  354. $tmpFrom = $from;
  355. $tmpTo = $to;
  356. $from = $tmpTo;
  357. $to = $tmpFrom;
  358. unset($tmp);
  359. }
  360. }
  361. $angle = 1 * k($params, 'bezier');
  362. // Midpoint between the two ends
  363. $M = [
  364. 'x' => ($from['x'] + $to['x']) / 2,
  365. 'y' => ($from['y'] + $to['y']) / 2
  366. ];
  367. // Derived from http://math.stackexchange.com/a/383648 and http://www.wolframalpha.com/input/?i=triangle+%5B1,1%5D+%5B5,2%5D+%5B1-1%2Fsqrt(3),1%2B4%2Fsqrt(3)%5D
  368. // See for details
  369. $A = $from;
  370. $B = $to;
  371. $P = [
  372. 'x' => ($M['x']) - (($A['y']-$M['y']) * tan(deg2rad($angle))),
  373. 'y' => ($M['y']) + (($A['x']-$M['x']) * tan(deg2rad($angle)))
  374. ];
  375. $draw->pathStart();
  376. $draw->pathMoveToAbsolute($A['x']-$leftEdge,$A['y']-$topEdge);
  377. $draw->pathCurveToQuadraticBezierAbsolute(
  378. $P['x']-$leftEdge, $P['y']-$topEdge,
  379. $B['x']-$leftEdge, $B['y']-$topEdge
  380. );
  381. $draw->pathFinish();
  382. } else {
  383. $draw->line($from['x']-$leftEdge,$from['y']-$topEdge, $to['x']-$leftEdge,$to['y']-$topEdge);
  384. }
  385. }
  386. $previous = $point;
  387. }
  388. }
  389. $mg->drawImage($draw);
  390. $mg->setImageFormat("png");
  391. $pathImg = imagecreatefromstring($mg);
  392. imagecopy($im, $pathImg, 0,0, 0,0, $width,$height);
  393. }
  394. // Add markers
  395. foreach($markers as $marker) {
  396. // Icons that have 'dot' in the name do not have a shadow and center vertically and horizontally
  397. $shadow = !preg_match('/dot/', $marker['icon']);
  398. if($width < 120 || $height < 120) {
  399. $shrinkFactor = 1.5;
  400. } else {
  401. $shrinkFactor = 1;
  402. }
  403. // Icons with a shadow are centered at the bottom middle pixel.
  404. // Icons with no shadow are centered in the center pixel.
  405. $px = webmercator\latLngToPixels($marker['lat'], $marker['lng'], $zoom);
  406. $pos = array(
  407. 'x' => $px['x'] - $leftEdge,
  408. 'y' => $px['y'] - $topEdge
  409. );
  410. if($shrinkFactor > 1) {
  411. $markerImg = imagecreatetruecolor(round(imagesx($marker['iconImg'])/$shrinkFactor), round(imagesy($marker['iconImg'])/$shrinkFactor));
  412. imagealphablending($markerImg, true);
  413. $color = imagecolorallocatealpha($markerImg, 0, 0, 0, 127);
  414. imagefill($markerImg, 0,0, $color);
  415. imagecopyresampled($markerImg, $marker['iconImg'], 0,0, 0,0, imagesx($markerImg),imagesy($markerImg), imagesx($marker['iconImg']),imagesy($marker['iconImg']));
  416. } else {
  417. $markerImg = $marker['iconImg'];
  418. }
  419. if($shadow) {
  420. $iconPos = array(
  421. 'x' => $pos['x'] - round(imagesx($markerImg)/2),
  422. 'y' => $pos['y'] - imagesy($markerImg)
  423. );
  424. } else {
  425. $iconPos = array(
  426. 'x' => $pos['x'] - round(imagesx($markerImg)/2),
  427. 'y' => $pos['y'] - round(imagesy($markerImg)/2)
  428. );
  429. }
  430. imagecopy($im, $markerImg, $iconPos['x'],$iconPos['y'], 0,0, imagesx($markerImg),imagesy($markerImg));
  431. }
  432. if(k($params,'attribution') != 'none') {
  433. $logo = imagecreatefrompng($assetPath . '/powered-by-esri.png');
  434. // Shrink the esri logo if the image is small
  435. if($width > 120) {
  436. if($width < 220) {
  437. $shrinkFactor = 2;
  438. imagecopyresampled($im, $logo, $width-round(imagesx($logo)/$shrinkFactor)-4, $height-round(imagesy($logo)/$shrinkFactor)-4, 0,0, round(imagesx($logo)/$shrinkFactor),round(imagesy($logo)/$shrinkFactor), imagesx($logo),imagesy($logo));
  439. } else {
  440. imagecopy($im, $logo, $width-imagesx($logo)-4, $height-imagesy($logo)-4, 0,0, imagesx($logo),imagesy($logo));
  441. }
  442. }
  443. }
  444. #header('Cache-Control: max-age=' . (60*60*24*30) . ', public');
  445. #header('X-Tiles-Downloaded: ' . $numTiles);
  446. // TODO: add caching
  447. $fmt = k($params,'format', 'png');
  448. switch($fmt) {
  449. case "jpg":
  450. case "jpeg":
  451. header('Content-type: image/jpg');
  452. $quality = k($params, 'quality', 75);
  453. imagejpeg($im, $filename, $quality);
  454. break;
  455. case "png":
  456. default:
  457. header('Content-type: image/png');
  458. imagepng($im, $filename);
  459. break;
  460. }
  461. imagedestroy($im);
  462. /**
  463. * http://msdn.microsoft.com/en-us/library/bb259689.aspx
  464. * http://derickrethans.nl/php-mapping.html
  465. */
  466. }
  467. function k($a, $k, $default=false) {
  468. if(is_array($a) && array_key_exists($k, $a) && $a[$k])
  469. return $a[$k];
  470. elseif(is_object($a) && property_exists($a, $k) && $a->$k)
  471. return $a->$k;
  472. else
  473. return $default;
  474. }