I'm currently having an issue with my google maps implementation and I was hoping I could get some help from the S.O. google maps community.
Currently I'm creating a map adding a bunch of markers and then fit the map to the bounds of the markers. However when the map is displayed only half of the map has been updated by the map.fitBounds(bounds).
I'm not sure how to solve for this. I've never seen a map partially zoomed like this before.
Thanks in advance to everyone who submits a response!
Here is the code to create the map:
<script>
var markersData = [
@if(count($properties) > 0)
@foreach($properties as $property)
@if($property->lat == 0 && $property->lng == 0)
// Don't add the marker
@else
{
lat: "{{ $property->lat }}",
lng: "{{ $property->lng }}",
address: "{{ $property->street }}",
citystatezip: "{{ $property->city.', '.$property->state.' '.$property->zip }}"
},
@endif
@endforeach
@endif
];
function displayMarkers(){
if(markersData.length > 0){
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markersData.length; i++){
var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
var address = markersData[i].address;
var citystatezip = markersData[i].citystatezip;
createMarker(latlng, address, citystatezip);
bounds.extend(latlng);
}
// JUST ADDED THIS CODE AND ITS WORKING NOW
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
this.setZoom(map.getZoom()-1);
if (this.getZoom() > 15) {
this.setZoom(15);
}
});
map.fitBounds(bounds);
}else{
var center = new google.maps.LatLng( "{{$county->lat}}", "{{ $county->lng }}" );
map.panTo(center);
}
}
function createMarker(latlng, address, citystatezip){
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: address,
});
google.maps.event.addListener(marker, 'click', function() {
var iwContent = '<div id="iw_container">' +
'<div class="iw_title">' + address + '</div>' +
'<div class="iw_content">' + citystatezip + '</div></div>';
infoWindow.setContent(iwContent);
infoWindow.open(map, marker);
});
}
function initialize() {
var mapOptions = {
zoom: 9,
mapTypeId: 'roadmap',
scrollwheel: false
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
displayMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>