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
user7100805
2 Answers 2
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
Kolby
2,8733 gold badges29 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
lang-js
""to define the string and inside you are using'. Color coding show it is just one big string.