Generate static map image with two markers and an arc inbetween, serverside

Viewed 1317

My question is similar to "Curved line between two near points in google maps" but I want to generate the map as a static image serverside (PHP or NodeJS), so that it can be used in an offline environment.

In short, I have two sets of Latitudes and Longitudes that I want to place markers on and draw a non-geodesic arc between, to then save the map as an image. Google Maps is not a requirement.

This is essentially what I want to achieve:

Static map image with curved line between two markers

3 Answers

Done with PHP (requires ImageMagick) and Open Street Map (via curl).

PLEASE NOTE: You must understand the license and terms of using Open Street Map before implementing this solution to ensure it is acceptable for your use.

https://operations.osmfoundation.org/policies/tiles/

TODO: Improve the bezier curve between the 2 points

TODO: Check the response from the tile server to ensure it is an image

<?php
/**
 * adapted from https://wiki.openstreetmap.org/wiki/ProxySimplePHP
 * get the map tile and save as png
 *
 * @param float   $lat1  Latitude in degrees
 * @param float   $lng1  Longitude in degrees
 * @param float   $lat2  Latitude in degrees
 * @param float   $lng2  Longitude in degrees
 * @param integer $zoom Zoom level 0-20
 *
 * @throws Exception
 */
function createMap($lat1, $lng1, $lat2, $lng2, $zoom)
{
  //from https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#X_and_Y
  //convert lat/lng to x/y tile coords
  $x1 = floor((($lng1 + 180) / 360) * pow(2, $zoom));
  $y1 = floor((1 - log(tan(deg2rad($lat1)) + 1 / cos(deg2rad($lat1))) / pi()) / 2 * pow(2, $zoom));

  $x2 = floor((($lng2 + 180) / 360) * pow(2, $zoom));
  $y2 = floor((1 - log(tan(deg2rad($lat2)) + 1 / cos(deg2rad($lat2))) / pi()) / 2 * pow(2, $zoom));

  $startX = min($x1,$x2)-1;
  $startY = min($y1,$y2)-1;

  if($startX<0)
  {
    $startX = 0;
  }
  if($startY<0)
  {
    $startY = 0;
  }

  $endX = max($x1,$x2)+1;
  $endY = max($y1,$y2)+1;

  if($endX>(pow(2,$zoom))-1)
  {
    $endX = (pow(2,$zoom))-1;
  }
  if($endY>(pow(2,$zoom))-1)
  {
    $endY = (pow(2,$zoom))-1;
  }

  if(($endX-$startX+1)*($endY-$startY+1)>=50)
  {
    //https://operations.osmfoundation.org/policies/tiles/#bulk-downloading
    //terms of use state: In particular, downloading an area of over 250 tiles at zoom level 13 or higher for offline or later usage is forbidden
    //we're going to be a lot more strict here
    throw new Exception('Zoom level is too high, please reduce');
  }

  if(!is_dir(__DIR__."/tiles"))
  {
    mkdir(__DIR__."/tiles",0755);
  }

  for($x=$startX;$x<=$endX;$x++)
  {
    for($y=$startY;$y<=$endY;$y++)
    {
      $file = "tiles/${zoom}_${x}_${y}.png";
      if(!is_file($file) || filemtime($file) < time() - (86400 * 30))
      {
        $server = array();
        $server[] = 'a.tile.openstreetmap.org';
        $server[] = 'b.tile.openstreetmap.org';
        $server[] = 'c.tile.openstreetmap.org';

        $url = 'http://'.$server[array_rand($server)];
        $url .= "/".$zoom."/".$x."/".$y.".png";

        $ch = curl_init($url);
        $fp = fopen($file, 'wb');
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        global $userAgent;
        if(empty($userAgent))
        {
          throw new Exception('User agent required');
        }
        curl_setopt($ch,CURLOPT_USERAGENT,$userAgent);
        curl_exec($ch);
        curl_close($ch);
        fflush($fp);    // need to insert this line for proper output when tile is first requested
        fclose($fp);
      }
    }
  }

  //now stitch all tiles into 1 image
  $tileWidth = 0;
  $tileHeight = 0;

  $map = new Imagick();
  $cols = array();
  for($x=$startX;$x<=$endX;$x++)
  {
    $col = new Imagick();
    for($y = $startY; $y <= $endY; $y ++)
    {
      $col->readImage("tiles/${zoom}_${x}_${y}.png");
      if($tileWidth===0)
      {
        $tileWidth = $col->getImageWidth();
        $tileHeight = $col->getImageHeight();
      }
    }
    $col->resetIterator();
    $cols[] = $col->appendImages(true);
  }
  foreach($cols as $col)
  {
    $map->addImage($col);
  }
  $map->resetIterator();
  $map = $map->appendImages(false);

  //calculate the pixel point of the lat lng
  $x1 = $tileWidth*(((($lng1 + 180) / 360) * pow(2, $zoom))-$startX);
  $y1 = $tileHeight*(((1 - log(tan(deg2rad($lat1)) + 1 / cos(deg2rad($lat1))) / pi()) / 2 * pow(2, $zoom))-$startY);
  $x2 = $tileWidth*(((($lng2 + 180) / 360) * pow(2, $zoom))-$startX);
  $y2 = $tileHeight*(((1 - log(tan(deg2rad($lat2)) + 1 / cos(deg2rad($lat2))) / pi()) / 2 * pow(2, $zoom))-$startY);

  $draw = new ImagickDraw();
  $draw->setFillAlpha(0);
  $draw->setStrokeColor(new ImagickPixel('black'));
  $draw->setStrokeWidth(2);
  $draw->bezier(array(array('x'=>$x1,'y'=>$y1),array('x'=>$x1+(($x2-$x1)/2)+50,'y'=>$y1+(($y2-$y1)/2)-50),array('x'=>$x2,'y'=>$y2)));
  $map->drawImage($draw);

  if(file_exists('map-marker.png'))
  {
    $icon = new Imagick('map-marker.png');
    $icon->scaleImage(30,30,true);
    $markerX = $x1-($icon->getImageWidth()/2);
    $markerY = $y1-$icon->getImageHeight();
    $map->compositeImage($icon->clone(),$icon::COMPOSITE_DEFAULT,$markerX,$markerY);

    $markerX = $x2-($icon->getImageWidth()/2);
    $markerY = $y2-$icon->getImageHeight();
    $map->compositeImage($icon->clone(),$icon::COMPOSITE_DEFAULT,$markerX,$markerY);
  }

  $map->setImageFormat('png');
  $map->writeImage('base_map.png');
}

//https://operations.osmfoundation.org/policies/tiles/#technical-usage-requirements
//You MUST provide a valid "user agent". For example the application name and a contact email address
//If you violate the terms of use the tiles will not be images but html
$userAgent = '';
createMap(23.634501, - 102.552783, 17.987557, - 92.929147, 5);

You can draw 2-point bezier curves in ImageMagick as follows varying the arc radii.

p1=172,197
p2=483,231

convert map.png -fill none -stroke red -strokewidth 2 -draw "path 'M $p1   A 1,1  0  0,1 $p2'" map_arc1.png

enter image description here

convert map.png -fill none -stroke red -strokewidth 2 -draw "path 'M $p1   A 3,2  0  0,1 $p2'" map_arc2.png

enter image description here

convert map.png -fill none -stroke red -strokewidth 2 -draw "path 'M $p1   A 4,2  0  0,1 $p2'" map_arc3.png

enter image description here

Here's my NodeJS take on it using TurfJS, SVG.JS and Static Google Maps: Runkit Link. Just gotta replace GMAPS_API_KEY.

The preliminary result looks like this

enter image description here

and some geodesic corrections are still needed. Nonetheless, this should set you on the right ... path.

Related