Having trouble resetting the bounds after they are extended. I.e a user searches the map, the map zooms out to fit the markers. This works fine, as long as the map is extending (i.e bounds.extend) however if the user puts a smaller radius in, the map just stays the same. This is expected, because it still fits the bounds which is what the fitBounds method checks for. However, obviously for aesthetic purposes it should zoom back in when a smaller radius of markers is present.
I have tried a few options, see these questions:
- Reset bounds on Google Maps API v3
- Reset Bounds on Google Map v3 API
- Google Maps API V3 fitbounds() zooms out but never in
The 3rd question has some excellent answers, most of which (for once in my programming life) I had managed to work out myself before resorting to a stack overflow search. Unfortunately none of them are working.
I have tried various things in various places:
bounds = null;
delete bounds;
bounds = new google.maps.LatLngBounds(null);
Have also tried calling map.setZoom(20) before calling fitBounds to force it to have to zoom out, but that isn't helping either. This tells me that it's got to be something to do with the bounds variable not being emptied somehow.
In which case, perhaps I am looping in the wrong place, or setting the bounds to null at the wrong point, or have the bounds variables in the wrong scope etc.
I have also tried a few things in the console on the browser to debug but that hasn't helped me.
Code:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=AIzaSyC04mFN3hiFMiZyyYb6TZNMW4ucUtKF5wE&libraries=places®ion=GB"></script>
<script type="text/javascript">
var geocoder;
var map;
var search_coordinates;
var markers = [];
var bounds = new google.maps.LatLngBounds();
$('#matching_results').hide();
function initialize() {
var center = new google.maps.LatLng(51.508515,-0.125487)
var input = document.getElementById('location');
var autocomplete = new google.maps.places.Autocomplete(input, options);
var options = {
types: [],
componentRestrictions: {country: 'uk'}
};
var mapOptions = {
zoom:13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
geocoder = new google.maps.Geocoder();
function customMarker(category_id) {
switch (category_id) {
case 1:
return "<%= image_path("marker_icons/hotel.png") %>";
case 2:
return "<%= image_path("marker_icons/meeting.png") %>";
case 3:
return "<%= image_path("marker_icons/bar_restaurant.png") %>";
case 4:
return "<%= image_path("marker_icons/healthclub.png") %>";
case 5:
return "<%= image_path("marker_icons/academic.png") %>";
case 6:
return "<%= image_path("marker_icons/civic.png") %>";
case 7:
return "<%= image_path("marker_icons/cinema_theatre.png") %>";
case 8:
return "<%= image_path("marker_icons/historic.png") %>";
case 9:
return "<%= image_path("marker_icons/gallery.png") %>";
case 10:
return "<%= image_path("marker_icons/theme_park.png") %>";
break;
default:
}
}
function addMarker(location) {
var point = new google.maps.LatLng(location.latitude, location.longitude);
var marker = new google.maps.Marker({
position: point,
map: map,
title: name,
icon: customMarker(location.venue_category_id)
});
markers.push(marker);
bound = new google.maps.LatLngBounds(null);
for(var i in markers)
{
bounds.extend(markers[i].getPosition());
map.fitBounds(bounds);
}
}
function removeMarker(marker) {
marker.setMap(null);
}
function codeAddress() {
var address = document.getElementById('location').value;
geocoder.geocode( { 'address': address+" UK"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
search_coordinates = results[0].geometry.location;
$('#longitude').val(search_coordinates.lng());
$('#latitude').val(search_coordinates.lat());
fetchResults($('#search_form').serialize())
map.setCenter(results[0].geometry.location);
// var marker = new google.maps.Marker({
// map: map,
// position: results[0].geometry.location
// });
} else {
// alert('Geocode was not successful for the following reason: ' + status);
alert('Please add a valid town or postcode.')
}
});
}
// Does the initial search if that one is coming from the home page
var search_location = $('#location').val();
if ( search_location != '') {
codeAddress();
}
function fetchResults(params) {
$.getJSON( "/venues/search.json", params)
.done(function( data ) {
// Remove old Markers
$.each(markers, function(key, val) {
removeMarker(val);
});
// Add new markers
var venue_ids = [];
$.each(data, function(key, val) {
addMarker(val);
venue_ids.push(val.id);
});
// fit map to markers
// Change results text
$('#matching_empty').hide();
$('#matching_results').show();
$('#results_counter').text(data.length);
$('#enquiry_venue_ids_string').val("[" + venue_ids + "]");
console.log(data);
// gon.venues defines venues, is an array of objects straight from db
$( "#venue_names" ).empty();
$( "#venue_names" ).append("<div id='continued' style='height:620px; overflow:scroll;'></div>")
$.each(data, function(key, venue) {
if (venue.venue_images[0]) {
$("#continued").append("<div class='row' style='padding-top:10px;'><div class='col-md-12'><a href='http://www.wefindvenues.com/browse/" + (venue.id) + "' target='_blank' class='h5'>" + (venue.name) + "</a></div><div class='col-md-12'>" + (venue.address) + "<br /><strong>Max Capacity </strong>" + (venue.max_capacity) + "</div><div class='col-md-12'><img src='" + (venue.venue_images[0].url).replace(/'/g, "%27") + "' class='img-responsive'></div></div>");
console.log(venue.venue_images[0].url)
};
});
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ', ' + error;
console.log( "Request Failed: " + err);
});
}
$('#search_form').submit(function() {
codeAddress();
return false;
})
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Cheers for any help chaps