<?php

class MapGoogle extends Map
{
  function Route()
  {
    $Origins = array();
    $Destinations = array();
    foreach ($this->Path as $Index => $PathItem)
    if ($Index > 0)
    {
       if ($Index == 1) $Origins[] = $this->Path[$Index - 1];
       $Destinations[] = $this->Path[$Index];
    }
    $URL = 'https://maps.googleapis.com/maps/api/distancematrix/json'.
      '?origins='.implode('|', $Origins).'&destinations='.implode('|', $Destinations).'&key='.$this->Key;
    $Result = file_get_contents($URL);
    $Points = array(array('Destination' => $this->Path[0], 'Distance' => 0, 'Duration' => 0));
    $I = 1;
    while (strpos($Result, '"distance"') !== false) {
      $Distance = trim($this->Parse($Result, '"value" :', '}'));
      $Duration = trim($this->Parse($Result, '"value" :', '}'));
      $Points[] = array('Destination' => $this->Path[$I], 'Distance' => $Distance, 'Duration' => $Duration);
      $I++;
    }
    return $Points;
  }

  function Show()
  {
    $WayPoints = $this->Path;
    array_shift($WayPoints);
    array_pop($WayPoints);
    if (count($WayPoints) > 0)
      $WaypointsQuery = '&waypoints='.implode('|', $WayPoints);
      else $WaypointsQuery = '';

    $Output = '<iframe width="'.$this->Width.'" height="'.$this->Height.'" frameborder="0" scrolling="no" '.
      'marginheight="0" marginwidth="0" src="'.'https://www.google.com/maps/embed/v1/directions'.
      '?key='.$this->Key.'&origin='.$this->Path[0].$WaypointsQuery.
      '&destination='.$this->Path[count($this->Path) - 1].''.
      '" style="border: 1px solid black"></iframe>';
    return $Output;
  }
}
