Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHenrik Christensen
Python Web Development Techdegree Student 38,322 PointsGeolocation
Hi,
I'm trying to use geolocation in a local weather app, but about 50% of the times it says I'm located in Japan, but I'm actually in Denmark - any idea why this is?
EDIT:
- It looks like the latitude and longitude is being changed in the XMLHttpRequest (sometimes)
- comments added
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
const latitude = position.coords.latitude; // always 57.46
const longitude = position.coords.longitude; // always 9.99
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
const data = JSON.parse(xhr.responseText);
console.log(data.coord.lat); // sometimes changed to 35
console.log(data.coord.lon); // sometimes changed to 139
const weatherContainer = document.getElementById("weather-container");
const userLocation = document.getElementById("user-location");
const weatherIcon = document.getElementById("weather-icon");
const temperature = document.getElementById("temperature");
weatherContainer.style.display = "block";
userLocation.textContent = `${data.name}, ${data.sys.country}`;
weatherIcon.setAttribute("src", data.weather[0].icon);
temperature.innerHTML = `${Math.round(data.main.temp)} °C`;
}
};
xhr.open("GET", `https://fcc-weather-api.glitch.me/api/current?lat=${latitude}&lon=${longitude}`);
xhr.send();
});
} else {
alert("Geolocation is not supported in your browser");
}
2 Answers
Blake Larson
13,014 PointsLog your latitude and longitude to make sure it's identical with your home latitude and longitude.
Henrik Christensen
Python Web Development Techdegree Student 38,322 PointsWhen I'm logging the data I get from the XMLHttpRequest I get one set of coords, but when I'm logging the coords before the XMLHttpRequest I get the same longitude and latitude no matter if it thinks I'm in Denmark or Japan :-/