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

Se modifica para que cambie el zoom y el centro cada vez que cambie el marcador

parent 02993c1e
Loading
Loading
Loading
Loading
+29 −26
Original line number Diff line number Diff line
import { useState, Dispatch, SetStateAction, useEffect } from "react";
import { REACT_APP_GOOGLE_API_KEY } from "../../constants/api_keys";
import { Dispatch, SetStateAction, useEffect } from "react";
import { UseFormClearErrors, UseFormSetValue } from "react-hook-form";
import { Place } from "../../infraestructure/entities/place";
import { APIProvider, Map, Marker } from "@vis.gl/react-google-maps";
import { Map, Marker, useMap } from "@vis.gl/react-google-maps";

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

export interface Position{
@@ -17,35 +16,39 @@ export interface Position{
  longitude: number;
}

export const MapComponent = ({setValue, setIsLoading, latitude, longitude, clearErrors}: props) => {
  const [position, setPosition] = useState<Position>({latitude: 0.0, longitude: 0.0});
  const center = {lat: 23.687, lng: -102.74};

  useEffect(() => {
    if(latitude && longitude){
      setPosition({latitude, longitude});
    }
  }, [latitude]);
export const MapComponent = ({setValue, setIsLoading, position, setPosition, clearErrors}: props) => {
  const defaultCenter = {lat: 23.687, lng: -102.74};
  const mapRef = useMap();

  useEffect(() => {
    if(position && position.latitude!==0 && position.longitude!==0){
      setValue('latitude',position.latitude);
      setValue('longitude',position.longitude);
      if(mapRef){
        mapRef.setCenter({lat: position.latitude, lng: position.longitude});
        mapRef.setZoom(16);
      }
      clearErrors('latitude');
      clearErrors('longitude');
    }
  },[position]);

  return (
    <APIProvider apiKey={REACT_APP_GOOGLE_API_KEY} onLoad={() => setIsLoading(false)}>
    <div style={{width: '100%', height: '100%'}}>
        <Map defaultCenter={center} defaultZoom={8} gestureHandling={'greedy'}
        disableDefaultUI={true} onClick={(event)=> {
      <Map defaultCenter={defaultCenter}
        defaultZoom={8}
        gestureHandling={'greedy'}
        disableDefaultUI={true} 
        onClick={(event)=> {
          const lat = event.detail.latLng?.lat || 0.0;
          const lng = event.detail.latLng?.lng || 0.0;
          setPosition({latitude: lat, longitude: lng});
        }}>
          <Marker position={{lat: position.latitude, lng: position.longitude}}/>
        }}
        
      >
        {position && <Marker position={{lat: position.latitude, lng: position.longitude}}/>}
      </Map>
    </div>
    </APIProvider>
  );
}
 No newline at end of file