在Google Maps API v3和MarkerWithLabel上添加多个事件侦听器

时间:2015-02-25 10:44:39

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

我想为每个标记添加一个点击该事件的事件。我使用lib" MarkerWithLabel"当我点击一个标记时,地图每次都会放大最后一个标记。

这是我的代码:

var map         = new google.maps.Map(document.getElementById('map-canvas')),
        bounds      = new google.maps.LatLngBounds(),
        marker      = [],
        grafxUrl    = $('#map-canvas').data('grafx'),
        image       = {
            url : grafxUrl + 'universal/icons/pin_locator.png',
            size: new google.maps.Size(24, 31),
            origin: new google.maps.Point(0,0),
            anchor: new google.maps.Point(12, 31)
        };

for (var i = 0; i < response.length; i++) {
        marker = new MarkerWithLabel({
            position: new google.maps.LatLng(response[i].fLatitude, response[i].fLongitude),
            map: map,
            icon : image ,
            title : (i+1)+' '+response[i].sName,
            labelContent: (i+1),
            labelAnchor: new google.maps.Point(3, 25),
            labelClass: "markerNum", // the CSS class for the label
        });
        google.maps.event.addListener(marker, 'click', function() {
            map.setZoom(15);
            map.setCenter(marker.position);
        });
        bounds.extend(marker.position);
        //now fit the map to the newly inclusive bounds
        map.fitBounds(bounds);
    }

我的剧本出了什么问题?

非常感谢。

1 个答案:

答案 0 :(得分:1)

以下是有关如何扩展边界对象以显示地图上所有标记的完整示例。

function initialize() {

    var southWest = new google.maps.LatLng(40.744656, -74.005966);
    var northEast = new google.maps.LatLng(34.052234, -118.243685);
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();

    var map = new google.maps.Map(document.getElementById("map-canvas"), {
        zoom: 12,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    // Create the bounds object
    var bounds = new google.maps.LatLngBounds();

    // Create random markers
    for (var i = 0; i < 100; i++) {

        // Calculate a random position
        var position = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(), southWest.lng() + lngSpan * Math.random());

        var marker = new google.maps.Marker({
            position: position,
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                map.setZoom(5);
                map.setCenter(marker.position);
            }
        })(marker, i));

        // Extend the bounds with the last marker position
        bounds.extend(position);
    }

    // Fit map to the extended bounds    
    map.fitBounds(bounds);
}

initialize();

这会在定义的边界(southWest / northEast coords)中创建100个随机标记,然后扩展边界对象,最后将地图拟合到此边界对象。了解如何定义标记变量(在for循环中)以及如何调用fitBounds()(在for循环之外)。这同样适用于您的代码。

以下是工作演示。希望这有帮助!

JSFiddle demo