473,626 Members | 3,369 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 2116
"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******* ***********@new ssvr25.news.pro digy.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*****@invali d.invalid> wrote in message
news:BF0E9D15.3 572E%in*****@in valid.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*****@invali d.invalid> wrote in message
news:BF0EE186.3 577B%in*****@in valid.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((lat itude)*(pi()/180)) *
sin((".$latitud e.")*(pi()/180)) + cos((latitude)* (pi()/180)) *
cos((".$latitud e.")*(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.supernew s.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?

Precomputin g 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

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

Similar topics

51
5252
by: Mudge | last post by:
Please, someone, tell me why OO in PHP is better than procedural.
9
3856
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 users, and listing assignments use similar type commands. Is there a "better" way I can organize my code?
4
2426
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
3099
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
5843
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 question that identifies the warning signs to look out for, the things that most easily and clearly identify the author of code as something less than a master of the art. I did not find an FAQ that answered it, but I think the FAQ
5
4045
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 employee based on their region, zone, job code and avg job time. (See code below). My problem is that I do not know how to rank the ties. Right now if two people have the same avg time one will be ranked 3rd and the other ranked 4th. I would...
0
2083
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 allow it ro run then it will execute, the code execution depends on the permission provided to the assembly. If the code is not trusted wnough to run or it attempts to perform an action which doe not have the required permissions then its execution...
18
3150
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 question is what happens to the dynamically created assembly when the method is done running? Does GC take care of it? Or is it stuck in RAM until the ASP.Net process is recycled? This code executes pretty frequently (maybe 4 times per transaction) and...
37
5948
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 in a separate file from the HTML. Apart from the obvious advantage if you have a separate designer and programmer, are there any other advantages to code behind? Most of the stuff I've seen so far uses code inside, but that's probably
171
7688
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) like it because you can split the code from the design. That is logical. But if you are the only one working on the code, it seem a little overkill. I use Dreamweaver to do my design and find it a bit of a hassle to have multiple files open...
0
8265
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8196
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8637
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7193
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4092
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4197
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2625
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 we have to send another system
1
1808
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1511
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.