I am trying to build a map using information from an API. Unfortunately the dataset does not have coordinates. So i am using the address and Geocoding them to build a google map with markers and get the distance along with directions from current location. I takes the user's current location and finds the requested information with a 10 mile radius around them.
Here is my Geocoding function
<script>
var geocoder = new google.maps.Geocoder();
function geocodeAddress(geocoder, street, city, zip) {
var address = street + ', ' + city + ', ' + zip;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
console.log(results[0].geometry.location.lat(), results[0].geometry.location.lng());
debugger;
return(results[0].geometry.location.lat(), results[0].geometry.location.lng());
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
Here is the loop that scans through all the data from the API call
$my_counter = 0;
foreach ($param as &$value){
$row = $value;
echo"
<script>
//the return information is messy so i use this to clean it up
var coordinates = geocodeAddress(geocoder, '".trim(str_replace(',', '',$row->address))."', '".trim($row->city)."', '".trim($row->zip)."');
console.log(coordinates);
var new_lat = parseFloat(coordinates[0]);
var new_long = parseFloat(coordinates[1]);
var distance_to_the_point = haversineGreatCircleDistance (".$original_gps_lat.", ".$original_gps_long.", new_lat, new_long);
if (distance_to_the_point <= ".$radius."){
var data = '".$row->phone."';
var result = data;
var rounded_distance = distance_to_the_point.toFixed(2);
var name = '".trim($row->provider_name)."';
document.getElementById('name').innerHTML = name.toString();
}
";
</script>
Now when i run this with break points and logs throughout, I see the geocoding function running, but never giving a return. Then once the page has loaded, the geocoder finishes and i see the returned coordinates. i do not understand why it's not running in sync.