I have these basics code and all I need is to access location, but this is not working at my end. Would someone help me out why this is not working?
local Weather App
Weather in my local area
City:
°C
var location = document.getElementById(“locat-city”);
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
location.innerHTML = “Geolocation is not supported by this browser.”;
}
}
function showPosition(position) {
location.innerHTML = "Latitude: " + position.coords.latitude +
"
Longitude: " + position.coords.longitude;
}
There is a global variable named location. Either change the variable name or wrap your code in an IIFE to scope the variable.
Thank your for your reply.Changes made but location cannot be accessed still.
Are you actually calling the getLocation function?
Does this work for you?
Yes it’s working thanks so much.
And to display city name instead of longitude and latitude?
You need to use an API which returns the location. Looks like it is a weather app you are making so here is a list of weather APIs.
You also need to know how to fetch the data from the API.
Introduction to the JSON APIs and AJAX Challenges
The above challenges shows using XMLHttpRequest, but there is also the newer Fetch API, or libraries like jQuery and Axios.
1 Like