I use the following code to set markers on my map:
var latLngs = []
$.each(locations.markers, function(i, m){
var myLatLng = new google.maps.LatLng(m.latitude, m.longitude);
latLngs[i] = myLatLng
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
shadow: shadow,
icon: image,
shape: shape,
title: m.city,
zIndex: i
});
})
The markers show up on my map. Now I would like to center & zoom the map on these markers. How can I accomplish this? I have tried:
map.fitBounds(getBoundsForLatLngs(latLngs));
The console.log of latLngs gives out:
[(46.793182, 7.146903) { b=46.793182, more...}, (46.8077779, 7.1709386) { b=46.8077779, more...}]
But it doesn't seem to work, and I get no error in the console. What am I doing wrong?
This question is related to
javascript
jquery
google-maps-api-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 );
});
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);
for center and auto zoom on display markers
// map: an instance of google.maps.Map object
// latlng_points_array: an array of google.maps.LatLng objects
var latlngbounds = new google.maps.LatLngBounds( );
for ( var i = 0; i < latlng_points_array.length; i++ ) {
latlngbounds.extend( latlng_points_array[i] );
}
map.fitBounds( latlngbounds );
Source: Stackoverflow.com