Leaflet + Turf strange squareGrid behaviour - leaflet

After a week of tests, and researches I've decided to "give up" and ask you guys for some help.
What I'm trying to accomplish is fairly easy.
Take the world map and split it in 4 quadrants (done)
Take each quadrant, and using turf calculate how many squares of N units are contained.
Everything works fine with the 2 first quadrants: A (red), B (green)
In fact, if I then try to fill the first two quadrants with squares using turf the result is correct:
The problem is that when trying to replicate the same logic on the squares below, turf returns 0 squares...
The code used to create the 4 quadrants with Leaflet is the following:
const quadrantA = L.rectangle(L.latLngBounds(L.latLng(90, -180), L.latLng(0, 0)), { weight: 1, fillColor: 'red', color: 'red' });
const quadrantB = L.rectangle(L.latLngBounds(L.latLng(90, 0), L.latLng(0, +180)), { weight: 1, fillColor: 'green', color: 'green' });
const quadrantC = L.rectangle(L.latLngBounds(L.latLng(0, -180), L.latLng(-90, 0)), { weight: 1, fillColor: 'blue', color: 'blue' });
const quadrantD = L.rectangle(L.latLngBounds(L.latLng(0, 0), L.latLng(-90, 180)), { weight: 1, fillColor: 'yellow', color: 'yellow' });
quadrantA.addTo(this.map);
quadrantB.addTo(this.map);
quadrantC.addTo(this.map);
quadrantD.addTo(this.map);
Meanwhile the code used to calculate the squares in each quadrant with turf is the following:
const QGrid_A = turf.squareGrid(turf.bbox(quadrantA.toGeoJSON()), 500, { units: 'kilometers' });
const QGrid_B = turf.squareGrid(turf.bbox(quadrantB.toGeoJSON()), 500, { units: 'kilometers' });
const QGrid_C = turf.squareGrid(turf.bbox(quadrantC.toGeoJSON()), 500, { units: 'kilometers' });
const QGrid_D = turf.squareGrid(turf.bbox(quadrantD.toGeoJSON()), 500, { units: 'kilometers' });
Problem is, that the "second round" of calculations returns always 0 features for the quadrants C and D.
QGrid_A features: 800
QGrid_B features: 800
QGrid_C features: 0
QGrid_D features: 0
I've also read about that Leaflet reverses the standard GeoJSON coordinates positions, by using [LAT,LON] instead of [LON,LAT], so I've also tried to reverse the result of the Leaflet generated GeoJSONs by doing a reverse on the coordinates array, but still nothing.
I wonder where am I wrong here? Is it a problem of "looped" coordinates? Is it a problem due to a falsy conversion between Leaflet and Turf? Is it me dumb? Please help me guys.

My solution
At the end of the day, I've adopted another strategy. Pretty simple tbh.
I've created a polygon which is the "area to map". This polygon then is split in several sub-squares polygons. Each square then can be used as an individual "tile".
Using #turf/square-grid and #turf/bbox was to achieve this was pretty easy,
the code for this is all incapsulated in 2 functions:
export interface ISplitAreaInSubareasConf {
squareCellSide?: number;
units?: `meters` | `kilometers`;
}
private splitAreaToMapInSubAreas(areaToMap: Polygon, opts?: ISplitAreaInSubareasConf): BBox[] {
const units = opts && opts.units ? opts.units : this.SQUARE_UNIT;
const side = opts && opts.squareCellSide ? opts.squareCellSide : this.SQUARE_CELL_SIDE_IN_KM;
const grid = turfSquareGrid.default(this.getAreaToMapBBox(areaToMap), side, {units, mask: areaToMap});
return grid.features.map(feat => this.getAreaToMapBBox(feat.geometry));
}
private getAreaToMapBBox(areaToMap: Polygon) {
return bbox.default(areaToMap);
}

Related

Deck.GL, Creating a Polygon layer with a rectangle that has a slope

