Solved

enter zip code, calculate distance from my zip code

Posted on 2009-03-31
17
733 Views
Last Modified: 2013-12-12
Is there a way to calculate distance from my zip code

by allowing user to enter their zip code in a text box
0
Comment
Question by:shopjd
17 Comments
 
LVL 9

Expert Comment

by:pmessana
ID: 24033569
You will have to write something.  Rather than reinventing the wheel, take a look at this.

http://www.micahcarrick.com/04-19-2005/php-zip-code-range-and-distance-calculation.html

and

http://www.idealog.us/2006/07/zip_code_distan.html
0
 
LVL 6

Expert Comment

by:digital0iced0
ID: 24033599
You need a zipcode database with longitude and latitude coordinates.  Then you have to calculate the distance between the two points.  

This link below should help you it has a link to download a database and it has some sample code.  Let me know if you still need help.

http://www.idealog.us/2006/07/zip_code_distan.html
0
 
LVL 14

Accepted Solution

by:
shobinsun earned 500 total points
ID: 24035827
Hello,

Use the code below:

ext1.php:

<?php

include 'class.geodata.inc.php';



// Compare the distance between two different zip/postal codes

$x = new EyeGeoData();

$x->query('M5X 1J2');



$y = new EyeGeoData();

$y->query('90210');



echo $x->calcDistance($y, EyeGeoData::KMS, 2) . ' kms'; // prints "6923.05 kms"
?>

use $_GET method in  "query()"  function for the values from a form(user entered value).



class.geodata.inc.php:

<?php
 

/**
 

 * EyeGeoData
 

 * Retrieve geographical information of a postal/zip/post code
 

 *
 

 * LICENSE: This source file is subject to the BSD license
 

 * that is available through the world-wide-web at the following URI:
 

 * http://www.eyesis.ca/license.txt.  If you did not receive a copy of
 

 * the BSD License and are unable to obtain it through the web, please
 

 * send a note to mike@eyesis.ca so I can send you a copy immediately.
 

 *
 

 * @author     Micheal Frank <mike@eyesis.ca>
 

 * @copyright  2008 Eyesis
 

 * @license    http://www.eyesis.ca/license.txt  BSD License
 

 * @version    v1.0.0 6/18/2008 3:13:34 PM
 

 * @link       http://www.eyesis.ca/projects/geodata.html
 

 */
 
 
 

class EyeGeoData
 

{
 

	const FEED = 'http://api.eyesis.ca/geo.xml';
 
 
 

	const KMS = 1;
 

	const MIS = 2;
 
 
 

	private $key = false;
 

	private $status_code, $lookups_left;
 

	public $result = false;
 

	public $out = 'xml';
 
 
 

	/**
 

	* Set a key for premium accounts
 

	* 
 

	* @param string $key Key provided by Eyesis for premium accounts
 

	*/
 

	public function setKey($key)
 

	{
 
 
 

		$this->key = $key;
 
 
 

	}
 
 
 

	/**
 

	* Get postal/zip code information
 

	* 
 

	* @param string $code The postal/zip code you want to lookup
 

	* @return mixed The result of the query, false on error
 

	*/
 

	public function query($code)
 

	{
 
 
 

		// Build the query
 

		$query = '?code=' . urlencode($code);
 

		if ($this->key)
 

			$query .= '&key=' . urlencode($this->key);
 
 
 

		$info = false;
 
 
 

		if ($this->out == 'xml')
 

		{
 

			// Use XML feed and SimpleXML
 
 
 

			if ($feed = new SimpleXMLElement(self::FEED . $query, NULL, true))
 

			{
 
 
 

				$this->status_code		= (integer) $feed->Request->StatusCode;
 

				$this->lookups_left		= (integer) $feed->Client->LookupsLeft;
 
 
 

				if ($this->status_code == 200)
 

				{
 

					$info = array (
 

						'PostalCode' 	=> (string) $feed->Details->PostalCode,
 

						'City' 				=> (string) $feed->Details->City,
 

						'Province' 		=> (string) $feed->Details->Province,
 

						'Country' 		=> (string) $feed->Details->Country,
 

						'AreaCode' 		=> (integer) $feed->Details->AreaCode,
 

						'TimeZone' 		=> (integer) $feed->Details->TimeZone,
 

						'Coordinates' => array (
 

							'Latitude' 		=> (float) $feed->Details->Coordinates->Latitude,
 

							'Longitude' 	=> (float) $feed->Details->Coordinates->Longitude
 

						)
 

					);
 

				}
 
 
 

			}
 
 
 

		} else {
 

			// Use Serialized feed
 
 
 

			if ($feed = file_get_contents(self::FEED . $query . '&out=php'))
 

			{
 
 
 

				$feed = unserialize($feed);
 
 
 

				$this->status_code		= (integer) $feed['PostalCode']['Request']['StatusCode'];
 

				$this->lookups_left		= (integer) $feed['PostalCode']['Client']['LookupsLeft'];
 
 
 

				if ($this->status_code == 200)
 

					$info = $feed['PostalCode']['Details'];
 
 
 

			}
 
 
 

		}
 
 
 

		$this->result = $info;
 
 
 

    return $this->result;
 
 
 

	}
 
 
 

	/**
 

	* Get the status code of the previous result
 

	* 
 

	* @return mixed
 

	*/
 

	public function getStatusCode()
 

	{
 
 
 

		return ($this->status_code) ? $this->status_code : false;
 
 
 

	}
 
 
 

	/**
 

	* Get the amount of lookups left
 

	* 
 

	* @return mixed
 

	*/
 

