As of your sample in fiddle, It's normal that your array
in console is still empty because you're using $.get which does an asynchronous process (AJAX).
In short, you're logging the output before the operation of $.get
finishes.
When it finishes, you should see your array
has the lat and lng value.
You'll notice the output in console would be like,
var address = 'Champ de Mars, 5 Avenue Anatole France, 75007 Paris, Frankrike';
var array = [];
$.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address), function(data, status) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
/* Array got pushed here */
array.push({
lat,
lng
});
/* This console is executed 3rd */
console.log("Array just got pushed with lat n lng :::", array);
});
/* This console is executed 1st */
console.log("Printing value of array 1 :::", array)
/* These consoles are executed 2nd */
if (array[0] === undefined) {
console.log('this sucks');
} else {
console.log('it works');
}
This is the result of your console.log
> Printing value of array 1 ::: []
> this sucks
> Array just got pushed with lat n lng ::: [Object]
Here's your updated fiddle
Edit:
As per your comment, one way to achieve what you want could be something like this.
var getAddressLatLng = function (address) {
var defer = $.Deferred();
$.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address), function (data) {
if (data && data.results && data.results.length) {
var res = data.results[0];
if (typeof(res) === "object" && res.hasOwnProperty("geometry") && res.geometry.hasOwnProperty("location") && typeof(res.geometry.location) === "object") {
var lat = res.geometry.location.lat,
lng = res.geometry.location.lng;
if (lat && lng) {
defer.resolve({
"latitude": lat,
"longitude": lng
});
}
}
}
defer.resolve(null);
});
return defer;
};
Or if you dont want to use $.get
s callback function, You can do;
var getAddressLatLng = function (address) {
return $.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address)).then(function (data) {
if (data && data.results && data.results.length) {
var res = data.results[0];
if (typeof(res) === "object" && res.hasOwnProperty("geometry") && res.geometry.hasOwnProperty("location") && typeof(res.geometry.location) === "object") {
var lat = res.geometry.location.lat,
lng = res.geometry.location.lng;
if (lat && lng) {
return {
"latitude": lat,
"longitude": lng
};
}
}
}
return null;
});
};
To use it, you can just call the function like;
getAddressLatLng("Champ de Mars, 5 Avenue Anatole France, 75007 Paris, Frankrike").then(function (result) {
/* result is either 'null' or an object with 'lat' and 'lng' property */
if (result) {
console.log("RESULT:: ", result);
/* And you can do your db operation here */
}
});