CoachLocationService.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Services\Client;
  3. use App\Models\CoachLocation;
  4. use Illuminate\Support\Facades\Auth;
  5. use Illuminate\Support\Facades\Redis;
  6. class CoachLocationService
  7. {
  8. /**
  9. * 获取技师定位地址列表
  10. */
  11. public function getAllLocations()
  12. {
  13. $result = [];
  14. // 1. 从 Redis 中获取所有技师定位地址
  15. $coachLocationNames = Redis::zrange('coach_locations', 0, -1);
  16. foreach ($coachLocationNames as $locationName) {
  17. $positions = Redis::geopos('coach_locations', $locationName);
  18. if (! empty($positions) && isset($positions[0])) {
  19. [$longitude, $latitude] = $positions[0];
  20. [$coachId, $type] = explode('_', $locationName);
  21. $result['coaches'][] = [
  22. 'coach_id' => $coachId,
  23. 'type' => $type,
  24. 'longitude' => $longitude,
  25. 'latitude' => $latitude,
  26. ];
  27. }
  28. }
  29. // 2. 从 Redis 中获取所有订单位置
  30. $orderLocationNames = Redis::zrange('order_locations', 0, -1);
  31. foreach ($orderLocationNames as $locationName) {
  32. $positions = Redis::geopos('order_locations', $locationName);
  33. if (! empty($positions) && isset($positions[0])) {
  34. [$longitude, $latitude] = $positions[0];
  35. $orderId = str_replace('order_', '', $locationName);
  36. $result['orders'][] = [
  37. 'order_id' => $orderId,
  38. 'longitude' => $longitude,
  39. 'latitude' => $latitude,
  40. ];
  41. }
  42. }
  43. return response()->json($result);
  44. }
  45. /**
  46. * 创建技师定位地址
  47. */
  48. public function createLocation(array $data)
  49. {
  50. $user = Auth::user();
  51. $coach = $user->coach;
  52. $longitude = $data['longitude'];
  53. $latitude = $data['latitude'];
  54. $type = $data['type'];
  55. $locationName = $coach->id . '_' . $type; // 假设数据中有一个名称字段
  56. // 使用 Redis 的 GEOADD 命令
  57. Redis::geoadd('coach_locations', $longitude, $latitude, $locationName);
  58. $location = $coach->locations()->where('type', $type)->first();
  59. if ($location) {
  60. $location->update($data);
  61. } else {
  62. $coach->locations()->create($data);
  63. }
  64. return response()->json(['message' => 'Location added successfully']);
  65. }
  66. /**
  67. * 删除技师定位地址
  68. */
  69. public function deleteLocation($coachId, $type)
  70. {
  71. $location = CoachLocation::where('type', $type)
  72. ->where('coach_id', $coachId)
  73. ->first();
  74. $location?->delete();
  75. // 从 Redis 中删除地理位置记录
  76. $locationName = $coachId . '_' . $type;
  77. Redis::zrem('coach_locations', $locationName);
  78. return response()->json(['message' => 'Deleted successfully']);
  79. }
  80. }