473,498 Members | 1,873 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Zip code

I have a database of zipcodes with latitude and longitude. I also have the
method of calculating the distance between two zipcodes. What I want to
know is if there is an efficient algorithm for obtaining the zip codes
within a specified distance of the first zipcode without having to retrieve
and calculate for every record in the database.

Shelly
Jul 28 '05 #1
11 2085
"News" wrote:
I have a database of zipcodes with latitude and longitude. I also have the
method of calculating the distance between two zipcodes. What I want to
know is if there is an efficient algorithm for obtaining the zip codes
within a specified distance of the first zipcode without having to retrieve
and calculate for every record in the database.

Shelly


Not really a PHP issue, but I'd try something like this:

1. Imagine a circle of the specified range centred on the target zip code.

2. Now imagine two (square-ish) boxes centred on the same point, whose sides
correspond to lines of latitude and longitude. One box just fits inside this
circle (i.e., all four corners lie exactly on the circle), and the other
just fits around the circle (i.e., the circle is tangential to all four
sides). You can calculate the corner coordinates of these boxes by simple
trigonometry.

3. Build a DB query to extract all the zip codes that lie inside the smaller
box. These all lie inside the specified range.

4. Build another DB query to extract all the zip codes that lie inside the
larger box but not inside the smaller one. These may or may not lie inside
the specified range, and will have to be tested individually.

5. If there are still a large number of zip codes to test at step 4, divide
this region into a grid based on the latitude and longitude values, and
pre-calculate a flag for each cell to indicate whether it is completely
inside or outside the region, or if it partially intersects (in which case
you will have to test the zip codes individually).
--
phil [dot] ronan @ virgin [dot] net
http://vzone.virgin.net/phil.ronan/
Jul 28 '05 #2
News wrote:
I have a database of zipcodes with latitude and longitude. I also have the
method of calculating the distance between two zipcodes. What I want to
know is if there is an efficient algorithm for obtaining the zip codes
within a specified distance of the first zipcode without having to retrieve
and calculate for every record in the database.


You may do that in the query itself; but the DB will definitely scan
all the records. Look at the previous discussions
<news:CW******************@newssvr25.news.prodigy. com> (
http://groups-beta.google.com/group/...418b46576b2cd3
)

Indexing latitude and longitude might help.

--
<?php echo 'Just another PHP saint'; ?>
Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com

Jul 28 '05 #3

"Philip Ronan" <in*****@invalid.invalid> wrote in message
news:BF0E9D15.3572E%in*****@invalid.invalid...
"News" wrote:
I have a database of zipcodes with latitude and longitude. I also have
the
method of calculating the distance between two zipcodes. What I want to
know is if there is an efficient algorithm for obtaining the zip codes
within a specified distance of the first zipcode without having to
retrieve
and calculate for every record in the database.

Shelly


Not really a PHP issue, but I'd try something like this:

1. Imagine a circle of the specified range centred on the target zip code.

2. Now imagine two (square-ish) boxes centred on the same point, whose
sides
correspond to lines of latitude and longitude. One box just fits inside
this
circle (i.e., all four corners lie exactly on the circle), and the other
just fits around the circle (i.e., the circle is tangential to all four
sides). You can calculate the corner coordinates of these boxes by simple
trigonometry.

3. Build a DB query to extract all the zip codes that lie inside the
smaller
box. These all lie inside the specified range.


Thanks. While waiting for an answer I did a similar thing to the above on
my own. All I did was calculate the delta latitude and longitude
(radius*360/24902) and added and subtracted from the center point. That
gave the surrounding box. From there I will have not that many zipcodes. I
can test each one for distance and see if it lies within the specified
radius. That is the simplest method.

Shelly
Jul 28 '05 #4
>I have a database of zipcodes with latitude and longitude. I also have the
method of calculating the distance between two zipcodes. What I want to
know is if there is an efficient algorithm for obtaining the zip codes
within a specified distance of the first zipcode without having to retrieve
and calculate for every record in the database.


It depends on what you are doing, and how accurate you need to be.
Is that distance supposed to be DRIVING distance or distance as
the missile flies?

Precomputing some of this can be used to advantage.

(1) You could precalculate the distance between every zip code and
every other zip code. This takes a lot of storage but it only has
to be computed once. You didn't say whether a zip code can be
characterized by its center or whether you have to take into account
whether any part of it is within the distance given.

(2) If the objective is to find the nearest store, or all stores
within N miles, where N has a small number of choices on a web page
(like 5, 10, 20, 50 miles), you can precalculate the distance between
each zip code WITH A STORE IN IT (and you could use the exact
lat/long of the store, not that of the zip code it's in, if you
know it) and each zip code where customers might be.

