Google MAP API v3: Center & Zoom on displayed markers
Solution 1:
I've also find this fix that zooms to fit all markers
LatLngList: an array of instances of latLng, for example:
// "map" is an instance of GMap3
var LatLngList = [
new google.maps.LatLng (52.537,-2.061),
new google.maps.LatLng (52.564,-2.017)
],
latlngbounds = new google.maps.LatLngBounds();
LatLngList.forEach(function(latLng){
latlngbounds.extend(latLng);
});
// or with ES6:
// for( var latLng of LatLngList)
// latlngbounds.extend(latLng);
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
Solution 2:
In case you prefer more functional style:
// map - instance of google Map v3
// markers - array of Markers
var bounds = markers.reduce(function(bounds, marker) {
return bounds.extend(marker.getPosition());
}, new google.maps.LatLngBounds());
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
Solution 3:
Try this function....it works...
$(function() {
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
var latlng_pos=[];
var j=0;
$(".property_item").each(function(){
latlng_pos[j]=new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val());
j++;
var marker = new google.maps.Marker({
position: new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val()),
// position: new google.maps.LatLng(-35.397, 150.640),
map: map
});
}
);
// map: an instance of google.maps.Map object
// latlng: an array of google.maps.LatLng objects
var latlngbounds = new google.maps.LatLngBounds( );
for ( var i = 0; i < latlng_pos.length; i++ ) {
latlngbounds.extend( latlng_pos[ i ] );
}
map.fitBounds( latlngbounds );
});