dcolumbus dcolumbus - 17 days ago 5
Javascript Question

Google Maps: Centering Map on Dynamic Markers

I'm trying to ensure that the map is centered on the markers that have been dynamically added. The markers themselves are added to the map perfectly, but the map keep centering in the middle of the pacific ocean. I don't think initiating the bounds in the proper order.

Here is my map code:

<script>

var map, bounds, locations, markers;

function initMap() {

map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: -28.024, lng: 140.887}
});

google.maps.event.addListenerOnce(map, 'idle', function() {
bounds = new google.maps.LatLngBounds();
loadAllProperties();
});

}

function loadAllProperties() {

$.post("/wp-admin/admin-ajax.php", {action: 'get_all_properties'}, function(result) {
locations = JSON.parse(result);
createMarkers();
});

}

function createMarkers() {

var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

markers = locations.map(function(location, i) {

return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});

bounds.extend(location);

});

map.fitBounds(bounds);

// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}

</script>

Answer

You are returning the marker before you extend the bounds... so the bounds is always empty. Reorder the code to extend the bounds first.

function createMarkers() {
    var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    markers = locations.map(function(location, i) {
        bounds.extend(location);
        return new google.maps.Marker({
            position: location,
            label: labels[i % labels.length]
        });
    });
    map.fitBounds(bounds);
    // Add a marker clusterer to manage the markers.
    var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
Comments