Make a table (store number, zip code (of CUSTOMER), distance) where
you drop any entries where the distance is unreasonably large or
much better alternatives exist. For example, you might leave in
an entry for a store 200 miles away if it's the closest one, but
drop it if there are 3 others within 10 miles of the customer. This
is a decision needed when constructing the table but you only have
to re-do it when you add/delete/move stores or if zip codes move
(they have been known to split, so the center moves).

You can also hand-tune recommendations (e.g. drop any that are close
but require the customer to travel through war zones, swim across
rivers where there aren't bridges, or over military artillery
practice areas. This requires a lot more detailed info than what
you've got, but someone familiar with the area around the store
might know this). Select on zip code matching and distance < the
radius the customer specified.

(3) You can try to simplify the calculation by converting the
coordinates to a linear grid (E-W and N-S from some point in the
middle of the area in question). This is terrible if you are trying
to do the entire USA (including Alaska and Hawaii) since the world
really isn't flat, but not too bad if you're trying to do a 100-mile
radius around some city, where the world is a reasonable approximation
to flat. Use a bounding box to limit the calculation. If you want
zip codes within 20 miles of (x,y), anything not within (x-21 ..
x+21, y-21 .. y+21) is DEFINITELY out, and you can use the more
precise calculation on the remaining candidates. Indexes on the
coordinates might help.

Gordon L. Burditt
Jul 28 '05 #5
"News" wrote:
Thanks. While waiting for an answer I did a similar thing to the above on
my own. All I did was calculate the delta latitude and longitude
(radius*360/24902) and added and subtracted from the center point. That
gave the surrounding box. From there I will have not that many zipcodes. I
can test each one for distance and see if it lies within the specified
radius. That is the simplest method.


The delta longitude will be a bit different unless you're at the equator.
Off the top of my head, I'd say it's probably (radius*360/(24902*cos(lat))

Rajesh's solution also looks good, BTW.

--
phil [dot] ronan @ virgin [dot] net
http://vzone.virgin.net/phil.ronan/
Jul 28 '05 #6

"Philip Ronan" <in*****@invalid.invalid> wrote in message
news:BF0EE186.3577B%in*****@invalid.invalid...
"News" wrote:
Thanks. While waiting for an answer I did a similar thing to the above
on
my own. All I did was calculate the delta latitude and longitude
(radius*360/24902) and added and subtracted from the center point. That
gave the surrounding box. From there I will have not that many zipcodes.
I
can test each one for distance and see if it lies within the specified
radius. That is the simplest method.


The delta longitude will be a bit different unless you're at the equator.
Off the top of my head, I'd say it's probably (radius*360/(24902*cos(lat))


Excellent point! Duh, I should have known that. After all, I teach Math.
Of course I will have to be careful with deg/rad. I will go no and look it
up.

Shelly
Jul 28 '05 #7
>I have a database of zipcodes with latitude and longitude. I also have the
method of calculating the distance between two zipcodes. What I want to
know is if there is an efficient algorithm for obtaining the zip codes
within a specified distance of the first zipcode without having to retrieve
and calculate for every record in the database.


How about a single select statement?

In this case I use a table called cities, where I have the fields city,
latitude and longitude. I have indexed the lat / long for improved speed.

$sqlstr="select city, ((acos(sin((latitude)*(pi()/180)) *
sin((".$latitude.")*(pi()/180)) + cos((latitude)*(pi()/180)) *
cos((".$latitude.")*(pi()/180)) * cos((longitude -
".$longitude.")*(pi()/180))))*(180/pi())* 60 * 1.1515 * 1.609344) dist,
latitude, longitude from cities order by dist limit 30";

On my server this query returns results in under a second when the table is
indexed correctly.

This query is only returning the 30 closest cities to a latitude longitude,
but perhaps you can search where the dist is less than so many kilometers.

oh the *1.609344 at the end of the equation converts miles to kilometers.

I was originally thinking something much more complex was necessary, but it
isn't.

Hope it helps!

OH - where did you get the lat long database?

Michael
Jul 28 '05 #8
In article <11*************@corp.supernews.com>,
Gordon Burditt <go***********@burditt.org> wrote:
I have a database of zipcodes with latitude and longitude. I also have the
method of calculating the distance between two zipcodes. What I want to
know is if there is an efficient algorithm for obtaining the zip codes
within a specified distance of the first zipcode without having to retrieve
and calculate for every record in the database.


It depends on what you are doing, and how accurate you need to be.
Is that distance supposed to be DRIVING distance or distance as
the missile flies?

Precomputing some of this can be used to advantage.


