I'm trying to implement a service that gets the GPS coordinates of a provided address, so I came up with the following, which works fine locally. However, when I tried to implement it on a hosting provider, all of a sudden the function fails, as no results are returned from Google - not even a blank array, just nothing.
I assume it's something blocked via the web host, but am not sure what to even look for.
Function:
function getCoordinates($Address, $APIKey) {
$BaseURL = "https://maps.googleapis.com/maps/api/geocode/json?key=".$APIKey."&address=";
$data = @file_get_contents($BaseURL.str_ireplace(" ","+",$Address));
//echo "Data:".$data."<br>";
$jsondata = json_decode($data,true);
//echo "<pre>";
//print_r($jsondata);
//echo "</pre>";
switch($jsondata["status"]) {
case "OK" :
if (count($jsondata["results"]) > 1) {
return array("status" => "FAIL", "message" => "Multiple results were returned");
}
else {
if (isset($jsondata["results"][0]["geometry"]["location"])) {
return array("status" => "SUCCESS","latitude" => $jsondata["results"][0]["geometry"]["location"]["lat"],"longitude" => $jsondata["results"][0]["geometry"]["location"]["lng"]);
}
}
return $jsondata["results"];
break;
case "ZERO_RESULTS" :
return array("status" => "FAIL", "message" => "Zero Results were returned");
break;
case "OVER_QUERY_LIMIT" :
return array("status" => "FAIL", "message" => "API Key is over the daily limit. It will automatically try again tomorrow");
break;
case "REQUEST_DENIED" :
return array("status" => "FAIL", "message" => "Request was denied");
break;
case "INVALID_REQUEST" :
return array("status" => "FAIL", "message" => "Invalid request, typically because the address is missing");
break;
case "UNKNOWN_ERROR" :
return array("status" => "FAIL", "message" => "Unknown error, Request could not be processed due to a Google server error. It may work again if you try later.");
break;
case "ERROR" :
return array("status" => "FAIL", "message" => "Error, the request timed out");
break;
default:
$Message = array("Failure",print_r($jsondata));
return array("status" => "FAIL", "message" => $Message);
break;
}
}
Called via:
$LocationCoordinates = getCoordinates("123 Main Street, Toronto, ON", [[$MapsAPIKey]]);
For testing purposes, I uncommented out the 4 lines close to the top of the function and the first returned the word 'Data' with nothing following. The next three lines, expectedly just returned the corresponding 'pre' tags.
Checked the console log and there are no errors indicated. I tried a quick client side script on the server and it seems to work fine.