I have an array of arrays which looks like this:
var data = [["street1", "zipcode1", "city1"], ["street2", "zipcode2", "city2"], ...]
I want to get the lat/lng using Googles Geocoding API of each address and save everything in a new array which should look like this:
var newdata = [["street1", "zipcode1", "city1", lat1, lng1], ["street2", "zipcode2", "city2", lat2, lng2], ...]
So here is how I try to solve the problem:
var newData = [];
function writeNewData(oldArray) {
for (i = 0; i < oldArray.length; i++) {
var temp = [];
var address = "";
// note: loop 5 times because I want to add 2 new values to each array
for (j = 0; j < 5; j++) {
// this gives me the full address as a string
address += oldArray[i][j] + " ";
// just copy the old data to the new array
if (j < 3) {
temp.push(oldArray[i][j]);
}
// add the new data to the array
if (j == 3) {
getLatLng(address);
var lat = jQuery("#lat").val();
temp.push(lat);
} elseif (j == 4) {
getLatLng(address);
var lng = jQuery("#lng").val();
temp.push(lng);
}
}
newData.push(temp);
}
};
Note: I use Gmaps.js
function getLatLng(myAddress) {
GMaps.geocode({
address: myAddress,
callback: function(results, status) {
if (status == 'OK') {
var loc = [];
loc[0] = results[0].geometry.location.lat();
loc[1] = results[0].geometry.location.lng();
jQuery("#lat").val(loc[0]);
jQuery("#lng").val(loc[1]);
}
}
});
}
Since I can't return the lat/lng from inside the Geocode request I thought outputting it inside an html file and just getting the values and writing them to the new array would work.
The output of the lat and lng works but when I try to get the values inside the loop I get an empty string back. I also tried adding a Timeout after calling getLatLng() which gave me the values but it kinda messed up the new array by adding all the new values to the last array in the loop.
Looked like this:
if (j == 3) {
getLatLng(address);
setTimeout(function () {
var lat = jQuery("#lat").val();
temp.push(lat);
}, 200);
}
Anyone have an idea what Im missing here and is there maybe an easier way to accomplish this?