Calculate distance between PLZs if given

This commit is contained in:
Jannis Portmann 2021-06-14 14:10:07 +02:00
parent 853b570f0f
commit d33e28467b
7 changed files with 716 additions and 472 deletions

View file

@ -8,6 +8,8 @@ use App\Form\OfferingFormType;
use App\Repository\OfferingRepository;
use App\Repository\WishRepository;
use App\Service\PlzToCoordinate;
use App\Service\DistanceCalculator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
@ -73,12 +75,27 @@ class OfferController extends AbstractController
}
#[Route('/offer/{id}', name: 'show_offer')]
public function show_offer(Offering $offer, WishRepository $wishRepository): Response
public function show_offer(Offering $offer, WishRepository $wishRepository, PlzToCoordinate $plzconverter, DistanceCalculator $distanceCalculator): Response
{
$distance = 0;
$user = $this->getUser();
$offerPlz = $offer->getZipCode();
if (isset($user))
{
$userPlz = $user->getZipCode();
}
if (isset($userPlz))
{
$distance = $distanceCalculator->calculateDistance($plzconverter->getCoordinates($offerPlz), $plzconverter->getCoordinates($userPlz));
}
return $this->render('app/offer.html.twig', [
'user' => $this->getUser(),
'user' => $user,
'offer' => $offer,
'wishes' => $wishRepository->findByUser($offer->getByUser()),
'distance' => $distance,
]);
}

View file

@ -0,0 +1,20 @@
<?php
namespace App\Service;
use Location\Coordinate;
use Location\Distance\Vincenty;
class DistanceCalculator
{
public function calculateDistance(Coordinate $coordinate1, Coordinate $coordinate2)
{
$calculator = new Vincenty();
$distance = $calculator->getDistance($coordinate1, $coordinate2);
$distance = round($distance / 1000);
return $distance;
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace App\Service;
use Location\Coordinate;
class PlzToCoordinate
{
public function getCoordinates(int $plz)
{
$content = file_get_contents("https://swisspost.opendatasoft.com/api/records/1.0/search/?dataset=plz_verzeichnis_v2&q=postleitzahl%3D" . $plz);
$result = json_decode($content);
if (isset($result->records[0]->fields->geo_point_2d[0]) && isset($result->records[0]->fields->geo_point_2d[1])) {
$coordinate = new Coordinate($result->records[0]->fields->geo_point_2d[0], $result->records[0]->fields->geo_point_2d[1]);
}
return $coordinate;
}
}