Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
810 views
in Technique[技术] by (71.8m points)

web services - How to find the distance between two ZipCodes using Java Code?

My requirements are similar to this question, except the fact that I am prohibited to use the latitude and longitude values. I want to caluclate the "walking" distance between two zipcodes. Later I would also require to query "who is within X kms ?"

I am not sure whether it is achievable or not. Is it really possible to find the distance between two given zipcodes ? I don't want the answers which will work only for US/UK zip codes. I need a generic solution which will work for any two zipcodes of the world.

If the calculation of distance without using Langitude & longitude is not possible then can I get the Langitude / longitude values of a given ZIPCODE ? (amazing) but How ?

Any tutorial / example will be of great help..Since I am working on a commercial project cant use the Google Maps API. So please don't suggest any other licensed services.

Thanks in advance,

UPDATE one of the answers of this question suggests the use of MySQL or Postgress... Will that work for me..?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're interested, here's my java implementation of the haversine formula

/**
 * Calculates the distance in km between two lat/long points
 * using the haversine formula
 */
public static double haversine(
        double lat1, double lng1, double lat2, double lng2) {
    int r = 6371; // average radius of the earth in km
    double dLat = Math.toRadians(lat2 - lat1);
    double dLon = Math.toRadians(lng2 - lng1);
    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
       Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) 
      * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = r * c;
    return d;
}

I hereby donate this to the public arena under GPL :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...