0

I'm trying to embed tweets into the popups for a map I've made in Mapbox. The text of the tweets is displaying properly, but not the styling — the embed code contains a script tag to load a widget for styling, and I would guess that this is not being executed by the "sethtml" function. How can I execute the JavaScript when the popup is opened in Mapbox?

I've run into this problem in Leaflet before, and solved it with the following function.

map.on('popupopen', function(e) {
    $.getScript("https://platform.twitter.com/widgets.js");
});

I admit I'm new to Mapbox, but I thought this script would also work for mapbox GL JS. I have the following (not working) code for GL JS:

// add markers to map
geojson.features.forEach(function(marker) {

  // create a HTML element for each feature
  var el = document.createElement('div');
  el.className = 'marker';

//get JS widget and move marker down
  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/1.5;
    map.panTo(map.unproject(px),{animate: true});
});

  // make a marker for each feature and add to the map
  new mapboxgl.Marker(el)
    .setLngLat(marker.geometry.coordinates)
    .setPopup(new mapboxgl.Popup({ offset: 5 }) // add popups
    .setHTML(marker.properties.Embed + marker.properties.Name))
    .addTo(map);

});
2

I've figured this out; leaving the question up in case the solution helps anyone else:

 new mapboxgl.Marker(el)
    .setLngLat(marker.geometry.coordinates)
    .setPopup(new mapboxgl.Popup({ offset: 5 }) // add popups
    .on('open', function(e) {
      $.getScript("https://platform.twitter.com/widgets.js");
    })
    .setHTML(marker.properties.Embed + marker.properties.Name))
    .addTo(map);
1
  • If this answers your question, please mark it as solution (click the check mark next to the answer). – Stefan Dec 21 '19 at 21:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.