1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
- namespace App\Services\Client;
- use App\Models\CoachLocation;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Redis;
- class CoachLocationService
- {
- /**
- * 获取技师定位地址列表
- */
- public function getAllLocations()
- {
- $result = [];
- // 1. 从 Redis 中获取所有技师定位地址
- $coachLocationNames = Redis::zrange('coach_locations', 0, -1);
- foreach ($coachLocationNames as $locationName) {
- $positions = Redis::geopos('coach_locations', $locationName);
- if (! empty($positions) && isset($positions[0])) {
- [$longitude, $latitude] = $positions[0];
- [$coachId, $type] = explode('_', $locationName);
- $result['coaches'][] = [
- 'coach_id' => $coachId,
- 'type' => $type,
- 'longitude' => $longitude,
- 'latitude' => $latitude,
- ];
- }
- }
- // 2. 从 Redis 中获取所有订单位置
- $orderLocationNames = Redis::zrange('order_locations', 0, -1);
- foreach ($orderLocationNames as $locationName) {
- $positions = Redis::geopos('order_locations', $locationName);
- if (! empty($positions) && isset($positions[0])) {
- [$longitude, $latitude] = $positions[0];
- $orderId = str_replace('order_', '', $locationName);
- $result['orders'][] = [
- 'order_id' => $orderId,
- 'longitude' => $longitude,
- 'latitude' => $latitude,
- ];
- }
- }
- return response()->json($result);
- }
- /**
- * 创建技师定位地址
- */
- public function createLocation(array $data)
- {
- $user = Auth::user();
- $coach = $user->coach;
- $longitude = $data['longitude'];
- $latitude = $data['latitude'];
- $type = $data['type'];
- $locationName = $coach->id . '_' . $type; // 假设数据中有一个名称字段
- // 使用 Redis 的 GEOADD 命令
- Redis::geoadd('coach_locations', $longitude, $latitude, $locationName);
- $location = $coach->locations()->where('type', $type)->first();
- if ($location) {
- $location->update($data);
- } else {
- $coach->locations()->create($data);
- }
- return response()->json(['message' => 'Location added successfully']);
- }
- /**
- * 删除技师定位地址
- */
- public function deleteLocation($coachId, $type)
- {
- $location = CoachLocation::where('type', $type)
- ->where('coach_id', $coachId)
- ->first();
- $location?->delete();
- // 从 Redis 中删除地理位置记录
- $locationName = $coachId . '_' . $type;
- Redis::zrem('coach_locations', $locationName);
- return response()->json(['message' => 'Deleted successfully']);
- }
- }
|