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

时间:2013-08-07 07:14:23

标签: php geolocation zipcode

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

是否有可能做到,如果有人知道解决方案,请帮助我?

2 个答案:

答案 0 :(得分:2)

我分两部分来做这件事:

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

天气预报

<?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;
    }
}

计算距离

正如马克所说,这里有很多很好的例子,例如Measuring the distance between two coordinates in PHP

答案 1 :(得分:0)

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