Update Popup data in Mapbox GL JS - mapbox

I'm making a fleet tracker with Mapbox GL JS, it gets the data from a GeoJson and inserts in the map, as the Add live realtime data, I've also integrated the Mapbox store locator example, by now I can update in realtime the sidebar and the points on the map. A modification that I would like to make is not display only one single popup, but a popup for every icon located there. I would like to know how to update this popups, because in the way I'm making it's creating a new popup every movement of the object, but is not closing the previous one. Here is the function that I'm using for the popups
function createPopUp(currentFeature, data) {
var popUps = document.getElementsByClassName('mapboxgl-popup');
//if (popUps[0]) popUps[0].remove();
// mapboxgl.Popup.remove();
if (map.getZoom() > 9) {
var popup = new mapboxgl.Popup({closeOnClick: false})
.setLngLat(currentFeature.geometry.coordinates)
.setHTML('<h3> Aeronave: '+ currentFeature.properties.dev_id + '</h3>' +
'<h4> Curso: ' + currentFeature.properties.curso + 'ยบ<br> Altitude: ' + currentFeature.properties.alt + ' ft<br> Sinal: ' + currentFeature.properties.rssi +'</h4>')
.addTo(map)
.setMaxWidth("fit-content(10px)");
} else{if (popUps[0]) popUps[0].remove()};
}
If I uncomment the popUps[0] line it will only allow 1 popup to be displayed, I've also tried to change dynamically the number between the [] by the number of active tracked devices, it reduced the popup number, but it still repeat some popups of one ID. Also I've tried to change the class name via the .addClasName but it didn't worked.
Thanks

Without seeing how you're calling the createPopUp method in the context of your application, it is difficult to diagnose exactly what is going wrong. I'm not sure why a new popup is being created each time the map moves, so it sounds like you might be calling this method within the Map#on('move') event. That being said, I'm assuming that you're iterating over all of your features and calling the createPopUp method for each in order to initialize all of the popups.
Rather than using an array of DOM nodes generated with var popUps = document.getElementsByClassName('mapboxgl-popup');, I'd recommend specifying a unique and reproducible class name for each feature's popup element when initialized. It looks like each of your features has a dev_id property, so you could do something like:
var popup = new mapboxgl.Popup({closeOnClick: false, className: `mapbox-gl-popup-${dev_id}`})
If you need to change the popup for a particular feature in the future, you can create a helper function to retrieve the relevant DOM node:
function retrievePopUp(feature) {
return document.getElementsByClassName(`mapboxgl-popup-${feature.properties.dev_id}`);
}

Related

How to drag features in Open Layers 3?

In the OL3 examples I can drag objects and drop on the map, but I want to move/resize/rotate things that are already on the map like ol.geom.Point and other ol.geom objects. What is the OL3 way do do this?
Example in OL2:
OpenLayers.Control.DragFeature(layer)
Not sure why the example on OL3 website is so complicated. Dragging vector objects can be easily achieved using new ol.interaction.Modify.
Here is a simpler working example: jsFiddle
In short, if you marker was:
var pointFeature = new ol.Feature(new ol.geom.Point([0, 0]));
You can define modify interaction as :
var dragInteraction = new ol.interaction.Modify({
features: new ol.Collection([pointFeature]),
style: null
});
map.addInteraction(dragInteraction);
You can then get a event for getting the new location of marker after drag like so:
pointFeature.on('change',function(){
console.log('Feature Moved To:' + this.getGeometry().getCoordinates());
},pointFeature);
Take a look at the modify interaction (example). Though rotation is not yet supported.
I have create a simple lib that add drag interaction to openlayers 4 by slightly changing this official example: https://openlayers.org/en/latest/examples/custom-interactions.htm
you can find the lib here :
https://gist.github.com/kingofnull/0ad644be69d8dd43c05721022ca5c3a5
and you should simply add it this way:
var map = new ol.Map({
interactions: ol.interaction.defaults().extend([new ol.interaction.Drag(),])
});
Update
I test the translate and it works in openlayer 4 and there is no need for a custom interaction. keep it in mind if you going to combine it with modify interaction you should add it before modify. here is my final code:
var map = new ol.Map({...});
var featureDrager = new ol.interaction.Translate();
var modify = new ol.interaction.Modify({...});
map.addInteraction(featureDrager);
map.addInteraction(modify);

How do I get the information about the selected node in the Google Charts Org Chart widget?

I have a chart rendered via the Google Charts Org Chart API. How do I get the data about the selected node when a user clicks on a node. I understand it to the point where I make the "getSelection" call to output selection information to the Javascript console:
console.log(chart.getSelection());
When I look in the Chrome Javascript console, I can see the object (see below), but it doesn't show any attributes of the node in the chart. It only shows row and column. Is there another call to get the actual attributes of the node (like the name, etc)?
You should call chart.getSelection(), not this., because in your function this refers to window, and thus you call window.getSelection() that returns an unrelated object.
Here is the complete example how to get chart selection:
Google Charts. Interacting With the Chart
The correct code from the link above, where chart and data refer to global variables:
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var selectedValue = data.getValue(selectedItem.row, 0);
console.log('The user selected ' + selectedValue);
}
This works for me.
chart is the instance of your chart and data is the container of your data (a google DataTable instance), composed in the page or fetched via ajax.
Once you get the current selection object with chart.getSelection() you are able to query your dataset with the current row position data.getValue(row, col), to obtain the corresponding record.
showCurrentDetailCard() is a custom function that i use to display the details of the current node.
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler() {
var selection = chart.getSelection();
if (selection.length > 0) {
var c = selection[0];
showCurrentDetailCard(data.getValue(c.row, 0));
}
}
Hope this helps.

