Creating an array from GeoJSON file in OpenLayers 3 - arrays

I am using OpenLayers 3 to animate the paths of migrating animals tagged by scientists. I load the geoJSON file like so
var whaleSource = new ol.source.Vector({
url: 'data/BW2205005.json',
format: new ol.format.GeoJSON()
});
Instead of loading this directly into a layer, I would like to use and reuse the data in the geoJSON file for different purposes throughout my program. For example, I want to pull the lat & lon coordinates into an array to manipulate them to create interpolated animated tracks. Later I will want to query the geoJSON properties to restyle the tracks of males and females.
How might I load the geoJSON data into various arrays at different stages of my program instead of directly into a layer?
Thanks much

When using the url property of ol.source.Vector the class loads the given url via XHR/AJAX for you:
Setting this option instructs the source to use an XHR loader (see ol.featureloader.xhr) and an ol.loadingstrategy.all for a one-off download of all features from that URL.
You could load the file yourself using XHR/AJAX using XMLHttpRequest or a library like jquery which has XHR/AJAX functionality. When you've retreived the GeoJSON collection you can loop over the features array it holds and split it up into what every you need and put those features into new separate GeoJSON collections. Here's a very crude example to give you and idea of the concept:
Assume the following GeoJSON collection:
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [0, 0]
},
"properties": {
"name": "Free Willy"
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [1, 1]
},
"properties": {
"name": "Moby Dick"
}
}, {
// Etc.
}]
}
Here's how to load it (using jQuery's $.getJSON XHR function) and to split it up in to separate collections:
// Object to store separated collections
var whales = {};
// Load url and execute handler function
$.getJSON('collection.json', function (data) {
// Iterate the features of the collection
data.features.forEach(function (feature) {
// Check there is a whale already with that name
if (!whales.hasOwnProperty(feature.properties.name)) {
// No there isn't create empty collection
whales[feature.properties.name] = {
"type": "FeatureCollection",
"features": []
};
}
// Add the feature to the collection
whales[feature.properties.name].features.push(feature);
});
});
Now you can use the separate collections stored in the whale object to create layers. Note this differs some from using the url property:
new ol.layer.Vector({
source: new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(whales['Free Willy'], {
featureProjection: 'EPSG:3857'
})
})
});
Here's a working example of the concept: http://plnkr.co/edit/rGwhI9vpu8ZYfAWvBZZr?p=preview
Edit after comment:
If you want all the coordinates for Willy:
// Empty array to store coordinates
var willysCoordinates = [];
// Iterate over Willy's features
whales['Free Willy'].features.forEach(function (feature) {
willysCoordinates.push(feature.geometry.coordinates);
});
Now willysCoordinates holds a nested array of coordinates: [[0, 0],[2, 2]]

Related

How to iterate through a JSON array and display specific information based on an API response value in React?

I'm building a ReactJS web application, I have a JSON array:
[{
"2149166938": {
"name": "Classical-42",
"icon": "/common/destiny2_content/icons/e6885dab15cafeaf0dbf80f1ff9b5eb8.jpg"
},
"2149166939": {
"name": "Countess SA/2",
"icon": "/common/destiny2_content/icons/de8906743db9fce201b33802c8498943.jpg"
},
"2154059444": {
"name": "The Long Goodbye",
"icon": "/common/destiny2_content/icons/fe07633a2ee87f0c00d5b0c0f3838a7d.jpg"
}
}]
When I make a call to an API I am returned a value of lets say 2154059444 which is the same value as the last object in my JSON file.
How would I iterate through the JSON file to find the object which has a value of 2154059444 and then access and render it's child values like name or icon?
you can do something like this. Your array is not proper please edit.
Create filtered data :
//here i am addding single dummy point you can make your function
l
et filteredData = [].concat(data.map(test => {
if(Object.keys(test)[0]==="2154059444"){
return test["2154059444"]
}
})).filter(Boolean)
and simply render it app like this .
{ filteredData.map(test => <div>{test.name}</div>)}
Here is live link
This is simple. JSON is equivalent to Javascript object. So you can do something like result[0]["2154059444"]. You might want to use JSON.parse for converting the JSON string to Javascript object.

Custom data unwrapping in ampersand.js model

I have a model - Configuration:
var Configuration = Model.extend({
props: {
name: 'string'
}
});
In the database, configuration model / table has 3 columns -> id, name and fields. The latter stores site config as a serialized array. When retrieving the entry from the database, I unserialize it and then pass it to the front end, so the front end receives this:
{
"id": 1,
"name": 'global',
"fields": {
"enabled": true,
"site_name": "Test"
}
};
What I want to do is to set whatever is inside fields object as properties on my model, or maybe session so that things get triggered throughout the site when they are updated. To visualize it, I want to achieve something like this:
var Configuration = Model.extend({
props: {
enabled: 'boolean',
site_name: 'string'
}
});
So basically, is there are a way to 'unwrap' stuff in fields object somehow?
The parse method is what you're looking for in this case. See https://github.com/AmpersandJS/ampersand-state/blob/master/ampersand-state.js#L93-L98 It allows you to transform incoming props.

