Reputation: 173
I'm trying to show a certain area in a map in a responsive website. I want it to display the same area, when loaded, whatever is the window size, by zooming in and out. After some research I understood I need to use the fitBounds function of the Google Maps JS API, but can't get it to work. Here's my code so far:
<div id="map"></div><!--css rules to make it a 16/9 responsive box-->
<script src="https://maps.googleapis.com/maps/api/js?key=mykey" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(x, y), //any coordinates I put here don't matter, as I need the map to adjust using bounds, right?
zoom: 11
};
var bounds = google.maps.LatLngBounds(
new google.maps.LatLng(x, y), //SW coordinates here
new google.maps.LatLng(x, y) //NE coordinates here
);
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var bounds = map.getBounds();
google.maps.event.trigger(map, "resize");
map.fitBounds(bounds);
});
</script>
It seems the map is just showing the center position in the options, and ignoring the fitBounds call. What am I missing/doing wrong?
Upvotes: 1
Views: 3072
Reputation: 20162
Here is how it might be implemented (using jQuery window resize event):
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(x, y),
zoom: 11
};
var bounds = google.maps.LatLngBounds(
new google.maps.LatLng(x, y), //SW coordinates here
new google.maps.LatLng(x, y) //NE coordinates here
);
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.fitBounds(bounds);
// Listen for events after map initialization
$(window).resize(function() {
google.maps.event.trigger(map, 'resize');
});
google.maps.event.addListener(map, 'resize', function() {
var bounds = map.getBounds();
map.fitBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Upvotes: 2
Reputation: 7225
You are currently retrieving the bounds of the map before its had a chance to resize
You need to add an extra handler for the map resize event and then move your fitBounds code into that. Still keep your trigger of the map resize in the window resize handler.
Edit
You need to move your map variable outside of your initialize function so its globally accessible to your map listeners
Upvotes: 2