PluginProbe
Block Animations, Motion & Scroll Effects – Ghost Kit / 3.3.2
Block Animations, Motion & Scroll Effects – Ghost Kit v3.3.2
3.7.2 3.7.1 3.7.0 3.6.1 trunk 1.6.3 2.25.0 3.3.0 3.3.1 3.3.2 3.3.3 3.4.0 3.4.1 3.4.2 3.4.3 3.4.4 3.4.5 3.4.6 3.5.0 3.5.1 3.6.0
ghostkit / gutenberg / blocks / google-maps / map-block.js

map-block.js in Block Animations, Motion & Scroll Effects – Ghost Kit 3.3.2, at gutenberg/blocks/google-maps/map-block.js

102 lines 2.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import { useEffect, useRef, useState } from '@wordpress/element';
2
3 import { addMarker, InitGoogleMaps } from './gmaps-api';
4
5 export default function MapBlock(props) {
6 const { apiUrl, options, markers, onChangeMarkers } = props;
7
8 const [instance, setInstance] = useState(null);
9 const mapRef = useRef(null);
10 const markersRef = useRef(null);
11
12 // Load Google Maps API and initialize the map
13 useEffect(() => {
14 if (!mapRef.current) {
15 return;
16 }
17
18 if (!instance) {
19 InitGoogleMaps(
20 mapRef.current,
21 { apiUrl, ...options },
22 (newInstance) => {
23 setInstance(newInstance);
24 }
25 );
26 } else {
27 instance.setOptions(options);
28 }
29 }, [apiUrl, instance, options]);
30
31 // Add markers to the map.
32 useEffect(() => {
33 if (!instance || !markers || !markers.length) {
34 return;
35 }
36
37 // Reset old markers.
38 if (markersRef.current?.length) {
39 markersRef.current.forEach((marker) => {
40 marker.setMap(null);
41 });
42 }
43
44 markersRef.current = [];
45
46 markers.forEach((markerData, i) => {
47 const thereIsIcon =
48 markerData.iconImageURL &&
49 markerData.iconImageCustomWidth &&
50 markerData.iconImageWidth &&
51 markerData.iconImageHeight;
52 let iconURL = null;
53 let iconWidth = null;
54 let iconHeight = null;
55 if (thereIsIcon) {
56 const iconImageCustomHeight =
57 markerData.iconImageCustomWidth *
58 (markerData.iconImageHeight / markerData.iconImageWidth);
59
60 iconURL = markerData.iconImageURL;
61 iconWidth = markerData.iconImageCustomWidth;
62 iconHeight = iconImageCustomHeight;
63 }
64
65 const { marker } = addMarker({
66 map: instance,
67 lat: markerData.lat,
68 lng: markerData.lng,
69 title: markerData.title,
70 description: markerData.infoWindowText,
71 iconURL,
72 iconWidth,
73 iconHeight,
74 draggable: true,
75 });
76
77 markersRef.current.push(marker);
78
79 // Drag markers.
80 window.google.maps.event.addListener(marker, 'dragend', (event) => {
81 const lat = event.latLng.lat();
82 const lng = event.latLng.lng();
83
84 const newMarkers = Object.assign([], markers);
85
86 newMarkers[i].lat = lat;
87 newMarkers[i].lng = lng;
88
89 onChangeMarkers(newMarkers);
90 });
91 });
92 }, [apiUrl, instance, options, markers, onChangeMarkers]);
93
94 return (
95 <div
96 ref={mapRef}
97 className="ghostkit-google-maps-wrap"
98 style={{ minHeight: '100%' }}
99 />
100 );
101 }
102