aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/components/Map.tsx
blob: c6e9583491302e061c0a39b7a5f38bf72451973f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"use client";

import { useEffect, useState } from "react";
import { MapContainer, TileLayer, Marker, Popup, useMap, Polyline } from "react-leaflet";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import { toast } from "sonner";
import { useSocket } from "@/hooks/useSocket";

// Type for location
interface LocationType {
  latitude: number;
  longitude: number;
  accuracy?: number;
  timestamp: Date;
}

// Location update handler that recalculates position
function LocationMarker({
  position,
  onLocationUpdate,
  shareToken,
}: {
  position: [number, number] | null;
  onLocationUpdate: (location: LocationType) => void;
  shareToken?: string;
}) {
  const [positionHistory, setPositionHistory] = useState<[number, number][]>([]);
  const [isClient, setIsClient] = useState(false);
  const map = useMap();
  const { sendLocationUpdate, isConnected } = useSocket();

  // Safely check if we're on the client side
  useEffect(() => {
    setIsClient(true);
  }, []);

  useEffect(() => {
    map.locate({ watch: true, enableHighAccuracy: true });

    map.on("locationfound", (e) => {
      const newPosition: [number, number] = [e.latlng.lat, e.latlng.lng];
      
      // Update position history
      setPositionHistory((prev) => [...prev, newPosition]);
      
      // Create location data
      const locationData = {
        latitude: e.latlng.lat,
        longitude: e.latlng.lng,
        accuracy: e.accuracy,
        timestamp: new Date(),
      };
      
      // Notify parent component
      onLocationUpdate(locationData);
      
      // Send location update to Socket.IO if sharing
      if (shareToken && isConnected) {
        sendLocationUpdate({
          latitude: e.latlng.lat,
          longitude: e.latlng.lng,
          accuracy: e.accuracy,
          shareToken,
        });
      }

      // Center map on the new position
      map.flyTo(e.latlng, map.getZoom());
    });

    map.on("locationerror", (e) => {
      toast.error("Error accessing location: " + e.message);
      console.error("Location error: ", e);
    });

    return () => {
      map.stopLocate();
      map.off("locationfound");
      map.off("locationerror");
    };
  }, [map, onLocationUpdate, sendLocationUpdate, shareToken, isConnected]);

  // Return null if position is null or if we're not on client yet
  if (!position || !isClient) return null;
  
  // Only render the polyline if we have enough points and we're on the client side
  const showPolyline = isClient && positionHistory && positionHistory.length > 1;

  return (
    <>
      <Marker position={position}>
        <Popup>
          {shareToken ? "Sharing location in real-time" : "You are here"}
          {isConnected && shareToken && (
            <div className="text-xs mt-1 text-green-600">Connected</div>
          )}
        </Popup>
      </Marker>
      
      {/* Draw path if we have position history and we're on client */}
      {showPolyline && (
        <Polyline
          pathOptions={{ color: "blue", weight: 3 }}
          positions={positionHistory}
        />
      )}
    </>
  );
}

// Component to display a shared location
function SharedLocationMarker({ position, lastUpdate }: { position: [number, number]; lastUpdate?: string }) {
  return (
    <Marker position={position} icon={new L.Icon({
      iconUrl: '/marker-icon-red.png',
      iconRetinaUrl: '/marker-icon-2x-red.png',
      shadowUrl: '/marker-shadow.png',
      iconSize: [25, 41],
      iconAnchor: [12, 41],
      popupAnchor: [1, -34],
      shadowSize: [41, 41]
    })}>
      <Popup>
        <div>
          <div>Shared Location</div>
          {lastUpdate && (
            <div className="text-xs mt-1">Last updated: {new Date(lastUpdate).toLocaleTimeString()}</div>
          )}
        </div>
      </Popup>
    </Marker>
  );
}

