ClickMarkerMap.jsx 1021 B

1234567891011121314151617181920212223242526272829303132333435
  1. import React, { useRef, useEffect } from "react";
  2. /* global google */
  3. export default ({ onMarkerMoved }) => {
  4. const mapDivRef = useRef(null);
  5. const mapRef = useRef(null);
  6. const markerRef = useRef(null);
  7. useEffect(() => {
  8. if (mapRef.current) {
  9. console.log("Attempted to re-run effect with existing Map");
  10. return;
  11. }
  12. mapRef.current = new google.maps.Map(mapDivRef.current, {
  13. center: { lat: 25, lng: -25 },
  14. zoom: 0,
  15. disableDefaultUI: true,
  16. fullscreenControl: true,
  17. });
  18. if (onMarkerMoved) {
  19. mapRef.current.addListener("click", ({ latLng }) => {
  20. if (markerRef.current) {
  21. markerRef.current.setMap(null);
  22. }
  23. markerRef.current = new google.maps.Marker({ map: mapRef.current, position: latLng });
  24. console.log({ lat: latLng.lat(), lng: latLng.lng() });
  25. onMarkerMoved({ lat: latLng.lat(), lng: latLng.lng() });
  26. });
  27. }
  28. }, [onMarkerMoved]);
  29. return <div className="map-div" ref={mapDivRef} />
  30. }