5

This the code I'm using to find the latitude and longitude of place:

function coords($address){ echo $url="http://maps.googleapis.com/maps/api/geocode/json?address=".$address; $json = file_get_contents(urlencode($url)); $data = json_decode($json, TRUE); print_r($data['results'][0]['geometry']['location']['lat']); print_r($data['results'][0]['geometry']['location']['lng']); } 

However it always returns this warning:

failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

If I use the above code in a simple procedure it works fine but not in the function.

Note: I have tried the curl_init()... method which produced the same result?

2
  • you should use urlencode inside file_get_contents instead of urldecode Commented Apr 29, 2015 at 13:24
  • 1
    You are using the wrong variable for $url check your variable name $add and $address Commented Apr 29, 2015 at 13:25

1 Answer 1

19

Instead of encoding whole URL just encode the address part. The following code will work fine

$add='jamshoro phase 2'; $url="http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($add); $json = file_get_contents($url); $data = json_decode($json, TRUE); print_r($data['results'][0]['geometry']['location']['lat']); print_r($data['results'][0]['geometry']['location']['lng']); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.