have you looked at a zip code map for Manhattan?

--
a d y k e s @ p a n i x . c o m

Don't blame me. I voted for Gore.
Jul 29 '05 #9
>>>I have a database of zipcodes with latitude and longitude. I also have the
method of calculating the distance between two zipcodes. What I want to
know is if there is an efficient algorithm for obtaining the zip codes
within a specified distance of the first zipcode without having to retrieve
and calculate for every record in the database.


It depends on what you are doing, and how accurate you need to be.
Is that distance supposed to be DRIVING distance or distance as
the missile flies?

Precomputing some of this can be used to advantage.


have you looked at a zip code map for Manhattan?


Assuming for the moment that you have 100 stores, and you need to
compute the distance between the 100 stores and all the Zip codes
in Manhattan, and every (9 digit) Zip code that begins with 1 is
in Manhattan (this is a ridiculous over-estimate: Westchester
county contains 10510 and the far end of New York state contains
14092 (Lewiston), and that range of zip codes certainly covers
several states), and that it takes 1 millisecond to do a distance
calculation (with a 2-3 GHz processor with a floating point unit,
this should be easy), this calculation will take about 115 days.
But you only have to do it once.

Gordon L. Burditt
Jul 29 '05 #10
Hello,

on 07/28/2005 09:28 AM News said the following:
I have a database of zipcodes with latitude and longitude. I also have the
method of calculating the distance between two zipcodes. What I want to
know is if there is an efficient algorithm for obtaining the zip codes
within a specified distance of the first zipcode without having to retrieve
and calculate for every record in the database.


You may want to take a look at this class that is capable of computing a
range of latitude and longitude values to perform a distance search in
such way that it won't perform a full table scan (provide that you have
some indexes in place):

Class: Zip Codes Range
http://www.phpclasses.org/zipcodesrange

--

Regards,
Manuel Lemos

PHP Classes - Free ready to use OOP components written in PHP
http://www.phpclasses.org/

PHP Reviews - Reviews of PHP books and other products
http://www.phpclasses.org/reviews/

Metastorage - Data object relational mapping layer generator
http://www.meta-language.net/metastorage.html
Jul 29 '05 #11
Here's one way (which I used in an air-defense application decades
ago):

Create a grid covering the geographic area under consideration, and for
each zipcode, compute the grid number in which its center exists, a
one-time task. (That grid number is retained as another field in the
database.)

Then, given an argument zip code, compute its grid number, and then
check against only that grid number and its eight (or 16, or 25)
surrounding grid neighbors. (Determining these neighbors is a bit
tricky, but ... .)

Grid configuration will depend on yr app's requirements.

AS

Jul 29 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

51
5200
by: Mudge | last post by:
Please, someone, tell me why OO in PHP is better than procedural.
9
3843
by: bigoxygen | last post by:
Hi. I'm using a 3 tier FrontController Design for my web application right now. The problem is that I'm finding to have to duplicate a lot of code for similar functions; for example, listing...
4
2415
by: jason | last post by:
Hello. Newbie on SQL and suffering through this. I have two tables created as such: drop table table1; go drop table table2; go
16
3083
by: Dario de Judicibus | last post by:
I'm getting crazy. Look at this code: #include <string.h> #include <stdio.h> #include <iostream.h> using namespace std ; char ini_code = {0xFF, 0xFE} ; char line_sep = {0x20, 0x28} ;
109
5739
by: Andrew Thompson | last post by:
It seems most people get there JS off web sites, which is entirely logical. But it is also a great pity since most of that code is of such poor quality. I was looking through the JS FAQ for any...
5
4033
by: ED | last post by:
I currently have vba code that ranks employees based on their average job time ordered by their region, zone, and job code. I currently have vba code that will cycle through a query and ranks each...
0
2075
by: Namratha Shah \(Nasha\) | last post by:
Hey Guys, Today we are going to look at Code Access Security. Code access security is a feature of .NET that manages code depending on its trust level. If the CLS trusts the code enough to...
18
3136
by: Joe Fallon | last post by:
I have some complex logic which is fairly simply to build up into a string. I needed a way to Eval this string and return a Boolean result. This code works fine to achieve that goal. My...
37
5914
by: Alan Silver | last post by:
Hello, Newbie here, so please forgive what is probably a basic question ... I see a lot of discussion about "code behind", which if I have understood correctly, means that the script code goes...
171
7579
by: tshad | last post by:
I am just trying to decide whether to split my code and uses code behind. I did it with one of my pages and found it was quite a bit of trouble. I know that most people (and books and articles)...
0
7125
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7004
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7167
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7208
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7379
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4915
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4593
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3095
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1423
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.