How to reference dynamically added element after DOM loaded without a need to act on any events?

I know there is .on and .live (deprecated) available from JQuery, but those assume you want to attach event handlers to one ore more events of the dynamically added element which I don't. I just need to reference it so I can access some of the attributes of it.
And to be more specific, there are multiple dynamic elements like this all with class="cluster" set and each with a different value for the: title attribute, top attribute, and left attribute.
None of these jquery options work:
var allClusters = $('.cluster');
var allClusters2 = $('#map').children('.cluster');
var allClusters3 = $('#map').find('.cluster');
Again, I don't want to attach any event handlers so .on doesn't seem like the right solution even if I were to hijack it, add a bogus event, a doNothing handler, and then just reference my attributes.
There's got to be a better solution. Any ideas?
UPDATE:
I mis-stated the title as I meant to say that the elements were dynamically added to the DOM, but not through JQuery. Title updated.
I figured it out. The elements weren't showing up because the DOM hadn't been updated yet.
I'm working with Google Maps and MarkerClustererPlus to give some more context, and when I add the map markers using markerclustererplus, they weren't available in the javascript code following the add.
Adding a google maps event listener to my google map fixed the problem:
google.maps.event.addListener(myMarkerClusterer, 'clusteringend', function () {
// access newly added DOM elements here
});
Once I add that listener, all the above JQuery selectors and/or methods work just fine:
var allClusters = $('.cluster');
var allClusters3 = $('#map').find('.cluster');
Although this one didn't, but that's because it only finds direct decendants of parent:
var allClusters2 = $('#map').children('.cluster');
Do what you need to do in the ajax callback:
$.ajax(...).done(function (html) {
//append here
allClusters = $('.cluster');
});
If you want them to be separate, you can always bind handlers after the fact, or use $.when:
jqxhr = $.ajax(...).done(function (html) { /* append html */ });
jqxhr.done(function () { allClusters = $('.cluster') });
$.when(jqxhr).done(function () { /* you get it */ });
If these are being appended without ajax changes, then just move the cluster-finding code to wherever the DOM changes take place.
If that's not an option, then I guess you would just have to check on an interval.

How to trigger native popup on Leaflet polygon

How do you manually trigger the native popup on a Leaflet polygon?
I can bind the native popup to each layer like this:
geojsonLayer.on("featureparse", function (e){
// bind the native popup
var popupContent = "popup content goes here";
e.layer.bindPopup(popupContent);
});
And I have manually assigned an ID to each polygon so I can reference them later like this:
map._layers['poly0']
I've tried triggering the popup like this:
map._layers['poly0'].openPopup();
But that gives me an error like this:
map._layers['poly0'].openPopup is not a function
Any idea where I'm going wrong?
openPopup for vector layers only recently appeared in the latest version, it wasn't there before.
Also, check out the Leaflet 0.4 release announcement: http://leaflet.cloudmade.com/2012/07/30/leaflet-0-4-released.html (and note that GeoJSON API was changed and it's not backwards compatible, so you also have to update your code)

Test to see if you are in a specific content block in TinyMCE and not allow a plugin to add to that content block if in it

So I have a TinyMCE form on my page and it is pre-filled with "sections" (divs with specific class names).
I have a couple of plugins that will add to TinyMCE with more "sections".
I need it so when I push the plugin button it will test to make sure the cursor is not inside a "section" and paste a "section" inside another "section".
Not sure the direction I need to take to accomplish this. Any help would be great.
more info:
So below is an example of a plugin that adds a button that just inserts a simple dov into the editor at the selection/cursor.
ed.addButton('pluginbutton', {
title : 'MyPlugin',
image : 'img/test.png',
onclick : function() {
ed.selection.setContent('<div>test</div>');
}
});
I am currently thinking that onBeforeSetContent is the API event handler I need to set to process whether or not I am in another section and if so send a message to the screen. If not just do the setContent method. I am not sure exactly how to set that up though so I am still figuring that out. Any help here?
Since it seems like you have control over the plugin, here is how I would edit it to work.
Note: I am using the jQuery method closest. I figured since you are on the jQuery core team, you are probably using it for this project. If not, just refactor that line as needed. The important part is that selection.getNode() returns the DOM element that is the parent of both the start and end selection points.:
ed.addButton('pluginbutton', {
title : 'MyPlugin',
image : 'img/test.png',
onclick : function() {
if( !$(ed.selection.getNode()).closest('div.section').length ){
ed.selection.setContent('<div class="section">test</div>');
}
}
});
Additional thoughts
Also, to make your plugin aware enough so it won't put a div as the child of a p tag, you could do something like this:
Replace onclick above with this:
onclick: function(){
var $node = $(ed.selection.getNode());
if( !$node.closest('div.section').length ){
// Get highest element that is a direct child of the `body` tag:
var $parent = $node.closest('body > *');
// Wrap with our special section div
if($parent.length) $parent.wrap('<div class="section"></div>');
}
}
I don't know TinyMCE specifically, but it should be possible to extract the current DOM element from ed.selection. If that is possible (I'm sure it is using some sort of getter function or property), you should be able to do the following:
Mark a "forbidden" area using an id or class ("<div class='protected'> ")
traverse through the selection's ancestry (using the parentNode property of the element) and check whether one of the parent elements has the "protected" class or ID.
If the ID was found, do not execute setContent(); otherwise execute it.