Having trouble doing Show the Local Weather project

Having trouble doing Show the Local Weather project
0

#1

Hi all , I encounter an error while doing Local Weather project:

function getGeo(){
  var long=0,lat=0;
  if (!navigator.geolocation) throw "Geolocation not supported";
  navigator.geolocation.getCurrentPosition(function(pos){
    lat=pos.coords.latitude;
    long=pos.coords.longitude;
  });
  return {
    long:long,
    lat:lat
  };
};

function getWeather(position){
  console.log(position);
  var endpoint='https://fcc-weather-api.glitch.me/api/current?';
  var request=endpoint+"lat="position.lat+"lon="+position.long;
  console.log(request);
  $.getJSON(request,function(data){
    console.log(data);
  });
};

$(function(){
  var pos=getGeo();
  getWeather(pos);
});

I keep having an error Uncaught SyntaxError: Unexpected identifier on line var request=endpoint+"lat="position.lat+“lon=”+position.long;
I don’t see any wrong with my code, hopefully you guy can help me point it out
here is my codepen: https://codepen.io/thanhvannguyen2205/pen/NaxYRG?editors=1010#0


#2
request=endpoint + "lat=" + position.lat + "&lon=" + position.long;

You missed a + after lat= . You’re also gonna need the & since you are building a query.


#3

Thank you, I have another issue, I’ve changed my code, it can get my position in the getGeo func, but it return undefined when I tried to return my position object:

function getGeo(){
  var long=0,lat=0;
 if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    lat= position.coords.latitude ;//work fine
    long=position.coords.longitude;//work fine
    return {
      long:long,
      lat:lat
    };
  });
 }
 else return null; 
};

function getWeather(position){
  var endpoint='https://fcc-weather-api.glitch.me/api/current?';
  if(position){
    console.log("position"+position);
    var request=endpoint+"lat="+position.lat+"&lon="+position.long;
    $.getJSON(request,function(data){
    console.log(data);
  });
 }   
};

$(function(){
  var pos=getGeo();
  console.log(pos);//return undefined here
  getWeather(pos);
});


#4

getCurrentPosition() is an asynchronous function, this means that the response won’t arrive immediately, but you probably have to wait for it (same when you call an API).

This means that in order to pass the data you have to wait for the function to resolve, or better yet call your getWeather method directly inside the success callback function as:

 if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    lat= position.coords.latitude ;//work fine
    long=position.coords.longitude;//work fine
    var dataToPass = {
      lat: lat,
      lon: long
    }
    getWeather(dataToPass) // call the method directly inside the success callback
  });
 }

hope it helps :slight_smile:

edit: resources
getCurrentPosition MDN
using geolocation MDN