我们的系统中有100个用户,在注册时已经输入了他们的邮政编码,现在我需要的是如果我输入任何邮政编码,它应该给我输入的邮政编码和其他100个用户邮政编码之间的距离?
是否可以做,如果有人知道解决方案,请帮帮我?
最佳答案 我分两部分来做:
>地理编码脚本,运行一次,结果存储在持久高速缓存(例如数据库)中.这样您就可以避免达到速率限制并加快最终查找速度.
>用于计算距离的脚本,在需要时运行或缓存此脚本以构建存储每个邮政编码与所有其他邮政编码之间的距离的查找表.由于您只有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