Store Locator Using PHP, Mysql and Google Maps geocoding

Posted by admin Wed, 20 Feb 2008 22:32:00 GMT

I recently had a project where I had to develop a search with PHP.
This search had to return the distance based on an address entered by the user.
Here is what I did to get this working in the simplest way possible.

First I had to sign up for the Google Maps API Key.
Then, I created a database called Addresses with the following structure.
CREATE TABLE `Addresses` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  `address_physical` varchar(255) default NULL,
  `city` varchar(255) default NULL,
  `state` varchar(255) default NULL,
  `zip` varchar(255) default NULL,
  `phone` varchar(255) default NULL,
  `fax` varchar(255) default NULL,
  `webpage` varchar(255) default NULL,
  `email` varchar(255) default NULL,
  `latitude` varchar(255) default NULL,
  `longitude` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

Then I created a database connection.
If you are playing along at home, I will assume you know how to do this
If you need to you can download these as well as a file called distcal.php HERE
You will have to edit config.php to reflect your database user and password and host.
Next, I had to make a form to insert the data into the database..
This consists of an index
<?php
//index.php
require ('includes/dbconnection.php');
$sql = "SELECT * FROM Addresses ORDER BY name ASC";
        $result = mysql_query($sql);

        while($row = mysql_fetch_array($result))
             {
               echo "";
               echo $row['name'];
               echo "<br>";
           
          
          
              <a href=\"edit.php?id=$row[id]\">Edit</a>
                 || <a href=\"delete.php?id=$row[id]\">Delete</a><br><hr>";
             }//end of loop
?>

<br><br>
 <a href=add.php>Add</a>

and three additionals file edit, add.php and delete.php
you can download all three HERE
//edit.php
<title>Edit</title>

<?php


<title>Edit Churches</title>

<?php


require('includes/dbconnection.php');

   $id = $_GET['id'];

  if ($_POST['submit']) {
echo $id;
	if (isset($_POST['address_physical'])){
	$address_physical = $_POST['address_physical'];

	}
	if (isset($HTTP_POST_VARS['city'])){
	$city = $HTTP_POST_VARS['city'];

	}
	if (isset($HTTP_POST_VARS['state'])){
	$state = $HTTP_POST_VARS['state'];

	}
	if (isset($_POST['name'])){
	$parish_name = $_POST['name'];

	}

	if (isset($HTTP_POST_VARS['zip'])){
	$zip = $HTTP_POST_VARS['zip'];

	}
	if (isset($HTTP_POST_VARS['phone'])){
	$phone = $HTTP_POST_VARS['phone'];

	}if (isset($HTTP_POST_VARS['fax'])){
	$fax = $HTTP_POST_VARS['fax'];

	}if (isset($HTTP_POST_VARS['email'])){
	$email = $HTTP_POST_VARS['email'];

	}if (isset($HTTP_POST_VARS['webpage'])){
	$webpage = $HTTP_POST_VARS['webpage'];

	}
	//Three parts to the querystring: q is address, output is the format, key is the GAPI key
	$key = "ABQIAAAAsbc8lBSz7WAqNwH1pNerBRQ7jsNPLpBjHicJAXoKFf2V3Pr1JBS040yyXtWX97g8QvNpgEGqMNm6Tg";
	$address = urlencode($address_physical . " " . $city . " " . $state . " " . $zip);
	//If you want an extended data set, change the output to “xml” instead of csv
	$url = "http://maps.google.com/maps/geo?q=".$address."&output=xml&key=".$key;
	//Set up a CURL request, telling it not to spit back headers, and to throw out a user agent.
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER,0); //Change this to a 1 to return headers
	curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$data = curl_exec($ch);
	curl_close($ch);


	?><br /><?php

	$xml = new SimpleXMLElement($data);

	$xml_data = explode(",",$xml->Response->Placemark->Point->coordinates);
	$latitude = $xml_data[1];
	$longitude = $xml_data[0];



