RobertFrenette
RobertFrenette

Reputation: 627

Bind click event listener to map marker (using D3 and JS)

I'm following an example on the D3 site to add markers to a Google Map. The example is working, but now I'm trying to bind the click event handler to each marker using the following:

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

However, nothing is written to the console when I click any of the markers. Does anyone know where I'm going wrong here?

Thanks

Upvotes: 0

Views: 1887

Answers (1)

RobertFrenette
RobertFrenette

Reputation: 627

Note the fix (overlayMouseTarget) on the following lines:

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");

Upvotes: 3

Related Questions