Commit f6456dbb authored by Omar Luna Hernández's avatar Omar Luna Hernández
Browse files

Se crea un componente de mapa para usar el api de MapBox

parent d53507ee
Loading
Loading
Loading
Loading
+91 −0
Original line number Diff line number Diff line
import { Dispatch, SetStateAction, useEffect, useRef } from "react";
import { UseFormClearErrors, UseFormSetValue } from "react-hook-form";
import { Place } from "../../infraestructure/entities/place";
import Map, { Marker, useMap } from "react-map-gl";
import "mapbox-gl/dist/mapbox-gl.css";

interface props {
  setValue: UseFormSetValue<Place>;
  setIsLoading: Dispatch<SetStateAction<boolean>>;
  clearErrors: UseFormClearErrors<Place>;
  position: Position | null;
  setPosition: Dispatch<SetStateAction<Position | null>>;
}

export interface Position {
  latitude: number;
  longitude: number;
}

const PositionListener = ({
  setValue,
  position,
  setPosition,
  clearErrors,
}: props) => {
  const mapRef = useMap();

  useEffect(() => {
    if (position && position.latitude !== 0 && position.longitude !== 0) {
      setValue("latitude", position.latitude);
      setValue("longitude", position.longitude);
      if (mapRef.current) {
        mapRef.current.flyTo({
          center: [position.longitude, position.latitude],
          zoom: 17,
        });
      }
      clearErrors("latitude");
      clearErrors("longitude");
    }
  }, [position]);

  return <div />;
};

export const MapBoxComponent = ({
  setValue,
  setIsLoading,
  position,
  setPosition,
  clearErrors,
}: props) => {
  const defaultCenter = { lat: 23.687, lng: -102.74 };

  return (
    <div style={{ width: "100%", height: "100%" }}>
      <Map
        mapboxAccessToken={process.env.REACT_APP_MAP_BOX || ""}
        initialViewState={{
          longitude: defaultCenter.lng,
          latitude: defaultCenter.lat,
          zoom: 7,
        }}
        mapStyle="mapbox://styles/mapbox/streets-v9"
        onClick={(event) => {
          if (event.lngLat) {
            setPosition({
              latitude: event.lngLat.lat,
              longitude: event.lngLat.lng,
            });
          }
        }}
      >
        <PositionListener
          setValue={setValue}
          setIsLoading={setIsLoading}
          position={position}
          clearErrors={clearErrors}
          setPosition={setPosition}
        />
        {position && (
          <Marker
            longitude={position.longitude}
            latitude={position.latitude}
            color="red"
          />
        )}
      </Map>
    </div>
  );
};