champagne anarchist | armchair activist

Embedding tweets in Leaflet popups

I just created a map showing where so-called Biro’s (small cars) are parked on the pavement and annoying people. Twitter has quite a few photos of the phenomenon. In some cases, finding their location took a bit of detective work.

First you’ll need the embed code for the tweet. You can get it manually from the Twitter website, but if you want to automate your workflow, use a url like the one below. It’ll download a bit of json containing the embed code:

https://publish.twitter.com/oembed?url=https://twitter.com/nieuwsamsterdam/status/958761072214896640

When trying to embed the tweets in Leaflet popups, I ran into a few problems:

  • When popups open, the markers didn’t properly move down. As a result, most of the popup would be outside the screen. The problem and how to solve it are described here.
  • Twitter embed code contains a script tag to load a widget. Apparently you can’t execute javascript by adding it directly to the html for the popup content, but you can add it using a selector (cf here).

Here’s the code that’ll solve both problems:

map.on('popupopen', function(e) {
    $.getScript("https://platform.twitter.com/widgets.js");
    var px = map.project(e.popup._latlng); 
    px.y -= e.popup._container.clientHeight;
    map.panTo(map.unproject(px),{animate: true});
});

You may also want to do something about the width of the popups, because otherwise they will obscure most of the map on mobile screens and it will be difficult to close a popup (which you can normally do by clicking outside of the popup). You can change the width of embedded tweets, but this will not change the width of the popup itself. A simple solution is to give popups a maxWidth of 215 (.bindPopup(html, {maxWidth: 215})).

Of course, you could also vary maxWidth depending on screen width, but I think 215px works well on all screens. Further, embedded tweets appear to have a minimum width of about 200px, so if you want popups narrower than 215px you’ll have to figure out a way to fix that.

If you embed tweets, Twitter can track people who visit your webpage. Add <meta name="twitter:dnt" content="on"> to your page and Twitter promises they won’t track your visitors. I wasn’t sure whether this should be put in the web page itself or in the html content of the popups (I opted for both).

If the popups have a somewhat spartan look and do not contain photos: Good for you! You’re probably using something like Firefox with tracking protection enabled. This blocks sites which have been identified as ‘engaging in cross-site tracking of users’ - including, apparently, platform.twitter.com.

Follow this blog:
Twitter (English) | Twitter (Nederlands) | RSS data blog (English) | RSS dirkmjk (Nederlands)