-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
198 lines (164 loc) Β· 7.32 KB
/
Copy pathscript.js
File metadata and controls
198 lines (164 loc) Β· 7.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
document.addEventListener("DOMContentLoaded", () => {
// π DOM Elements
const form = document.querySelector(".travel-form");
const loadingMessage = document.getElementById("loading-message");
const travelPlanContainer = document.getElementById("travel-plan-container");
const interestButtons = document.querySelectorAll(".interest-button");
const selectedInterestsInput = document.getElementById("selected-interests");
const weatherCard = document.getElementById("weather-card");
const imageContainer = document.getElementById("destination-image");
// π API Keys (Move to environment variables for security)
const UNSPLASH_ACCESS_KEY = "VDe53wmJz2fr6bUtiu5UgDbgNNGrJNgn2SMdBAfGsWw";
const WEATHER_API_KEY = "cbfae166ed8241a12093367b15d4b392";
const GEMINI_API_KEY = "AIzaSyDw2gMVC65Ov3yTwZCH67GE30dR7hpPe6s";
// β
Handle Interest Button Selection
interestButtons.forEach((button) => {
button.addEventListener("click", () => {
button.classList.toggle("active");
updateSelectedInterests();
});
});
function updateSelectedInterests() {
const selected = Array.from(interestButtons)
.filter((btn) => btn.classList.contains("active"))
.map((btn) => btn.dataset.interest);
selectedInterestsInput.value = selected.join(", ");
}
//handling the loading page
function showLoading() {
loadingMessage.style.display = "flex"; // Show the loading screen
document.body.classList.add("no-scroll"); // Disable scrolling
}
function hideLoading() {
loadingMessage.style.display = "none"; // Hide the loading screen
document.body.classList.remove("no-scroll"); // Enable scrolling again
}
// β
Fetch & Display Weather Information
async function fetchWeather(destination) {
const weatherApiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${destination}&units=metric&appid=${WEATHER_API_KEY}`;
try {
const response = await fetch(weatherApiUrl);
if (!response.ok) throw new Error("Weather data not found.");
const weatherData = await response.json();
displayWeather(weatherData, destination);
} catch (error) {
console.error("Error fetching weather:", error);
weatherCard.style.display = "none";
}
}
function displayWeather(weatherData, destination) {
weatherCard.innerHTML = `
<h3>Current Weather in ${destination}</h3>
<div class="weather-info">
<div class="weather-detail"><span>Condition:</span> ${weatherData.weather[0].description}</div>
<div class="weather-detail"><span>Temperature:</span> ${Math.round(weatherData.main.temp)}Β°C</div>
<div class="weather-detail"><span>Humidity:</span> ${weatherData.main.humidity}%</div>
<div class="weather-detail"><span>Wind Speed:</span> ${weatherData.wind.speed} m/s</div>
</div>
`;
weatherCard.style.display = "block";
weatherCard.classList.add("visible");
}
// β
Fetch & Display Destination Images
async function fetchDestinationImages(destination) {
const unsplashUrl = `https://api.unsplash.com/search/photos?query=${destination}&client_id=${UNSPLASH_ACCESS_KEY}&per_page=12&orientation=landscape`;
try {
const response = await fetch(unsplashUrl);
if (!response.ok) throw new Error("Failed to fetch images");
const data = await response.json();
if (data.results.length > 0) {
imageContainer.innerHTML = data.results
.map((img) => `<img src="${img.urls.regular}" alt="${destination}" class="destination-img">`)
.join("");
} else {
imageContainer.innerHTML = `<p>No images available for ${destination}</p>`;
}
} catch (error) {
console.error("Error fetching destination images:", error);
imageContainer.innerHTML = `<p>Image not available</p>`;
}
}
// β
Generate AI-Based Travel Plan using Gemini API
// β
Generate AI-Based Travel Plan using Gemini API
async function generateTravelPlan(from, destination, duration, budget, interests, specialRequirements) {
const prompt = `
Generate a structured travel itinerary for a trip from **${from}** to **${destination}** for **${duration} days**.
- **Budget**: ${budget} INR per person
- **Preferences**: ${interests || "None"}
- **Special Requirements**: ${specialRequirements || "None"}
**Format (Use HTML with Dark Mode Styling)**:
- **Title**: "Travel Itinerary for ${destination}"
- **Day-wise Plan** (Morning, Afternoon, Evening)
- **Transportation & Stay Recommendations**
- **Must-Try Food**
- **Packing & Safety Tips**
Return the response in **HTML format**.
`;
// β
FIXED MODEL NAME (THIS IS THE ONLY REQUIRED CHANGE)
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=${GEMINI_API_KEY}`;
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [
{
parts: [{ text: prompt }]
}
]
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error?.message || response.statusText);
}
const data = await response.json();
displayTravelPlan(data);
} catch (error) {
console.error("Error fetching travel plan:", error);
travelPlanContainer.innerHTML = `<p>An error occurred: ${error.message}. Please try again later.</p>`;
hideLoading();
}
}
function displayTravelPlan(data) {
hideLoading();
travelPlanContainer.classList.add("visible");
if (data.candidates?.length > 0 && data.candidates[0].content?.parts?.length > 0) {
let sanitizedOutput = data.candidates[0].content.parts[0].text || "";
sanitizedOutput = sanitizedOutput.replace(/```html|```/g, "").trim();
travelPlanContainer.innerHTML = `<div class='travel-plan-content'>${sanitizedOutput}</div>`;
} else {
travelPlanContainer.innerHTML = "<p>Sorry, we couldn't generate a travel plan at this time. Please try again.</p>";
}
}
// β
Handle Form Submission
form.addEventListener("submit", async (event) => {
event.preventDefault();
showLoading();
travelPlanContainer.innerHTML = "";
travelPlanContainer.classList.remove("visible");
weatherCard.style.display = "none";
weatherCard.classList.remove("visible");
imageContainer.innerHTML = "";
const destination = document.getElementById("destination").value.trim();
const from = document.getElementById("from").value.trim();
const duration = document.getElementById("duration").value.trim();
const budget = document.getElementById("budget").value.trim();
const interests = selectedInterestsInput.value.trim();
const specialRequirements = document.getElementById("special-requirements").value.trim();
if (!destination || !from || !duration || !budget) {
alert("Please fill in all required fields.");
hideLoading();
return;
}
await fetchWeather(destination);
await generateTravelPlan(from, destination, duration, budget, interests, specialRequirements);
await fetchDestinationImages(destination);
});
});
window.whoMadeYou = function () {
console.log("%cπ₯ I was created by HellO! π", "color: green; font-size: 16px; font-weight: bold;");
};
function whoMade(){
console.log("Sumit")
}