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);
});
1 Answer 1
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);
-
If this answers your question, please mark it as solution (click the check mark next to the answer).StefanBrand_EOX– StefanBrand_EOX2019年12月21日 21:58:59 +00:00Commented Dec 21, 2019 at 21:58
Explore related questions
See similar questions with these tags.