1
0

user_ajax.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. JSON::header();
  3. $user = User::get($id);
  4. if(!$user) JSON::fail("User not found.");
  5. switch($action) {
  6. case "get-addresses":
  7. $addresses = $user->getAddresses();
  8. $output = [];
  9. foreach($addresses as $address) {
  10. $output[] = [
  11. "name" => $address->name,
  12. "latitude" => (float) $address->latitude,
  13. "longitude" => (float) $address->longitude
  14. ];
  15. }
  16. JSON::success([
  17. "addresses" => $output
  18. ]);
  19. break;
  20. case "get-locations":
  21. $output = [];
  22. $address_id = http::value("address_id", "int");
  23. $max_distance = http::value("max_distance", "int");
  24. if($max_distance <= 0) $max_distance = 25;
  25. $address = UserAddress::queryOne([
  26. "id" => $address_id,
  27. "user_id" => $id,
  28. ]);
  29. if(!$address) throw new Exception("Cannot find address.");
  30. $bounds = Geolocation::getBounds($address->getGeolocation(), $max_distance);
  31. list($min_lat, $min_lng) = $bounds->southWest;
  32. list($max_lat, $max_lng) = $bounds->northEast;
  33. $locations = Location::query([
  34. "latitude" => (new Constraint("BETWEEN"))->setValues($min_lat, $max_lat),
  35. "longitude" => (new Constraint("BETWEEN"))->setValues($min_lng, $max_lng),
  36. "closed" => 0
  37. ]);
  38. $customers = Customer::load(array_column($locations, "customer_id"));
  39. usort($locations, function($a, $b) use ($address) {
  40. return
  41. Geolocation::getDistance($address->getGeolocation(), $a->getGeolocation())
  42. <=>
  43. Geolocation::getDistance($address->getGeolocation(), $b->getGeolocation());
  44. });
  45. foreach($locations as $location) {
  46. $distance = Geolocation::getDistance($address->getGeolocation(), $location->getGeolocation());
  47. if($distance > $max_distance) continue;
  48. $customer = $location->getCustomer();
  49. $customer_slug = str_replace("-", "_", Util::slug($customer->name));
  50. $icon = null;
  51. $icon_file = "{$customer_slug}.png";
  52. if($icon_file && file_exists("public/img/markers/$icon_file")) {
  53. $icon = $icon_file;
  54. }
  55. $output[] = [
  56. "id" => (int) $location->id,
  57. "internalId" => (int) $location->internal_id,
  58. "name" => $location->name,
  59. "address" => $location->getDisplayAddress(),
  60. "distance" => $distance,
  61. "latitude" => (double) $location->latitude,
  62. "longitude" => (double) $location->longitude,
  63. "icon" => $icon,
  64. ];
  65. }
  66. JSON::success([
  67. "name" => $address->name,
  68. "latitude" => (double) $address->latitude,
  69. "longitude" => (double) $address->longitude,
  70. "locations" => $output
  71. ]);
  72. break;
  73. }