Fire Event to Open CartoDB/Leaflet Marker - javascript

I've got a pretty specific question that I'm not really expecting a direct answer to, but any guidance will be helpful.
Simple and plain, I want to programmatically fire a click event on a marker positioned on a Leaflet map, powered by CartoDB. I have a single layer on the map that contains markers, and each marker has click events associated with them. So, essentially, I just need to find the marker and fire the click event on it.
For context, Mapbox actually does exactly this, but unfortunately I can not use Mapbox for this particular implementation:
https://www.mapbox.com/mapbox.js/example/v1.0.0/open-popup-externally/
I'm open to suggestions, but preferably, I'd like to do something similar to the code in the link above -- interrogate either Leaflet or CartoDB via javascript to find and access the marker via custom properties/lat-lng/??. I figure it would be simple enough to go from there.
Another way could be to hook an event when the markers are created, store them in a hash, then access that storage when I need to do my manual click. However, I don't know of any such event that exists, and I can't locate documentation that lists supported events.
Since I'm not creating the markers myself, and can not (for reasons), storing them as I add them to the map is not an option here.
I assume since Mapbox is doing it, there must be some hook, but I can't find any valuable documentation to point me in the right direction.
Any suggestions or pointers?

To anyone who stumbles upon this, I've got a workable solution for my particular case. This call will do it for you:
layer.trigger 'featureClick', event, latlng, pos, data, layer_count
Essentially, you'll want to grab the layer in question and trigger the click, passing the appropriate data:
event: this can be null, since there is no event
latlng: the lat/long position
data: an object like { cartodb_id: 123 }. The cartodb_id is required.
layer_count: the index of your layer (probably 0)
To grab the latlng and the cartodb_id here, you'll probably need to do what I did -- query for it:
function openMarker(layer, my_object_id) {
vars = { database_id: my_object_id };
opts = { format: 'geojson' };
query = "SELECT * FROM my_table WHERE my_object_id = {{ my_object_id }}"
sql = new cartodb.SQL({user: my_user_id});
sql.execute(query, vars, opts).done(function(data) {
if (data.features != undefined && data.features.length == 1)
row = data.features[0];
latlng = [ row.geometry.coordinates[1], row.geometry.coordinates[0] ];
layer.trigger('featureClick', null, latlng, null, { cartodb_id: row.properties.cartodb_id }, 0);
});
}
Then, you can just call open_marker, passing the layer you wish to open the marker on and your object identifier. As long as that's in your cartodb database, you can grab it. Of course, the query can be adjusted to suit your means.
For my particular implementation, I had to use a setTimeout call to get the flow of control right, as I do my calls on page load. But if you're calling after the page has loaded, should be no problem.
So, simple enough way to open a marker given a local identifier. Hope this helps someone else!
Kudos for the inspiration for this solution go to:
https://gist.github.com/javisantana/7b817fda1e7511c451c7#file-index-html-L39

Related

Leaflet - markers duplicating, removeLayer, clearLayers only hide markers

markerGroup: L.LayerGroup;
this.markerGroup.eachLayer(function (layer) {
this.markerGroup.removeLayer(layer);
});
this.markerGroup.clearLayers();
removeLayer() and clearLayers() are working as described in the leaflet documentation but I am wondering if there is a way to remove the layer/marker/instance from my markerGroup variable entirely. Even though the markers are cleared/removed, when my refresh button is called it still has the previous markers in the markerGroup variable and adds the same ones again thus duplicating them. This is a problem as I have shadows for these markers which duplicate over each other and eventually becoming 100% opaque. Has anybody got any suggestions or come across this problem before?
Edit: Thanks for the suggestion #Falke Design. map.removeLayer doesn't work for me unfortunately. Hopefully the information below is more helpful:
refreshButton() {
this.markerGroup = new L.LayerGroup;
clearInterval(this.refreshTimer);
this.dynamicLatLong = this.map.getCenter();
this.dynamicZoom = this.map.getZoom();
this.markerGroup.clearLayers();
this.polygonGroup.clearLayers();
this.map.removeLayer(this.markerGroup);
this.getCurrentAzure();
this.leafletMap();
}
getCurrentAzure() uses a for loop to get the data such as lat, lng, etc. of each instance and assigns it to a variable named marker. Each marker is added to markerGroup with this line:
marker.addTo(this.markerGroup);
leafletMap() creates the map and draws the markerGroup onto the map with this line:
this.markerGroup = L.layerGroup().addTo(this.map);

About mxGraph: how can I first add Edge, and add my own custom attribute, then add to the graph?

