My geolocation code doesn't work

I’m trying to retrieve data from api.apixu.com. My browser asks me for permission to access my location but then noting happens.

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
}
else {
alert(‘Geolocation is not supported’);
}
}

function success(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var Weather = “https://api.apixu.com/v1/current.json?key=4c04934e9d91459b823135519173112&q=” + lat + “,” + lng;

$(document).ready(function($) {
$.ajax({
url : Weather,
dataType : “jsonp”,
success : function(get_json) {
var location = get_json[‘Name’][‘country’];
var current = get_json[‘temp_c’][‘temp_f’];
var condition = get_json[‘text’];
var img = get_json[‘icon’];
}
});
$(‘#location’).html(location);
$(‘#current’).html(current);
$(‘#condition’).html(condition);
$(‘#img’).attr(‘src’, img);
});
}

I’ve made a codepen for you: https://codepen.io/v-lai/pen/jYmoqX/
It has been working for me in Chrome and Firefox, but not Safari.

The main reason this is not working is because you have a variable Weather which is not seen in the ajax request which is inside the document ready function. At no point is the getLocation function called and that’s the first thing we want to have done when the page loads in order to get the location to be passed down to the url and then send the request for the weather.

Also, it would be a good idea to take a closer look at how the API you are using works. https://www.apixu.com/api-explorer.aspx

Screenshot 1 shows the inputs and screenshot 2 is the response object which you will use to display the info you want to show.


1 Like

Thank you. Before you post your answer I also had figured out the variables inside the Ajax function were in a wrong format and I couldn’t get the .text and .icon data. Your code solves all those issues. Thanks.