diff --git a/src/Controller/OfferController.php b/src/Controller/OfferController.php index 06066cd..5c56165 100644 --- a/src/Controller/OfferController.php +++ b/src/Controller/OfferController.php @@ -81,7 +81,16 @@ class OfferController extends AbstractController if (isset($userPlz)) { - $distance = $distanceCalculator->calculateDistance($plzconverter->getCoordinates($offerPlz), $plzconverter->getCoordinates($userPlz)); + if (isset($offerPlz)) + { + $offerCoordinate = $plzconverter->convertPlzToCoordinate($offerPlz); + $userCoordinate = $plzconverter->convertPlzToCoordinate($userPlz); + + if ($userCoordinate != null && $offerCoordinate != null) + { + $distance = $distanceCalculator->calculateDistance($offerCoordinate, $userCoordinate); + } + } } return $this->render('app/offer.html.twig', [ diff --git a/src/Service/DistanceCalculator.php b/src/Service/DistanceCalculator.php index 20598ca..02d3546 100644 --- a/src/Service/DistanceCalculator.php +++ b/src/Service/DistanceCalculator.php @@ -9,12 +9,19 @@ class DistanceCalculator { public function calculateDistance(Coordinate $coordinate1, Coordinate $coordinate2) { - $calculator = new Vincenty(); + if ($coordinate1 == null || $coordinate2 == null) + { + $distance = "N/A"; + } + else + { + $calculator = new Vincenty(); - $distance = $calculator->getDistance($coordinate1, $coordinate2); - - $distance = round($distance / 1000); + $distance = $calculator->getDistance($coordinate1, $coordinate2); + $distance = round($distance / 1000); + } + return $distance; } } \ No newline at end of file diff --git a/src/Service/PlzToCoordinate.php b/src/Service/PlzToCoordinate.php index a156fa0..2c6e9ea 100644 --- a/src/Service/PlzToCoordinate.php +++ b/src/Service/PlzToCoordinate.php @@ -11,8 +11,21 @@ class PlzToCoordinate $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]); + for ($i=0; $i<2; $i++) + { + try { + $lat = $result->records[$i]->fields->geo_point_2d[0]; + $long = $result->records[$i]->fields->geo_point_2d[0]; + } catch (\Throwable $th) { + // throw $th; + } + } + + if (isset($lat) && isset($long)) { + $coordinate = new Coordinate($lat, $long); + } + else { + $coordinate = null; } return $coordinate;