Export GPX file from Leaflet

What I want to do is let the users create a GPX file by selecting some GeoJson features in Leaflet. The way in which I'm doing it is by creating a new GeoJson layer to store the selected features, then converting this to gpx with a plugin called togpx (https://github.com/tyrasd/togpx). Now I have a gpx file, but I don't know how can I let the users download it. Any suggestions? Here's my code:
var GPXfile;
var trails = new L.GeoJSON.AJAX('data/trasee.geojson', {
onEachFeature: function(feature, layer) {
layer.on({
click: function () {
var selectedGeojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "Rocka Rolla"
},
"geometry": {
"type": "LineString",
"coordinates": feature.geometry.coordinates
}
}]
}
GPXfile = togpx(selectedGeojson);
}
})
}
}).addTo(map);
A JsFiddle might help: http://jsfiddle.net/pufanalexandru/20ara4qe/1/
You can try that ...
A link to trigger the dowload:
Export to file
Some javascript (you have to include jquery):
$("#exportGPX").on('click', function (event) {
// prepare the string that is going to go into the href attribute
// data:mimetype;encoding,string
data = 'data:application/javascript;charset=utf-8,' + encodeURIComponent(gpxData);
// set attributes href and target in the <a> element (with id exportGPX)
$(this).attr({
'href': data,
'target': '_blank'
});
// let the click go through
});
An example here: http://jsfiddle.net/FranceImage/vxe23py4/
Note: it works with Chrome, but you should try other browsers too.

Trouble with updating object properties in AngularJs

I am building my first app in AngularJs.
Here is the plunkr with what I've done so far. The user should be able to add new websites and group them in groups. Groups are also made by the user. Any time the new group is created it is available for new websites. What app should also do is to update group objects with newly assigned websites... and this is where I fail.
Here is how json should look like:
{
"sites": [
{
"url": "http://sfdg",
"id": 0,
"groups": [
{
"name": "adsf",
"id": 0
}
]
}
],
"groups": [
{
"name": "adsf",
"id": 0,
"sites": [//sites assigned
]
}
]
}
In the plunkr code I used push but that just adds new group...
Could you please direct me to the right way of achieving this.
Thanks!
To prevent circular references (a website object refers to a group object that refers to the website object, etc...), I would store id's to the relevant objects instead.
First, when creating a new group, add an empty sites array to it:
function createGroup(newGroup) {
newGroup.sites = []; // <-- add empty array of sites
$scope.groups.push(newGroup);
newGroup.id = groupIdSeq;
groupMap[newGroup.id] = newGroup;
groupIdSeq++;
return newGroup;
}
Then, when you create a new site, update each group to which the site is added:
function createSite(newSite, groups) {
$scope.sites.push(newSite);
newSite.id = siteIdSeq;
sitesMap[newSite.id] = newSite;
// instead of storing the groups array, only store their id:
newSite.groups = groups.map(function(group) { return group.id });
// and add this new sites id to the groups' sites array.
groups.forEach(function(group) {
group.sites.push(newSite.id);
});
siteIdSeq++;
return newSite;
}
(updated plunker here)

pulling in a collection with backbone.js

I am trying to pull in a collection from the url attribute and am having some problems. It seems fetch() returns successfully, but then I cannot access the models in my collection with get(). I am using bbb and requireJS to develop my modules
var rooms = new Rooms.Collection(); // calls the rooms module
rooms.fetch({success: function(){
console.log(rooms.get(1)); // should output the first model
});
Here is my collection code in the rooms module:
Rooms.Collection = Backbone.Collection.extend({
model: Rooms.Model,
url: 'http://localhost:8888/projects/meeting-room/app/data/rooms.json'
});
If I output rooms, everything turns out fine. But when I try for a specific model, that is when I get an error.
[{
"id": 12345,
"name": "Ford",
"occupied": false
},
{
"id": 23458,
"name": "Chevy",
"occupied": false
},
{
"id": 83565,
"name": "Honda",
"occupied": false
}]
The collection.get method looks up a model by id. If you want to find a model by position, use collection.at instead.
Also notice that array indices in javascript are 0-based, so the first model can be found with:
var model = collection.at(0);
For convenience, Backbone collections also implement some of underscore's array and collection methods, including first. That means you can also find the first model with:
var model = collection.first();

Resources