shop_email = Configuration::get('PS_SHOP_EMAIL'); } /** * Get Address from postcode and country * @param $postcode * @param $country */ public function getAddress($postcode, $country) { $postcode = urlencode($postcode); $result = Tools::file_get_contents('https://nominatim.openstreetmap.org/search?country=' . $country . '&postalcode=' . $postcode . '&format=json&email=' . $this->shop_email); $result = json_decode($result); if (empty($result['0'])) { return ''; } else { return $result['0']->display_name; } } /** * @param $postcode * @return array */ private function getCoordinateForPostcode($postalcode, $country) { $result = Tools::file_get_contents('https://nominatim.openstreetmap.org/search?country=' . $country . '&postalcode=' . $postalcode . '&format=json&email=' . $this->shop_email); $result = json_decode($result); if (empty($result['0'])) { return false; } $return = array( 'lat' => $result[0]->lat, 'lon' => $result[0]->lon, ); return $return; } /** * Return the distance between two points on a map * @param $source * @param $destination * @return int */ private function getDistanceBetweenTwoPoints($source, $destination) { $url = 'http://router.project-osrm.org/route/v1/driving/' . $source['lon'] . ',' . $source['lat'] . ';' . $destination['lon'] . ',' . $destination['lat'] . '?overview=false'; $result = Tools::file_get_contents($url); $result = json_decode($result); if (!empty($result->routes[0]->legs)) { $distance = (int)$result->routes[0]->legs[0]->distance; } return $distance; } /** * @param $source_address * @param array $destination_addresses */ public function getDistancesByPostCodes($source_address, array $destination_addresses) { $source_address['location'] = $this->getCoordinateForPostcode($source_address['postal_code'], $source_address['country']); if (empty($source_address['location'])) { return array(); } foreach ($destination_addresses as &$destination_address) { $destination_address['location'] = $this->getCoordinateForPostcode($destination_address['postal_code'], $destination_address['country']); } unset($destination_address); // now get the distances between each carrier and customer foreach ($destination_addresses as &$destination_address) { if (!empty($destination_address['location'])) { $destination_address['distance'] = $this->getDistanceBetweenTwoPoints($source_address['location'], $destination_address['location']) / 1000; } } // return the array expected $carrier_distances = array(); foreach ($destination_addresses as $address) { if (!empty($address['distance'])) { $distance = $address['distance']; } else { $distance = 0; } $carrier_distances[$address['id_carrier']] = array( 'id_carrier' => $address['id_carrier'], 'country' => $address['country'], 'postal_code' => $address['postal_code'], 'distance' => $distance, ); } return $carrier_distances; } }