$sqlu = "UPDATE Addresses SET name='$name', address_physical='$address_physical',  phone='$phone', fax='$fax', email='$email', webpage='$webpage', latitude='$latitude', longitude='$longitude' WHERE id='$id'";
$resultu = mysql_query($sqlu);



          echo "<b>Thank you! UPDATED Successfully!<br>You'll be redirected to Home Page after (3) Seconds";
		  echo "Thank you! Information entered.<br />";
		  echo "The Following information was inserted into the database <br />";
		  echo "Name:" . $name . "<br />";
		  echo "Physical Address:" . $address_physical . "<br />";
		  echo "Mailing Address:" . $address_mailing . "<br />";
		  echo "Phone:" . $phone . "<br />";
		  echo "Fax:" . $fax . "<br />";
		  echo "Email:" . $email . "<br />";
		  echo "WebSite:" . $webpage . "<br />";
		  echo "Latitude:" . $latitude . "<br />";
		  echo "Longitude:" . $longitude . "<br />";
		echo $data;
          echo "<meta http-equiv=Refresh content=3;url=index.php>";
}
elseif($id)
{
        $sql = "SELECT * FROM Addresses WHERE id='$id'";
        $result = mysql_query($sql);
        while($row = mysql_fetch_row($result))
             {
                $parish_name = $row[0];
                $address_physical = $row[1];
                $city_name= $row[3];
                $state_name= $row[4];
                $zip_code = $row[5];
			    $address_mailing = $row[2];
		        $phone = $row[6];
		        $fax= $row[7];
		        $email= $row[9];
		        $website = $row[8];
?>
<br>

<table border="0" align="center" cellpadding="2" cellspacing="2">
	<h3>edit</h3>

	<form method="POST" action="edit.php?id=<?php echo $id;?>">
	<input type="hidden" name="id" value="<?php echo $id;?>">
     <tr>
       <td align="right" style="font-weight:bold;"> Name:</td>
       <td><input type="Text" size="40" name="name" class="inputbox" value="<?php echo $name;?>"></td>
     </tr>
     <tr>
       <td align="right" style="font-weight:bold;">Physical Address:</td>
       <td><input type="Text" size="40" name="address_physical" class="inputbox" value="<?php echo $address_physical;?>"></td>

	 </tr>
	      <tr>
	        <td align="right" style="font-weight:bold;">City:</td>
	        <td><input type="Text" size="40" name="city" class="inputbox" value="<?php echo $city;?>"></td>
	      </tr>
	      <tr>
	        <td align="right" style="font-weight:bold;">State:</td>
	        <td><input type="Text" size="40" name="state" class="inputbox" value="<?php echo $state_name;?>"></td>
	      </tr>
	      <tr>
	        <td align="right" style="font-weight:bold;">Zip Code:</td>
	        <td><input type="Text" size="40" name="zip" class="inputbox" value="<?php echo $zip_code;?>"></td>
	      </tr>

		      <tr>
		        <td align="right" style="font-weight:bold;">Phone:</td>
		        <td><input type="Text" size="40" name="phone" class="inputbox" value="<?php echo $phone;?>"></td>
		      </tr>
		
			 <tr>
			        <td align="right" style="font-weight:bold;">Fax:</td>
			        <td><input type="Text" size="40" name="fax" class="inputbox" value="<?php echo $fax;?>"></td>
			      </tr>
			      <tr>
			        <td align="right" style="font-weight:bold;">Email:</td>
			        <td><input type="Text" size="40" name="email" class="inputbox" value="<?php echo $email;?>"></td>
			      </tr>
			      <tr>
			        <td align="right" style="font-weight:bold;">Web Site:</td>
			        <td><input type="Text" size="40" name="webpage" class="inputbox" value="<?php echo $website;?>"></td>
			      </tr>
			      <tr>
			<td colspan="2" align="center"><input type="Submit" name="submit" value="Update" class="inputbox"></td>
				      </tr>
				    </table>
				        <br>
				</form>

<?
              }//end of while loop

  }//end else
?>


//add.php

<html>

<body>



<?php



