我编写的代码是在搜索到的邮政编码50英里范围内进行半径搜索。如何更改此代码以仅查找最近的诊所位置,而不是诊所位置列表?因此,如果我输入科罗拉多州丹佛的邮政编码,我的位置主要位于纽约,宾夕法尼亚州和俄亥俄州,我如何才能到达俄亥俄州最近的位置?
/* RADIUS SEARCH - 50 MILES FROM THE ZIP CODE VARIABLE */
$zipcode=trim($_REQUEST['zipcode']);
//Find Out The Longitude & Latitude of Zipcode in existing database
$zcquery = "SELECT * FROM wp_nava5jxxyp_zipcodes WHERE zipcode = $zipcode";
$result = mysqli_query($dbc, $zcquery);
$row = mysqli_fetch_array($result);
$lat = $row['latitude'];
$long = $row['longitude'];
//Setting the Default Distance 50 Miles
// (Equation 1 / 69 = 0.0144927536231884 * 50 miles equals result below)
$miles = 0.7246376811594203;
/* Query To Search for all of the Zip Codes within the range */
$query = 'SELECT zipcode from wp_nava5jxxyp_zipcodes
WHERE latitude between ' . $lat . ' - ' . $miles . ' and ' . $lat . ' + ' . $miles . '
and longitude between ' . $long . ' - ' . $miles . ' and ' . $long . ' + ' . $miles;
$result = mysqli_query($dbc, $query);
//Put those zip codes into a variable array
$variabele = array();
while($row = mysqli_fetch_array($result))
{
if($row['zipcode'] != '')
$variabele[] = $row['zipcode'];
}
$zipcodelist = implode(', ', $variabele);
// Close Connection
mysqli_close($dbc);
//Query Database For Any Clinics that are included in zip code list
$args = array(
'posts_per_page' => 10,
'orderby' => 'post_title',
'order' => 'DESC',
'post_type' => 'clinics',
'meta_query' => array (
array (
'key' => 'cliniczipcode',
'value' => $zipcodelist,
'compare' => 'IN'
)
) );
// the query
$the_query = new WP_Query( $args );
答案 0 :(得分:0)
请参阅此Fastest Way to Find Distance Between Two Lat/Long Points
基本上,您计算到基础latlon的距离,按最短距离排序,并将项目放在最顶层。如果您不想打扰复杂的查询,也可以在代码中执行此操作。
关键词是“大圆距离”和“半正式公式”
修改
假设我在洛杉矶有一个兽医诊所数据库
Limehouse Veterinary Clinic 34.1534500122 -118.3630599976
LA Pet Clinic 34.0838623047 -118.3284454346
Bestfriends Animal Hospital 34.1692466736 -118.3970489502
我的基准坐标在好莱坞lat 34.092324,lon -118.337122
半正弦公式需要弧度而不是度数的坐标。
360度有2 pi的弧度 y弧度= 6.28319 * x度/ 360(求解y)
以下是半正式公式,其中r
2 r arcsin
是地球的半径:6,371,000米
-- haversine
-- latdif londif
-- 2 r arcsin [ sqrt[ sin^2(------) + cos(lat1) * cos(lat2) * sin^2(------) ] ]
-- 2 2
因此,为了获得我所在地附近最近的诊所,我可以使用此查询作为上述公式的翻译
select
name,
2 * 6371000 * ASIN(
sqrt(
SIN(6.28319 * (34.092324 - lat) / 360 / 2) * SIN(6.28319 * (34.092324 - lat) / 360 / 2)
+
COS( 6.28319 * 34.092324 / 360 ) * COS( 6.28319 * lat / 360 )
*
SIN(6.28319 * (-118.337122 - lon) / 360 / 2) * SIN(6.28319 * (-118.337122 - lon) / 360 / 2)
)
)
as dist_in_meters
from locations ORDER BY dist_in_meters;
给我
name dist_in_meters
LA Pet Clinic 1234.3897096551932
Limehouse Veterinary Clinic 7204.075434291492
Bestfriends Animal Hospital 10177.689847331932