CoachLocationService.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. // 从 Redis 中获取所有技师定位地址
  14. $locationNames = Redis::zrange('coach_locations', 0, -1);
  15. $result = [];
  16. foreach ($locationNames 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[] = [
  22. 'coach_id' => $coachId,
  23. 'type' => $type,
  24. 'longitude' => $longitude,
  25. 'latitude' => $latitude,
  26. ];
  27. }
  28. }
  29. return response()->json($result);
  30. // return CoachLocation::all();
  31. }
  32. /**
  33. * 创建技师定位地址
  34. */
  35. public function createLocation(array $data)
  36. {
  37. $user = Auth::user();
  38. $coach = $user->coach;
  39. $longitude = $data['longitude'];
  40. $latitude = $data['latitude'];
  41. $type = $data['type'];
  42. $locationName = $coach->id . '_' . $type; // 假设数据中有一个名称字段
  43. // 使用 Redis 的 GEOADD 命令
  44. Redis::geoadd('coach_locations', $longitude, $latitude, $locationName);
  45. $location = $coach->locations()->where('type', $type)->first();
  46. if ($location) {
  47. $location->update($data);
  48. } else {
  49. $coach->locations()->create($data);
  50. }
  51. return response()->json(['message' => 'Location added successfully']);
  52. }
  53. /**
  54. * 删除技师定位地址
  55. */
  56. public function deleteLocation($coachId, $type)
  57. {
  58. $location = CoachLocation::where('type', $type)
  59. ->where('coach_id', $coachId)
  60. ->first();
  61. $location?->delete();
  62. // 从 Redis 中删除地理位置记录
  63. $locationName = $coachId . '_' . $type;
  64. Redis::zrem('coach_locations', $locationName);
  65. return response()->json(['message' => 'Deleted successfully']);
  66. }
  67. }