将click事件监听器绑定到映射标记(使用D3和JS)

时间:2014-05-01 23:19:35

标签: javascript d3.js

我在D3网站上按照示例向Google地图添加标记。该示例正在运行,但现在我尝试使用以下方法将click事件处理程序绑定到每个标记:

d3.json("stations.json", function(data) {
    var overlay = new google.maps.OverlayView();

    // Add the container when the overlay is added to the map.
    overlay.onAdd = function() {
        var layer = d3.select(this.getPanes().overlayLayer).append("div")
        .attr("class", "stations");

        // Draw each marker as a separate SVG element.
        // We could use a single SVG, but what size would it have?
        overlay.draw = function() {
        var projection = this.getProjection(),
        padding = 10;

        var marker = layer.selectAll("svg")
        .data(d3.entries(data))
        .each(transform) // update existing markers
        .enter().append("svg:svg")
        .each(transform)
        .attr("class", "marker")
        .on("click", function(d) { console.log(d); });

        // Add a circle.
        marker.append("svg:circle")
        .attr("r", 4.5)
        .attr("cx", padding)
        .attr("cy", padding);

        // Add a label.
        marker.append("svg:text")
        .attr("x", padding + 7)
        .attr("y", padding)
        .attr("dy", ".31em")
        .text(function(d) { return d.key; });

        function transform(d) {
            d = new google.maps.LatLng(d.value[1], d.value[0]);
            d = projection.fromLatLngToDivPixel(d);
            return d3.select(this)
            .style("left", (d.x - padding) + "px")
            .style("top", (d.y - padding) + "px");
            }
        };
    };

    // Bind our overlay to the map…
    overlay.setMap(map);
});

但是,当我单击任何标记时,没有任何内容写入控制台。有谁知道我在哪里出错?

由于

1 个答案:

答案 0 :(得分:3)

请注意以下行中的修正(overlayMouseTarget):

overlay.onAdd = function() {
    //var layer = d3.select(this.getPanes().overlayLayer).append("div").attr("class", "stations");
    var layer = d3.select(this.getPanes().overlayMouseTarget).append("div").attr("class", "stations");