GeoJSON: fire custom event on marker drag, listen on another feature

751 views
Skip to first unread message

Jindřich Mynarz

unread,
Mar 18, 2015, 6:59:57 AM3/18/15
to leafl...@googlegroups.com
Hi,

when rendering GeoJSON on a Leaflet.js map, I want to fire a custom event on marker drag that is propagated to an event listener on another GeoJSON feature. What I have now in GeoJSON options along these lines:

var opts = {
  pointToLayer: function (feature, latlng) {
    var marker = L.marker(latlng);
    if (feature.properties && feature.properties.id === "trigger") {
      marker.on("drag", function (event) {
        event.target._map.fire("customEvent");
      });
    }
    return marker;
  },
  onEachFeature: function (feature, layer) {
    if (feature.properties && feature.properties.id === "listener") {
      layer.on("customEvent", function (event) {
        console.log("Event received!");
      });
    }
  }
};

There are at least 2 problems with this.

First, I haven't found a way how to fire an event on marker drag other than abusing the pointer to map: event.target._map.fire("customEvent"). Is there any better way?

Second, if the event listener is attached in onEachFeature, no event is received. However, if I attach the event listener directly to the map object, only then I can see the custom event is fired. How should I properly attach the event listener in onEachFeature?

Finally, is this a wrong approach to communication between GeoJSON features? I base my understanding on Leaflet.js reference, which explicitly mentions that onEachFeature is "Useful for attaching events and popups to features." I've tried to find examples of using events for communication between features, but I was unsuccessful. I'd appreciate any links to posts explaining how to go about this.

Best,

Jindřich

-- 
Jindřich Mynarz

Jindřich Mynarz

unread,
Mar 26, 2015, 12:12:45 PM3/26/15
to leafl...@googlegroups.com
Hi,

I have temporarily resolved this issue by completely bypassing Leaflet event system and using a custom event dispatcher as global object (see http://stackoverflow.com/a/27071169/385505).

It's a shame that I had to sidestep Leaflet's event system. Unfortunately, because of the lack of documentation for the event system I wasn't able to figure out how to propagate Leaflet events among GeoJSON features. I heard that OpenLayers events propagate both to parent and child objects. I'd be curious to find out if this is also possible in Leaflet (and it's just not documented) or if it's not possible.

Best,

Jindřich

-- 
Jindřich Mynarz
Reply all
Reply to author
Forward
0 new messages