我想写一个php程序,从我的数据库400个点中随机选择16个gps点。
(点表: id -标题-纬度-经度)。
最新版本37.9824
lon -87.5781547
唯一需要的是16个随机点,每个点之间的距离至少为1 1km (找出1 1KM范围内的点)
这是一个选择药店的系统,每个药店之间的最小距离为1公里。我的数据库中有400家药店,每周我必须选择16家药店。我不能选择两家离得很近的药店。
示例:
如果程序返回3个药房A、B和C。
药店之间的差异必须是:
A和B=1公里
A和C=1公里
B和C=1公里
发布于 2012-03-21 14:47:37
让我们试一试,因为你只有400条记录,可能只需要几个小时……我还没有试过,但它可能会给你一个想法
$min =1;
$n =16;
$pharmas = fillUp();
// main function
function fillUp(){
$points = array();
while(count($points)< $n){
$tmp = getRandomPoint();
if(checkAll($tmp, $points){
$points[] = $tmp;
}
}
return $points; // after a few hours ??
}
// get a random point
// after all we might get lucky
function getRandomPoint(){
//...
// return array with ['latitude'] & ['longitude']
}
// check that all points meet the requirements
function checkAll($pt, $points){
foreach($points as $point){
if(distance($point, $pt) < $min {
return false;
}
}
return true;
}
// calculate the distance between 2 points
function distance ($point1, $point2, $uom='km') {
// Use Haversine formula to calculate the great circle distance
// between two points identified by longitude and latitude
switch (strtolower($uom)) {
case 'km' :
$earthMeanRadius = 6371.009; // km
break;
case 'm' :
$earthMeanRadius = 6371.009 * 1000; // km
break;
case 'miles' :
$earthMeanRadius = 3958.761; // miles
break;
case 'yards' :
case 'yds' :
$earthMeanRadius = 3958.761 * 1760; // miles
break;
case 'feet' :
case 'ft' :
$earthMeanRadius = 3958.761 * 1760 * 3; // miles
break;
case 'nm' :
$earthMeanRadius = 3440.069; // miles
break;
}
$deltaLatitude = deg2rad($point2['latitude'] - $point1['latitude']);
$deltaLongitude = deg2rad($point2['longitude'] - $point1['longitude']);
$a = sin($deltaLatitude / 2) * sin($deltaLatitude / 2) +
cos(deg2rad($point1['latitude'])) * cos(deg2rad($point2['latitude'])) *
sin($deltaLongitude / 2) * sin($deltaLongitude / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$distance = $earthMeanRadius * $c;
return $distance;
}发布于 2012-03-21 15:00:28
下面是一个即兴的回答:
我将首先使用笛卡尔距离公式创建一个视图,其中包含与您感兴趣的点最接近的对象列表,然后应用PHP代码来计算实际的球面距离。
@MY_LAT = 37.9824;
@MY_LONG = -87.5781547;
SELECT *, SQRT(
ABS((latitude - @MY_LAT) * (latitude - @MY_LAT) +
(longitude - @MY_LONG) * (longitude - @MY_LONG)))
AS DIST
FROM POINT_TABLE
ORDER BY DIST ASC从该视图中选择前n行,以获得距离您的“兴趣点”最近的16个点。要检查这些点是否在距参考点1公里的范围内,您可以在获得结果后编写一小段PHP代码。这应该会对您的代码片段有所帮助:
http://www.zipcodeworld.com/samples/distance.php.html
在这里,我在查询中使用了笛卡尔距离公式,其目的只是为了减少在PHP.x中应用球面距离公式所获得的记录数
https://stackoverflow.com/questions/9797690
复制相似问题