i center google map based on dynamically loaded markers. have seen use of 'bounds' , tried implement fit bounds, haven't been able apply correctly map. here code:
var mapstart = new google.maps.latlng(41.664723,-91.534548); var markers; var map; var infowindow = new google.maps.infowindow({maxwidth: 650}); function initialize() { markers = new array(); var mapoptions = { zoom: 15, maptypeid: google.maps.maptypeid.roadmap, center: mapstart }; map = new google.maps.map(document.getelementbyid("map"), mapoptions); $("#map_list ul li").each(function(index) { var marker = new google.maps.marker({ position: new google.maps.latlng($(this).children(".marker_long").text(), $(this).children(".marker_lat").text()), map: map, animation: google.maps.animation.drop, title : $(this).children(".marker_title").text(), brief: $("div.infowindow", this).html() }); google.maps.event.addlistener(marker, 'click', function() { infowindow.setcontent(marker.brief); infowindow.open(map, marker); }); markers.push(marker); }); }
this easy, in initialize method create bounds object, , extend bounds object each marker's position. finally, call map.fitbounds() on map object center , fit map markers:
function initialize() { ... var bounds = new google.maps.latlngbounds(); ... $("#map_list ul li").each(function(index) { ... //extend bounds include each marker's position bounds.extend(marker.position); ... }); ... //now fit map newly inclusive bounds map.fitbounds(bounds); ... } //(optional) restore zoom level after map done scaling var listener = google.maps.event.addlistener(map, "idle", function () { map.setzoom(15); google.maps.event.removelistener(listener); });
Comments
Post a Comment