如何显示半径包含目标标记的Google地图标记?

时间:2019-03-05 14:08:32

标签: javascript php mysql google-maps

我正在为这个问题绞尽脑汁。我有一个存储位置的数据库,每个位置都有一个纬度,经度和半径。我要做的是显示具有给定中心(用户位置)的地图,如果用户位置落在商店位置半径的任何半径内,则显示这些商店。如果商店半径未触及中心(用户的位置),则不显示商店。

我当前正在使用IP GEO LOCATION来获取访客的ip地址,并返回纬度和经度。然后根据用户的位置,查询数据库:

select s.street, s.city, s.latitude, s.longitude, s.radius, sa.north, 
sa.east, sa.south, sa.west from shops as s inner join service_areas as sa on 
s.id = sa.shop_id where 32.931354 between sa.south and sa.north and 
-97.095583 between sa.west and sa.east

北,南,东,西的值是从我几年前做过的这个php脚本生成的。

<?php

include "dbconnect.php";

$query="select id, latitude, longitude, radius from shops where state = 'Colorado';";
$rs=$mysqli->query($query);

while($r=$rs->fetch_object()) {
$sho_id=$r->id;
$lat=$r->latitude;
$lng=$r->longitude;
$radius=$r->radius;
$north=-90;
$east=-180;
$south=90;
$west=180;

$circlePolygon=createCirclePolygon($lat,$lng,$radius);

$polygon=array();

foreach($circlePolygon as $cPoint) {
if($cPoint['lat']<$south) $south=$cPoint['lat'];
if($cPoint['lat']>$north) $north=$cPoint['lat'];
if($cPoint['lng']>$east) $east=$cPoint['lng'];
if($cPoint['lng']<$west) $west=$cPoint['lng'];
$polygon[]=implode(",", $cPoint);
}
$polygon=implode(" ", $polygon);
$fields="shop_id=$sho_id, north=$north, south=$south, east=$east, west=$west, polygon='$polygon'";
$query="insert into service_areas set $fields on duplicate key update $fields;";
$mysqli->query($query);
if($mysqli->error) {
echo "ERROR: $mysqli->error\n";
}
echo "done<br/>";
}
echo "complete";

function createCirclePolygon($lat, $lng, $radius) {
$pointArray=array();
$d2r = pi() / 180;
$clat = ($radius / 3963.189) / $d2r; // miles
$clng = $clat / cos($lat * $d2r);
for($ang=0;$ang<=360;$ang+=10) {
$a=$ang*$d2r;
$plat=$lat+($clat*sin($a));
$plng=$lng+($clng*cos($a));
$point=array("lat"=>$plat,"lng"=>$plng);
array_push($pointArray,$point);
}
return $pointArray;
}
?>

我一直认为这是可行的,直到我运行了上面的查询。如果查看所附图像,您将看到一个蓝色标记(用户),该标记不在红色标记的任何半径内。红色标记唯一应显示的是半径是否触及蓝色标记。 (红色标记周围的半径是由javascript仅使用纬度,经度和半径值生成的)

Texas Shops

最后,如果查看数据库的附加屏幕截图,您将看到我具有上述脚本生成的北,东,西和南坐标。但是令我感到困惑的是,目标标记的(蓝色)纬度和经度确实落在北,南,东和西值之内。这让我想知道在每个标记周围生成圆的坐标的脚本是否不正确。

Database Screen Shot

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么您正在尝试查找所有半径范围内具有用户位置的商店吗?如果是,请尝试此查询(未经测试)。

SELECT s.street, s.city, s.latitude, s.longitude, s.radius, sa.north, sa.east, sa.south, sa.west, ( 3959 * acos( cos( radians(32.931354) ) * cos( radians( s.latitude ) ) * cos( radians( s.longitude ) - radians(-97.095583) ) + sin( radians(32.931354) ) * sin( radians( s.latitude ) ) ) ) AS distance
FROM shops AS s
WHERE distance <= s.radius

您需要相应地替换值。

查询使用haversine formula,我引用了Wikipedia:

  

haversine公式根据球的两个点的经度和纬度确定球上两个点之间的大圆距离。