Feeding array to json for use in turf.polygon, structure problems - arrays

I have a linestring and a polygon and I am using turf.booleanIntersect() to determine if the line goes through the polygon. The example that i have tested and works is:
var poly1 = turf.polygon([
[
[148.535693, -29.6],
[154.553967, -29.64038],
[154.526554, -33.820031],
[148.535693, -33.6],
[148.535693, -29.6]
]
]);
//const p1 = L.geoJSON(poly1).addTo(mymap);
console.log("TEST: " + turf.booleanIntersects(line, poly1));
In my real code I read the polygon values from a file and need to insert them into an array which needs to be converted into a "GeoJSON Feature or Geometry" (from webpage).
I am having trouble getting the array to json convert correct.
var polygonlines = [];
var start = [long,lat];
polygonlines.push([start]); //add multiple of these points to the to polygonlines array
//create my json
var geojsonPolygon =
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": polygonlines
}
}
var turfpolygon = turf.polygon(geojsonPolygon.data.geometry.coordinates); //ERROR HERE
const p2 = L.geoJSON(turfpolygon).addTo(mymap);
var result = turf.booleanIntersects(line, turfpolygon)
The error I get is "Uncaught Error Error: Each LinearRing of a Polygon must have 4 or more Positions."
I can't quite get the structure of the geojsonPolygon correct. I think that it is look at geojsonPolygon Array(1) in attached picture instead of Array(10), but I can't work out how to fix it.
Would love some help getting this structure fixed. Thank you :)
p.s. please ignore values of lat/longs, just examples.
I have seen this question but it hasn't helped How to feed JSON data of coordinates to turf.polygon?

Ongoing answer..., content and code will be edited.
Here is a LIVE demo code that you can run to see how it works. It may help to answer you question.
Usage:
click Run code snippet button
click Full page in top-right corner to see map and console
//Using turf_polygon object style
var poly1 = turf.polygon([
[
[148.535693, -29.6],
[154.553967, -29.64038],
[154.526554, -33.820031],
[148.535693, -33.6],
[148.535693, -29.6]
]
]);
// Using geojson style data
// Coordinates are slightly different from poly1
// This can be used as a good example to compare/contrast with your implementation
// This geojson of poly2 works, you can see it on the map.
var poly2 = {
type: "Feature",
properties: { id: 102, name: "Poly_2" },
geometry: {
type: "Polygon",
coordinates: [
[
[148, -29],
[154, -29],
[154, -33],
[148, -33],
[148, -29]
]
]
}
};
var line12 = turf.lineString([[144, -30], [153, -31.8], [159, -32]]);
var line34 = turf.lineString([[144, -20], [160, -30]]);
/* Init and draw Leaflet map */
var map;
function initMap(coords, zoom) {
// initialize map container
map = L.map("mapid").setView(coords, zoom);
// get the stamen toner-lite tiles
var Stamen_Toner = L.tileLayer(
"https://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.{ext}",
{
attribution:
'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
subdomains: "abcd",
minZoom: 0,
maxZoom: 20,
ext: "png"
}
);
// add the tiles to the map
Stamen_Toner.addTo(map);
//disable scroll wheel zoom
map.scrollWheelZoom.disable();
}
/* Leaflet use (lat,long) */
var coordinates = [-30, 150]; //[lat,long]
var zoom = 5;
initMap(coordinates, zoom);
//Add polygons and lines
L.geoJson(turf.featureCollection([poly1, poly2, line12, line34])).addTo(map);
// Intersection op
var result1 = turf.booleanIntersects(line12, poly1); //True
var result2 = turf.booleanIntersects(line34, poly1); //False
console.log(result1, result2);
//EOF
#mapid { height: 480px; width: 800px}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" />
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet#1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Turf.js/6.5.0/turf.min.js"></script>
<div id="mapid"></div>

How to get the polygonline array into geojson for use in turf polygon:
var polygonlines = [];
//these 2 lines occur multiple times in a loop
{
var start = [vol.lines[k].start.lng, vol.lines[k].start.lat];
polygonlines.push(start);
}
var geojsonPolygon =
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [polygonlines]
}
var turfpolygon = turf.polygon(geojsonPolygon.geometry.coordinates);
turf.booleanIntersects(line, turfpolygon)

Related

How to display text on MapBox at specific coordinates?

