How to find nearest cities in a given radius?

前端 未结 6 1903
遇见更好的自我
遇见更好的自我 2020-12-31 15:41

Do you know some utility or a web site where I can give US city,state and radial distance in miles as input and it would return me all the cities within that radius?

<
6条回答
  •  盖世英雄少女心
    2020-12-31 16:35

    Here is how I do it.

    You can obtain a list of city, st, zip codes and their latitudes and longitudes. (I can't recall off the top of my head where we got ours)

    edit: http://geonames.usgs.gov/domestic/download_data.htm like someone mentioned above would probably work.

    Then you can write a method to calculate the min and max latitude and longitudes based on a radius, and query for all cities between those min and max. Then loop through and calculate the distance and remove any that are not in the radius

    double latitude1 = Double.parseDouble(zipCodes.getLatitude().toString());
    double longitude1 = Double.parseDouble(zipCodes.getLongitude().toString());
    
    //Upper reaches of possible boundaries
    double upperLatBound = latitude1 + Double.parseDouble(distance)/40.0;
    double lowerLatBound = latitude1 - Double.parseDouble(distance)/40.0;
    
    double upperLongBound = longitude1 + Double.parseDouble(distance)/40.0;
    double lowerLongBound = longitude1 - Double.parseDouble(distance)/40.0;
    
    //pull back possible matches
    SimpleCriteria zipCriteria = new SimpleCriteria();
    zipCriteria.isBetween(ZipCodesPeer.LONGITUDE, lowerLongBound, upperLongBound);
    zipCriteria.isBetween(ZipCodesPeer.LATITUDE, lowerLatBound, upperLatBound);
    List zipList = ZipCodesPeer.doSelect(zipCriteria);
    ArrayList acceptList = new ArrayList();
    
    if(zipList != null)
    {
        for(int i = 0; i < zipList.size(); i++)
        {
            ZipCodes tempZip = (ZipCodes)zipList.get(i);
            double tempLat = new Double(tempZip.getLatitude().toString()).doubleValue();
            double tempLon = new Double(tempZip.getLongitude().toString()).doubleValue();
            double d = 3963.0 * Math.acos(Math.sin(latitude1 * Math.PI/180) * Math.sin(tempLat * Math.PI/180) + Math.cos(latitude1 * Math.PI/180) * Math.cos(tempLat * Math.PI/180) *  Math.cos(tempLon*Math.PI/180 -longitude1 * Math.PI/180));
    
            if(d < Double.parseDouble(distance))
            {
                acceptList.add(((ZipCodes)zipList.get(i)).getZipCd());  
            }
        }
    }
    

    There's an excerpt of my code, hopefully you can see what's happening. I start out with one ZipCodes( a table in my DB), then I pull back possible matches, and finally I weed out those who are not in the radius.

提交回复
热议问题