gpt4 book ai didi

javascript - 使用 Google map 绘制半径内的点

转载 作者:行者123 更新时间:2023-11-28 01:46:20 30 4
gpt4 key购买 nike

我有一个包含一组特定地址的数据库,我想使用 Google Maps API 搜索半径范围内的所有地址并为其使用标记。

我从 PHP 获得的数据如下:

<tr>
<td><?php echo $row['firstName']; echo " "; echo $row['lastName'] ?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['city'];?></td>
<td><?php echo $row['state'];?></td>
<td><?php echo $row['zipcode'];?></td>
<td><?php echo $row['phoneNumber'];?></td>
</tr>

我正在使用以下地址创建纬度/经度:

<!-- Snippet to convert Address to Geo code using Google APIs Starts -->
<?php
$completeAddress = $row['address1'].",".$row['city'].",".$row['state'].",".$row['zipcode'];
$httpGetCallUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($completeAddress) . "&sensor=false";
$curlObject = curl_init();
curl_setopt($curlObject, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObject, CURLOPT_URL, $httpGetCallUrl);
$resultGeocodeJson = curl_exec($curlObject);
$json = json_decode($resultGeocodeJson, true);
$volunteerLat = $json['results'][0]['geometry']['location']['lat'];
$volunteerLng = $json['results'][0]['geometry']['location']['lng'];
curl_close($curlObject);
?>

但是,我无法添加按半径搜索的功能并在该半径内绘制标记。

添加标记的代码是:

function getMarkers() {
var contentString = "<?php echo $row['firstName'];?>" + " " + "<?php echo $row['lastName'];?>";
var myLatlng = new google.maps.LatLng(<?php echo $volunteerLat;?>, <?php echo $volunteerLng;?>);
//Map Marker Object initialization
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
//Adding map marker content
var infowindow = new google.maps.InfoWindow({
content: contentString
});
//Event listner for map marker
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}

最佳答案

假设您已经知道用户输入的地址的坐标(可以使用 google.maps.Geocoder 来实现)和半径。

有了这个,您就可以使用google.maps.geometry.spherical library中的computeDistanceBetween方法了。了解用户输入的地址与您的其他位置(标记)之间的距离。

对于以下示例代码,我假设数据库中的位置已加载,并且标记已生成并存储在 markers 数组中。用户输入的地址的LatLng已经计算出来并存储在address变量中,radius变量中的半径也是如此.

// markers already bound to the map.
var markers;
// LatLng calculated with Geocoder from the address entered by the user.
var address;
// radius (in meters) entered by the user.
var radius;

function MarkerIsInCircle(marker){
var position = marker.getPosition(),
// distance in meters between the marker and the address
distance = google.maps.geometry
.spherical.computeDistanceBetween(position, address);

return radius >= distance;
}
function UpdateMarkersVisibility(){

for(var i=0; i < markers.length; i++){
// show the markers in the circle. Hide the markers out the circle.
markers[i].setVisible(MarkerIsInCircle(markers[i]));
}
}

当用户单击搜索按钮时,您必须调用 UpdateMarkersVisibility 方法,并且您已完成计算他输入的地址的 LatLng

注意:此代码尚未经过测试,但应该可以正常工作并实现您想要的效果。

关于javascript - 使用 Google map 绘制半径内的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20263895/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com