我已经使用API v3设置了一个谷歌地图。该地图包含多个标记,并附有信息框。我希望在地图外面设置一个搜索框供用户输入地址,然后根据距离(例如半径搜索)返回最近的标记。
从API文档中我认为我需要使用Places服务。有人能指点我正确的方向吗?
我已经使用API v3设置了一个谷歌地图。该地图包含多个标记,并附有信息框。我希望在地图外面设置一个搜索框供用户输入地址,然后根据距离(例如半径搜索)返回最近的标记。
从API文档中我认为我需要使用Places服务。有人能指点我正确的方向吗?
要使用API进行半径搜索,请使用Geometry Library中的google.maps.geometry.spherical.computeDistanceBetween方法计算每个标记和由地址编码得到的结果之间的距离。如果该距离小于请求的半径,请显示该标记,否则隐藏它。
代码假设:
function codeAddress() {
var address = document.getElementById('address').value;
var radius = parseInt(document.getElementById('radius').value, 10)*1000;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if (circle) circle.setMap(null);
circle = new google.maps.Circle({center:marker.getPosition(),
radius: radius,
fillOpacity: 0.35,
fillColor: "#FF0000",
map: map});
var bounds = new google.maps.LatLngBounds();
for (var i=0; i<gmarkers.length;i++) {
if (google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),marker.getPosition()) < radius) {
bounds.extend(gmarkers[i].getPosition())
gmarkers[i].setMap(map);
} else {
gmarkers[i].setMap(null);
}
}
map.fitBounds(bounds);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}