示例#1
0
 /**
  * Generates directions URL API according to the request.
  *
  * @param \Ivory\GoogleMap\Services\Directions\DirectionsRequest $directionsRequest The direction request.
  *
  * @return string The generated URL.
  */
 protected function generateUrl(DirectionsRequest $directionsRequest)
 {
     $httpQuery = array();
     if (is_string($directionsRequest->getOrigin())) {
         $httpQuery['origin'] = $directionsRequest->getOrigin();
     } else {
         $httpQuery['origin'] = sprintf('%s,%s', $directionsRequest->getOrigin()->getLatitude(), $directionsRequest->getOrigin()->getLongitude());
     }
     if (is_string($directionsRequest->getDestination())) {
         $httpQuery['destination'] = $directionsRequest->getDestination();
     } else {
         $httpQuery['destination'] = sprintf('%s,%s', $directionsRequest->getDestination()->getLatitude(), $directionsRequest->getDestination()->getLongitude());
     }
     if ($directionsRequest->hasWaypoints()) {
         $waypoints = array();
         if ($directionsRequest->hasOptimizeWaypoints() && $directionsRequest->getOptimizeWaypoints()) {
             $waypoints[] = 'optimize:true';
         }
         foreach ($directionsRequest->getWaypoints() as $waypoint) {
             $stopover = $waypoint->getStopover() ? 'via:' : '';
             if (is_string($waypoint->getLocation())) {
                 $waypoints[] = $stopover . $waypoint->getLocation();
             } else {
                 $waypoints[] = sprintf('%s%s,%s', $stopover, $waypoint->getLocation()->getLatitude(), $waypoint->getLocation()->getLongitude());
             }
         }
         $httpQuery['waypoints'] = implode('|', $waypoints);
     }
     if ($directionsRequest->hasTravelMode()) {
         $httpQuery['mode'] = strtolower($directionsRequest->getTravelMode());
     }
     if ($directionsRequest->hasProvideRouteAlternatives()) {
         $httpQuery['alternatives'] = $directionsRequest->getProvideRouteAlternatives() ? 'true' : 'false';
     }
     if ($directionsRequest->hasAvoidTolls() && $directionsRequest->getAvoidTolls()) {
         $httpQuery['avoid'] = 'tolls';
     } elseif ($directionsRequest->hasAvoidHighways() && $directionsRequest->getAvoidHighways()) {
         $httpQuery['avoid'] = 'highways';
     }
     if ($directionsRequest->hasUnitSystem()) {
         $httpQuery['units'] = strtolower($directionsRequest->getUnitSystem());
     }
     if ($directionsRequest->hasRegion()) {
         $httpQuery['region'] = $directionsRequest->getRegion();
     }
     if ($directionsRequest->hasLanguage()) {
         $httpQuery['language'] = $directionsRequest->getLanguage();
     }
     if ($directionsRequest->hasDepartureTime()) {
         $httpQuery['departure_time'] = $directionsRequest->getDepartureTime()->getTimestamp();
     }
     if ($directionsRequest->hasArrivalTime()) {
         $httpQuery['arrival_time'] = $directionsRequest->getArrivalTime()->getTimestamp();
     }
     $httpQuery['sensor'] = $directionsRequest->hasSensor() ? 'true' : 'false';
     $url = sprintf('%s/%s?%s', $this->getUrl(), $this->getFormat(), http_build_query($httpQuery));
     return $this->signUrl($url);
 }
 public function testIsValidWithValidTransitDepartureTimeAndArrivalTime()
 {
     $this->directionsRequest->setDestination('foo');
     $this->directionsRequest->setOrigin('bar');
     $this->directionsRequest->setTravelMode(TravelMode::TRANSIT);
     $this->directionsRequest->setArrivalTime(new DateTime());
     $this->directionsRequest->setDepartureTime(new DateTime());
     $this->assertTrue($this->directionsRequest->isValid());
 }
 /**
  * Provides map for specified Track
  * @param Track $track
  * @throws \Ivory\GoogleMap\Exception\DirectionsException
  * @throws \Ivory\GoogleMap\Exception\MapException
  * @return Map
  */
 public function getMap($track)
 {
     $directionsRequest = new DirectionsRequest();
     $directionsRequest->setOrigin($track->getStartLatitude(), $track->getStartLongitude());
     $directionsRequest->setDestination($track->getEndLatitude(), $track->getEndLongitude());
     $directionsRequest->setTravelMode(TravelMode::DRIVING);
     $directions = new Directions(new CurlHttpAdapter());
     $response = $directions->route($directionsRequest);
     $map = new Map();
     $map->setCenter((double) ($track->getStartLatitude() + $track->getEndLatitude()) / 2, (double) ($track->getStartLongitude() + $track->getEndLongitude()) / 2);
     $map->setAutoZoom(false);
     $map->setMapOption('zoom', 14);
     $map->setMapOption('mapTypeId', MapTypeId::SATELLITE);
     $map->setMapOption('disableDefaultUI', true);
     $map->setMapOption('draggable', false);
     $map->setMapOption('scrollwheel', false);
     $map->setStylesheetOptions(array('width' => '100%', 'height' => '300px'));
     foreach ($response->getRoutes() as $route) {
         $overviewPolyline = $route->getOverviewPolyline();
         $map->addEncodedPolyline($overviewPolyline);
     }
     return $map;
 }
