· 6 years ago · Feb 24, 2020, 07:24 PM
1<?php
2
3namespace App\Helpers;
4
5use http\Exception;
6
7class Trimble
8{
9 /**
10 * holds Trimble api key
11 * @var string
12 */
13 private $apiKey;
14
15 /**
16 * guzzle client
17 * @var Client
18 */
19 private $client;
20
21 /**
22 * base URL
23 */
24 const API_BASE_URL = "https://pcmiler.alk.com/apis/rest/v1.0/service.svc/";
25
26 /**
27 * saves Trimble api key and initializes guzzle client
28 */
29 public function __construct()
30 {
31 if (function_exists('config')) {
32 $this->apiKey = config('custom.trimble.key');
33 }
34 $this->client = new \GuzzleHttp\Client($this->guzzleClientOptions());
35 }
36
37 /**
38 * fetches the distance between to locations (points)
39 * @param array $point1 - coordinates of first location
40 * @param array $point2 - coordinates of second location
41 * @param string $unit - unit of location (km/mi/nmi)
42 * @param integer $decimals - precision
43 * @return string - distance
44 */
45 public function getDistanceBetween($point1, $point2, $unit = 'km', $decimals = 2)
46 {
47 $queryString = $this->constructQueryString($point1['lng'].','.$point1['lat'].';'.$point2['lng'].','.$point2['lat'], "calcMiles");
48 $res = $this->makeRequest($queryString);
49 if(!is_null($res)){
50 return round($res[0]['TMiles'], $decimals);
51 } else {
52 return 0;
53 }
54 }
55
56 private function makeRequest($queryString)
57 {
58 try {
59 $response = $this->client->get($queryString);
60 } catch (\Exception $e) {
61 return null;
62 }
63 $results = json_decode($response->getBody(), true, 512);
64 return $results;
65 }
66
67 /**
68 * constructs the query string used in the Trimble api request
69 * @param string/array $locationOrCoordinates - location or coordinates
70 * @param string $type - request type
71 * @return string
72 */
73 private function constructQueryString($locationOrCoordinates, $type)
74 {
75 switch ($type) {
76 case "calcMiles":
77 $queryString = 'route/routeReports?stops=' . urlencode($locationOrCoordinates) . '&reports=CalcMiles&authToken='. $this->apiKey;
78 break;
79 }
80 return $queryString;
81 }
82
83 /**
84 * returns options for the guzzle client
85 * @return array
86 */
87 private function guzzleClientOptions()
88 {
89 return [
90 'base_uri' => self::API_BASE_URL,
91 'cookies' => false,
92 'defaults' => [
93 'verify' => 'true',
94 ],
95 ];
96 }
97}