Reputation: 13
I am writing a small script that takes an array of locations and geocodes them to add lat long to another object. I have it working so it geocodes and writes to the console flawlessly. How can I take that output and put it into a predefined variable outside of the function? I am not vary familiar with jquery and do not intend on using it anyplace else in the script.
Just started learning JavaScript this weekend so don't shoot me if Something else is messed up.
Thanks for any help!!
Also, I changed my Google API key so it isn't stolen.
//test array of locations to geocode
var locationsToGeoCode = ["China: Shandong: Jinan",
"China: Shandong: Jinan",
"United States: Washington: La Conner",
"United States: Texas: Dallas",
"United States: California: Walnut"
];
//empty object to place geocoded places
var coordinates;
for (var i = 0; i < locationsToGeoCode.length; i += 1) {
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address=" + locationsToGeoCode[i] + "&key=MIzaSyCywKsD_50EI9rheDLyqPOUdUzi6s6u-q8", function (geocodeResult) {
console.log(geocodeResult);
});
}
Upvotes: 1
Views: 60
Reputation: 8065
Modifying your code like such should work:
//test array of locations to geocode
var locationsToGeoCode = ["China: Shandong: Jinan",
"China: Shandong: Jinan",
"United States: Washington: La Conner",
"United States: Texas: Dallas",
"United States: California: Walnut"
];
//empty object to place geocoded places
var coordinates = {};
function fetchGeoCode(location){
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address=" + location + "&key=MIzaSyCywKsD_50EI9rheDLyqPOUdUzi6s6u-q8", function (geocodeResult) {
coordinates[location] = geocodeResult;
});
}
for (var i = 0; i < locationsToGeoCode.length; i += 1) {
fetchGeoCode(locationsToGeoCode[i]);
}
Upvotes: 1