Making a call to the openweather API. When I input the URL into a browser, I can see the JSON object. However my ajax below is not allowing anything to appear in my HTML. Even if I want to document.write the entire json object, I cannot. I can output the lat and long just find so the geolocation is working. Not sure what's wrong with this code.
Here's the HTML:
<body>
<div class="container">
<div class="col-lg-12 header">
<h1>My Location</h1>
</div>
<div class="row text-center box">
<div class="col-lg-12" id="data">Lat Long</div>
</div>
</div>
</body>
Here's the JS:
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(main);
}
});
function main(position){
var lat = position.coords.latitude;
var long = position.coords.longitude;
var api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=[redacted key]";
$.ajax({
dataType: 'json',
url: api,
success: function(data) {
city = data.name;
$("#data").html(city);
}
});
}
The problem is not in your ajax call.
You code seems to work pretty good with hardcoded coordinates and also works in its current form on all other browsers besides Chrome.
If you want to use the geolocation on the newer versions of Google Chrome your host would have to be a secure one (HTTPS).
Chrome warning:
getCurrentPosition() and watchPosition() are deprecated on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins for more details.
Try $.getJson
instead of $.ajax
: $.getJSON( { dataType: 'jsonp', url: api, success: function(data) { city = data.name; $("#data").html(city); }
In the HTML, make sure to add jquery:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script> <script src="a.js"></script>
// whatever your js file is named
Without modifying your code, the page asked to access my location and then displayed my current city. I'm not sure what it is supposed to output though. What are you expecting the output to be?