relevant hexids inside a hexagon - h3

i am generating a set of hex ids via "h3.geoToH3(lng, lat, res)".
after that i am creating a FeatureCollection via "let polygons = geojson2h3.h3SetToFeatureCollection(hexIds)"
When i am clicking on a hexagon on the map i just want the ids of the relevant hexagons inside the initiated hexagon.
How can i do that in a performant way?
getHexIds = (res) => {
let hexIds = this.props.stations.features.map(element => {
const [lng, lat] = element.geometry.coordinates;
const hexId = h3.geoToH3(lng, lat, res);
return hexId;
})
let polygons = geojson2h3.h3SetToFeatureCollection(hexIds);
this.setState({
polygons: polygons
}, () => {
this.geoJsonLayer.current.leafletElement.clearLayers().addData(this.state.polygons);
})
// console.info(this.state.polygons, res);
}
onEachFeature = (feature, layer) => {
layer.on('click', (e) => {
// show the relevant hexids
})
}

If I understand the question correctly, this might have more to do with your map library (presumably Leaflet) than H3, but here are some general approaches:
If you want to get the H3 index at the point where the user clicked, find the lat/long (probably something your map library provides in the click event) and then just run it through h3.geoToH3(lat, long) again. This is very fast, and it's much easier to recalculate it than to store it and look it up.
If you want to get a set of H3 indexes associated with the click point (i.e. you have multiple features, each made up of multiple H3 indexes), then you usually want to build a reverse index like {[h3Index]: h3Set}. Then you can use h3.geoToH3 to find the index at the click point, and look that up in your reverse index to find the set.
If your map doesn't give you lat/long on click, you can use a library like viewport-mercator-project to find the lat/long from the x/y screen coordinates of the click (available on the DOM event).

Related

Panning around globe until user interacts

Trying to loop around the globe until the user interacts with the map.
Locations are currently based on the flyTo example, as I'm still trying to get the functionality working. I'm struggling to make it animate smoothly, from point to point and loop.
Final version will ideally pan around the globe, and continue until user interacts.
map.on('load', () => {
for (const [index, coordinate] of cityCoordinates.entries()) {
setTimeout(() => {
map.easeTo({
center: coordinate,
duration: 10000
});
coordinate.push(coordinate.shift())
}, 2000 * index);
}
});
https://jsfiddle.net/r8fs2kbd/2/
I saw the animate along a path example, however I don't want the map to rotate or move altitude.

Using L.esri.DynamicMapLayer, is it possible to bind a mouseover event rather than a pop-up on a dynamic map?

