Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 36 additions & 100 deletions src/front/components/AddProduct.jsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,16 @@
"use_client";
import React, { useEffect, useState, createPortal, useRef } from "react";
import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { APIProvider, ControlPosition, MapControl, Map, useMap, useMapsLibrary, AdvancedMarker, useAdvancedMarkerRef } from '@vis.gl/react-google-maps';

import { createRoot } from "react-dom/client";
import { App } from "../components/App.jsx"
import { APIProvider, Map, AdvancedMarker, Pin, InfoWindow } from '@vis.gl/react-google-maps';

export const AddProduct = () => {

const { id } = useParams(); // <- si existe, estamos editando
const { id } = useParams(); // si existe, estamos editando
const isEdit = Boolean(id);
const navigate = useNavigate();
const currentUser = JSON.parse(localStorage.getItem("user"));
// Zona de api Google Maps
const API_KEY = globalThis.GOOGLE_MAPS_API_KEY ?? "AIzaSyAZGZS8YvpJUtpA8KHH5CbnoYUU05xTVak";

const position = { lat: 41.3872516334326, lng: 2.171430948862673 };
const [selectedPlace, setSelectedPlace] = useState(null);
const [markerRef, marker] = useAdvancedMarkerRef();
const [open, setOpen] = useState(false);

const [form, setForm] = useState({
title: "",
Expand Down Expand Up @@ -103,7 +97,6 @@ export const AddProduct = () => {
if (response.status === 403) { alert("No puedes editar este producto"); return; }
if (!response.ok) throw new Error(isEdit ? "Error al guardar cambios" : "Error al crear producto");


const data = await response.json();
alert(isEdit ? "Cambios guardados" : "Producto creado con éxito");
navigate(`/products/details/${data.id}`);
Expand Down Expand Up @@ -239,43 +232,37 @@ export const AddProduct = () => {
</select>
)}

<input type="number" name="price" placeholder="Precio por día (€)"
value={form.price} onChange={handleChange} className="w-full border mb-3 px-3 py-2 rounded"
/>

<div className="mapContiner">
<APIProvider
apiKey={API_KEY}
solutionChannel="GMP_devsite_samples_v3_rgmautocomplete"
>
<Map
mapId={"2cff1ef28229f873716f5413"}
defaultZoom={9}
defaultCenter={position}
gestureHandling={"greedy"}
disableDefaultUI={true}
className="map"
>
<AdvancedMarker ref={markerRef} position={null} />
</Map>


<MapControl position={ControlPosition.TOP}>
<div className="autocomplete-control">
<PlaceAutocomplete onPlaceSelect={setSelectedPlace} />
</div>
</MapControl>
<Maphandler place={selectedPlace} marker={marker} />




<input type="number" name="price" placeholder="Precio por día (€)"
value={form.price} onChange={handleChange} className="w-full border mb-3 px-3 py-2 rounded" />

<input type="text" name="location" placeholder="Ubicación"
value={form.location} onChange={handleChange} className="w-full border mb-3 px-3 py-2 rounded" />

<APIProvider apiKey={"AIzaSyAZGZS8YvpJUtpA8KHH5CbnoYUU05xTVak"} onLoad={() => console.log('Maps API loaded')}>
<div
style={{
height: "30vh",
width: "100%",
borderRadius: "16px",
overflow: "hidden",
marginBottom: "15px"
}}>
<Map
defaultZoom={10}
defaultCenter={position}
mapId={"2cff1ef28229f873716f5413"}
>
<AdvancedMarker position={position} onClick={() => setOpen(true)}>
<Pin />
</AdvancedMarker>
{open && (
<InfoWindow position={position} onClose={() => setOpen(false)}>
<p>Barcelona</p>
</InfoWindow>
)}
</Map>
</div>
</APIProvider>
</div>

);
{/* Input de ubicación arriba del mapa */}


<button type="submit" className="btn"
style={{ backgroundColor: "#2E676A", border: "none", borderRadius: "8px", color: "#ffffff" }}
Expand All @@ -286,55 +273,4 @@ export const AddProduct = () => {
)}
</div>
);
};

const Maphandler = ({ place, marker }) => {
const map = useMap();
useEffect(() => {
if (!map || !place || !marker) return;
if (place.geometry?.viewport) {
map.fitBounds(place.geometry?.location);
}
marker.position = place.geometry?.location;
}, [map, place, marker]);
return null;
}
const PlaceAutocomplete = ({ onPlaceSelect }) => {
const [placeAutocomplete, setPlaceAutocomplete] = useState(null);
const inputRef = useRef(null);
const places = useMapsLibrary("places");
console.log(places)

useEffect(() => {
if (!places || !inputRef.current) return;

const options = {
fields: ["geometry", "name", "formatted_address"],
types: ["establishment", "geocode"]
};

setPlaceAutocomplete(new places.Autocomplete(inputRef.current, options));
}, [places]);
useEffect(() => {
if (!placeAutocomplete) return;


const listener = placeAutocomplete.addListener("place_changed", () => {
let places = placeAutocomplete.getPlace()
console.log("lugares:", places)
onPlaceSelect(places);
});

return () => {
if (listener) {
google.maps.event.removeListener(listener)
}
}
}, [onPlaceSelect, placeAutocomplete]);

return (
<div className="autocomplete-container">
<input ref={inputRef} />
</div>
);
}
};
4 changes: 1 addition & 3 deletions src/front/pages/MisProductos.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,7 @@ export const MisProductos = () => {
<div className="container my-4">
<div className="d-flex align-items-center justify-content-between mb-3">
<h2 className="m-0">Mis productos</h2>
<Link to="/add-product" className="btn btn-primary">
Añadir producto
</Link>

<button className="btn btn-outline-secondary" onClick={() => navigate("/")}>
</button>
Expand Down