Two Google Maps Tips

Two Google Maps Tips

Centre a map on a collection of pins

The basic way to centre a Google Map is to give it co-ordinates of where you want the map to centre. But what if you have a collection of pin/markers and you want to show all of them but don't know beforehand where they will be.

The solution is to create a LatLngBounds object and for each of your pins call the extend method of your bounds object. Once this is done call fitBounds on your map.

1var bounds = new google.maps.LatLngBounds();
2
3$.each(mapMarkers(), function(index, value) {
4 bounds.extend(value.marker.position);
5});
6
7map.fitBounds(bounds);

Loading a map in a hidden div

The reason for doing this could be that you have a set of tabs and a non-visible one contains the Google Map. If you instantiate a Google Map when it isn't visible you end up with the smallest map size possible.

One popular solution for this is to only create the map when the tab is being displayed, which is a good option as it means the map is only loaded when it's viewed. However if your using something like Knockout to bind you've views to a model it may not be possible to attach an event to the tab change.

Google Maps actually have an event handler for just this scenario called resize. You simply need to trigger it at the point in which you can size the map.

1google.maps.event.trigger(map, 'resize')