Question
I've been trying multiple ways to create a rectangle that has a slope, tried using the GeoJsonLayer and PolygonLayer to accomplish this. I can't seem to find a way to create the shape and have it extend all the way to the ground on all sides. I use the Z index on the coordinates to tell it what altitude it should put the vertex at.
To give a clear picture of what I'm trying to do, I basically want to have a rectangle that can be sloped on a side but still have it extend until the ground instead of floating in the air.
const data = [
{
contour: [[-122.4, 37.75, 2000], [-122.4, 37.8, 2000], [-122.5, 37.8], [-122.5, 37.75], [-122.4, 37.75]],
}
];
const overlay = new MapboxOverlay({
layers: [
new PolygonLayer({
id: 'polygon-layer',
data: data,
pickable: true,
stroked: true,
filled: true,
wireframe: true,
extruded: true,
lineWidthMinPixels: 5,
getPolygon: d => d.contour,
getFillColor: [255, 0, 0, 100],
getLineColor: [80, 80, 80],
getLineWidth: 1,
transitions: { getElevation: 600 }
})
]
});

Changing style of Leaflet Realtime geoJson features

I have a leaflet map using leaflet-realtime to display and update a position, polygon and line from a geoJson source (data is the position and field of view from an airborne camera). I want to change the style of the line and polygon from the default blue. I understand the leaflet-realtime extends L.geojson so I thought the following code should work but I get options.style is not a function. I have been looking at other examples to try and do this but have spent the day frustrated.
var lineStyle = {
color: 'black',
weight: 5,
opacity: 0.5
}
los = L.realtime({
url: 'http://127.0.0.1/geojson/los2.geojson',
crossOrigin: true,
type: 'json'
}, {
interval: 1 * 500,
style: lineStyle
}).addTo(map);
los.on('update', function(){
map.flyTo(
[this._features.los.geometry.coordinates[1][1],
this._features.los.geometry.coordinates[1][0]]
)
});
If anyone can point me in the right direction it would be hugely appreciated.
Thanks
Yes options.style must be a function - look at:
https://leafletjs.com/reference-1.7.1.html#geojson-style
Change your code:
var lineStyle = {
color: 'black',
weight: 5,
opacity: 0.5
}
los = L.realtime({
url: 'http://127.0.0.1/geojson/los2.geojson',
crossOrigin: true,
type: 'json'
}, {
interval: 1 * 500,
style: function() { return lineStyle; }
}).addTo(map);
los.on('update', function(){
map.flyTo(
[this._features.los.geometry.coordinates[1][1],
this._features.los.geometry.coordinates[1][0]]
)
});

Finding Leaflet Layer Dasharray

I am creating a document from a leaflet map. The legend from the map features will not be part of the map but a separate area on the document. I am trying to get the Layer information such as color and dasharray(solid, dashed....) information from each layer.
I have used feature.option.style, but I get function style(feature) {return....}. I want to get the actual values.
var lyrs = map._layers;
for (var f in map._layers) {
var feature = map._layers[f];
alert(feature.options.style);
return false;
}
I get this:
function style(feature) {
return {
weight: 1,
opacity: 1,
color: 'black',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.Rights, "geojson", "parcel")
};
}
I want to be able to get:
fillColor:black;
dashArray: '3'
Instead of using the style call the code should read as follows
var lyrs = map._layers;
for (var f in lyrs) {
var feature = map._layers[f];
var properties = feature.options.dashArray;
alert(properties);
return false;
}
This returns the value of 3. Exactly what was desired. The same call could be used to find the weight, opacity, color, fillOpacity or fillColor

Show legend of "Indicator plot" in dojo charts

Is there a way to create a Legend control for series that belong to Indicator Plot with Dojo Charting.
I've tried some standard well described ways from the documentation. But with no success! Legend are not appearing for Indicator Plot.
Maybe somebody know is it possible to draw legend for this case or not?
Thanks in advance!
EDIT(my code added):
1. id - id of chart dom element.
2. opts.chartOpts - chart options from outside js.
3. legname - id of legend dom element.
4. scale.avg - is just a double value.
this.chart = new Chart(id, this.opts.chartOpts);
this.chart.addPlot("default", {
animate: { duration: 1000, easing: easing.linear },
type: ColumnsPlot,
markers: true,
gap: 1
});
this.chart.addPlot("avgline", {
type: IndicatorPlot,
vertical: false,
lineStroke: { color: "#00ff00", style: "ShortDash" },
stroke: { width: '1.2px' },
fill: '#eeeeee',
font: 'normal normal normal 11px Arial',
labels: 'none',
offset: { x: 32, y: 4 },
values: [scale.avg],
precision: this.opts.precision
});
//Add axis code goes here... cutted for clearance
this.chart.addSeries('Power', chartOptions.data);
this.chart.addSeries('Average', [scale.avg], { plot: 'avgline' });
var tip = new Tooltip(this.chart, "default", { 'class' : 'kaboom' });
var mag = new Magnify(this.chart, "default");
var hightlight = new Highlight(this.chart, "default");
this.chart.render();
this.leg = new Legend({ chart: this.chart, horizontal: false }, this.legName);
And as result of this code I see legend for 'default' plot 'Power' series only. And nothing for 'Average' series.

