使用谷歌地图绘制半径内的点


Plot Points within a Radius using 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库中的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

注意:这段代码还没有经过测试,但应该可以正常工作并达到您想要的效果。