Set automatic Zoom to fit all markers on Map using JavaScript in Google Maps API V3

alex0230
 
on May 21, 2021 11:02 PM
920 Views

Is it posible to automaticaly make zoom wich will be better to show all markers.

Thank you very much.

Bind (Populate) Google Map Marker from Address using C# and VB.Net in ASP.Net

 

 

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on May 22, 2021 12:05 AM
on May 22, 2021 12:06 AM

Hi alex0230,

Google Maps API provides a LatLngBounds object to which you can add multiple LatLng objects. Then you can pass this to fitBounds() function to set the automatic zoom.

HTML

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_Key"></script>
<script type="text/javascript">
    var markers = [
        <asp: Repeater ID="rptMarkers" runat="server">
            <ItemTemplate>
            {
                "title": '<%# Eval("Name") %>',
                "lat": '<%# Eval("Latitude") %>',
                "lng": '<%# Eval("Longitude") %>',
                "description": '<%# Eval("Description") %>'
            }
            </ItemTemplate>
            <SeparatorTemplate>
                ,
            </SeparatorTemplate>
        </asp: Repeater >
    ];
</script>
<script type="text/javascript"> 
    window.onload = function () {
        var infoWindow = new google.maps.InfoWindow();
        var map = new google.maps.Map(document.getElementById("dvMap"), {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        //Create LatLngBounds object.
        var latlngbounds = new google.maps.LatLngBounds();
        for (var i = 0; i < markers.length; i++) {
            var data = markers[i]
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.title
            });
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent("<div style = 'width:200px;min-height:40px'>" + data.description + "</div>");
                    infoWindow.open(map, marker);
                });
            })(marker, data);
            latlngbounds.extend(marker.position);
        }

        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);
    }
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>

For more details refer below article.

Google Maps API V3: Center and Zoom to fit all markers on Google Maps