Juan Juan - 1 year ago 63
Javascript Question

Insert variables inside another string variable in Javascript

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);
});
});
}
});

Answer Source

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";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download