I have set up a Google Map using API v3. The map has a number of markers with infoboxes attached. I am looking to set up a search box outside of the map for the user to input
To do a radius search with the API, use the Geometry Library google.maps.geometry.spherical.computeDistanceBetween method to calculate the distance between each marker and the geocoded result from the address. If that distance is less than the requested radius, show the marker, else hide it.
code assumes:
google.maps.Map object called map
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);
}
});
}
example