Google Maps Centering and Zooming
OK fought this for a while yesterday so thought I would share. The original objective was to display a Google Map with pointers for all the locations on the map, the map would then be re-zoomed and centered so all points show. Sounds simple! After hours of fighting the system the big problem is Google Maps wants to have the map centered and zoomed before adding any pointers. Here’s my take on this, BTW this was built from various other authors code snippets but the combination of them to make it work is my original code:
First off you need a div to put the map into.
{code type=html}
<div id=’FacilityMap’ class=’MultipleFacilityMap’></div>
{/code}
I then added CSS to make the map the correct size:
{code type=css}
#FacilityMap *{
border:none;
}
#FacilityMap a{
font-weight:bold;
}
#FacilityMap a.more{
font-weight:normal;
text-decoration:underline;
}
.IndividualFacilityMap{
width: 450px;
height: 350px;
}
.MultipleFacilityMap{
width: 650px;
height: 550px;
}
{/code}
And then in javascript added the following code:
{code type=php}
function createMarker(point,title,html) {
var markerOpts = { title: title } ;
var marker = new GMarker(point, markerOpts );
GEvent.addListener(marker, “click”, function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
// Set up markers with info windows
var markers = [];
var bound = new GLatLngBounds();
<?php foreach( $FacilityMap as $FacilityInfo ) : ?>
var posn = new GLatLng(<?=$FacilityInfo[‘latitude’]?>,<?=$FacilityInfo[‘longitude’]?>);
var marker = createMarker(posn,”<?=$FacilityInfo[‘FacilityName’]?>”,'<div style=”width:240px”><a href=”<?=$FacilityInfo[‘DRC_URL’]?>”><?=$FacilityInfo[‘FacilityName’]?></a><br /><?=$FacilityInfo[‘streetaddress’]?><\/div>’)
markers.push( marker );
bound.extend( posn );
<?php endforeach; ?>
// Display the map, with some controls and set the initial location
var map = new GMap2(document.getElementById(“FacilityMap”));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
var level = map.getCurrentMapType().getBoundsZoomLevel(bound, map.getSize());
var ne = bound.getNorthEast();
var sw = bound.getSouthWest();
map.setCenter(new GLatLng((ne.lat() + sw.lat()) / 2.0 , (ne.lng() + sw.lng()) / 2.0 ), level);
map.enableDoubleClickZoom();
for ( i=0; i < markers.length; i++ )
{
map.addOverlay(markers[i]);
}
{/code}