Input geometry is not a valid Polygon in turf.js - javascript

I try to use turf.js and its function intersect in my Leaflet project. My original question can be found here. The problem is I cannot get a proper polygon in order to call it. The idea is to get the waypoints of the calculated route make a polgyon out of them and check where they intersect with a given buffered area.
var testpoint = turf.point([9.9354, 49.799]);
var buffered = turf.buffer(testpoint, 50, {units: 'meters'});
var array = []
control._routes[0]['coordinates'].forEach(function(e){
array.push([e['lat'],e['lng']])
});
var test = turf.polygon(L.polygon([[array]]))
var intersection = turf.lineIntersect(buffered, test)
I am getting the following error message:
Uncaught Error: Input geometry is not a valid Polygon or MultiPolygon
Here I have to point out that, when using line.intersect(buffered,buffered) it is working correctly, therefore I am assuming that the buffered variable is correct.
When it comes down to the test variable, I have tried with no [], one pair and double pair. But they all result in the same problem. I also tried to pass the array to turf.polygon but it couldn`t be done.

Related

Turfjs Point In Polygon always returns false

I'm using Google maps API that geolocates the user and, if they are in the city of Los Angeles, will tell them what LAPD reporting district they are in. I have a geojson overlay of the reporting districts (RD's) that's loading from here.
I want to get the geolocated coordinates, and use Turfjs's booleanPointInPolygon to determine if it's in an RD and if so, return that RD.
But no matter what I do, the turfjs function always returns false even though I'm clearly in an RD/Polygon.
I downloaded the geojson file and import it locally as a regular json file.
Here is my function:
getRd() {
const repdist = require("../assets/LAPD_Reporting_Districts.json");
let point = turf.point([34.05350702472784, -118.24291762202074]);
var poly;
repdist.features.forEach(rd => {
poly = turf.polygon(rd.geometry.coordinates);
var found = turf.booleanPointInPolygon(point, poly);
console.log("found: ", found);
});
As far as I can tell, the turf.point and turf.polygon array are properly formed and there are no errors on execution. I've stepped through the turf function and everything seemed fine.
Given the coords in the code sample (LA City Hall, which is in RD 124), I would expect the result to return true, but "found" returns 1135 falses.
I'd suggest checking two things:
The turf.point coordinate must be Lon,Lat instead of Lat,Lon. This might be the issue because -118 is not a valid latitude. Lon,Lat is a very common convention.
Also check the value passed in to booleanPointInPolygon The documentation shows the coordinate arrays being wrapped in two arrays, not just one.

Identify point inside a polygon (inclusive of point lying on boundaries and edges)

I am using turf.js to find a point inside a polygon and i found the problem persisting for several use cases one of such use case is as below below mentioned use case (i.e. for point (X=32.8,Y=40). I have also plotted the image for reference for which turf.booleanPointInPolygon is showing false.
Image of Graph plot
var turf = require("#turf/turf");
var pt = turf.point([32.8,40]);
var poly = turf.polygon([[
[ 7.2 , 160.0],
[38.3, 30.0],
[65.1 , 30.0],
[62.3 , 96.0],
[18.4 , 325.0],
[7.6 , 380.0],
[7.5 , 307.0],
[7.4 , 234.0],
[7.2 , 160.0]
]]);
var bool = turf.booleanPointInPolygon(pt, poly, {ignoreBoundary: false});
//bool = false, even though the point is inside the polygon
failed to recognize a point within the polygon, this is a glitch from turf.js.
How to report to turf.js. Anyone please help in fixing this.
I converted the cartesian x-axis array, y-axis array and the point to be found to log scale using Math.log(x) in javascript before feeding to turf.js for creating polygon and the point to be found within it. It is rendering correctly now. The major flaw was that i plotted my coordinates in log scale and was seeking turfs solution by passing cartesian data (which i converted to log scale before sending to turf)
Your point is not inside the polygon. There is no bug in turf.js. You probably been tricked because your plotted graph is completely wrong.
Here it is how your polygon should look likes on a graph. You see that your point (J) is clearly outside:

Tensorflow Error: Constructing tensor of shape (120800) should match the length of values (121881)

I am new to machine and new to tensorflow. As a method of learning, I have been following along with Dan Shiffman of the Coding Train as he shows how to create a color classifier.
I, however, wanted to do something different, so I collected data of hand-drawn shapes. Each shape has a label (square, circle, or triangle) and also has an array of 400 pixels (each picture was draw in a 20x20 grid). The data is stored in an object, which is contained within a JSON file.
Using p5.js's 'loadJSON' function, I can access the JSON file, iterate the entries, and create two arrays: 'shapes,' which is a an array of an array of pixels, and 'labels,' which is an array of the corresponding labels.
Below is the code, which utilizes p5's 'preload' and 'setup' functions.
let data;
let model;
// list of labels from which you can get the oneHot index
let labelList = [
"square",
"circle",
"triangle"
];
// function that is ran before setup
function preload() {
data = loadJSON('shapeData.json'); // loads the json file
}
// called after preload
function setup() {
let shapes = []; // an array of the pixels of hand-drawn shapes
let labels = []; // the corresponding label of each hand-drawn shape
// iterates over all of the entries in data
for (let record of data.entries) {
let pixels = record.pixels;
shapes.push(pixels);
labels.push(labelList.indexOf(record.label));
}
// ---------------- ERROR ------------------------
let xs = tf.tensor2d(shapes);
// these tensors work great
let labelsTensor = tf.tensor1d(labels, 'int32');
let ys = tf.oneHot(labelsTensor, 3);
}
The problem arises when I try to create the 'xs' as a tensor2d.
I get the error:
Error: Constructing tensor of shape (120800) should match the length of values (121881)
at assert (tfjs#0.11.7:2)
at new e (tfjs#0.11.7:2)
at Function.e.make (tfjs#0.11.7:2)
at Function.e.tensor (tfjs#0.11.7:2)
at Object.e.tensor2d (tfjs#0.11.7:2)
at setup (sketch.js:27)
at p5.<anonymous> (p5.js:46551)
at _runIfPreloadsAreDone (p5.js:46499)
at p5._decrementPreload (p5.js:46509)
at p5.js:59586
I have a total of 302 data points, each of which is an array of 400 binary numbers. Therefore the shape of the tensor should be [302, 400], and when I change the shape to something that is wrong (like [303, 401]) it gives an error saying that it should be [302, 400].
I am new to this whole process, so any help will be appreciated.
Thanks
I have found the fix! The separate script which downloads the data had an error. This created data of different lengths...
For instance, one shape had 400 pixels and another had 410 pixels. This difference created a problem within tensorflow. After removing the data points that did not have 400 pixels, the program worked just fine!

Creating accurate line buffer in ESRI Javascript API

I'm using the ESRI JavaScript API v3.8. (I know 3.11 is out - can't upgrade yet.)
What I'm trying to do is to create a geometric buffer of a size provided by the user from an arbitrary line (or point) selected by the user. Some of the relevant code is shown below:
var params = new esri.tasks.BufferParameters();
params.distances = [values.distance]; //the input distance
params.geometries = [gr.geometry]; //the input geometry
params.unit = esri.tasks.GeometryService.UNIT_FOOT;
params.outSpatialReference = mapView.map.spatialReference; //always 3857
params.bufferSpatialReference = gr.geometry.spatialReference; //always 3857
esri.config.defaults.io.corsEnabledServers.push('mydomain.com');
esri.config.defaults.io.proxyUrl = 'https://serverdomain.com/proxy';
var gsvc = new esri.tasks.GeometryService('https://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer');
gsvc.simplify(params.geometries, function(geometries){
params.geometries = geometries;
gsvc.buffer(params, function(geometries){
//add output geometry to the map and perform spatial query with it
}, function(err){
//handle error
});
}, function(err){
//handle error
});
The problem is that, if I use an input distance of 500 (feet), then measure the distance from the center line of the input geometry on self._queryGeometry, using ESRI's measurement tool, the actual width of the polygon created is something like 370 feet on either side of the center line.
I've managed to get this to work more accurately using the Illinois State Plane spatial reference, as my test objects are in Illinois, but the logic needs to work everywhere.
When I try various incarnations of doing a geodesic buffer, the input distance unit seems to get ignored and, using an input distance value of 500, I get a buffer that spans the entire world! Either that or the results are exactly the same, depending on how things are set up.
I believe I need to do a geodesic buffer, but I have absolutely no idea how to go about that in such a way that the geometry service will actually pay attention to the units I'm sending in.
Any ideas would be greatly appreciated. Let me know if I've left anything out.
Sounds like there might be a spatial reference issue somewhere. You can try re-projecting geometry into 3857 if that's what the map is and I would inspect the geometry being returned from the buffer and simplify to make sure it looks like what your expecting. I have had issues with the geometry service area's and length's returning slightly incorrect geometries and in my case it ended up being an issue with an incorrect spatial reference. Also, I know you said you can't upgrade, but 3.13 is out and can do geometry options locally without the need for a proxy or any network requests, if possible, it would be worth trying out.

D3.geo.bounds does not return bounding box?

I am having a problem that I have traced to unexpected behavior in the d3.geo.bounds function.
var bounds = d3.geo.bounds(data);
For a geoJSON FeatureCollection containing only point features, a proper bounding box isn't returned: specifically, the x-values of the first and last points in the collection appear to used instead of the min and max x-values for the group of points. This can be seen in action at http://jsbin.com/icosof/4/edit.
The bounding-box coordinates returned thus includes the min and max y-values, but not the largest and smallest x-values. Instead, these seemed to be grabbed from the first and last features in the set:
[[6113.30166221, -6663.98951731], [5153.32052977, -77.3529517971]]
Generating a bounds object by manipulating the coordinates directly
xvalues = [];
$.each(data.features, function(i,el){
xvalues.push(el.geometry.coordinates[0]);
});
yvalues = [];
$.each(data.features, function(i,el){
yvalues.push(el.geometry.coordinates[1]);
});
console.log([[Math.min.apply(null,xvalues),Math.min.apply(null,yvalues)],
[Math.max.apply(null,xvalues),Math.max.apply(null,yvalues)]]);
produces the desired result:
[[3397.33954824, -6663.98951731], [6504.18296202, -77.3529517971]]
Does d3.geo.boundsexpect a FeatureCollection sorted by x-coordinates (and if so how would I work around this), or is this a bug?
I think the confusion here is that d3.geo.bounds expects features to have latitude/longitude values, not x/y values. So your input is taken as % 360, and you won't get the max/min you expect.
You may need to convert your coordinates to lat/lon values to get this to work - left as an exercise for the reader, as I don't know what your coordinate system is.

Categories