Warning while using file_get_contents for google api

I am using this code for finding the lat lon of a location

$api='http://maps.googleapis.com/maps/api/geocode/json?address=United States Neversink&sensor=false';

$result = file_get_contents($api);

$data = json_decode($result);

But it give the warning Warning: file_get_contents(http://maps.googleapis.com/maps/api/geocode/json?address=United States Neversink&sensor=false) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in C:\wamp\www\new_yellowpages\modules\mod_yellowpages_item_map\helper.php on line 139

if anyone know about this problem help me please.

Answers


Use curl instead of file_get_contents:

$address = "India+Panchkula";
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=India";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response);
echo $lat = $response_a->results[0]->geometry->location->lat;
echo "<br />";
echo $long = $response_a->results[0]->geometry->location->lng;

Use urlencode to encode the address part. (The problem is the space in the address.)

$address = urlencode("United States Neversink");
$api='http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false';

$result = file_get_contents($api);

Use urlenocde function to encode your address like google map standard and change Http to https. Hope this will work for you


Try change HTTP to HTTPS and replace ' ' to '+'

https://maps.googleapis.com/maps/api/geocode/json?address=United+States+Neversink&sensor=false

Use curl_init() instead of file_get_contents():

$address = "India+Panchkula";
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=India";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);

$response_a = json_decode($response);
echo $lat = $response_a->results[0]->geometry->location->lat;
echo "<br />";
echo $long = $response_a->results[0]->geometry->location->lng;

Need Your Help

JQUERY Prepending an LI to an UL with Animation

jquery hide slidedown prepend

I have a UL and I'm working to dynamically add a new LI to the top of the UL with some animation.