Search code examples
javascriptnode.jsreactjsmapboxmapbox-gl

can not move location and create marker mapbox react


this code is o create a marker using the value introduced by the user, and make this marker fixed. but I don't even can create the marker, nothing happen.

it's stick in the initial location after rendering. I taught maybe it was a lat and lng order but I try that and it's keep loading. I try also to remove flyTo but nothing changed

  export default function Map() {
    
    const mapContainer = useRef(null);
    const [lng, setLng] = useState(-70.9);
    const [lat, setLat] = useState(42.35);
    const [zoom, setZoom] = useState(9);
  
    const [searchValue, setSearchValue] = useState("");
  
  
    useEffect(() => {
      const map = new mapboxgl.Map({
        container: mapContainer.current,
        style: "mapbox://styles/mapbox/streets-v11",
         center: [lng, lat],
        zoom: zoom,
      });
      map.addControl(new mapboxgl.NavigationControl(), "top-right");
      map.on("move", () => {
        setLng(map.getCenter().lng.toFixed(4));
        setLat(map.getCenter().lat.toFixed(4));
        setZoom(map.getZoom().toFixed(2));
      });
    }, []); // eslint-disable-line react-hooks/exhaustive-deps
  
    function getCoordinates(placesContent) {
      const { center, place_name } = placesContent.features[0];
      return {
        coordinates: center.reverse(),
        name: place_name,
      };
    }
    const changeMapCenter = async () => {
      const map = new mapboxgl.Map({
        container: mapContainer.current,
         style: "mapbox://styles/mapbox/streets-v11",
        center: [lng, lat],
        zoom: zoom,
      });
      return fetch(
        `${MAPBOX_PLACES_API}${searchValue}${REST_PLACES_URL}`,
        FETCH_HEADERS
      )
        .then((res) => res.json())
        .then((apiData) => {
          console.log("apidata=>", apiData);
          const { coordinates } = getCoordinates(apiData);
          console.log("coordinates=>", coordinates);
          map.flyTo(coordinates);
          new mapboxgl.Marker().setLngLat(coordinates).addTo(map);
        });
    };
    const handleChange = (event) => {
      setSearchValue(event.target.value);
    };
    return (
      <div className="mapBox">
        <div className="sidebar">
          Longitude: {lng} | Latitude: {lat} | Zoom: {zoom}
          <div>
            <label>create your spot collection</label>
            <input
              type="text"
              id="spotLocation"
              onChange={handleChange}
              value={searchValue}
            />
            <button onClick={changeMapCenter}>search and create </button>
          </div>
        </div>
        <div className="map-container" ref={mapContainer} />
      </div>
    );
  }

Solution

  • Try saving the map in a state and use setCenter

     const [ customMap, setMap ] = useState({ lat: 0, lng: 0}) // set your own initial value
    
     useEffect(() => {
          const map = new mapboxgl.Map({
            container: mapContainer.current,
            style: "mapbox://styles/mapbox/streets-v11",
             center: [lng, lat],
            zoom: zoom,
          });
          map.addControl(new mapboxgl.NavigationControl(), "top-right");
          map.on("move", () => {
            setLng(map.getCenter().lng.toFixed(4));
            setLat(map.getCenter().lat.toFixed(4));
            setZoom(map.getZoom().toFixed(2));
          });
          setMap(map);
        }, []);
    
    
        const handleChange = (event) => {
          // i assume event.target.value contains the coordinates
          // example 929292, 2929292
          setSearchValue(event.target.value)
        };
        const onSubmit = () => {
             let coordinates = searchValue.split(',')
             customMap.setCenter({ lat: coordinates[0], lng: coordinates[1]});
        }