Quellcode durchsuchen

Breaking out map components

Kirk Trombley vor 5 Jahren
Ursprung
Commit
89b97d7bff

+ 19 - 0
client/src/components/maps/click-marker-map.component.jsx

@@ -0,0 +1,19 @@
+import React from "react";
+import MapComponent from "./map.component";
+/* global google */
+
+export default ({
+  onMarkerMoved
+}) => {
+  // avoid re-rendering by using let (similar to instance field)
+  let marker = null;
+  return <MapComponent onMapClick={(map, position) => {
+    if (marker) {
+      marker.setMap(null);
+    }
+    marker = new google.maps.Marker({ map, position });
+    if (onMarkerMoved) {
+      onMarkerMoved({ lat: position.lat(), lng: position.lng() });
+    }
+  }}/>
+};

+ 33 - 0
client/src/components/maps/map.component.jsx

@@ -0,0 +1,33 @@
+import React, { useRef, useEffect } from "react";
+/* global google */
+
+// TODO might want to look into forcing this to avoid updates
+export default ({
+  onMapClick
+}) => {
+  const mapDivRef = useRef(null);
+  useEffect(() => {
+    const googleMap = new google.maps.Map(mapDivRef.current, {
+      center: { lat: 25, lng: -25 },
+      zoom: 0,
+      disableDefaultUI: true,
+      fullscreenControl: true,
+    });
+    console.log("Created Map");
+    if (onMapClick) {
+      console.log("Adding click listener");
+      googleMap.addListener("click", ({latLng}) => onMapClick(googleMap, latLng));
+    }
+  });
+
+  return (
+    <div style={{ 
+        height: "100%",
+        display: "flex",
+        flexDirection: "column",
+        justifyContent: "center",
+      }} 
+      ref={mapDivRef}
+    />
+  );
+};