export default function Map({
  onLocationUpdate,
  shareToken,
  mode = 'tracking',
  initialLocation,
}: {
  onLocationUpdate?: (location: LocationType) => void;
  shareToken?: string;
  mode?: 'tracking' | 'viewing';
  initialLocation?: { latitude: number; longitude: number };
}) {
  const [position, setPosition] = useState<[number, number] | null>(null);
  const [sharedPosition, setSharedPosition] = useState<[number, number] | null>(null);
  const [lastUpdate, setLastUpdate] = useState<string | undefined>(undefined);
  const [isLoading, setIsLoading] = useState(true);
  const [isClient, setIsClient] = useState(false);
  const { subscribeToLocationUpdates } = useSocket();

  // Check if we're on client side
  useEffect(() => {
    setIsClient(true);
  }, []);

  // Fix Leaflet marker icon issues in Next.js
  useEffect(() => {
    // This is needed to fix the marker icon issues with webpack
    if (typeof window !== "undefined") {
      // @ts-ignore
      delete L.Icon.Default.prototype._getIconUrl;
      L.Icon.Default.mergeOptions({
        iconRetinaUrl: "/marker-icon-2x.png",
        iconUrl: "/marker-icon.png",
        shadowUrl: "/marker-shadow.png",
      });
    }
  }, []);

  // Subscribe to real-time location updates when viewing shared location
  useEffect(() => {
    if (mode === 'viewing' && shareToken && isClient) {
      // If we have initial location, set it
      if (initialLocation) {
        setSharedPosition([initialLocation.latitude, initialLocation.longitude]);
        setIsLoading(false);
      }
      
      // Subscribe to real-time updates
      const cleanup = subscribeToLocationUpdates(shareToken, (data) => {
        console.log('Received location update:', data);
        setSharedPosition([data.latitude, data.longitude]);
        setLastUpdate(data.timestamp);
        toast.info('Location updated');
      });
      
      return cleanup;
    }
  }, [mode, shareToken, subscribeToLocationUpdates, initialLocation, isClient]);

  useEffect(() => {
    if (!isClient) return;
    
    // Only get current position in tracking mode
    if (mode === 'tracking') {
      // Try to get initial position
      navigator.geolocation.getCurrentPosition(
        (position) => {
          setPosition([position.coords.latitude, position.coords.longitude]);
          setIsLoading(false);
          
          if (onLocationUpdate) {
            onLocationUpdate({
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
              accuracy: position.coords.accuracy,
              timestamp: new Date(position.timestamp),
            });
          }
        },
        (error) => {
          toast.error(`Error getting location: ${error.message}`);
          setIsLoading(false);
        },
        { enableHighAccuracy: true }
      );
    }
  }, [onLocationUpdate, isClient, mode]);

  // Handle location updates from the marker component
  const handleLocationUpdate = (location: LocationType) => {
    setPosition([location.latitude, location.longitude]);
    if (onLocationUpdate) {
      onLocationUpdate(location);
    }
  };

  if (!isClient || isLoading) {
    return <div className="h-full w-full flex items-center justify-center">Loading map...</div>;
  }

  // Determine which position to center on
  let defaultPosition: [number, number];
  if (mode === 'viewing' && sharedPosition) {
    defaultPosition = sharedPosition;
  } else if (position) {
    defaultPosition = position;
  } else {
    defaultPosition = [51.505, -0.09]; // Default to London
  }

  return (
    <div className="h-full w-full">
      <MapContainer
        center={defaultPosition}
        zoom={13}
        style={{ height: "100%", width: "100%" }}
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        
        {/* Show our location marker in tracking mode */}
        {mode === 'tracking' && position && (
          <LocationMarker 
            position={position} 
            onLocationUpdate={handleLocationUpdate} 
            shareToken={shareToken}
          />
        )}
        
        {/* Show shared location marker in viewing mode */}
        {mode === 'viewing' && sharedPosition && (
          <SharedLocationMarker position={sharedPosition} lastUpdate={lastUpdate} />
        )}
      </MapContainer>
    </div>
  );
}