谷歌地图自动适应(自动中心和自动缩放)不起作用

时间:2012-09-10 11:09:08

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

我在使用fitBounds地图方法的地图上遇到问题,这应该给出适当的缩放并使地图居中,为其提供latlon数组。这是代码:

<script type="text/javascript"
    src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>


<div id="map_canvas">

<script type="text/javascript">
    var map;
    var bounds = new google.maps.LatLngBounds(null);

    function initialize() {
        var mapOptions = {       

            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map =  new google.maps.Map(document.getElementById("map_canvas"), mapOptions);



        <?php
        foreach ($this->getProductCollection() as $_e):
            $event = Mage::getModel('catalog/product')->load($_e->getId());
            ?>
                var loc = new google.maps.LatLng("<?php echo $event->getEventLocationLatitude(); ?>","<?php echo $event->getEventLocationLongitude(); ?>");
                 bounds.extend(loc);
                addMarker(loc, '<?php echo $event->getName(); ?>', "active");
                bounds.extend(loc);

        <?php endforeach; ?>


        map.fitBounds(bounds);
        map.panToBounds(bounds);


    }


function addMarker(location, name, active) {          
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        title: name,
        status: active
    });

}



jQuery.noConflict();

jQuery(document).ready(function(){
    initialize();
});
</script>

标记已正确放置在地图上,但我可以获得最大缩放:

enter image description here

任何帮助?

1 个答案:

答案 0 :(得分:33)

我在这里更新了你的小提琴:http://jsfiddle.net/KwayW/1/

现在按预期工作。

以下是完整代码(将其另存为test.html并在浏览器中打开):

<style>#map_canvas { width:500px; height: 400px; }</style>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

<div id="map_canvas"></div>

<script>
var map;
var markersArray = [];
var image = 'img/';
var bounds = new google.maps.LatLngBounds();
var loc;

function init(){
    var mapOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP };
    map =  new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    loc = new google.maps.LatLng("45.478294","9.123949");
    bounds.extend(loc);
    addMarker(loc, 'Event A', "active");

    loc = new google.maps.LatLng("50.83417876788752","4.298325777053833");
    bounds.extend(loc);
    addMarker(loc, 'Event B', "active");

    loc = new google.maps.LatLng("41.3887035","2.1807378");
    bounds.extend(loc);
    addMarker(loc, 'Event C', "active");

    map.fitBounds(bounds);
    map.panToBounds(bounds);    
}

function addMarker(location, name, active) {          
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        title: name,
        status: active
    });
}

$(function(){ init(); });
</script>
相关问题