|
| 1 | +import { |
| 2 | + Map as GoogleMapGL, |
| 3 | + APIProvider, |
| 4 | + MapCameraChangedEvent, |
| 5 | +} from "@vis.gl/react-google-maps"; |
| 6 | +import { GoogleMapsSource, MapState } from "../types"; |
| 7 | +import { useState } from "react"; |
| 8 | + |
| 9 | +interface GoogleMapProps { |
| 10 | + mapState: MapState; |
| 11 | + source: GoogleMapsSource; |
| 12 | + apiKey: string; |
| 13 | + synchronized: boolean; |
| 14 | + onMapChange: (state: Partial<MapState>) => void; |
| 15 | + onViewStateChange: (state: Partial<MapState>) => void; |
| 16 | +} |
| 17 | + |
| 18 | +export function GoogleMap({ |
| 19 | + mapState: effectiveMapState, |
| 20 | + source, |
| 21 | + apiKey, |
| 22 | + synchronized, |
| 23 | + onMapChange, |
| 24 | + onViewStateChange, |
| 25 | +}: GoogleMapProps) { |
| 26 | + const [isActive, setIsActive] = useState(false); |
| 27 | + |
| 28 | + const handleCameraChange = (event: MapCameraChangedEvent) => { |
| 29 | + const newState: Partial<MapState> = { |
| 30 | + center: [event.detail.center.lng, event.detail.center.lat], |
| 31 | + zoom: event.detail.zoom, |
| 32 | + bearing: event.detail.heading ?? effectiveMapState.bearing, |
| 33 | + pitch: event.detail.tilt ?? effectiveMapState.pitch, |
| 34 | + }; |
| 35 | + |
| 36 | + if (synchronized) { |
| 37 | + onMapChange(newState); |
| 38 | + } else { |
| 39 | + onViewStateChange(newState); |
| 40 | + } |
| 41 | + }; |
| 42 | + |
| 43 | + return ( |
| 44 | + <APIProvider apiKey={apiKey}> |
| 45 | + <div className="relative w-full h-full"> |
| 46 | + <GoogleMapGL |
| 47 | + disableDefaultUI={true} |
| 48 | + center={{ |
| 49 | + lat: effectiveMapState.center[1], |
| 50 | + lng: effectiveMapState.center[0], |
| 51 | + }} |
| 52 | + zoom={effectiveMapState.zoom} |
| 53 | + mapTypeId={source.mapType} |
| 54 | + heading={effectiveMapState.bearing} |
| 55 | + tilt={effectiveMapState.pitch} |
| 56 | + gestureHandling="greedy" |
| 57 | + onMouseover={() => setIsActive(true)} |
| 58 | + onMouseout={() => setIsActive(false)} |
| 59 | + onCameraChanged={isActive ? handleCameraChange : undefined} |
| 60 | + /> |
| 61 | + </div> |
| 62 | + </APIProvider> |
| 63 | + ); |
| 64 | +} |
0 commit comments