javascript - push to array within function -
i'm trying build array of latitudes , longitudes start/end points routing.
function parkroute(){ var start = $('#start').val(); var end = $('#end').val(); var points = []; function printpoints(points){ console.log(points) } function getxy(add){ geocoder.geocode( {'address': add + ", glendale, ca"}, function(results, status) { if (status == google.maps.geocoderstatus.ok) { if (results[0].geometry.location) { var lon = results[0].geometry.location.kb; var lat = results[0].geometry.location.jb; points.push(lat,lon); console.log(points) } } }) } getxy(start); getxy(end); printpoints(points); }
it prints out empty array first though i'm calling function print them after function create array.
[] parks1.js:192 [34.1480811, -118.24759369999998] parks1.js:201 [34.1480811, -118.24759369999998, 34.1851925, -118.27651679999997] parks1.js:201
what doing wrong?
the problem you're not waiting callbacks, asynchronous, executed.
you :
var inprocess = 0; // number of tasks we're waiting function getxy(add){ inprocess++; // increment number of tasks geocoder.geocode( {'address': add + ", glendale, ca"}, function(results, status) { if (status == google.maps.geocoderstatus.ok) { if (results[0].geometry.location) { var lon = results[0].geometry.location.kb; var lat = results[0].geometry.location.jb; points.push(lat,lon); console.log(points) } } oneprocessisdone(); }) } function oneprocessisdone() { if (--inprocess==0) { // decrement number of tasks, , print points if done printpoints(points); } } getxy(start); getxy(end);
Comments
Post a Comment