JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>
<div id="googleMap" style="border: 2px solid #3872ac;"></div>
CSS
html, body, #googleMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
JavaScript
function initialize() {
var userCenter = new google.maps.LatLng(51.508742, -0.120850);
var userCenterMarker = new google.maps.Marker({
position: userCenter
});
userCenterMarker.setAnimation(google.maps.Animation.BOUNCE);
var mapProp = {
center: userCenter,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var bounds = new google.maps.LatLngBounds();
var markers = getMarkers();
$(markers).each(function() {
bounds.extend(this.position);
this.setMap(map);
});
userCenterMarker.setMap(map);
bounds.extend(userCenterMarker.getPosition());
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map,'bounds_changed', function() {
map.setZoom(map.getZoom()-1);
});
setTimeout(function() {
map.setCenter(userCenter);
}, 1500);
/*TODO:
How can i set the map center to the bouncing marker and zoom out or in so that all other markers are visible?
fitBounds centers/zooms to fit the markers in getMarkers()
Including userCenterMarker in the bounds doesn't help
*/
}
function getMarkers() {
var m1 = new google.maps.Marker({
position: new google.maps.LatLng(51.494834, -0.075445)
});
var m2 = new google.maps.Marker({
position: new google.maps.LatLng(51.483718, -0.050039)
});
var m3 = new google.maps.Marker({
position: new google.maps.LatLng(51.467022, -0.025921)
});
var m4 = new google.maps.Marker({
position: new google.maps.LatLng(51.465525, -0.022831)
});
var m5 = new google.maps.Marker({
position: new google.maps.LatLng(51.462069, -0.143166)
});
var m6 = new google.maps.Marker({
position: new google.maps.LatLng(51.455224, -0.169945)
});
var m7 = new google.maps.Marker({
position: new google.maps.LatLng(51.442386, -0.252342)
});
var m8 = new google.maps.Marker({
position: new google.maps.LatLng(51.442386, -0.106087)
});
var markers = [m1, m2, m3,...