Because I register a listener about the CELL_ADD to justify when I add two different types of edges, I deal with them in different ways.
But the problem is I failed to add the edge after I change my method to "add edge" action"
HERE IS MY FIRST successful version :
graph.insertEdge(parent, null, '', defiVertex, outVertex);
HERE IS MY WANTED NEW VERSION but failed:
edge.edge = true;
edge.type = AUTO_INSERT_EDGE;
graph.addEdge(edge);
THANK FOR HELP!!
Not sure what you are trying to do, but why don't you override the addListener function? In there, you can retrieve the changes, and if the name is mxTerminalChange you know you are adding/modifying an edge:
model.addListener(mx.mxEvent.CHANGE, function(sender, evt) {
var changes = evt.getProperty('edit').changes;
if (changes[i].constructor.name == "mxTerminalChange") {
// Manage the add of a new connection
...
}
});
I change another way to finish my problem which is use the vue data attribute to help me record the state of the two add edge situations: when the edge is add by code, this.isAutoAdd = true, when user create the edge, this.isAutoAdd=false,so when in the listener, I just need to determine whether "isAutoAdd" is false to call the change function.

Google maps alternative routes won't update

I have created a directions map from one point to multiple specific point. When one change end point the map should update, and alternative routes should be shown on the right sidebar, with details under it. However, when I change end point it's not updating nicely, sometimes it just add alternative directions under "old" directions,sometimes alternatives are messed up, not really sure what the problem is, though I suspect that there might be a problem if theres's no alternative routes returned for the specific end point. Here's a preview of what I made so far:
jsbin.com/hoqebofice/edit?output
Also in the end, I'd like to have map updated once alternative route is clicked from the right sidebar as well.
In your OnChangeHandler add this line:
var onChangeHandler = function() {
document.getElementById("setPanel").innerHTML = ""; // THIS ONE!
calculateAndDisplayRoute(directionsService, directionsDisplay);
};

Leaflet MarkerCluster open/spiderfy cluster based on known marker

My scenario is that the user would click on a marker that is part of a cluster and be redirected somewhere else. Then when they come back they need to return the the same bounds on the map where they were before at that marker, but the cluster in which the marker is found is no longer expanded/spiderfy'd, which I need to get done.
At this point I know which marker I'm looking for, but need to expand its cluster. What I've done so far:
Iterate through the markers in the initially populated L.markerClusterGroup() object:
layers = L.markerClusterGroup();
. . . populate 'layers' ...
$.each(layers, function (idx, layer) {
if(layer._tooltip._content === 'known marker tooltip') {
layer.__parent.spiderfy();
}
});
Although the spiderfy() function sort of works, it doesn't seem to be intended to be used on its own and breaks the cluster pretty bad.
Alternatively, I've tried calling fire('clusterclick') on the above layer object, as well as on layer.__parent, which I presume would represent the cluster, but can't get anything working.
I would need a solution in which I can properly trigger the clusterclick event that would handle everything, as if I had actually clicked the cluster myself.

Google Maps API - Map.data scope issue

I am trying to add a GeoJSON layer to Google Maps (v3) by doing the following:
imageActive = {
url: "images/target_red.png",
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(11, 11),
} // ACTIVE marker image
jQuery.getJSON('home/gcpts/geojson.php', function(data){
points = map.data.addGeoJson(data);
console.log(points); //this works
});
map.data.setStyle({
clickable: true,
draggable: false,
});
map.data.addListener('click', function(event){
setActiveImage(event);
})
function setActiveImage(event){
for(var i = 0;i<points.length;i++){ //can't read "length" of undefined
points[i].revertStyles();
}
map.data.overrideStyle(event.feature, {
icon: imageActive,
});
}
However when I try to iterate through the "points" variable, I can't seem to "see" it. I mainly get undefined, or if I try to call the length of points (points.length), then it doesn't exist.
If I console.log(points) within the jQuery function, then I can see all of the features within the variable. If I place it on the outside, then I can't see it. Is there something I am missing about the scope?
It's my hope that I can set a "click" event and use event.feature to overrideStyle. Then when a different feature is clicked, then the style is removed from the other geoJson features and overrides the newly clicked feature.
It seems that this should work fine, but I can't seem to figure out how to iterate through the features.
Thanks!
(Also, I am using jQuery in "No conflict" mode...)
All of your variables are globally scoped because you aren't using the var keyword. It seems likely that some other script is looking for a points variable and overwrites yours. Assuming your code is already wrapped up in some kind of function (such as a jQuery ready handler), you may solve your problem by just using var. I'd add this line of code before you call getJSON():
var points = [];
The previous answer noted you need to ensure your "points" variable is scoped appropriately, but a better answer is that you don't need that variable at all: Since you are using map.data you can just use that directly to access your features, using something like:
map.data.foreEch(function(feature) {console.log(feature);})
Note of course your "map" variable must be appropriately scoped.
Additionally, you also don't need to use jQuery -- you can just load the data using map.data.loadGeoJson(theUrl) which will do the ajax for you

Categories

Resources