Created
August 27, 2020 13:55
-
-
Save vesse/7e3ad2963f300b7ebc59c2432403ddcf to your computer and use it in GitHub Desktop.
@react-google-maps/api 1.9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const Main: React.FunctionComponent = () => { | |
const [ markers, setMarkers ] = React.useState<ReadonlyArray<Marker>>([]); | |
// Need to be in separate files for lazy loading, otherwise using window.google.maps | |
// in the actual map component will throw | |
return ( | |
<LoadScript googleMapsApiKey={apiKey}> | |
<Map markers={markers} /> | |
</LoadScript> | |
); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import { GoogleMap, Marker } from '@react-google-maps/api'; | |
const containerStyle = { | |
height: '100%', | |
width: '100%', | |
}; | |
export interface Marker { | |
readonly id: number; | |
readonly location: { | |
readonly lat: number; | |
readonly lng: number; | |
} | |
}; | |
interface Props { | |
readonly markers: ReadonlyArray<Marker>; | |
} | |
const defaultCenter = { lat: 60.170009, lng: 24.938368 }; | |
const defaultZoom = 10; | |
const Map: React.FunctionComponent<Props> = ({ markers }) => { | |
const [map, setMap] = React.useState<google.maps.Map<Element> | null>(null); | |
React.useEffect(() => { | |
if (markers.length > 0 && map) { | |
const bounds = new window.google.maps.LatLngBounds(); | |
markers.forEach(({ location }) => bounds.extend(location)); | |
map.fitBounds(bounds); | |
const center = bounds.getCenter(); | |
map.panTo({ lat: center.lat(), lng: center.lng() }); | |
} | |
}, [markers, map]); | |
return ( | |
<GoogleMap | |
center={defaultCenter} | |
zoom={defaultZoom} | |
mapContainerStyle={containerStyle} | |
onLoad={(mapInstance) => setMap(mapInstance)} | |
onUnmount={() => setMap(null)} | |
> | |
{markers.map((m) => ( | |
<Marker position={m.location} key={m.id} /> | |
))} | |
</GoogleMap> | |
); | |
}; | |
export default React.memo(Map); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment