Forum Moderators: coopster

Message Too Old, No Replies

How to set dynamic map from database (street addresses)?

         

toplisek

10:23 am on Jan 5, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Setting javascript file and its line:
center: new google.maps.LatLng(<?=$lat?>, <?=$lng?>),

Geo coder and pull data from database:

// get address from database
mysql_connect('host', 'user', 'pass');
mysql_select_db('dbname');
$address=str_replace(" ","+",$address);

$url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".
$address."&sensor=false";

# INITIATE CURL.
$curl = curl_init();

# CURL SETTINGS.
curl_setopt($curl, CURLOPT_URL,"$url");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);

# GRAB THE XML FILE.
$result = curl_exec($curl);

curl_close($curl);

# SET UP XML OBJECT.
$xml = new SimpleXMLElement($result);

$flag=0;
foreach ($xml->result->geometry as $item){
if($flag==0){
$lat=$item->location->lat;
$lng=$item->location->lng;
$flag=1;
}
}

setcookie("lat",$lat, time()+3600*24);
setcookie("lng",$lng, time()+3600*24);

header("location: index20.php");

?>
Can be improved this PHP code?

eelixduppy

5:43 pm on Jan 13, 2012 (gmt 0)



Only improvements I see at a quick glance is 1) you are iterating through more than you need to (assuming there are more than one items in your foreach) and 2) your headers should be properly formatted.

1) If you only want the first result from $xml->result->geometry you do not need to look through the rest that come after. If you were searching for anything other than the first, you should include a "break" once what you found is reached so the rest isn't checked. But this should be able to be written as:

$lat = $xml->result->geometry[0]->location->lat;
$lng = $xml->result->geometry[0]->location->lng;


2) When you send the location header, it really should contain the absolute URL to the page you are redirecting to, e.g.:

header("Location: http://www.example.com/index20.php");