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);
 });
 });
 }
});
Mike Cluck
32.6k13 gold badges84 silver badges95 bronze badges
asked Nov 3, 2016 at 19:34
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";
answered Nov 3, 2016 at 19:36
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`;
answered Nov 3, 2016 at 19:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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