duanhuan3012 2011-12-18 05:02
浏览 22
已采纳

PHP中的邮政编码邻近度计算

I've seen all sorts of "store locator"-type solutions on the Web for finding, for example, stores within a given radius of a particular Zip Code, and they have fancy maps that display the nearest stores, etc. Many use Google Maps or other databases, but many also rely on exact latitude and longitude conversions, etc. But that's all overkill for my project.

In my case, I'm just processing orders on the back end (using PHP) and I already have a list of all the ZIP Codes of all of my vendors' warehouses.

I simply want my customer to provide their Zip Code and with a single call I'd like to get back a sorted list of the warehouses nearest to my customer. Zip Codes are good enough - I don't wanna bother with latitude and longitude.

Any ideas?

  • 写回答

1条回答 默认 最新

  • douyiji3919 2011-12-18 05:10
    关注

    You should download Popular Data's ZIP code database.

    With this, you can use the following to calculate distance.

    function calc_distance($point1, $point2)
    {
        $radius      = 3958;      // Earth's radius (miles)
        $deg_per_rad = 57.29578;  // Number of degrees/radian (for conversion)
    
        $distance = ($radius * pi() * sqrt(
                    ($point1['lat'] - $point2['lat'])
                    * ($point1['lat'] - $point2['lat'])
                    + cos($point1['lat'] / $deg_per_rad)  // Convert these to
                    * cos($point2['lat'] / $deg_per_rad)  // radians for cos()
                    * ($point1['long'] - $point2['long'])
                    * ($point1['long'] - $point2['long'])
            ) / 180);
    
        return $distance;  // Returned using the units used for $radius.
    }
    

    Above was stolen from Adam Bellaire's answer in Calculating distance between zip codes in PHP. After doing this calculation, you can simply sort the results.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?