ClickMarkerMap.jsx 967 B

1234567891011121314151617181920212223242526272829303132
  1. import React, { useRef, useEffect } from "react";
  2. /* global google */
  3. // avoid re-rendering with memo(..., () => true)
  4. // this reduces reusability of this component, but that's fine for this
  5. export default React.memo(({
  6. onMarkerMoved
  7. }) => {
  8. const mapDivRef = useRef(null);
  9. useEffect(() => {
  10. const googleMap = new google.maps.Map(mapDivRef.current, {
  11. center: { lat: 25, lng: -25 },
  12. zoom: 0,
  13. disableDefaultUI: true,
  14. fullscreenControl: true,
  15. });
  16. if (onMarkerMoved) {
  17. googleMap.addListener("click", ({ latLng }) => {
  18. if (mapDivRef.current.mapMarker) {
  19. mapDivRef.current.mapMarker.setMap(null);
  20. }
  21. mapDivRef.current.mapMarker = new google.maps.Marker({ map: googleMap, position: latLng });
  22. if (onMarkerMoved) {
  23. onMarkerMoved({ lat: latLng.lat(), lng: latLng.lng() });
  24. }
  25. });
  26. }
  27. });
  28. return <div className="map-div" ref={mapDivRef} />
  29. }, () => true);