fix(blocks-google-maps): Fix onLoad event.

This commit is contained in:
Gervwyk 2022-06-24 11:27:21 +02:00
parent e9a75df9cb
commit 2c1de9a6f7
3 changed files with 12 additions and 10 deletions

View File

@ -44,7 +44,6 @@
},
"dependencies": {
"@lowdefy/block-utils": "4.0.0-alpha.12",
"@lowdefy/helpers": "4.0.0-alpha.12",
"@react-google-maps/api": "2.12.0",
"react": "18.1.0",
"react-dom": "18.1.0"

View File

@ -31,7 +31,7 @@ function updateHeatmap(data) {
const GoogleMapsHeatmap = ({ blockId, content, methods, properties }) => (
<Map blockId={blockId} content={content} methods={methods} properties={properties}>
{(map, bounds) =>
{({ map, bounds }) =>
map &&
bounds &&
properties.heatmap && (

View File

@ -17,7 +17,6 @@
import React, { useState, useEffect } from 'react';
import { GoogleMap, Marker, InfoWindow } from '@react-google-maps/api';
import { type } from '@lowdefy/helpers';
const STYLE_DEFAULTS = {
width: '100%',
@ -32,13 +31,15 @@ const MAP_DEFAULTS = {
},
};
const artifacts = {};
// Implements https://react-google-maps-api-docs.netlify.app/#googlemap
const Map = ({ blockId, children, content, methods, properties }) => {
const [map, setMap] = useState();
const [bounds, setBounds] = useState();
const [loaded, setLoaded] = useState(false);
useEffect(() => {
methods.registerMethod('fitBounds', (args) => {
const { bounds, map } = artifacts;
if (!bounds || !map) {
throw new Error('fitBounds can only be called once google maps has been mounted.');
}
@ -50,10 +51,11 @@ const Map = ({ blockId, children, content, methods, properties }) => {
map.setZoom(args.zoom);
}
});
}, [bounds, map]);
}, []);
// by default, fit infoWindow and markers to bounds
if (properties.autoBounds !== false && bounds && map) {
if (properties.autoBounds !== false && loaded) {
const { bounds, map } = artifacts;
if (properties.infoWindow) {
bounds.extend(properties.infoWindow.position ?? MAP_DEFAULTS.center);
}
@ -73,12 +75,13 @@ const Map = ({ blockId, children, content, methods, properties }) => {
center={properties.map?.center ?? MAP_DEFAULTS.center}
zoom={properties.map?.zoom ?? MAP_DEFAULTS.zoom}
onLoad={(map, event) => {
setMap(map);
setBounds(new window.google.maps.LatLngBounds());
artifacts.map = map;
artifacts.bounds = new window.google.maps.LatLngBounds();
methods.triggerEvent({
name: 'onLoad',
event,
});
setLoaded(true);
}}
onClick={(event) => {
methods.triggerEvent({
@ -122,7 +125,7 @@ const Map = ({ blockId, children, content, methods, properties }) => {
{content.infoWindow && content.infoWindow()}
</InfoWindow>
)}
{children && children(map, bounds)}
{children && children(artifacts)}
</GoogleMap>
);
};