Google地图:动态标记中心地图

时间:2016-11-15 17:39:39

标签: javascript google-maps google-maps-api-3 bounds

我正在尝试确保地图以已动态添加的标记为中心。标记本身完美地添加到地图中,但地图始终位于太平洋中部。我不认为以正确的顺序启动界限。

这是我的地图代码:

<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>

1 个答案:

答案 0 :(得分:0)

在扩展边界之前返回标记...因此边界始终为空。重新排序代码以扩展边界。

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'});
}