示例#4
0
 public function ajaxAction(Request $request)
 {
     if ($request->isXmlHttpRequest()) {
         //            $session = $request->getSession();
         //            $latitude = json_decode( $session->get('lat') );
         //            $longitude = json_decode( $session->get('lng') );
         $latitude = $request->request->get('lat');
         $longitude = $request->request->get('lng');
         $coordpolaire = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $latitude . "," . $longitude . "&key=AIzaSyDePZt3uyPPCISJtyM5nvkmL_s5YxjcqBo");
         $json = json_decode($coordpolaire);
         //                    echo '<pre>';
         //                    var_dump($json->{'results'}[0]->{'formatted_address'});
         //                    echo '</pre>';
         $address = $json->{'results'}[0]->{'formatted_address'};
         //            $latitude = json_decode($request->request->get('lat'));
         //            $longitude = json_decode($request->request->get('lng'));
         $em = $this->getDoctrine()->getManager();
         $fiches = $em->getRepository('ProjetAppBundle:Fiche')->findBy(array('status' => '1', 'user' => $this->getUser()));
         $res = array();
         $lol = "";
         foreach ($fiches as $fiche) {
             $directionRequest = new DirectionsRequest();
             $directionRequest->setOrigin($address, false);
             //                $directionRequest->setOrigin("46 rue jules ferry 14120 mondeville", true);
             $directionRequest->setDestination($fiche->addressString(), true);
             $directionRequest->setAvoidHighways(true);
             $directionRequest->setAvoidTolls(true);
             $directionRequest->setTravelMode(TravelMode::DRIVING);
             $directionRequest->setUnitSystem(UnitSystem::METRIC);
             $directions = new Directions(new CurlHttpAdapter());
             $responseDirection = $directions->route($directionRequest);
             $routes = $responseDirection->getRoutes();
             foreach ($routes as $route) {
                 $res = $route;
             }
         }
         //            $encoders = new JsonEncoder();
         //            $normalizers = array(new GetSetMethodNormalizer());
         //            $serializer = new Serializer($normalizers, $encoders);
         //            $json = $serializer->serialize($res, 'json');
         $response = new Response($json);
         $response->headers->set('Content-Type', 'application/json');
         return $response;
         //            return new JsonResponse($lol);
     }
 }
