I can't change an HTML element's contents through the callback to the jquery function $.getJSON()

50 views Asked by At

I'm trying to change the content of the div element with id attribute country (i.e. id="country") to the country of the user's current position. Is there anything wrong with my code?

function location (position){
    var a=position.coords.latitude;
    var b=position.coords.longitude;    
    $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat='+a+'&lon='+b+'&APPID=b84cde4a2b80a14ecfebbd9ea7d08831&units=metric', function getData(data){
      $("#country").html(data.sys.country);
    }) 
  }
1

There are 1 answers

0
mike510a On

EDIT

An important thing to mention is that As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS.

If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.

If your using HTTPS then,

ORIGINAL

I'm guessing your not building your position object correctly.

Make sure that you have a position object, which has a property called coords with a value of an object with two properties, latitude and longitute. Every object has to be encapsulated with { }

It works great in this snippet (original code unchanged):

function location(position) {
  var a = position.coords.latitude;
  var b = position.coords.longitude;
  $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + a + '&lon=' + b + '&APPID=b84cde4a2b80a14ecfebbd9ea7d08831&units=metric', function getData(data) {
    $("#country").html(data.sys.country);
  })
}

/* here we build our position object with a coords child object containing latitude and longitude */
var pos = {
  "coords": {
    "latitude": 34.7459360,
    "longitude": -118.2506350
  }
};

/* now we actually call the script  location(pos)  using our position object */
location(pos);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="country"></div>