Skip to content

Instantly share code, notes, and snippets.

@vesse
Created August 27, 2020 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vesse/7e3ad2963f300b7ebc59c2432403ddcf to your computer and use it in GitHub Desktop.
Save vesse/7e3ad2963f300b7ebc59c2432403ddcf to your computer and use it in GitHub Desktop.
@react-google-maps/api 1.9
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>
);
};
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