I am currently using MapBox GL JS in my React project.
I want to know how to display some text at specific coordinates after an interaction is over. I get the coordinates of the location from a function getMinCoords()
My current code is as follows
stop() {
let nextState = this.state;
if (nextState !== 'Complete') {
nextState = 'Stop';
}
if (this.vertices.length > 2) {
this.annotation.geometries = [{
type: 'Polygon',
coordinates: this.GetPolygonCoordinates(),
properties: {
annotationType: 'polygon',
},
}];
} else {
this.annotation.geometries = [];
}
console.log(this.getMinCoords());
this.map.off('click', this.onClickCallback);
this.setState(nextState);
this.flushState();
}
The function which takes care of annotations is as follows:
this.geometries.forEach((geometry) => {
switch (geometry.type) {
case 'Point':
case 'LineString':
case 'Polygon': {
const styling = GetStyles(geometry, styles);
const feature = GetFeatureFromGeometry(geometry, this.properties);
if (this.properties.annotationType === 'label') {
styling.textAnchor = 'center';
}
feature.properties = { ...feature.properties, ...styleProps };
features.push(feature);
break;
}
Before the state is flushed, I want to display the area at the coordinates returned by getMinCoords. I have another function getArea(), which returns the area. I just need to display it on the map
You can create an empty Layer once your map is instantiated with empty source like below:
Code Snippet:
//Empty Source
const textGeoJsonSource = {
type: 'geojson',
data: featureCollection //Initially this is empty
};
//Text Layer with textGeoJsonSource
const sectionTextLayer: mapboxgl.Layer = {
"id": "sectionTextLayer",
"type": "symbol",
"source": textGeoJsonSource,
"paint": {
"text-color": textColor, //Color of your choice
"text-halo-blur": textHaloBlur,
"text-halo-color": textHaloColor,
"text-halo-width": textHaloWidth,
"text-opacity": textOpacity
},
"layout": {
"text-field": ['get', 't'], //This will get "t" property from your geojson
"text-font": textFontFamily,
"text-rotation-alignment": "auto",
"text-allow-overlap": true,
"text-anchor": "top"
}
};
this.mapInstance.addLayer(sectionTextLayer);
Then later on set the source of "textGeoJsonSource" to below once you have the coordinates( like getMinCoords in your case ):
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ //Pass your coordinates here
5.823,
-6.67
]
},
"properties": {
"t": "18C" //Text you want to display on Map
}
}
]
}
Please note few things:
Your feature collection will need point coordinates in order to show text on Map on that point. If you have a polygon, first get centroid of that polygon for that you can use turf:
http://turfjs.org/docs/#centroid
Helpful Links: Centering text label in mapbox-gl-js?

Mapbox GL JS : Drag 1 point in many points map

We have a requirement where-in we have to provide drag drop facility for markers / points. The example https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/ works perfect for 1 marker. Because it is hardcoded to geojson.features[0].geometry.coordinates = [coords.lng, coords.lat];
However, in a multi point scenario how to set the geojson for respective feature which was dragged?
Kindly let know if any further details required.
Thankx
You can achieve that by storing the current marker and applying the change on it during onMove.
I have added a property to each object to define an id:
var geojson = {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [0, 0]
},
properties: {
id: 1
}
},
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [0, 1]
},
properties: {
id: 2
}
}
]
};
On the onmousedown event on point layer, store the current feature id
Here features[0] is usable because the event fired on point so the first feature is ever the clicked one
map.on("mousedown", "point", function(e) {
currentFeatureId = e.features[0].properties.id;
// Prevent the default map drag behavior.
e.preventDefault();
canvas.style.cursor = "grab";
map.on("mousemove", onMove);
map.once("mouseup", onUp);
});
After that, in the onMove method you can use it to move the right feature :
function onMove(e) {
var coords = e.lngLat;
// Set a UI indicator for dragging.
canvas.style.cursor = "grabbing";
// Update the Point feature in `geojson` coordinates
// and call setData to the source layer `point` on it.
var currentMarker = geojson.features.find(obj => {
return obj.properties.id === currentFeatureId
})
currentMarker.geometry.coordinates = [coords.lng, coords.lat];
map.getSource("point").setData(geojson);
}
See working exemple here : https://codepen.io/tmacpolo/pen/moxmpZ

Copy Array from http request to other array in Angular

