import { apiKey } from "../../lib/appwrite/config";
const fetchPlaceDetailsNew = async (placeId: string) => {
try {
console.log("Making request to Places API with API Key:", apiKey);
const response = await fetch(`https://places.googleapis.com/v1/places ... y=${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
input: placeId, // PlaceId or search term
}),
});
if (!response.ok) {
console.error('Error fetching place data:', response.statusText);
throw new Error('Failed to fetch place details');
}
const data = await response.json();
console.log('Place Data:', data);
return data;
} catch (error) {
console.error('Error in fetchPlaceDetailsNew:', error);
throw error;
}
};
export const fetchAutocompletePlaces = async (query: string) => {
const url = `https://places.googleapis.com/v1/places:autocomplete`;
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Goog-Api-Key": apiKey,
"X-Goog-FieldMask": "suggestions.placePrediction" // Limits response size
},
body: JSON.stringify({
input: query,
}),
});
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error in fetchAutocompletePlaces:", error);
return null;
}
};
type RestaurantDetails = {
name: string;
address: string;
phone: string;
rating: number | string;
website: string;
googleMapsUrl: string;
location: { lat: number; lng: number };
};
type Restaurant = {
name: string;
placeId: string;
};
type PlaceSuggestion = {
placePrediction: {
place: string;
placeId: string;
structuredFormat?: {
mainText?: { text: string };
};
};
};
const Restaurants = () => {
const [searchTerm, setSearchTerm] = useState('');
const [restaurants, setRestaurants] = useState([]);
const [loading, setLoading] = useState(false);
const [selectedRestaurant, setSelectedRestaurant] = useState(null); // Store selected restaurant details
const handleSearchChange = (event: React.ChangeEvent) => {
setSearchTerm(event.target.value);
};
const handleSearch = async (query: string) => {
console.log("Searching for:", query);
try {
const data = await fetchAutocompletePlaces(query);
if (!data || !data.suggestions) {
console.warn("No suggestions found!");
setRestaurants([]);
return;
}
const processedPlaces = data.suggestions.map((suggestion: PlaceSuggestion) => ({
name: suggestion.placePrediction?.structuredFormat?.mainText?.text || "No Name",
placeId: suggestion.placePrediction?.placeId || "No Place ID",
}));
console.log("Processed Places:", processedPlaces);
setRestaurants(processedPlaces);
} catch (error) {
console.error("Error fetching places:", error);
}
};
const handlePlaceSelect = async (place: { placeId: string }) => {
if (!place || !place.placeId) {
console.warn("Invalid place selected");
return;
}
try {
console.log("Fetching details for:", place.placeId);
const placeDetails = await fetchPlaceDetailsNew(place.placeId);
if (placeDetails) {
setSelectedRestaurant({
name: placeDetails.displayName?.text || "Unknown Name",
address: placeDetails.formattedAddress || "No address available",
phone: placeDetails.nationalPhoneNumber || "No phone number",
rating: placeDetails.rating || "No rating",
website: placeDetails.websiteUri || "",
googleMapsUrl: placeDetails.googleMapsUri || "",
location: {
lat: placeDetails.location?.latitude || 0,
lng: placeDetails.location?.longitude || 0,
},
});
} else {
console.warn("No details available for this place.");
}
} catch (error) {
console.error("Error fetching place details:", error);
}
};
useEffect(() => {
if (searchTerm) {
setLoading(true);
handleSearch(searchTerm).finally(() => setLoading(false));
}
}, [searchTerm]);
return (
Find Restaurants
{loading ? (
Loading restaurants...
) : (
{restaurants.length > 0 ? (
- {restaurants.map((restaurant) => (
-
{restaurant.name}
handlePlaceSelect(restaurant)}>
View Details
))}
No restaurants found.
)}
)}
{/* Display selected restaurant details */}
{selectedRestaurant && (
{selectedRestaurant.name}
{selectedRestaurant.website && (
Visit Website
)}
{selectedRestaurant.googleMapsUrl && (
View on Google Maps
)}
)}
);
};
export default Restaurants;
< /code>
Я тоже новичок в кодировании, поэтому любые советы или помощь ценятся
Подробнее здесь: https://stackoverflow.com/questions/795 ... javascript
Мобильная версия