示例#5
0
 /**
  * Get directions info
  *
  * @param Coordinate $from
  * @param Coordinate $to
  *
  * @return mixed
  * @throws \Ivory\GoogleMap\Exception\DirectionsException
  */
 public function getDirections(Coordinate $from, Coordinate $to) : array
 {
     $directions = new Directions(new CurlHttpAdapter());
     $directionsRequest = new DirectionsRequest();
     $directionsRequest->setOrigin($from);
     $directionsRequest->setDestination($to);
     $response = $directions->route($directionsRequest);
     return $response->getRoutes();
 }
 /**
  * View action
  * @param int $id
  * @throws \Exception
  */
 public function viewAction($id = null)
 {
     if (is_null($id)) {
         throw new \Exception('Bad request');
     }
     $id = abs((int) $id);
     $userId = $this->session->get('uid');
     $model = $this->loadModel('events');
     $comments = $this->loadModel('comment');
     $event = $model->getEvent($id);
     $isJoined = $model->checkJoinedUser($id, $userId);
     $attendingUsers = $model->getAttendingUsers($id);
     /** Google Maps API */
     $map = new Map();
     $markerPositions = $instructions = $commonInfo = [];
     $map->setLanguage('uk');
     $map->setAutoZoom(true);
     $map->setPrefixJavascriptVariable('map_');
     $map->setHtmlContainerId('map-canvas-view');
     $map->setMapOptions(array('disableDefaultUI' => true, 'disableDoubleClickZoom' => true, 'mapTypeId' => 'roadmap'));
     $map->setStylesheetOptions(array('width' => '58%', 'height' => 'calc(100% - 0)', 'position' => 'absolute', 'right' => '0px', 'top' => '50px', 'bottom' => '2px', 'overflow' => 'hidden'));
     // Build directions
     $request = new DirectionsRequest();
     $request->setLanguage('uk');
     $request->setUnitSystem(UnitSystem::METRIC);
     $request->setTravelMode($event['routeMode']);
     $request->setOrigin($event['routeFrom']);
     $request->setDestination($event['routeTo']);
     // @TODO: Do it
     // $request->addWaypoint($event['routeVia']);
     // $request->setOptimizeWaypoints(true);
     // $request->setAvoidHighways(true);
     // $request->setAvoidTolls(true);
     // $request->setProvideRouteAlternatives(true);
     $directions = new Directions(new CurlHttpAdapter());
     $response = $directions->route($request);
     if ($response->getStatus() === 'OK') {
         $routes = $response->getRoutes();
         foreach ($routes as $route) {
             $overviewPolyline = $route->getOverviewPolyline();
             //$waypointOrder = $route->getWaypointOrder();  // Get the waypoint order
             foreach ($route->getLegs() as $leg) {
                 // Set the start location & the end location into array
                 $markerPositions = ['start' => [$leg->getStartLocation()->getLatitude(), $leg->getStartLocation()->getLongitude()], 'end' => [$leg->getEndLocation()->getLatitude(), $leg->getEndLocation()->getLongitude()]];
                 $commonInfo = ['distance' => $leg->getDistance()->getText(), 'duration' => $leg->getDuration()->getText(), 'startAddress' => $leg->getStartAddress(), 'endAddress' => $leg->getEndAddress()];
                 // Set the directions steps
                 foreach ($leg->getSteps() as $key => $step) {
                     $instructions[] = [$step->getInstructions(), $step->getDistance()->getText(), $step->getDuration()->getText(), $step->getTravelMode()];
                 }
             }
         }
         // Build markers
         foreach ($markerPositions as $latlng) {
             $position = new Coordinate($latlng[0], $latlng[1], true);
             $marker = new Marker($position, 'drop', null, null, null, new InfoWindow());
             $map->addMarker($marker);
         }
         // Build Polyline
         $encodedPolyline = new EncodedPolyline();
         $encodedPolyline->setValue($overviewPolyline->getValue());
         $encodedPolyline->setOptions(array('geodesic' => true, 'strokeColor' => '#3079ed', 'strokeOpacity' => 0.8, 'strokeWeight' => 5));
         $map->addEncodedPolyline($encodedPolyline);
     } else {
         $position = new Coordinate($event['latTo'], $event['lngTo']);
         $info = $event['routeTo'];
         $info .= !empty($event['date']) ? '<hr><i class="glyphicon glyphicon-time"></i> ' . $event['date'] : '';
         $info .= !empty($event['end_date']) ? '<br><i class="glyphicon glyphicon-time"></i> ' . $event['end_date'] : '';
         $marker = new Marker($position, 'drop', null, null, null, new InfoWindow($info));
         $map->addMarker($marker);
     }
     // Render map
     $mapHelper = new MapHelper();
     $this->view->map = $mapHelper->render($map);
     $this->view->event = $event;
     $this->view->comments = $comments->getComments($id);
     $this->view->commentsAccess = (bool) $userId;
     $this->view->isJoined = (bool) $isJoined;
     $this->view->attendingUsers = $attendingUsers;
     $this->view->instructions = $instructions;
     $this->view->render('events/view');
 }
 public function testRouteWithDirectionsRequestAndTransitModeAndDepartureTimeAndArrivalTime()
 {
     $request = new DirectionsRequest();
     $request->setOrigin('601-625 Ashbury Street, San Francisco');
     $request->setDestination('Bike Route 95, San Francisco');
     $request->setTravelMode(TravelMode::TRANSIT);
     $request->setArrivalTime(new DateTime());
     $request->setArrivalTime(new DateTime('+2 hours'));
     $response = $this->directions->route($request);
     $this->assertSame(DirectionsStatus::OK, $response->getStatus());
     $this->assertNotEmpty($response->getRoutes());
 }