How to place my dispatch function with React and React Leaflet for return coords lat + lng

Viewed 105

I have an input (on children component) that return coordinates by props (text):

import React, { useEffect, useState, useRef, useMemo } from 'react'
import { useEnderecoValue } from '../../contexts/EnderecoContext'

import 'leaflet/dist/leaflet.css'
import Leaflet from 'leaflet'
import { MapContainer, Marker, useMap, TileLayer, Popup } from 'react-leaflet'

export default function App(text: any) {
  const [lat, setLat] = useState(48.856614)
  const [lng, setLng] = useState(2.3522219)
  const [state, dispatch] = useEnderecoValue()

  const icon = new Leaflet.DivIcon({
    className: 'custom-div-icon',
    html:
      "<div style='background-color:#c30b82;' class='marker-pin'></div><i class='material-icons'><img src='img/marker-icon.png'></i>",
    iconSize: [30, 42],
    iconAnchor: [15, 42],
    popupAnchor: [-3, -42]
  })

  useEffect(() => {
    if (text.text) {
      setLat(text.text.features[0].geometry.coordinates[1])
      setLng(text.text.features[0].geometry.coordinates[0])
    }
  }, [text])

  function SetViewOnClick({ coords }: any) {
    const map = useMap()
    map.flyTo(coords, map.getZoom())
    return null
  }

My Marker is draggable and the popup display address and coords if I search address on input, or if the Marker is dragded:

const markerRef = useRef(null)

  const eventHandlers = useMemo(
    () => ({
      dragend() {
        const marker = markerRef.current
        if (marker != null) {
          const { lat, lng } = marker.getLatLng()
          setLat(lat)
          setLng(lng)
        }
      }
    }),
    []
  )

  const popup = () => {
    if (text.text) {
      return text.text.query + '   ' + `lat: ${lat}, long: ${lng}`
    }
    return (
      "Address by default" +
      '   ' +
      `lat: ${lat}, long: ${lng}`
    )
  }

  return (
    <MapContainer
      center={[lat, lng]}
      attributionControl={false}
      zoomControl={false}
      zoom={18}
      style={{
        height: '350px',
        position: 'relative',
        outline: 'none',
        maxWidth: '696px',
        display: 'block',
        margin: '15px auto',
        width: '100%'
      }}
    >
      <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
      <Marker
        position={[lat, lng]}
        icon={icon}
        draggable={true}
        ref={markerRef}
        eventHandlers={eventHandlers}
      >
        <Popup>
          <span>{popup()}</span>
        </Popup>
        <SetViewOnClick coords={[lat, lng]} />
      </Marker>
    </MapContainer>
  )
}

How to place my dispatch function for return coords when I search address and whenthe Marker is dragged ? (just when the value change)

  dispatch({
    type: 'SET_COORDS',
    latitude: lat,
    longitude: lng
  })
1 Answers

On your Search comp place dispatch inside searchLocation to be able to change lat long.

  const searchLocation = async () => {
    fetch(
      "https://api-adresse.data.gouv.fr/search?" +
        new URLSearchParams({
          q: state.location,
        })
    )
      .then((data) => data.json())
      .then((text) => {
        setResp({ text });
        dispatch({
          type: "SET_COORDS",
          latitude: text.features[0].geometry.coordinates[1],
          longitude: text.features[0].geometry.coordinates[0],
        });
      })
      .catch(function (error) {
        console.log("request failed", error);
      });
  };

Replace <Map {...resp} /> with <Map text={resp} /> because it causes multiple rerenders and the page becomes unresponsive. Not sure what you were trying to do.

Demo

Related