	public function getLookupsLeft()
 

	{
 
 
 

		return ($this->lookups_left) ? $this->lookups_left : false;
 
 
 

	}
 
 
 

	/**
 

	* Calculates the distance between this result and another GeoData object's result
 

	* 
 

	* @param GeoData $dest The object to compare to
 

	* @param integer $units The distance units
 

	* @return float
 

	*/
 

	public function calcDistance(EyeGeoData $dest, $units = self::KMS, $round = 3)
 

	{
 
 
 

		if (!$dest->result or !$this->result)
 

			trigger_error('Result empty; query either failed or has not been run', E_USER_ERROR);
 
 
 

		$dist = rad2deg(acos(sin(deg2rad($this->result['Latitude'])) * sin(deg2rad($dest->result['Coordinates']['Latitude'])) +  
 

			cos(deg2rad($this->result['Coordinates']['Latitude'])) * cos(deg2rad($dest->result['Coordinates']['Latitude'])) * 
 

			cos(deg2rad($this->result['Coordinates']['Longitude'] - $dest->result['Coordinates']['Longitude'])))) * 60 * 1.1515;
 
 
 

		// Convert to kms
 

		if ($units == self::KMS)
 

			$dist *= 1.609344;
 
 
 

		$dist = round($dist, $round); // Round off
 
 
 

    return (float) $dist;
 
 
 

	}
 
 
 

	/**
 

	* Convert this object to a string
 

	* 
 

	* @return string
 

	*/
 

	public function __toString()
 

	{
 
 
 

		if ($this->result)
 

			return print_r($this->result, true);
 

		else
 

			return "I've got nothing to say";
 
 
 

	}
 

}

Open in new window

0
 

Author Comment

by:shopjd
ID: 24044128
-shobinsun

I added
x->query('90035');

comparing it with


$y->query('90210');

the output is
5190.44 kms

how can I change the code so a user can input their zip code
and outputs distance in miles
0
 
LVL 14

Expert Comment

by:shobinsun
ID: 24046233
Hello,

Use this method:

$first = $_GET['distance1'];

$second = $_GET['distance2'];

x->query($first);

$y->query($second);

the  $_GET['distance1']  and $_GET['distance2']  are the values entered by the user in a form.

Regards.
0
 

Author Comment

by:shopjd
ID: 24046268
which file do I edit
0
 
LVL 14

Expert Comment

by:shobinsun
ID: 24046367
Hello,

You shoud edit the file: ext1.php
0
 
LVL 14

Expert Comment

by:shobinsun
ID: 24046446
Hello,

Here is the full code:

post.html(for user input):

<html>
<form action="ex1.php" method="post">
First code<input type="text" name="distance1"/>
Second code<input type="text" name="distance2"/>
<input type="Submit" name="submit" value="Send"/>
</form>
</html>


ex1.php:

<?php

include 'class.geodata.inc.php';



// Compare the distance between two different zip/postal codes

$x = new EyeGeoData();


$first = $_POST['distance1'];

$second = $_POST['distance2'];

$x->query($first);



$y = new EyeGeoData();

$y->query($second);



echo $x->calcDistance($y, EyeGeoData::KMS, 2) . ' kms'; // prints "6923.05 kms"
?>


regards.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:shopjd
ID: 24055766
line 291  of class.geodata.inc.php:
which is  
trigger_error('Result empty; query either failed or has not been run', E_USER_ERROR);

makes an error:
Error: E_USER_ERROR
Result empty; query either failed or has not been run
at class.geodata.inc.php line 291
0
 
LVL 14

Expert Comment

by:shobinsun
ID: 24056596
Hello,

The error is because of the invalid entry of code or you have entered only one code in the user field.

Which code you have entered ?

Regards.
0
 

Author Comment

by:shopjd
ID: 24073337
10021 10001  generates 6114.18 kms
10021 90210  generates 7050.58 kms

is there anyway to convert kms to miles
0
 
LVL 14

Expert Comment

by:shobinsun
ID: 24074320
Hello,

You can convert kms to miles in the code as:

$dist=$x->calcDistance($y, EyeGeoData::KMS, 2);
$dist=$dist/1.6093;
echo $x->calcDistance($y, EyeGeoData::KMS, 2) . ' kms';
echo $dist . ' miles';

regards.
0
 

Author Comment

by:shopjd
ID: 24101336
thank you for the kms to miles conversion

but

10021 new york 10001 new york  generates 6114.18 kms
10021 new york 90210 los angeles generates 7050.58 kms

the distance is wrong
0
 

Author Comment

by:shopjd
ID: 24157347
hank you for the kms to miles conversion

but

10021 new york 10001 new york  generates 6114.18 kms
10021 new york 90210 los angeles generates 7050.58 kms

the distance is wrong
0
 
LVL 14

Expert Comment

by:shobinsun
ID: 24159452
Hi,

Please find the script from the following link:

http://rapidshare.com/files/222096046/ZIPCODE.zip.html

I have uploaded a very good script for you.

hope this will help you.

Sorry for the delay.

Thanks and regards.
0
 
LVL 14

Expert Comment

by:shobinsun
ID: 24159798
Hi,

To calculate the distance between two UK postcodes, please go through the link:

http://www.sloomedia.com/php_postcode_script.php

Regards.
0
 
LVL 14

Expert Comment

by:shobinsun
ID: 24165776
Hello,

here is an another script for you.

Try with it.

http://rapidshare.com/files/222345520/zipcode.zip.html

Thanks and Regards
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now