0

I'm trying to put the variables lat and long inside the string url but it doesn't work. Here is my code:

$(document).ready(function() {
  var long;
  var lat;

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

      var api = "http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&appid=c873adc18574701f4fb0abe01d927819";
      $.getJSON(api, function(data) {
        alert(data.name);
      });
    });
  }
});
1
  • because you use "" to define the string and inside you are using '. Color coding show it is just one big string. Commented Nov 3, 2016 at 19:47

2 Answers 2

3

You need to use the same type of quote to close and reopen the string.

var api= "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&appid=c873adc18574701f4fb0abe01d927819";
Sign up to request clarification or add additional context in comments.

Comments

0

Or if the browsers you are developing for support it, you can use the new template literals. You can learn more about them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

So instead of this broken code that you have:

  var api = "http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&appid=c873adc18574701f4fb0abe01d927819";

You can do this instead:

  var api= `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=c873adc18574701f4fb0abe01d927819`;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.