if ($HTTP_POST_VARS['submit']) {

	if (isset($HTTP_POST_VARS['address_physical'])){
	$address_physical = $HTTP_POST_VARS['address_physical'];
				
	}
	if (isset($HTTP_POST_VARS['city'])){
	$city = $HTTP_POST_VARS['city'];
				
	}
	if (isset($HTTP_POST_VARS['state'])){
	$state = $HTTP_POST_VARS['state'];
				
	}
	if (isset($HTTP_POST_VARS['name'])){
	$parish_name = $HTTP_POST_VARS['name'];
				
	}

	if (isset($HTTP_POST_VARS['zip'])){
	$zip = $HTTP_POST_VARS['zip'];
				
	}
	if (isset($HTTP_POST_VARS['phone'])){
	$phone = $HTTP_POST_VARS['phone'];
				
	}if (isset($HTTP_POST_VARS['fax'])){
	$email = $HTTP_POST_VARS['fax'];
				
	}if (isset($HTTP_POST_VARS['email'])){
	$email = $HTTP_POST_VARS['email'];
				
	}if (isset($HTTP_POST_VARS['webpage'])){
	$webpage = $HTTP_POST_VARS['webpage'];
				
	}
//put your key here
	$key = "";
	$address = urlencode($address_physical . " " . $city . " " . $state . " " . $zip);
	//If you want an extended data set, change the output to “xml” instead of csv
	$url = "http://maps.google.com/maps/geo?q=".$address."&output=xml&key=".$key;
	//Set up a CURL request, telling it not to spit back headers, and to throw out a user agent.
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER,0); //Change this to a 1 to return headers
	curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$data = curl_exec($ch);
	curl_close($ch);


	?><br /><?php

	$xml = new SimpleXMLElement($data);

	$xml_data = explode(",",$xml->Response->Placemark->Point->coordinates);
	$latitude = $xml_data[1];
	$longitude = $xml_data[0];

require('includes/dbconnection.php');

  $sql = "INSERT INTO Addresses (name, address_physical, phone, fax, email, webpage,  latitude, longitude) VALUES ('$name', '$address_physical', '$address_mailing','$phone', '$fax', '$email', '$webpage',  '$latitude','$longitude')";

  $result = mysql_query($sql);

  echo "Thank you! Information entered.<br />";
  echo "The Following information was inserted into the database <br />";
  echo "Name:" . $name . "<br />";
  echo "Physical Address:" . $address_physical . "<br />";
  echo "Mailing Address:" . $address_mailing . "<br />";
  echo "Phone:" . $phone . "<br />";
  echo "Fax:" . $fax . "<br />";
  echo "Email:" . $email . "<br />";
  echo "WebSite:" . $webpage . "<br />";
  echo "Latitude:" . $latitude . "<br />";
  echo "Longitude:" . $longitude . "<br />";
echo $data;
} else{



  // display form



  ?>



  <form method="POST" action="add.php">



	Name<input type="Text" size="50px" name="name"><br>
	Physical Address<input type="Text" size="50px" name="address_physical"><br>
	City<input type="Text" size="50px" name="city"><br>
	State<input type="Text" size="50px" name="state"><br>
	Zip Code<input type="Text" size="50px" name="zip"><br>
	Mailing Address<input type="Text" size="50px" name="address_mailing"><br>
	Phone<input type="Text" size="50px" name="phone"><br>
	Fax<input type="Text" size="50px" name="fax"><br>
	Email<input type="Text" size="50px" name="email"><br>
	Web Site<input type="Text" size="50px" name="webpage"><br>
	




  <input type="Submit" name="submit" value="Enter information">

  </form>



  <?php



} // end if



?>



</body>



</html>

//delete.php

<?php


include('includes/dbconnection.php');
        $newsid = $_GET['id'];
        $sql = "DELETE FROM Addresses WHERE id='$id' "
        $result = mysql_query($sql);


                     echo "<b>Deleted!<br>You'll be redirected to Home Page after (3) Seconds";
 
                     echo "<meta http-equiv=Refresh content=3;url=index.php>";
?>


the final step is to create the frontend
I cannot assure anyone that this code will not need to be edited.
I changed some things around to make it less specific and I may have overlooked something
Just post a comment and I can help anyone that needs to get this working.
The following file is call address_search.php and can be downloaded HERE
<?php
require ("includes/distcal.php");
?>
<html>
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>