I pretty new to angular and I have a question.
I need 2 arrays for ng2-charts, one with labels and one with data.
I make http request to AWS and I got this json
{
"System1": [
{
"name": "MF3",
"descr": "Multifilo MF3",
"speed": [1,2,3,4],
"time": ["10.01", "10.02", "10.03", "10.04"]
}
]
}
I assing all the result to result: Array<SystemModel>;
For use speed and time on ng2-charts I have to copy the two array speed and time on new array: public lineChartSpeed: Array<number> = []; and public lineChartTime: Array<any> = [];
How can I copy this 2 array on my new array? I know how to access to data only on html template, but not on typscript file...
My component is:
public lineChartSpeed: Array<number> = [];
lineChartTime: Array<any> = [];
result: Array<ImpiantoModel>;
getdata() {
this.http.get<SystemModel[]>(this.myUrl)
.subscribe(
data => { this.result = data;
// perform the copy of speed and time on lineChartTime and lineChartSpeed
});
}
How can I copy the array?
If you need more details, please ask in the comments!
thank you !
var system1 = {
"System1": [
{
"name": "MF3",
"descr": "Multifilo MF3",
"speed": [1,2,3,4],
"time": ["10.01", "10.02", "10.03", "10.04"]
}
]
}
var speed = system1.System1[0].speed
var time = system1.System1[0].time
console.log('Array of Speed', speed)
console.log('Array of Time', time)
//Merge or concatenate two Arrays
var newArray = [...speed, ...time]
console.log('Merged or concatenated Arrays', newArray)
Use slice operator to create a new copy of the array
this.result = data.slice();
this.lineChartSpeed = [].concat(this.result[0].speed);
this.lineChartTime = [].concat(this.result[0].time);

How dynamically transform my "Object" to List in ng-model at view

I'm trying to transform my object to list dynamically, so I'm building at view instead of declaring at controller.
I don't want to declare like this: custom_fields.title_field.type_text_field = [] because the title_field is built dynamic, it could be any kind of text like full_name
My json as is:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":{
"name":"John",
"first_name":"Wick"
},
"type_boolean_field":{
"is_badass": true,
"is_good_movie": true
},
"type_select_field": {
"this_select": 1,
"i_got_this": "nope i didnt got this"
}
},
And to be:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":[{
"name":"John",
"first_name":"Wick"
}],
"type_boolean_field":[{
"is_badass": true,
"is_good_movie": true
}],
"type_select_field": [{
"this_select": 1,
"i_got_this": "nope i didnt got this"
}]
},
the object I'm trying to transform into array is type_text_field which can be dynamic too, like type_date_field or type_select_field and so on.
My ng-model is like this:
ng-model="objectApp.application.applicant.custom_fields[layout.dynamic_title][input.type][input.variable]"
the [input.type] is that I'm trying to transform into array, how can I achieve this? I tried to use $index, but got strange results.
We can do it by 2 solutions:
There is a question about your task:
? how you want handle if we have more than one type_text_field in title_dynamic_generate_field? because you want to convert it to "type_text_field":[{},...]
however my answers about the question are:
If we know what's the dynamic params which we want to send theme as json, i mean if we know what is the key of title_dynamic_generate_field or type_text_field, we do as this sample:
var data = {
"custom_fields": {
dynamicParamIs1: 'title_dynamic_generate_field',
dynamicParamIs2: 'type_text_field',
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var paramHelper1 = json.custom_fields[json.custom_fields.dynamicParamIs1];
var paramHelper2 = json.custom_fields.dynamicParamIs2;
var solutionA = function (object, as) {
var array = [];
for (var key in object) {
var newObject = object[key];
array.push(newObject);
}
object[as] = array;
}
solutionA(paramHelper1, paramHelper2);
We changed a model of our json which can help us to detect (find) the keys
If we don't know what is the dynamic params are, we do as this:
var data = {
"custom_fields": {
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var solutionB = function (json) {
var array = [];
for (var key in json) {
var j1 = json[key];
for (var key2 in j1) {
var j2 = j1[key2];
for (var key3 in j2) {
var fullObject = j2[key3];
array.push(fullObject);
j2[key3] = array;
}
}
}
}
solutionB(data);
This sample is manual which we use nested for to detect the keys name

openlayers 3 IGC source from text

I am using openlayers 3 and I am looking for a way to load track data not from urls, but directly by adding text to vectorsource IGC. I have the data with coordinates and times as arrays. What format is right? So, insted of this:
var vectorSource = new ol.source.IGC({
projection: 'EPSG:3857',
urls: [
'data/igc/Clement-Latour.igc',
'data/igc/Damien-de-Baenst.igc',
'data/igc/Sylvain-Dhonneur.igc',
'data/igc/Tom-Payne.igc',
'data/igc/Ulrich-Prinz.igc'
]
});
I'd like to use something like this (not sure about the format):
var vectorSource = new ol.source.IGC({
projection: 'EPSG:3857',
text: [
array1,
array2,
array3 // or arrayall with all three arrays, or text.. What is correct?
]
});
For more control and flexibility you can use an ol.source.Vector and an ol.format.IGC instead of the "convenient" ol.source.IGC. For example:
var source = new ol.source.Vector();
var format = new ol.format.IGC();
var readOptions = {featureProjection: 'EPSG:3857'};
var features = [
format.readFeature(text1, readOptions),
format.readFeature(text2, readOptions),
format.readFeature(text3, readOptions)
];
source.addFeatures(features);
var layer = new ol.layer.Vector({source: source});

Resources