|
@@ -1,35 +1,44 @@
|
|
|
import React, { useRef, useEffect } from "react";
|
|
|
/* global google */
|
|
|
|
|
|
-export default ({ onMarkerMoved }) => {
|
|
|
- const mapDivRef = useRef(null);
|
|
|
- const mapRef = useRef(null);
|
|
|
- const markerRef = useRef(null);
|
|
|
-
|
|
|
+const useMap = () => {
|
|
|
+ const mapDiv = useRef(null);
|
|
|
+ const map = useRef(null);
|
|
|
useEffect(() => {
|
|
|
- if (mapRef.current) {
|
|
|
+ if (map.current) {
|
|
|
console.log("Attempted to re-run effect with existing Map");
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
- mapRef.current = new google.maps.Map(mapDivRef.current, {
|
|
|
+ map.current = new google.maps.Map(mapDiv.current, {
|
|
|
center: { lat: 25, lng: -25 },
|
|
|
zoom: 0,
|
|
|
disableDefaultUI: true,
|
|
|
fullscreenControl: true,
|
|
|
});
|
|
|
+ }, []);
|
|
|
|
|
|
- if (onMarkerMoved) {
|
|
|
- mapRef.current.addListener("click", ({ latLng }) => {
|
|
|
- if (markerRef.current) {
|
|
|
- markerRef.current.setMap(null);
|
|
|
- }
|
|
|
- markerRef.current = new google.maps.Marker({ map: mapRef.current, position: latLng });
|
|
|
- console.log({ lat: latLng.lat(), lng: latLng.lng() });
|
|
|
- onMarkerMoved({ lat: latLng.lat(), lng: latLng.lng() });
|
|
|
- });
|
|
|
- }
|
|
|
- }, [onMarkerMoved]);
|
|
|
+ return [mapDiv, map];
|
|
|
+}
|
|
|
+
|
|
|
+const useClickMarker = (map, onMove) => {
|
|
|
+ const marker = useRef(null);
|
|
|
+ useEffect(() => {
|
|
|
+ const listener = map.current.addListener("click", ({ latLng }) => {
|
|
|
+ if (marker.current) {
|
|
|
+ marker.current.setMap(null);
|
|
|
+ }
|
|
|
+ marker.current = new google.maps.Marker({ map: map.current, position: latLng });
|
|
|
+ console.log({ lat: latLng.lat(), lng: latLng.lng() });
|
|
|
+ onMove({ lat: latLng.lat(), lng: latLng.lng() });
|
|
|
+ });
|
|
|
|
|
|
+ return () => { google.maps.event.removeListener(listener); }
|
|
|
+ }, [map, onMove]);
|
|
|
+}
|
|
|
+
|
|
|
+export default ({ onMarkerMoved }) => {
|
|
|
+ const [mapDivRef, mapRef] = useMap();
|
|
|
+ useClickMarker(mapRef, onMarkerMoved);
|
|
|
return <div className="map-div" ref={mapDivRef} />
|
|
|
}
|