Google Geocode API: Get the latitude and longitude of an address

Using the google geocode api, you can get the latitude and longitude of an address. This is useful when building google maps.

http://maps.googleapis.com/maps/api/geocode/json?address=street_number+street_name,city,country&sensor=false

If you type the above into your browser (with a real address) the result is a json file that contains, among other things, the latitude and longitude.

$http_request .= "address=";
$http_request .= $street_no . '+';
$http_request .= $street_name . ',';
$http_request .= $city . ',';
$http_request .= $province_or_state . ',';
$http_request .= $country;
$http_request .= '&sensor=false';

Replace all the blank spaces that might be in any of the names with ‘%20′ or else you will get an error that looks like this:

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

A simple way to replace the spaces with the correct encoding of ‘%20′:

$http_request = str_replace(" ", "%20", $http_request);

Then get the file contents:

$fp = file_get_contents($http_request);

Decode the result just json_decode:

$arr = json_decode($fp, true);

Then print the results:

echo '<pre>';
 print_r($arr['results'][0]['geometry']['location']);
 echo '</pre>';

Google Map basics: generating a map from coordinates

Sometimes you need to create a google map from a latitude and longitude. Here is one way to do it:

http://maps.google.com/maps/api/staticmap?center=40.714728,-73.998672&markers=color:blue|label:S|40.714728,-73.998672
&zoom=12&size=400x400&maptype=roadmap&sensor=true

Center
The center is the center of the map.

center=latitude,longitude

Markers
Here I’ve made the marker blue with a label of “S” and the coordinates of the marker are the same as the center

&markers=color:blue|label:S|latitude,longitude

Zoom
The zoom is a scale from 0 (this shows the entire earth) until 21 (all the way zoomed in)

&zoom=12

Size
Set the size in width and height.

&size=widthXheight

Maptype
You can set the maptype to be roadmap, satellite, terrain and hybrid.

&maptype=roadmap

Sensor
The sensor must be true or false. If you omit the sensor, the map won’t work!