Re: Finding nearest location, calculating distance - best way to store and sort info?
Arturo Perez <[email protected]>
| Newsgroups | gmane.comp.web.webobjects.devel |
|---|---|
| Message-ID | <[email protected]> |
Matt Kime wrote:
> the custom comparator is interesting. however, the distance from my
> central point should only be calculated once for each object. will it
> be calculated every time two objects are compared? in other words,
> many, many times when ordering a list.
>
Well, that's what caching/memoization is for. Rather than sort the
items directly, for example,
you could put them into a simple Object
private class SortableAddress {
Address address;
float distanceFromCentroid = -1;
}
then calculate and save the distance into that extra field.
-arturo
> thanks,
> matt
>
> On 5/3/06, Arturo Perez <[email protected]> wrote:
>> Matt Kime wrote:
>> > I have a database of addresses and i'm trying to find the nearest
>> > locations. Rather than computing the distance for all the addresses in
>> > the database, I'm starting by creating an array of addresses within x
>> > distance. Now that I have my array, I'm finding myself at my limit of
>> > java knowledge. I'd like to create an associative array that i can
>> > sort with, storing objects and sorting on their distance. What is the
>> > best java tool for this? The different types of maps are confusing me
>> > and I'm not sure if they'll work for what i want anyway. (it seems
>> > that a sortedMap won't work if I want to store an object - no way to
>> > compare my address objects)
>> >
>> > what solutions have you employed?
>>
>> When I've had to do this I used the database to calculate and return the
>> addresses in sorted order using a city-block metric.
>>
>> Say you have the addresses with lat/long info. You want the addresses
>> within 5 miles of a given address. The SQL (yeah, I know, evil) would
>> be something like
>>
>> SELECT address from ADDRESS where address.x between ($1.x and $1.x +
>> 5) and address.y between ($1.y and $1.y + 5).
>>
>> If you want to do it in Java then you can put everything into an array
>> and write a custom Comparator to do the calculation for you:
>> Collections.sort(array, new Comparator() { ...distance
>> calculation });
>>
>> Are these enough of hints?
>> -arturo
>>
>