0

I'm trying to establish a function which calculates the distance in between two locations by geocoding them via your geocode api.

The Link itself, when pasted in the browser seems to be working fine, but using phps function file_get_contents it returns failed to open stream and returns timeout.

Here the code:

function getDistance($addressFrom, $addressTo, $unit = ''){
// Google API key
$apiKey = 'gc5HYKu9JFdc0gkb5X8i0C7m6iFxsvt3';

// Change address format
$formattedAddrFrom = str_replace(' ', '+', $addressFrom);
$formattedAddrTo = str_replace(' ', '+', $addressTo);

// Geocoding API request with start address
$geocodeFrom = file_get_contents('http://www.mapquestapi.com/geocoding/v1/address?location='.$formattedAddrFrom.'&key='.$apiKey);
$outputFrom = json_decode($geocodeFrom);
if(!empty($outputFrom->error_message)){
return $outputFrom->error_message;
}

// Geocoding API request with end address
$geocodeTo = file_get_contents('http://www.mapquestapi.com/geocoding/v1/address?location='.$formattedAddrTo.'&key='.$apiKey);
$outputTo = json_decode($geocodeTo);
if(!empty($outputTo->error_message)){
return $outputTo->error_message;
}

// Get latitude and longitude from the geodata
$latitudeFrom = $outputFrom->results[0]->locations[0]->latLng->lat;
$longitudeFrom = $outputFrom->results[0]->locations[0]->latLng->lng;
$latitudeTo = $outputTo->results[0]->locations[0]->latLng->lat;
$longitudeTo = $outputTo->results[0]->locations[0]->latLng->lng;

EDIT - Full code:

<?php
/**
 * @function getDistance()
 * Calculates the distance between two address
 *
 * @params
 * $addressFrom - Starting point
 * $addressTo - End point
 * $unit - Unit type
 *
 * @param $addressFrom
 * @param $addressTo
 * @param string $unit
 * @return string
 *
 * @author CodexWorld
 * @url https://www.codexworld.com
 */
function getDistance($addressFrom, $addressTo, $unit = ''){
// Google API key
$apiKey = 'gc5HYKu9JFdc0gkb5X8i0C7m6iFxsvt3';

// Change address format
$formattedAddrFrom    = urlencode($addressFrom);
$formattedAddrTo     = urlencode($addressTo);


// Geocoding API request with start address
$geocodeFrom = file_get_contents('http://www.mapquestapi.com/geocoding/v1/address?location='.$formattedAddrFrom.'&key='.$apiKey);
$outputFrom = json_decode($geocodeFrom);
if(!empty($outputFrom->error_message)){
return $outputFrom->error_message;
}

// Geocoding API request with end address
    $geocodeTo = file_get_contents('http://www.mapquestapi.com/geocoding/v1/address?location='.$formattedAddrTo.'&key='.$apiKey);
    $outputTo = json_decode($geocodeTo);
if(!empty($outputTo->error_message)){
return $outputTo->error_message;
}

// Get latitude and longitude from the geodata
$latitudeFrom = $outputFrom->results[0]->locations[0]->latLng->lat;
$longitudeFrom = $outputFrom->results[0]->locations[0]->latLng->lng;
$latitudeTo = $outputTo->results[0]->locations[0]->latLng->lat;
$longitudeTo = $outputTo->results[0]->locations[0]->latLng->lng;

// Calculate distance between latitude and longitude
$theta    = $longitudeFrom - $longitudeTo;
$dist    = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
$dist    = acos($dist);
$dist    = rad2deg($dist);
$miles    = $dist * 60 * 1.1515;

// Convert unit and return distance
$unit = strtoupper($unit);
if($unit == "K"){
return round($miles * 1.609344, 2).' km';
}elseif($unit == "M"){
return round($miles * 1609.344, 2).' meters';
}else{
return round($miles, 2).' miles';
}
}

$addressFrom = "Am Felde 52, 22765 Hamburg, Germany";
$addressTo = "Beltgens Garten 25, 20537 Hamburg, Germany";

$distance = getDistance($addressFrom, $addressTo, "K");
echo $distance;

And the errors:

Warning: file_get_contents(http://www.mapquestapi.com/geocoding/v1/address?location=Am+Felde+52+227...): failed to open stream

...

Fatal error: Maximum execution time of 120 seconds exceeded in C:\xampp\htdocs...

I'm relatively new to this topic, the snippet is by codexworld.com.

Can anyone see the issue? Any help would be highly appreciated

Regards,

kuba44

kuba44
  • 1
  • 2
  • The `file_get_contents` part works fine for me, with the given API key and an example address. Instead of just replacing spaces, the data should rather be treated with `urlencode` though. As for the timeout issue - for how many addresses are you attempting to do this in one go? is it just one pair of to - from, or are you calling this in a loop? – CBroe May 14 '20 at 11:00
  • Just using it for a paired request, no loops. Using urlencode still returns the same error. – kuba44 May 14 '20 at 11:59
  • What does the API documentation say about any specific requirements these requests must fulfill? – CBroe May 14 '20 at 12:09
  • https://developer.mapquest.com/documentation/geocoding-api/address/get/ It says only key and location are required. – kuba44 May 14 '20 at 12:16
  • Could there be some setting in the php.ini, which could explain, why the code is working for you but not for me? I'll edit the original post and show the full request. – kuba44 May 14 '20 at 12:18
  • Sites expecting a User-Agent header to be set in the request, that mimics a current browser, is a common occurrence. For an actual _API_ request, that makes rather little sense to begin with though, but you can try and see if it changes anything. https://www.php.net/manual/en/filesystem.configuration.php#ini.user-agent – CBroe May 14 '20 at 12:21
  • In my ini it currenty says: `; Define the User-Agent string. PHP's default setting for this is empty. ; http://php.net/user-agent ;user_agent="PHP"`. What would be your suggested changes? – kuba44 May 14 '20 at 12:31
  • I just checked, I have that setting empty on my machine, so that’s probably not it. // Try and see if you can get an error message that has a little more to say using `error_get_last`, https://stackoverflow.com/a/13365281/1427878 – CBroe May 14 '20 at 12:36
  • Hm, thanks for the suggestion, but I'm still getting exactly the same error. – kuba44 May 14 '20 at 12:47
  • Is `allow_url_fopen` set to true in your PHP configuration to begin with? – CBroe May 14 '20 at 12:50
  • Yes, it is. In my .ini it says: `allow_url_fopen=On` – kuba44 May 14 '20 at 12:58
  • Can you make requests to other external URLs in general? – CBroe May 14 '20 at 13:14
  • How would I test that? – kuba44 May 14 '20 at 13:15
  • By making a request to a couple of _other_ sites, and seeing if you always get the same error, or the proper, expected response …? – CBroe May 14 '20 at 13:16
  • tested 3 other sites, same error. – kuba44 May 14 '20 at 13:27
  • Then you probably have a general issue with making connections to the outside from the web server / PHP environment. Could be a Windows firewall issue, if you’re working with XAMMP. – CBroe May 14 '20 at 13:31
  • Seems to be the issue. I can't look into the firewall settings. Working for the state, which is managing those. Is there any workaround? – kuba44 May 14 '20 at 13:34
  • No, if your webserver is blocked from making connections to the outside, then there is no workaround. Ask “the state” to fix this then. (Or change their requirements, what they want to you develop on your local machine.) – CBroe May 14 '20 at 13:42
  • Alright. Thanks for your support so far, really appreciated it. 'the state' in this case is the school department, which is managed by an external service provider. I'll try the code from my home network, just to make sure the problems lies within the restrictions @work. And my task in general is to think of something, which would distribute school inspections to inspectors living in the area, which is now made randomly. – kuba44 May 14 '20 at 13:54
  • I'll let you know, if I make some progress. – kuba44 May 14 '20 at 13:58
  • Any progress from the home network? – MQBrian May 18 '20 at 22:17

0 Answers0