我有一个包含特定地址集的数据库,我想使用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);
});
}
答案 0 :(得分:1)
假设您已经拥有用户输入的地址坐标(您可以通过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
方法。
注意:此代码尚未经过测试,但应该可以正常工作并实现您的目标。