Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get latitude and longitude automatically using php, API

Tags:

In one of my php applications I have to find out the latitude and longitude of the place from address.

I tried this code:

$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region"); $json = json_decode($json);  $lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'}; $long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'}; 

But it is showing the following Error :

Warning: file_get_contents(http://maps.google.com/maps/api/geocode/json?address=technopark, Trivandrun, kerala,India&sensor=false&region=IND) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in D:\Projects\lon.php on line 4

Please help me to solve this issue.

like image 963
ramesh Avatar asked Dec 26 '11 06:12

ramesh


2 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; 
like image 181
priyank saini Avatar answered Oct 26 '22 12:10

priyank saini


$address = str_replace(" ", "+", $address); 

Use the above code before the file_get_content. means, use the following code

$address = str_replace(" ", "+", $address);  $json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region"); $json = json_decode($json);  $lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'}; $long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'}; 

and it will work surely. As address does not support spaces it supports only + sign in place of space.

like image 26
Code Lღver Avatar answered Oct 26 '22 12:10

Code Lღver