Tag Archives: maps

Propagating events through element layers as rendered in page

I am currently working on a project involving Mapbox and Leaflet.  As part of a performance enhancement feature I was implementing I came across an interesting issue on event handling in the map layers.

I am using D3 to implement a light-weight custom Leaflet layer to better handle large FeatureCollections.  From the server I receive a GeoJSON FeatureCollection of features that includes shapes, markers, and text that I need to render to the map.  In my custom layer the different feature types in the collection need to be placed into different map panes (overlay, markers, and popup panes) to maintain the proper layering.  These “panes” are implemented as sibling DIVs as oppose to being in a tree layout.

Depending on the purpose of the map, any one of these layers can be enabled to accept click events (and possibly more than one).  The issue I encountered was that only the top layer would actually accept the click — this layer typically being the marker or text.  If that layer was deemed “un-clickable” then nothing would happen because the event propagated up the DOM tree and not to the sibling “panes.”

What I need to handle is passing this event to all of the sibling panes to see who could handle it.  But I cannot just broadcast it!  I need to pass it to the panes in the order they are rendered on the page and only to each pane’s feature located at the exact mouse-click position.

Some background…

In mapbox maps there is an overlay pane for adding new overlay shapes, like polygons.  There is also the marker pane, for things like “pins” on point locations.  There are still other panes, like “popups” for additional items.  Because these panes are sibling divs and not hierarchical event handling can be tricky.

The FeatureCollection I receive can contain features mapping to 1..n of these panes.  So what I can end up with is multiple overlapping features on a map — e.g., a shape, a marker (or more) on that shape, and a text label on that marker.  These features know nothing about their layer or other features, but do contain information in their properties so  I can determine if the feature is clickable.

Because the layers are actually laid out in the DOM as absolute-positioned sibling ‘div’ elements I cannot use the browser’s event propagation.   What I need for my situation is information about the stack of elements as layered on the page by the renderer at the X/Y point of the mouse click.  An example of what i mean by the “layers” of the DOM elements is nicely displayed in this picture:

Layers on the google home page.
Element layers as rendered on the google home page.

I took this screen shot using a cool firefox plugin called Tilt, although I found out after I installed it that the firefox dev tools already has it built in as “3D View.”   Because everyone is familiar with it, I used Google’s homepage to illustrate stacked DOM element layers as I am working with such layers on the map.  The actual map did not illustrate this as well since the Tilt plugin was not splitting out SVG trees into layers.

To propagate the event the way  I need to do it, I need to dig through these layers top-to-bottom at the coordinates of the mouse click regardless of how these layers are represented in the DOM tree — CSS can move them anywhere.  Its like driving a skewer through the page at the point of click and then peeling back the shish kabob of features until i get to the one that can process the event.

A solution emerges…

It turns out there is a very useful document function for this called document.elementFromPoint(x,y).  This function will take an X/Y coordinate and return the element first encountered at those coordinates.  This is great, but I already know the first encountered element… it’s the one in the event that is triggered when the mouse click occurs.  So this alone does not help much, especially since it is only available on document and not sub-elements in order to process sub-trees.  But, it is a start…

So digging deeper I found that I could manipulate the results of the elementFromPoint function using very simple CSS!  When an element has the style “pointer-events: none,” click events pass through the element to what ever is next behind it.  This style alone could solve this issue sometimes if you are able to throw it around multiple places, but in the case of creating a custom layer I need to be more surgical so i don’t affect other layers that may be added to the map.  When this style is on an element, it is also skipped by the elementFromPoint function!  

Aside: Another page on quirksmode says you can do this with “display: none” as well, but that would change the page visually…  

A happy merging of these two ideas and a dose of recursion solves the problem.  All of the features I add to the page have a click handler that routes the click to a special function that does the following:

  1. Get the elementFromPoint from the X/Y coordinates in the mouse event.
  2. Check if this element is
    1. one of my features, which means it contains data (i.e., a “__data__” property) and has a key/value attribute I put on the element specifically for matching.
    2. is clickable (a separate function to determine this based on whatever…)
    3. is a child of some baseline element that I know all of my elements are inside.  This is to fail faster instead of parsing a lot of the page I don’t care about.  The base element for me, inside the mapbox map, is an element classed with ‘.leaflet-objects-pane’.
  3. If it all tests in #2 pass, return this element and pass it and it’s data (remember in D3 this is the element.__data__) off to the real click handler.
  4. If the tests in #2 fail, either return null (if i’m outside of my base element) or add the “pointer-events: none” style to the current element and call this function again recursively.   The current element is added to an array of “passed over elements” so that we can come back later and remove this style.  In order to not break the page, maintain the prior value of this style if there was one.

This loop continues until we either find an element that will handle the event or we are outside of the base element.

The last important step before returning from this function is to iterate over the “passed over elements” array and revert the “pointer-events: none” style.

Implementation
Here is the implementation as a member in the custom layer class, a little generalized for clarity.

        _digForElements: function keepDigging(evt, passedOverElementsFromLast) {
            var layer = this,
                  jMapPane = jQuery('.leaflet-objects-pane');
            if (!jMapPane) return null;

            var baseElement = jMapPane[0]
                attr = 'data-d3layerkey',
                attrVal = layer._layerId,
                passedOverElements = passedOverElementsFromLast || [],
                firstFound,
                element,
                jElement,
                existingCssValue;

            element = document.elementFromPoint(evt.x, evt.y);
            if (element && jQuery.contains(baseElement, element)) {
                jElement = jQuery(element);

                if (jElement.attr(attr) && jElement.attr(attr) === attrVal &&
                    _.isObject(element.__data__) && layer.options.isSeriesClickable(element.__data__)) {
                    firstFound = element;
                } else {
                    existingCssValue = jElement.css('pointer-events');
                    passedOverElements.push({
                        element: element,
                        previousCSSValue: existingCssValue === 'auto' ? '' : existingCssValue;
                    });

                    // Add style to it so that elementFromPoint bypasses it next time.
                    jElement.css({
                        'pointer-events': 'none'
                    });

                    firstFound = keepDigging.call(this, evt, passedOverElements);
                }
            }

            // clean up all elements we added classes to.  Also, end a sentence with a preposition.  done.
            var info;
            while (passedOverElements.length > 0) {
                // It did not have it before or it would not have come up in the search...
                // so remove it again.
                info = passedOverElements.pop();
                jQuery(info.element).css({
                    'pointer-events': info.previousCSSValue
                });
            }

            return firstFound;
        },
Share