使用邮政编码完成两个地方之间的距离(英里)



我们的系统中有100个用户,在注册时他们已经输入了他们的邮政编码,现在我需要的是,如果我输入了任何邮政编码,它应该会给我输入的邮政编码和其他100个用户的邮政编码之间的距离的结果?

如果有人知道解决方案,可以帮我吗?

我会分两部分来完成:

  • 一个地理编码脚本,运行一次,结果存储在持久缓存(例如数据库)中。这样可以避免达到速率限制,并加快最终查找的速度
  • 用于计算距离的脚本,在需要时运行或缓存该脚本,以构建一个查找表,存储每个邮政编码与所有其他邮政编码之间的距离。由于您只有100个zip,所以这个查找表不会很大

地理编码

<?php
// Script to geocode each ZIP code. This should only be run once, and the
// results stored (perhaps in a DB) for subsequent interogation.
// Note that google imposes a rate limit on its services.
// Your list of zipcodes
$zips = array(
    '47250', '43033', '44618'
    // ... etc ...
);
// Geocode each zipcode
// $geocoded will hold our results, indexed by ZIP code
$geocoded = array();
$serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false";
$curl = curl_init();
foreach ($zips as $zip) {
    curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip)));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $data = json_decode(curl_exec($curl));
    $info = curl_getinfo($curl);
    if ($info['http_code'] != 200) {
        // Request failed
    } else if ($data->status !== 'OK') {
        // Something happened, or there are no results
    } else {
        $geocoded[$zip] =$data->results[0]->geometry->location;
    }
}

计算距离

正如Mark所说,有很多很好的例子,比如在PHP 中测量两个坐标之间的距离

有一个邮政编码为API的程序可以做到这一点-http://zipcodedistanceapi.redline13.com/API.

最新更新