Embed bubble charts on a web site

I'm looking for a way to create what come to know to be called a "bubble chart" for a website I'm building. It needs to be compatible with IE7 and above, and of course all the good browsers like Firefox, Chrome and Safari. And no flash since this thing will need to run on iOS.
The chart needs to look like this, http://www.flickr.com/photos/jgrahamthomas/5591441300/
I've browse online and tried a few things, including:
Google Scatter Charts. This doesn't work as it seems Google Charts limits the size of a point to something smaller than I need. And Venn Diagrams are limited to three circles.
Protovis Dots. Great library, but isn't compatible with IE8.
Raphael Javascript. This one might be my best bet, but there's no explicit support for bubble charts.
Thanks for your help.
It looks like Raphael javascript is the way to go. It's compatible with IE6. I found a great tutorial at http://net.tutsplus.com/tutorials/javascript-ajax/an-introduction-to-the-raphael-js-library/ and am able to get the example working on my rails site with this code:
# window.onload = function() {
# var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
# var circle = paper.circle(100, 100, 80);
# for(var i = 0; i < 5; i+=1) {
# var multiplier = i*5;
# paper.circle(250 + (2*multiplier), 100 + multiplier, 50 - multiplier)
# }
# var rectangle = paper.rect(200, 200, 250, 100);
# var ellipse = paper.ellipse(200, 400, 100, 50);
# }
You can give Protovis a chance, the library looks good for your needs: http://vis.stanford.edu/protovis/ex/
Another charting library is Highcharts, but I haven't tried it yet: http://www.highcharts.com/
Have you had a look at flot?
It's a plotting library for jQuery. While it technically doesn't have any "native" support for bubble charts it is possible to create bubble charts with it by using a few tricks, the simplest one probably being to simply put each point in its own data series (thus allowing you to control the radius of each individual point.
By defining your points similar to this you'll be able to create a bubble chart:
var dataSet = [{
color:"rgba(0,0,0,0)", // Set the color so it's transparent
shadowSize:0, // No drop shadow effect
data: [[0,1],], // Coordinates of the point, normally you'd have several
// points listed here...
points: {
show:true,
fill:true,
radius: 2, // Here we set the radius of the point (or rather, all points
// in the data series which in this case is just one)
fillColor: "rgba(255,140,0,1)", // Bright orange :D
}
},
/* Insert more points here */
];
There is a bubble chart available for flot here
Note that you need to scale your bubbles size yourself if you don't want them to coverup the graph. Documentation is here.
To use it, add the following at the beggining of your html page:
and call it from a json result or any data object like in this sample:
$.getJSON('myQuery.py?'+params, function(oJson) {
// ... Some validation here to see if the query worked well ...
$.plot('#myContainer',
// ---------- Series ----------
[{
label: 'Line Sample',
data: oJson.lineData,
color: 'rgba(192, 16, 16, .2)',
lines: { show: true },
points: { show: false }
},{
label: 'Bubble Sample',
data: oJson.bubbleData, // arrays of [x,y,size]
color: 'rgba(80, 224, 80, .5)',
lines: { show: false },
points: { show: false },
},{
label: 'Points sample',
data: oJson.pointsData,
color: 'rgba(255, 255, 0, 1)',
lines: { show: false },
points: { show: true, fillColor: 'rgba(255, 255, 0, .8)' }
},{
...other series
}],
// ---------- Options ----------
{ legend: {
show: true,
labelBoxBorderColor: 'rgba(32, 32, 32, .2)',
noColumns: 6,
position: "se",
backgroundColor: 'rgba(224, 224, 224, .2)',
backgroundOpacity: .2,
sorted: false
},
series: {
bubbles: { active: true, show: true, fill: true, linewidth: 2 }
},
grid: { hoverable: true, clickable: true } },
xaxis: { tickLength: 0 }
}); // End of plot call
// ...
}); // End of getJSON call
I tried to do the same thing with jqPlot which has some advantages but doesn't work with bubbles and other kind of series on the same graph. Also Flot does a better job to synchronise common axis scale with many series. Highchart does a really good job here (mixing bubble chart with other kind of series) but isn't free for us (government context).