I'm aware of binding a pop-up to ESRI's L.esri.DynamicMapLayer here. The following code below is successful.
$.ajax({
type: 'GET',
url: url + '?f=json',
data: { layer: fooType },
dataType: 'json',
success: function(json) {
var foo_layer = fooLayers[fooType].layers;
foo = L.esri.dynamicMapLayer({
url: url,
layers: [foo_layer],
transparent: true
}).addTo(map).bringToFront();
foo.bindPopup(function(error, featureCollection) {
if (error || featureCollection.features.length === 0) {
return false;
} else {
var obj = featureCollection.features[0].properties;
var val = obj['Pixel Value'];
var lat = featureCollection.features[0].geometry.coordinates[1];
var lon = featureCollection.features[0].geometry.coordinates[0];
new L.responsivePopup({
autoPanPadding: [10, 10],
closeButton: true,
autoPan: false
}).setContent(parseFloat(val).toFixed(2)).setLatLng([lat, lon]).openOn(map);
}
});
}
});
But rather than a click response I am wondering as to whether you can mouseover using bindTooltip instead on a dynamic map. I've looked at the documentation for L.esri.DynamicMapLayer which says it is an extension of L.ImageOverlay. But perhaps there is an issue outlined here that I'm not fully understanding. Maybe it is not even related.
Aside, I've been testing multiple variations of even the simplest code to get things to work below but have been unsuccessful. Perhaps because this is asynchronous behavior it isn't possible. Looking for any guidance and/or explanation(s). Very novice programmer and much obliged for expertise.
$.ajax({
type: 'GET',
url: url + '?f=json',
data: { layer: fooType },
dataType: 'json',
success: function(json) {
var foo_layer = fooLayers[fooType].layers;
foo = L.esri.dynamicMapLayer({
url: url,
layers: [foo_layer],
transparent: true
}).addTo(map).bringToFront();
foo.bindTooltip(function(error, featureCollection) {
if (error || featureCollection.features.length === 0) {
return false;
} else {
new L.tooltip({
sticky: true
}).setContent('blah').setLatLng([lat,lng]).openOn(map);
}
});
}
});
Serendipitously, I have been working on a different problem, and one of the byproducts of that problem may come in handy for you.
Your primary issue is the asynchronous nature of the click event. If you open up your map (the first jsfiddle in your comment), open your dev tools network tab, and start clicking around, you will see a new network request made for every click. That's how a lot of esri query functions work - they need to query the server and check the database for the value you want at the given latlng. If you tried to attach that same behavior to a mousemove event, you'll trigger a huge number of network requests and you'll overload the browser - bad news.
One solution of what you can do, and its a lot more work, is to read the pixel data under the cursor of the image returned from the esri image service. If you know the exact rgb value of the pixel under the cursor, and you know what value that rgb value corresponds to in the map legend, you can achieve your result.
Here is a working example
And Here is the codesandbox source code. Don't be afraid to hit refresh, CSB is little wonky in the way it transpiles the modules.
What is happening here? Let's look step by step:
On map events like load, zoomend, moveend, a specialized function is fetching the same image that L.esri.dynamicMapLayer does, using something called EsriImageRequest, which is a class I wrote that reuses a lot of esri-leaflet's internal logic:
map.on("load moveend zoomend resize", applyImage);
const flashFloodImageRequest = new EsriImageRequest({
url: layer_url,
f: "image",
sublayer: "3",
});
function applyImage() {
flashFloodImageRequest
.fetchImage([map.getBounds()], map.getZoom())
.then((image) => {
//do something with the image
});
}
An instance of EsriImageRequest has the fetchImage method, which takes an array of L.LatLngBounds and a map zoom level, and returns an image - the same image that your dynamicMapLayer displays on the map.
EsriImageRequest is probably extra code that you don't need, but I happen to have just run into this issue. I wrote this because my app runs on a nodejs server, and I don't have a map instance with an L.esri.dynamicMapLayer. As a simpler alternative, you can target the leaflet DOM <img> element that shows your dynamicMapLayer, use that as your image source that we'll need in step 2. You will have to set up a listener on the src attribute of that element, and run the applyImage in that listener. If you're not familiar with how leaflet manages the DOM, look into your elements tab in the inspector, and you can find the <img> element here:
I'd recommend doing it that way, and not the way my example shows. Like I said, I happened to have just been working on a sort-of related issue.
Earlier in the code, I had set up a canvas, and using the css position, pointer-events, and opacity properties, it lays exactly over the map, but is set to take no interaction (I gave it a small amount of opacity in the example, but you'd probably want to set opacity to 0). In the applyImage function, the image we got is written to that canvas:
// earlier...
const mapContainer = document.getElementById("leafletMapid");
const canvas = document.getElementById("mycanvas");
const height = mapContainer.getBoundingClientRect().height;
const width = mapContainer.getBoundingClientRect().width;
canvas.height = height;
canvas.width = width;
const ctx = canvas.getContext("2d");
// inside applyImage .then:
.then((image) => {
image.crossOrigin = "*";
ctx.drawImage(image, 0, 0, width, height);
});
Now we have an invisible canvas who's pixel content is exactly the same as the dynamicMapLayer's.
Now we can listen to the map's mousemove event, and get the mouse's rgba pixel value from the canvas we created. If you read into my other question, you can see how I got the array of legend values, and how I'm using that array to map the pixel's rgba value back to the legend's value for that color. We can use the legend's value for that pixel, and set the popup content to that value.
map.on("mousemove", (e) => {
// get xy position on cavnas of the latlng
const { x, y } = map.latLngToContainerPoint(e.latlng);
// get the pixeldata for that xy position
const pixelData = ctx.getImageData(x, y, 1, 1);
const [R, G, B, A] = pixelData.data;
const rgbvalue = { R, G, B, A };
// get the value of that pixel according to the layer's legend
const value = legend.find((symbol) =>
compareObjectWithTolerance(symbol.rgbvalue, rgbvalue, 5)
);
// open the popup if its not already open
if (!popup.isOpen()) {
popup.setLatLng(e.latlng);
popup.openOn(map);
}
// set the position of the popup to the mouse cursor
popup.setLatLng(e.latlng);
// set the value of the popup content to the value you got from the legend
popup.setContent(`Value: ${value?.label || "unknown"}`);
});
As you can see, I'm also setting the latlng of the popup to wherever the mouse is. With closeButton: false in the popup options, it behaves much like a tooltip. I tried getting it to work with a proper L.tooltip, but I was having some trouble myself. This seems to create the same effect.
Sorry if this was a long answer. There are many ways to adapt / improve my code sample, but this should get you started.

amCharts: Map Recentering after JSON DataSource Despite Previous chart.homeGeoPoint

I'm mapping a series of points with amChart; after loading the data from an external JSON source, the map re-centers instead of staying at the point I'd set earlier with chart.homeGeoPoint.
I believe I need to use an event listener and set the homeGeoPoint after the map renders the points... but I'm at a bit of a loss; the only events I've found are from dataSource.events, and those appear to be related to fetching/parsing the JSON, as opposed to rendering the map.
// Create map instance
var chart = am4core.create("chartdiv", am4maps.MapChart);
// Set map definition
chart.geodata = am4geodata_region_world_northAmericaLow;
// Set projection
chart.projection = new am4maps.projections.Miller();
// Initial Position / Zoom
chart.homeZoomLevel = 2.6;
chart.homeGeoPoint = {
latitude: 39,
longitude: -96.2456
};
// Series for World map
var worldSeries = chart.series.push(new am4maps.MapPolygonSeries());
worldSeries.useGeodata = true;
// Markers
// Create image series
var imageSeries = chart.series.push(new am4maps.MapImageSeries());
// Create a circle image in image series template so it gets replicated to all new images
var imageSeriesTemplate = imageSeries.mapImages.template;
var circle = imageSeriesTemplate.createChild(am4core.Circle);
circle.radius = 5;
circle.fill = am4core.color("#116ad6");
circle.stroke = am4core.color("#FFFFFF");
circle.strokeWidth = 2;
circle.nonScaling = true;
circle.tooltipText = "{title}";
// Set property fields
imageSeriesTemplate.propertyFields.latitude = "latitude";
imageSeriesTemplate.propertyFields.longitude = "longitude";
imageSeriesTemplate.propertyFields.url = "url";
// Load data
imageSeries.dataSource.url = "/foo/map-points.php";
imageSeries.dataSource.parser = new am4core.JSONParser();
imageSeries.dataSource.parser.options.emptyAs = 0;
// Center after render
imageSeries.dataSource.events.on("done", function(ev) {
// This doesn't work - perhaps it is firing too early?
chart.homeGeoPoint = {
latitude: 39,
longitude: -96.2456
};
});
By request, here is a foo.json file for expirmenting with.
[{"title":"ISP","url":"\/airport\/kisp\/","latitude":40.7952,"longitude":-73.1002},{"title":"AEX","url":"\/airport\/kaex\/","latitude":31.3274,"longitude":-92.5486}]
What do I need to do to make sure the map stays centered on my desired location after the JSON data are loaded and rendered?
I've created an issue on GitHub in regards to why the map re-positions on the MapImageSeries' dataSource load and how to better work with that. (If you've a GitHub account, please subscribe to the issue.)
In the meantime, presuming the first time your dataSource gets its data that the user hasn't moved the map and we want to maintain homeGeoPoint as the current center, we can chain events to achieve that.
When the dataSource is "done" with its data, that doesn't necessarily imply anything has been done on the actual map level. The data still needs to propagate to the MapImageSeries, that still needs to create MapImages per data item, have the data validated/parsed there, and for whatever reason the map position shifts around. So the first time that happens (using events.once instead of events.on), we then listen for the MapImageSeries' "datavalidated" event also only one time (because "datavalidated" will have run before this, e.g. as soon as you create the MapImageSeries, if no data is supplied or it's taking some time, it will still run the event and the "inited" event, i.e. I guess you can say the series itself will successfully render nothing).
And to center the map we use chart.goHome(0);, this method will zoom to your homeGeoPoint and homeZoomLevel, the 0 is for how long the animation duration should run, i.e. just do the work, don't animate.
So all that together will look something like this:
// Center after render
imageSeries.dataSource.events.once("done", function(ev) {
imageSeries.events.once("datavalidated", function() {
chart.goHome(0);
});
});
Here's a demo:
https://codepen.io/team/amcharts/pen/239bfdc8689c65468df32d71b29759b8
Even though the map does re-position once the MapImageSeries loads, then it re-centers with the above code, I haven't actually seen the map shift at all anymore. So it looks to me the above code is doing the job of maintaining the homeGeoPoint. Let me know if that is still the case once implemented in your application.

Get id of dragged element in d3.js

I am probably having some kind of brain damage atm because something like this should be trivial.
I got a bunch of SVG circles rendered manually (via React). I am then attaching d3 drag behavior to all of them. The drag behavior is applied, and the drag function is being executed, but when I drag one of these circles I am not able to respond accordingly because I do not know which one of them was moved. Where can I get the ID of dragged element?
I have checked a few other questions and found just some crazy filter solution... that cannot be it.
I have also peeked at docs and found the subject property.. however that one is null everywhere I tried it.
My code:
componentWillUpdate() {
let nodes = d3.selectAll("circle");
const dragFn = (d,i) => {
d3.event.sourceEvent.stopPropagation();
this.props.onNodeDrag(I_NEED_AN_ID_HERE);
}
const dragBehavior = d3.behavior.drag();
dragBehavior.on('drag', dragFn);
dragBehavior.on('dragstart', () => {
d3.event.sourceEvent.stopPropagation();
});
nodes.call(dragBehavior);
}
I don't know what your "this" is inside the function but in plain js you can get any attribute of the html element with:
d3.select(this).attr("id"); //or class etc.
or if it's wrapped
d3.select(this).select("circle").attr("id");
Here's an example: http://jsfiddle.net/a2QpA/343/

jsPlumb: Large endpoint to make touch easier

My implementation has two lists of elements and you basically connect items from the list on the left to items from the list on the right.
We have set the endpoints to be transparent so on the desktop it looks like you just drag from elements on one side to the other.
It works brilliantly on desktop but on touch devices we need the endpoint to cover exactly the space of the element it is attached to in order for it to work as the user would expect. So in effect the whole element becomes an endpoint.
I can achieve this by making the endpoint a rectangle of the same size and anchoring in the center, but I want to anchor on the right/left. If I anchor in the right/left, then my large endpoint is then half covering the element.
Is there a way of anchoring on the right/left but have the endpoint covering the element entirely? Or offsetting the endpoint somehow so it still covers the element?
Thanks in advance for any help
Btw jsPlumb is awesome
You can do it using a transparent image. I did it that way.
endpoint:[ "Image", { src:"/javascript/project/img/c.png",
cssClass:'node' } ]
If you use jsPlumb.addEndpoint() you can add additional parameters for each endpoint you create.
I got this code from one of the examples:
var exampleGreyEndpointOptions = {
endpoint:"Rectangle",
paintStyle:{ width:25, height:21, fillStyle: color }, // size and color of the endpoint
isSource:true,
connectorStyle : { strokeStyle: color }, // color of the line AND the arrow
isTarget:false,
maxConnections:20,
anchor: "BottomCenter"
};
var endpointOptions = {
isTarget:true,
endpoint:"Dot",
paintStyle:{
fillStyle: color // color of the end point
},
beforeDrop: function(info){
return handleConnectionDrop(info);
},
dropOptions: exampleDropOptions,
maxConnections: 20,
anchor: "TopCenter"
};
function InitContainer(el, data) {
elem = $(el);
jsPlumb.addEndpoint(el, {
uuid: elem.attr("id")+"sr"
}, exampleGreyEndpointOptions);
jsPlumb.addEndpoint(el, {
uuid: elem.attr("id")+"tr",
parameters: data // store data in the drain Endpoint
}, endpointOptions);
....
}
in this function I added two endpoints to one element, each with different attributes.
The actual problem you have is that the surface of the endpoint needs to be offset from it's position so that it is within the element. This is mentioned in the API docs, but I didn't find an example yet:
http://jsplumb.org/apidocs/files/jquery-jsPlumb-1-3-16-all-js.html#Endpoint.paint
You can change the position of a anchor, not only by the documented text (like "TopCenter") But also by a array:
anchor: [0.2, 1,0,1]
Give it a try, You'll be able to position the anchor relative to it's element

Resources