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);
});
Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked Dec 21, 2019 at 20:05

1 Answer 1

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);
answered Dec 21, 2019 at 21:17
1
  • If this answers your question, please mark it as solution (click the check mark next to the answer). Commented Dec 21, 2019 at 21:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.