Tutorials
- Print this article
- Page 1
Introduction & setting up your database - Page 2
Search for nearest supplier, adding maps and conclusion - Page 3
Full source code listing for this tutorial
How to build your own UK nearest search using PostCoder Web SOAP
Page 3 of 3
Full source code for client-side page
Here is the full source code for the client-side page "NearestExample.html", including styles:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<!--
********************************************************************************
Released under the GNU General Public License
The following copyright announcement is in compliance
to section 2c of the GNU General Public License, and
thus can not be removed, or can only be modified
appropriately.
Please leave this comment intact together with the
following copyright announcement.
Copyright(c) 2008 Allies Computing Ltd
The authors provide no warranty.
PostCoder Web SOAP - Nearest Search Example version 1.01
By Allies Computing Ltd - www.allies-computing.co.uk
Last Modified 08/10/2008
********************************************************************************
This page and its associated server-side page NearestExample.php
demonstrate how to retrieve grid reference information from the
PostCoder Web SOAP Service and search for the nearest items in a MySQL database
Insert a valid Postcoder Web Nearest user name and password into
findMyNearestExample.php, and insert a valid Google maps ID into
google_mapExample.php page before use.
********************************************************************************
-->
<title>PostCoder Web SOAP - Nearest Example</title>
<style type="text/css">
<!--
body, html{
font : 11px, verdana, sans-serif;
color :#000080;
background : #FFF;
}
div.main {
width: 720px;
padding: 5px;
}
div.row {
clear :both;
padding-top :10px;
}
iframe.nearestframe, iframe.mapframe{
width :340px;
height :340px;
border :1px solid #CDCDCD;
}
iframe.nearestframe{
float :left;
scrolling :auto;
frameborder :1;
}
iframe.mapframe{
float :right;
margin-left :10px;
}
label {
float :left;
width :10em;
text-align :right;
padding :5px 5px 0px 0px;
font-weight :bold;
}
fieldset {
border :1px solid #000080;
padding :10px;
}
legend {
padding :2px 5px;
border :1px solid #000080;
text-align :right;
}
input{
padding :2px;
border :inset 1px #330066;
}
input.button{
font : 11px, verdana, sans-serif;
background-color :#E5E5E5;
border :inset 1px #000080;
width :110px;
}
div.message{
padding :1px;
margin :0px;
font-weight :bold;
color :#0000FF;
}
-->
</style>
<script type="text/javascript">
function findaddress(pcode, radius, limit_results){
if (pcode != ''){
// clear the message if any
showMessage(' ');
// disable the button
toggleFormButton(true);
// submit the form and data
document.PostCoderForm.postcode.value = pcode;
document.PostCoderForm.radius.value = radius;
document.PostCoderForm.limit_results.value = limit_results;
document.PostCoderForm.submit();
}
}
function showMessage(str){
if(document.getElementById){
document.getElementById('message').innerHTML = str;
}
else if (document.all){
document.all['message'].innerHTML = str;
}
}
function toggleFormButton(status) {
var theform = document.NearestForm;
if (status == true)
theform.searchbutton.value = 'Searching...';
else
theform.searchbutton.value = 'Find my Nearest';
}
function clearMapFrame() {
map_result.document.body.innerHTML = "";
}
</script>
</head>
<body>
<!-- Hidden form to allow easy communication with server-side page -->
<form name="PostCoderForm" method="post" action="NearestExample.php" target="nearest_result">
<input type="hidden" name="postcode" />
<input type="hidden" name="radius" />
<input type="hidden" name="limit_results" />
<input type="hidden" name="identifier" value="Example - Find My Nearest" />
</form>
<div class="main">
<form name="NearestForm">
<fieldset>
<legend>Nearest Search</legend>
<div style="float:left;">
<div class="row">
<label>Postcode:</label>
<input maxlength="10" tabindex="1" type="text" name="pcode" size="9" onkeypress="if ((window.event) && (window.event.keyCode==13))findaddress(this.value)" />
<input id="searchbutton" tabindex="4" type="button" class="button" value="Find my Nearest"
onclick="findaddress(this.form.pcode.value,this.form.radius.value,this.form.limit_results.value)" />
</div>
<div class="row">
<label>Radius (miles):</label>
<input maxlength="4" tabindex="2" type="text" name="radius" size="4" value="1"/>
</div>
<div class="row">
<label>Max Items:</label>
<input maxlength="4" tabindex="3" type="text" name="limit_results" size="4" value="10"/>
</div>
<div class="row">
<div align="center" id="message" class="message"> </div>
<div>
<iframe src="blank.html" class="nearestframe" id="nearest_result" name="nearest_result">
</iframe>
<iframe src="blank.html" class="mapframe" id="map_result" name="map_result"></iframe>
</div>
</fieldset>
</form>
</div>
</body>
</html>
Full source code for server-side page
Here is the full source code for the server-side page "NearestExample.php".
(Note: Please ensure you enter your PostCoder Web SOAP username and password, and also the hostname, database name, username and password for your MySQL database in this code before use.)
<?php
/* *************************************************************
Released under the GNU General Public License
The following copyright announcement is in compliance
to section 2c of the GNU General Public License, and
thus can not be removed, or can only be modified
appropriately.
Please leave this comment intact together with the
following copyright announcement.
Copyright(c) 2008 Allies Computing Ltd
The authors provide no warranty.
PostCoder Web SOAP - Nearest Search Example version 1.01
By Allies Computing Ltd - www.allies-computing.co.uk
Last Modified 08/10/2008
*************************************************************
This PHP script demonstrates how to retrieve grid reference
information from the PostCoder Web SOAP Service and search
for the nearest items in a MySQL database
*************************************************************
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>PostCoder Web SOAP Nearest Example</title>
<style type="text/css">
.resulttext {
font :11px, verdana, sans-serif;
}
</style>
</head>
<body>
<?php
// Enter Your PostCoder Web SOAP Username and Password Below.
$username = 'MyPostCoderWebSOAPUsername';
$password = 'MyPostCoderWebSOAPPassword';
// Get parameters from client-side page
$identifier = $_POST['identifier'];
$postcode = $_POST['postcode'];
$radius = $_POST['radius'];
$limit_results = $_POST['limit_results'];
$proxy='';
$result='';
if (!empty($postcode)){
// Set up the SOAP service
initiate_SOAP_Service($proxy);
// Find grids for input postcode
if (getGrids($proxy, $postcode, $identifier, $username, $password,
$result)) {
// Get the list of Nearest Items
getNearestItems($result['grideast'],$result['gridnorth'], $radius, $limit_results);
}
else showmessage("Please enter a postcode");
}
toggleFormButton();
clearMapFrame();
/*********************************************************************
* End of main logic, function defintions follow
*********************************************************************/
/*********************************************************************
* initiate_SOAP_Service()
* Sets up the SOAP service.
*********************************************************************/
function initiate_SOAP_Service(&$proxy)
{
/* Setting the $useWSDLcache variable below to TRUE may improve the
overall speed of the service by creating a cached version of the
WSDL document on your server. To use this feature, the user on your
server that runs this script (apache, httpd, etc) must have write access in the
directory this script lies. */
$useWSDLcache = TRUE;
// Get the WSDL Document from the PostCoder Web SOAP server.
$wsdlPath = "http://www.postcoderwebsoap.co.uk/websoap/websoap.php?wsdl";
// Pull in the NuSOAP code
require('nusoap/lib/nusoap.php');
if ($useWSDLcache){
// include the nusoap wsdl cache classes
require('nusoap/lib/class.wsdlcache.php');
// use a wsdl cache
$cache = new wsdlcache(".",604800); //1 week
$wsdl = $cache->get($wsdlPath);
if (is_null($wsdl)){
$wsdl = new wsdl($wsdlPath);
$cache->put($wsdl);
}
// create a soap client from WSDL cache
$client = new soap_client($wsdl,TRUE);
}
else {
// Create the client from WSDL document.
$client = new soap_client($wsdlPath,'wsdl');
}
// Check for an error
if ($err = $client->getError()) exitScript();
// get proxy client.
$proxy = $client->getproxy();
// Check for an error
if ($err = $proxy->getError()) exitScript();
}
/*********************************************************************
* getGrids()
* Get the Grid References and other geo data for a given postcode
*********************************************************************/
function getGrids($proxy, $postcode, $identifier, $username, $password, &$result)
{
// call the SOAP method for getGrids.
$result = $proxy->getGrids($postcode,$identifier,$username,$password);
if ($proxy->fault) { // Check for a fault
exitScript();
} elseif ($err = $proxy->getError()) { // Check for errors
exitScript();
} elseif ($result['error_code'] != '0'){ // No SOAP error, but some other error
exitScript();
} elseif ($result['retcode'] == '3'){ // Invalid Postcode
exitScript('Invalid Postcode ' . $postcode . ' - please check and try again');
} elseif ($result['retcode'] == '4'){ // No Postcode found in search term
exitScript('Please input a valid UK Postcode');
} elseif (empty($result['grideast'])) {
exitScript('Grid references for ' . $postcode . ' not available, please try another Postcode');
} else {
return TRUE;
}
}
/*********************************************************************
* getNearestItems()
* Find nearest items in database
*********************************************************************/
function getNearestItems($grideast, $gridnorth, $radius_mi, $limit_results)
/* Note the output from this function is purely in the form of HTML
to the client page at this stage in the development process */
{
// Enter the hostname for your database server, database name, username and password
$hostname="localhost";
$dbname="MyDatabaseName";
$dbusername="MyDatabaseUserName";
$dbpassword="MyDatabasePassword";
$k_to_mi = 0.621371192; // Kilometres to miles factor
$tenm_to_mi = $k_to_mi/100; // Ten Metre to miles factor
$mi_to_k = 1.609344; // Miles to Kilometres factor
$radius_km=$radius_mi*$mi_to_k; // Radius in Km
$radius_tenm=$radius_km*100; // Radius in 10m units (which is the same as Grid Refs)
//connect to the database
$db=mysql_connect ($hostname, $dbusername, $dbpassword) or exitScript();
//-select the database to use
$mydb=mysql_select_db($dbname) or exitScript();
//-find the nearest items
$nearest_query = "SELECT SupplierID, SupplierName, Premise, Dependent_street, Street, Double_dependent_locality,
Dependent_locality, Post_Town, Postcode, Telephone, EmailAddress, Website,
(SQRT(POW(($grideast - GridEasting),2)+POW(($gridnorth - GridNorthing),2))) AS distance,
Latitude, Longitude
FROM suppliers
HAVING distance <= $radius_tenm
ORDER BY distance
LIMIT $limit_results";
$result=mysql_query($nearest_query);
if (($result) && (mysql_num_rows($result) > 0)) {
//-loop through result set
while($row=mysql_fetch_array($result)){
// distance in Miles
$miles = sprintf("%01.2f",$tenm_to_mi*$row['distance']);
echo '<p class="resulttext"> Distance - <span style="color: red">approx '.$miles.' miles</span><br>';
if (!empty($row['SupplierName'])) echo $row['SupplierName'] .'<br>';
if (!empty($row['Premise'])) echo $row['Premise'] . ' ';
if (!empty($row['Dependent_street']))
echo $row['Dependent_street'].'<br>';
if (!empty($row['Street']))
echo $row['Street'].'<br>';
if (!empty($row['Double_dependent_locality']))
echo $row['Double_dependent_locality'].'<br>';
if (!empty($row['Dependent_locality']))
echo $row['Dependent_locality'].'<br>';
if (!empty($row['Post_Town']))
echo $row['Post_Town'].'<br>';
if (!empty($row['Postcode']))
echo $row['Postcode'].'<br>';
if (!empty($row['Telephone']))
echo 'Tel: ' . $row['Telephone'].'<br>';
if (!empty($row['EmailAddress']))
echo 'Email: <a href="mailto:' . $row['EmailAddress'] . '" "target="_blank">' . $row['EmailAddress'] . '</a><br>';
if (!empty($row['Website']))
echo 'Web: <a href="http://' . $row['Website']. '" target="_blank">' . $row['Website'] . '</a><br>';
// Display Map Link
if (!empty($row['Latitude']) && !empty($row['Longitude']))
echo '<a href="google_map.php?long=' . $row['Longitude'] . '&lat=' . $row['Latitude'] . '" target="map_result">Show Map</a><br>';
}
}
else { // Problem with query syntax or (more likely) no results found
showMessage('No results found within radius of ' . $radius_mi . ' mile(s), please try a larger radius');
}
}
/*********************************************************************
* toggleFormButton()
* Toggle the search button in the client-side form
*********************************************************************/
function toggleFormButton()
{
?>
<script type="text/javascript">
// reset the search button.
parent.toggleFormButton(false);
</script>
<?php
}
/*********************************************************************
* showMessage($message)
* Show message in the client-side form
*********************************************************************/
function showMessage($message)
{
?>
<script type="text/javascript">
parent.showMessage("<?php echo $message; ?>");
</script>
<?php
}
/*********************************************************************
* clearMapFrame()
* Clear map frame in the client-side form
*********************************************************************/
function clearMapFrame()
{
?>
<script type="text/javascript">
parent.clearMapFrame();
</script>
<?php
}
/*********************************************************************
* exitScript($message)
* Exit script, but in a tidy fashion.
*********************************************************************/
function exitScript($message='Unable to conduct Nearest search, please report to site owner')
{
showMessage($message);
toggleFormButton();
clearMapFrame();
exit("</body></html>");
}
?>
</body>
</html>