Первым шагом является перевод вашего адреса в кодированное URL-адрес для использования в API геокодирования Google.Вот пример:
$Address = '';
$format = 'xml'; // Set this to xml or json
if(!empty($row['Address_1'])) $Address .= ($row['Address_1']);
if(!empty($row['Address_2'])) $Address .= ($row['Address_2']);
if(!empty($Address)) $Address .= ",+";
if(!empty($row['City'])) $Address .= ($row['City']);
if(!empty($Address)) $Address .= ",+";
if(!empty($row['State'])) $Address .= ($row['State']);
$Address = str_replace(' ', '+', $Address);
$url = 'http://maps.googleapis.com/maps/api/geocode/'.$format.'?address='.htmlentities($Address).'&sensor=false';
Далее вы захотите получить результат и сохранить его:
if($format == 'xml')
{
$document = new DOMDocument('1.0');
$document->load($url);
// Check Status
$RequestStatus = $document->getElementsByTagName("status")->item(0)->firstChild->nodeValue;
if($RequestStatus !== 'OK')
{
echo("There was an error with the request. The status returned was: ".$RequestStatus);
}
// Grab the Geometry->Location Node
$GeoLoc = $document->getElementsByTagName("location")->item(0);
foreach ($GeoLoc->childNodes as $node)
{
if($node->nodeName == 'lat') echo "Latitude: " . $node->nodeValue . "<br />";
if($node->nodeName == 'lng') echo "Longitude: " . $node->nodeValue . "<br />";
}
}
else if($format == 'json')
{
$json = file_get_contents($url,0,null,null);
$json_output = json_decode($json, true);
if($json_output['status'] != 'OK')
{
echo("There was an error with the request. The status returned was: ".$json_output['status']);
// Set your lat/long data to 0, null, etc
}
foreach ($json_output['results'] as $result)
{
echo "Latitude: " . $result['geometry']['location']['lat'] . "<br />";
echo "Longitude: " . $result['geometry']['location']['lng'] . "<br />";
// Store your lat/long data in your database
}
}