Reputation: 97
I want to center Google Map based on dynamically loaded markers. Right now I am displaying two markers on the map (see script.js file):
$mapster.mapster('addMarker', {
location: 'Golden Gate Bridge, San Francisco, CA',
content: 'Example text 2'
});
$mapster.mapster('addMarker', {
lat: 37.751350,
lng: -122.485833,
content: '<div style="color: #f00;">Example text 1</div>'
});
Everything works fine, because I defined the coordinates for centering the map (see map-options.js file):
mapster.MAP_OPTIONS = {
center: {
lat: 37.791350,
lng: -122.435883
},
zoom: 10,
disableDefaultUI: false,
scrollwheel: true,
draggable: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM,
style: google.maps.ZoomControlStyle.DEFAULT
},
panControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
},
cluster: {
options: {
styles: [{
url: 'https://raw.githubusercontent.com/googlemaps/v3-utility-library/master/markerclusterer/images/m2.png',
height: 56,
width: 55
//textColor: '#000'
//textSize: 12
}, {
url: 'https://raw.githubusercontent.com/googlemaps/v3-utility-library/master/markerclusterer/images/m1.png',
height: 56,
width: 55
//textColor: '#000'
//textSize: 12
}]
}
},
geocoder: true
};
How could I center my Google Map based on any loaded markers? I basically want to achieve something like this: Center a Google Map based on Markers
Here is my code: https://plnkr.co/edit/sduZKBXIIijhnkCIpSoR?p=preview
Upvotes: 1
Views: 2567
Reputation: 106
As described in the post you linked, you'll want to add the coordinates to the bounds
object as you add them, and then call fitBounds(bounds)
on that. See documentation.
Try following this control flow:
let location1 = new google.maps.LatLng(lat, lng);
let location2 = new google.maps.LatLng(lat, lng);
let location3 = new google.maps.LatLng(lat, lng);
let marker = new google.maps.Marker({
position: location1,
map: map
});
marker = new google.maps.Marker({
position: location2,
map: map
});
marker = new google.maps.Marker({
position: location3,
map: map
});
let bounds = new google.maps.LatLngBounds();
bounds.extend(location1);
bounds.extend(location2);
bounds.extend(location3);
map.fitBounds(bounds);
If you have a long listing you'll likely want to do some iterating over an array or something instead.
Upvotes: 2