Google Maps API call returning nothing when trying to get latitude and longitude



I am working on the Show the Local Weather challenge, and cannot seem to get the latitude and longitude calls to return anything. Code pen here:

Here’s the code where I declare the variables and call the API.

var lat;
var lng;

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude, lng = position.coords.longitude;

I’m using the Google API to find the location. Console doesn’t show any network errors. Does anybody have any clue as to what is going on? I’ve tried just about everything I can think of and can’t seem to find any help online.



You use navigator.geolocation to get coordinates. It has nothing to do with google maps. And it seem to be working fine. But your ajax request to darksky api fails cause of cors issue.


Hey of no one replied, check out Udacity’s free JS course on using Google Maps API, it’s really strong, if a bit dated yet the added benefit of doing it may really fill in some colour on your efforts and working APIs in general.


Thanks for the response. Do you have any ideas on how I would go about solving the cors issue? I’ve never heard of that before. Thanks again


Use jsonp for your request


navigator.geolocation is asynchronous - it takes some time to get your location, and by that time, the rest of your code has executed. Look at the console.log entries below:

navigator.geolocation.getCurrentPosition(function(position) {
  var lat = position.coords.latitude;
  console.log(lat); // successfully gives your latitude
console.log(lat); // undefined because this code runs before your location comes back

The typical fix for this is to call a function inside your function(position) and send the location as an argument:

navigator.geolocation.getCurrentPosition(function(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
  getTheWeather(lat, lng); // pass lat, lng to the getTheWeather() function

// call your weather API using lat and lng arguments passed to this function
function getTheWeather(lat, lng) {
  $.getJSON('<<your key>>/' + lat + ',' + lng + '?callback=?', function(json) {
    // process json here, show it on the page, call other functions, etc.

For the CORS issues, notice the ?callback=? I added to the URL above. You can use JSONP to work around CORS issues. With $.ajax, we specify dataType: 'jsonp', with $.getJSON we add callback=? as a parameter to the URL.