Google Maps - converting address to latitude & longitude - PHP backend?
This works for me:
<?php $Address = urlencode($Address); $request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$Address."&sensor=true"; $xml = simplexml_load_file($request_url) or die("url not loading"); $status = $xml->status; if ($status=="OK") { $Lat = $xml->result->geometry->location->lat; $Lon = $xml->result->geometry->location->lng; $LatLng = "$Lat,$Lon"; }?>
References:
<?php/* * Given an address, return the longitude and latitude using The Google Geocoding API V3**/function Get_LatLng_From_Google_Maps($address) { $address = urlencode($address); $url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false"; // Make the HTTP request $data = @file_get_contents($url); // Parse the json response $jsondata = json_decode($data,true); // If the json data is invalid, return empty array if (!check_status($jsondata)) return array(); $LatLng = array( 'lat' => $jsondata["results"][0]["geometry"]["location"]["lat"], 'lng' => $jsondata["results"][0]["geometry"]["location"]["lng"], ); return $LatLng;}/* * Check if the json data from Google Geo is valid */function check_status($jsondata) { if ($jsondata["status"] == "OK") return true; return false;}/** Print an array*/function d($a) { echo "<pre>"; print_r($a); echo "</pre>";}
For sample code of how using the function above, feel free to visit my blog
Yes you can. You would do a request with file_get_contents
or curl
to a url like this:
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false
What is returned is a json encoded response. You can parse this into arrays using json_decode
.
The documentation page has an example of the what the response may look like, use that to find the data that you need.