<body bgcolor="#FFFFFF" text="#000000" leftmargin="0" topmargin="10" marginwidth="0" marginheight="10">
<table width="740" border="0" cellspacing="0" cellpadding="0" align="center">
	<tr>
		<td></td>
	</tr>

	<tr> 
		
	<td valign="top" width="740"></td>
	</tr>
	<tr> 
		<td valign="top" align="right"> 
		<table width="740" border="0" cellspacing="0" cellpadding="0">
			<tr> 
				<td width="1" bgcolor="#171717">&nbsp;</td>
				
		  <td valign="middle" align="center"> <br>
			<table border="0" style="{border:1px solid #474747;}" color="#474747">
				<tr>
					<td valign="top" align="center" class="form-header">
				<?php
				if (isset($_POST["address"]))
				{
					$address_physical = $_POST["address"];
					require('includes/dbconnection.php');
					if($conn)
					
					{	//Your Key Here
						$key = "";
						$address = urlencode($address_physical);
						
						$url = "http://maps.google.com/maps/geo?q=".$address."&output=xml&key=".$key;
						//Set up a CURL request, telling it not to spit back headers, and to throw out a user agent.
						$ch = curl_init();
						curl_setopt($ch, CURLOPT_URL, $url);
						curl_setopt($ch, CURLOPT_HEADER,0); //Change this to a 1 to return headers
						curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
						curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
						$data = curl_exec($ch);
						curl_close($ch);
						$xml = new SimpleXMLElement($data);

						$xml_data = explode(",",$xml->Response->Placemark->Point->coordinates);
						$latitude = $xml_data[1];
						$longitude = $xml_data[0];
						

							$sqlx="select name,latitude,longitude, address_physical, phone, webpage, email from Addresses";
							//echo $sqlx;
							$resultx=mysql_query($sqlx);
							$i = 0;
							while($rowx=mysql_fetch_row($resultx))
							{
							$name = $rowx[0];
							$latitude2 =$rowx[1];
							$longitude2 = $rowx[2];
							 $where = $rowx[3];
						        $phone = $rowx[4];
						        $webpage = $rowx[5];
						        $email = $rowx[6];
								$distance = distance($latitude2,$longitude2,$latitude,$longitude);
				
								if($distance<30)
								{
		                            $namearray = $name;
									$dis[$j]=$distance;
									$i++;
									$distance_rounded = round($distance);
								echo $namearray . "<br />";
								echo $phone . "<br />";
								echo $where . "<br />";
								echo "<a href=mailto:" . $email . ">" . $email . "</a><br />" ;
								echo "<a href=" . $webpage. ">" . $webpage . "</a><br />";
			                    echo ("$distance_rounded"." MI. ");
								}?><br /><br />
<?php
							}//end of while loop


						
							?>
							</td>
							</tr>
							</table>
							<?php

						}
						else
						{
							?>
							
							
							<span style='{font-size:12px; color:#474747;}'>
							No Results Returned for your Address.
							</span>
							<br>
							Please enter your Address to locate a whatever near you.
							<form method="post" action="address_search.php" id="form1" name="form1">
							<font class="form-header">Street Address:</font> 
							<input type="text" name="address" size="20">
							&nbsp;&nbsp; 
							<input type="submit" value="Find" id="submit1" name="submit1">
							</form>
							</td>
							</tr>
							</table>
							<?php
						}
						mysql_close ($conn);
					} //end conn here
				
			
				else
				{
				?>
				Please enter your address to locate a whatever near you.
				<form method="post" action="address_search.php" id="form1" name="form1">
				<font class="form-header">Street Address:</font> 
				<input type="text" name="address" size="20">
				&nbsp;&nbsp; 
				<input type="submit" value="Find" id="submit1" name="submit1">
				</form>
				</td>
			</tr>
		</table>
	<br>
	<?php
	}
	?>
				</td>
				<td width="1" bgcolor="#171717">&nbsp;</td>
			</tr>
		</table>
		</td>
	</tr>
	<tr>
		<td></td>
	</tr>
</table>
</body>
</html>
I actually had to integrate this Into Joomla, but that is another story..
As always, hope this helps someone .. leave a comment if you need help or can offer suggestions

One last note...
Please make sure you have PHP5 installed or else you will have to rethink the way
I am getting the xml output into lat and long
SimpleXMLElement is only in php5
If you have php4 installed it will return Fatal Error: can not instantiate non-existent class SimpleXMLElement

For instruction on how to use php's dom function or incorporating maps with markers and a radius search
You can check out
THIS

Posted in  | Tags , , , , , ,  | no comments