| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- <?php
- JSON::header();
- $user = User::get($id);
- if(!$user) JSON::fail("User not found.");
- switch($action) {
- case "get-addresses":
- $addresses = $user->getAddresses();
- $output = [];
- foreach($addresses as $address) {
- $output[] = [
- "name" => $address->name,
- "latitude" => (float) $address->latitude,
- "longitude" => (float) $address->longitude
- ];
- }
- JSON::success([
- "addresses" => $output
- ]);
- break;
- case "get-locations":
- $output = [];
- $address_id = http::value("address_id", "int");
- $max_distance = http::value("max_distance", "int");
- if($max_distance <= 0) $max_distance = 25;
- $address = UserAddress::queryOne([
- "id" => $address_id,
- "user_id" => $id,
- ]);
- if(!$address) throw new Exception("Cannot find address.");
- $bounds = Geolocation::getBounds($address->getGeolocation(), $max_distance);
- list($min_lat, $min_lng) = $bounds->southWest;
- list($max_lat, $max_lng) = $bounds->northEast;
- $locations = Location::query([
- "latitude" => (new Constraint("BETWEEN"))->setValues($min_lat, $max_lat),
- "longitude" => (new Constraint("BETWEEN"))->setValues($min_lng, $max_lng),
- "closed" => 0
- ]);
- $customers = Customer::load(array_column($locations, "customer_id"));
- usort($locations, function($a, $b) use ($address) {
- return
- Geolocation::getDistance($address->getGeolocation(), $a->getGeolocation())
- <=>
- Geolocation::getDistance($address->getGeolocation(), $b->getGeolocation());
- });
- foreach($locations as $location) {
- $distance = Geolocation::getDistance($address->getGeolocation(), $location->getGeolocation());
- if($distance > $max_distance) continue;
- $customer = $location->getCustomer();
- $customer_slug = str_replace("-", "_", Util::slug($customer->name));
- $icon = null;
- $icon_file = "{$customer_slug}.png";
- if($icon_file && file_exists("public/img/markers/$icon_file")) {
- $icon = $icon_file;
- }
- $output[] = [
- "id" => (int) $location->id,
- "internalId" => (int) $location->internal_id,
- "name" => $location->name,
- "address" => $location->getDisplayAddress(),
- "distance" => $distance,
- "latitude" => (double) $location->latitude,
- "longitude" => (double) $location->longitude,
- "icon" => $icon,
- ];
- }
- JSON::success([
- "name" => $address->name,
- "latitude" => (double) $address->latitude,
- "longitude" => (double) $address->longitude,
- "locations" => $output
- ]);
- break;
- }
|