How to create Mesh based on a JSON-Object in three.js - json

I have an ajax request which helps me to get a JSON-object from a webserver!
function _loadModel(filename) {
var request = new XMLHttpRequest();
request.open("GET", filename);//open(method, url, async)
request.onreadystatechange = function() {
console.info(request.readyState +' - '+request.status);
if (request.readyState == 4) {//4 == finished download
if(request.status == 200) { //OK -> bezogen auf http Spezifikation
handleLoadedGeometry(filename,JSON.parse(request.responseText));
}
else if (document.domain.length == 0 && request.status == 0){ //OK but local, no web server
handleLoadedGeometry(filename,JSON.parse(request.responseText));
}
else{
alert ('There was a problem loading the file :' + filename);
alert ('HTML error code: ' + request.status);
}
}
}
request.send();// send request to the server (used for GET)
}
_loadModel('http://localhost:8080/bbox?XMIN=3500060&YMIN=5392691&XMAX=3500277&YMAX=5393413')
JSON file:
[{"building_nr": 5, "geometry": "{\"type\":\"Polygon\",\"coordinates\":[[[3500267.16,5392933.95,456.904],[3500259.19,5392933.01,456.904],[3500258.586,5392938.152,456.904],[3500258.02,5392942.97,456.904],[3500265.98,5392943.94,456.904],[3500266.552,5392939.097,456.904],[3500267.16,5392933.95,456.904]]]}", "polygon_typ": "BuildingGroundSurface"}, ...]
This is one object and I have a lot of them in this array.
Now I want to create a mesh!
I think this can be done inside the function handleLoadedGeometry()
//Callback funktion
function handleLoadedGeometry(filename, model) {
var geom = new THREE.BufferGeometry();
for (var i=0;i<10;i++)
{
var vertex = new THREE.Vector3();
vertex.x = model.geometry[i].coordinates[0];
vertex.y = model.geometry[i].coordinates[1];
vertex.z = model.geometry[i].coordinates[2];
geometry.vertices.push( vertex );
}
geom.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
var material = new THREE.MeshBasicMaterial( { color: 0xff00f0 } );
var mesh = new THREE.Mesh( geom, material );
Scene.scene.add(mesh);
}
At the end I get this error in the browser: Cannot read property '0' of undefined
How can I refer to geometry coordinates inside the JSON?

from what you provided it seems the loaded JSON contains an array of multiple objects that is why you get the error
try something like this
function handleLoadedGeometry(filename, models) {
for (var i=0; i<models.length; i++)
{
var model = models[i];
var coordinates = model.geometry.coordinates;
var positions = [];
for (var j=0; j<coordinates.length; j++){
positions.push(coordinates[j][0]);
positions.push(coordinates[j][1]);
positions.push(coordinates[j][2]);
}
var geometry = new THREE.BufferGeometry();
// buffer attributes contain an array not vectors
var positionAttribute = new THREE.BufferAttribute(new Float32Array(positions),3);
geometry.addAttribute("position", positionAttribute);
var material = new THREE.MeshBasicMaterial( { color: 0xff00f0 } );
var mesh = new THREE.Mesh( geom, material );
Scene.scene.add(mesh);
}
}
or remove the first loop if you call it for each object in the JSON array

I did it in another way...I just created instead of BufferGeometry the default Geometry in three.js:
function handleLoadedGeometry(filename) {
var material = new THREE.MeshBasicMaterial({color: 0xFF0000});
for (var i=0; i<filename.length; i++)
{
var model = filename[i]; // erstes Objekt
var coordinates = JSON.parse(model.geometry);
var geometry = new THREE.Geometry();
var coordinates_updated = _transformCoordinates(coordinates.coordinates[0]);
for (var j = 0; j<coordinates_updated.vertices.length; j++){
geometry.vertices.push(
//new THREE.Vector3(coordinates.coordinates[0][j][0], coordinates.coordinates[0][j][1], coordinates.coordinates[0][j][2])//x,y,z Koordinatenpunkte für Surface 1
new THREE.Vector3(coordinates_updated.vertices[j][0],coordinates_updated.vertices[j][1],coordinates_updated.vertices[j][2])
);
geometry.faces.push(
new THREE.Face3(0,1,2),
new THREE.Face3(0,3,2)
geometry.computeBoundingSphere();
}
var mesh = new THREE.Mesh(geometry, material);
Scene.scene.add(mesh);
}
};
And now it works!
I think BufferGeometry is more for more complex surfaces.

Related

Angular 2 - Parsing Excel worksheet to Json

I have an Excel file with the following content:
Inside my component.ts, I extract the Excel's content as follow:
var testUrl= "excel.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", testUrl, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i){
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
var json = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {header:1, raw:true});
var jsonOut = JSON.stringify(json);
console.log("test"+jsonOut);
}
oReq.onerror = function(e) {
console.log(e);
}
oReq.send();
XLSX.utils.sheet_to_json will format JSON as follow:
However, I would like the JSON to be as follow:
Most probably I would need to manually create the JSON, but can anyone help me point to the direction on how I can accomplish this?
In your case we need to modify the JSON data by looping over XLSX.utils.sheet_to_json JSON object:
// This object will contain the data in the format we want
var finalObj = { "object": []};
// Variables to track where to insert the data
var locIndex, firstCondIndex, secondCondIndex,
lockey, firstCondKey, secondCondkey;
// We need to initialize all indexes to -1 so that on first time we can get 0, as arrays start with 0 in javascript
locIndex = -1;
// here obj is XLSX.utils.sheet_to_json
obj.object.map((value, index) => {
// we don't want to consider name of columns which is first element of array
if(!index) return;
// Go inside only if not null
if(value[0]) {
// For Location
finalObj.object.push(createObj(value[0]));
locIndex++;
// We also need to store key names to push it's children
lockey = value[0];
firstCondIndex = -1;
}
if(value[1]) {
// For First Condition
finalObj.object[locIndex][lockey].push(createObj(value[1]));
firstCondIndex++;
firstCondKey = value[1];
secondCondIndex = -1;
}
if(value[2]) {
// For Second Condition
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey].push(createObj(value[2]));
secondCondIndex++;
secondCondkey = value[2];
}
if(value[3]) {
// For Products
// We just push the string
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey][secondCondIndex][secondCondkey].push(value[3]);
}
});
function createObj(val) {
// We need to initialize blank array so we can push the children of that element later on
var obj = {};
obj[val] = [];
return obj;
}
console.log(finalObj);

Explanation for "need typeids" error

I have found a script on github to pull prices from the EVE-Central API to include in a Google Spreadsheet. I have uploaded that script into the editor and saved it. When I try to run it I get an error about a file or function that is missing.
need typeids (line 38, file 'Code')
When I try to use the function inside the spreadsheet it tells me the function does not exist. After a lot of reading I found out Google changed something in their script editors.
Here is the script I am using. And a picture of the error code I got.
/*
Takes a bunch of typeids from a list (duplicates are fine. multidimensional is fine) and returns a bunch of rows
with relevant price data.
TypeID,Buy Volume,Buy average,Buy max,Buy min,Buy Std deviation,Buy median,Buy Percentile,
Sell Volume,Sell Average,Sell Max,Sell Min,Sell std Deviation,Sell Median,sell Percentile
I'd suggest loading price data into a new sheet, then using vlookup to get the bits you care about in your main sheet.
loadRegionPrices defaults to the Forge
loadSystemPrices defaults to Jita
=loadRegionPrices(A1:A28)
=loadRegionPrices(A1:A28,10000002)
=loadRegionPrices(A1:A28,10000002,47)
=loadSystemPrices(A1:A28)
An example below:
https://docs.google.com/spreadsheets/d/1f9-4cb4Tx64Do-xmHhELSwZGahZ2mTTkV7mKDBRPrrY/edit?usp=sharing
*/
function loadRegionPrices(priceIDs,regionID,cachebuster){
if (typeof regionID == 'undefined'){
regionID=10000002;
}
if (typeof priceIDs == 'undefined'){
throw 'need typeids';
}
if (typeof cachebuster == 'undefined'){
cachebuster=1;
}
var prices = new Array();
var dirtyTypeIds = new Array();
var cleanTypeIds = new Array();
var url="http://api.eve-central.com/api/marketstat?cachebuster="+cachebuster+"&regionlimit="+regionID+"&typeid=";
priceIDs.forEach (function (row) {
row.forEach ( function (cell) {
if (typeof(cell) === 'number' ) {
dirtyTypeIds.push(cell);
}
});
});
cleanTypeIds = dirtyTypeIds.filter(function(v,i,a) {
return a.indexOf(v)===i;
});
var parameters = {method : "get", payload : ""};
var o,j,temparray,chunk = 100;
for (o=0,j=cleanTypeIds.length; o < j; o+=chunk) {
temparray = cleanTypeIds.slice(o,o+chunk);
var xmlFeed = UrlFetchApp.fetch(url+temparray.join("&typeid="), parameters).getContentText();
var xml = XmlService.parse(xmlFeed);
if(xml) {
var rows=xml.getRootElement().getChild("marketstat").getChildren("type");
for(var i = 0; i < rows.length; i++) {
var price=[parseInt(rows[i].getAttribute("id").getValue()),
parseInt(rows[i].getChild("buy").getChild("volume").getValue()),
parseFloat(rows[i].getChild("buy").getChild("avg").getValue()),
parseFloat(rows[i].getChild("buy").getChild("max").getValue()),
parseFloat(rows[i].getChild("buy").getChild("min").getValue()),
parseFloat(rows[i].getChild("buy").getChild("stddev").getValue()),
parseFloat(rows[i].getChild("buy").getChild("median").getValue()),
parseFloat(rows[i].getChild("buy").getChild("percentile").getValue()),
parseInt(rows[i].getChild("sell").getChild("volume").getValue()),
parseFloat(rows[i].getChild("sell").getChild("avg").getValue()),
parseFloat(rows[i].getChild("sell").getChild("max").getValue()),
parseFloat(rows[i].getChild("sell").getChild("min").getValue()),
parseFloat(rows[i].getChild("sell").getChild("stddev").getValue()),
parseFloat(rows[i].getChild("sell").getChild("median").getValue()),
parseFloat(rows[i].getChild("sell").getChild("percentile").getValue())];
prices.push(price);
}
}
}
return prices;
}
function loadSystemPrices(priceIDs,systemID,cachebuster){
if (typeof systemID == 'undefined'){
systemID=30000142;
}
if (typeof priceIDs == 'undefined'){
throw 'need typeids';
}
if (typeof cachebuster == 'undefined'){
cachebuster=1;
}
var prices = new Array();
var dirtyTypeIds = new Array();
var cleanTypeIds = new Array();
var url="http://api.eve-central.com/api/marketstat?cachebuster="+cachebuster+"&usesystem="+systemID+"&typeid=";
priceIDs.forEach (function (row) {
row.forEach ( function (cell) {
if (typeof(cell) === 'number' ) {
dirtyTypeIds.push(cell);
}
});
});
cleanTypeIds = dirtyTypeIds.filter(function(v,i,a) {
return a.indexOf(v)===i;
});
var parameters = {method : "get", payload : ""};
var o,j,temparray,chunk = 100;
for (o=0,j=cleanTypeIds.length; o < j; o+=chunk) {
temparray = cleanTypeIds.slice(o,o+chunk);
var xmlFeed = UrlFetchApp.fetch(url+temparray.join("&typeid="), parameters).getContentText();
var xml = XmlService.parse(xmlFeed);
if(xml) {
var rows=xml.getRootElement().getChild("marketstat").getChildren("type");
for(var i = 0; i < rows.length; i++) {
var price=[parseInt(rows[i].getAttribute("id").getValue()),
parseInt(rows[i].getChild("buy").getChild("volume").getValue()),
parseFloat(rows[i].getChild("buy").getChild("avg").getValue()),
parseFloat(rows[i].getChild("buy").getChild("max").getValue()),
parseFloat(rows[i].getChild("buy").getChild("min").getValue()),
parseFloat(rows[i].getChild("buy").getChild("stddev").getValue()),
parseFloat(rows[i].getChild("buy").getChild("median").getValue()),
parseFloat(rows[i].getChild("buy").getChild("percentile").getValue()),
parseInt(rows[i].getChild("sell").getChild("volume").getValue()),
parseFloat(rows[i].getChild("sell").getChild("avg").getValue()),
parseFloat(rows[i].getChild("sell").getChild("max").getValue()),
parseFloat(rows[i].getChild("sell").getChild("min").getValue()),
parseFloat(rows[i].getChild("sell").getChild("stddev").getValue()),
parseFloat(rows[i].getChild("sell").getChild("median").getValue()),
parseFloat(rows[i].getChild("sell").getChild("percentile").getValue())];
prices.push(price);
}
}
}
return prices;
}
The error message is very explicit. Here's the relevant code:
function loadSystemPrices(priceIDs,systemID,cachebuster){
if (typeof systemID == 'undefined'){
systemID=30000142;
}
if (typeof priceIDs == 'undefined'){
throw 'need typeids'; //// <<<< Line 38
}
Function loadSystemPrices() has been invoked with no value for the priceIDs parameter. This condition is explicitly checked by the code, and results in a custom error message being thrown on line 38.
That's happening because you've invoked the function from the debugger, with no parameters. You can work around this by writing a test function to pass parameters, as described in Debugging a custom function in Google Apps Script.

Convert a javascript array to specific json format

I have this JSON.stringify(array) result: ["id:1x,price:150","id:2x,price:200"] and I have to convert it in a json format similar to this (it would be sent to php):
[{
"id":"1x",
"price":150
},
{
"id":"2x",
"price":200
}]
Please help.
You can convert the structure of your data before using JSON.stringify, for example you can convert the data to a list of objects like so:
var strItems = ["id:1x,price:150", "id:2x,price:200"];
var objItems = [];
for (var i = 0; i < strItems.length; i++) {
var pairs = strItems[i].split(",");
objItems.push({
id: pairs[0].split(':')[1],
price: parseInt(pairs[1].split(':')[1])
});
}
Before calling JSON.stringify to get the result you're after:
var json = JSON.stringify(objItems);
console.log(json);
JSON.stringify(array) only does on layer, but you can change the stringify function to work for multiple layers with this function written by JVE999 on this post:
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Once you have declared this, then you can call JSON.stringify(array)

mapserver with WMS call with openlayers

I scenario is below :
map is shown under from TiledWMS layer from mapserver. It has 2 layers.
TiledWMS layer for OSM world map.
TiledWMS layer for layers defined in kml file placed in mapserver through .map file. This map file contains many layers.
Now , when user click on map : it got 2 layers as above.
But since 2nd layer is made up of different layers as given in .map file , i am not able to uniquely identify these layers. I want that since 2 nd layer is made up of different layers in kml file i should be able to uniquely identify them on mouse click or hower.
Thanks
Satpal
I am able to get it : below is samaple code for others.
var coord = evt.coordinate;
var pixel = $scope.map.getPixelFromCoordinate(coord);
var viewProjection = $scope.map.getView().getProjection();
var viewResolution = $scope.map.getView().getResolution();
var numberOfLayersOnMap = $scope.map.getLayers();
var feature = $scope.map.forEachFeatureAtPixel(pixel, function(feature, layer){return feature;}, null, function(layer) {return true;});
if(feature === undefined)
{
$scope.map.forEachLayerAtPixel(pixel, function (layer)
{
if(!layer)
{
return ;
}
var urlWMSGetFeatureInfo = layer.getSource().getGetFeatureInfoUrl(coord, viewResolution, viewProjection, {
'INFO_FORMAT': 'application/vnd.ogc.gml'
});
if(urlWMSGetFeatureInfo.indexOf("osm-google.map")<0)
{
$http({
method: 'GET',
url: urlWMSGetFeatureInfo,
}).success(function(data){
var parser = new ol.format.WMSGetFeatureInfo();
var features = parser.readFeatures(data);
if(features.length>0)
{
var featureName = features[0].n.Name;
topOverlayElement.innerHTML = featureName;
$scope.highlightOverlay.setFeatures(new ol.Collection());
if($scope.flagLinkage == true)
{
var xmlObj = utility.StringToXML(data);
var xmlDocumnet = xmlObj.childNodes[0];
var layerNode = xmlDocumnet.children[0];
var gmlLayerNode = layerNode.children[0];
var layerName = gmlLayerNode.textContent;
var layerInfoObject = {};
layerInfoObject.layerName = layerName;
//layerInfoObject.placemarkName = featureName;
$scope.placemarksSelectedObject.push(layerInfoObject);
$scope.placemarksSelectedFeatureObject.push(features[0]);
}
else
{
$scope.placemarksSelectedFeatureObject.length = 0;
$scope.placemarksSelectedFeatureObject.push(features[0]);
}
$scope.highlightOverlay.setFeatures(new ol.Collection($scope.placemarksSelectedFeatureObject));
var featureDescription = features[0].n.description;
middleOverlayElement.innerHTML = (featureDescription === undefined) ? '' : featureDescription;
$scope.showOverlay(coord);
}
}).error(function (data) {
console.log("Not able to get capabilty data.");
});
}
else
{
$scope.closeOverlay(evt);
}
});

Weird Google Maps V2 Marker issue

Got this code, that only works when alert (markers.length); is uncommented.
When this javascript alert not shown I dont get any Markers.. Really weird!!
In the body tag I have <body onload="load()" onunload="GUnload()">
Previoslly the load() function is called and other functions :
function showAddress(address) {
if (geocoder) {//+', '+init_street
geocoder.getLatLng(address,
function(point) {
if (!point) {
document.getElementById("place").value="not found";
//alert(address + " not found");
} else {
// document.getElementById("place").value=point.y.toFixed(4) + "," + point.x.toFixed(4);
map.setCenter(point, 16);
marker.setPoint(point);
//marker.openInfoWindowHtml(address);
}
}
);
}
}
//from a point returns and address!
function showPointAddress(response) {
if (!response || response.Status.code != 200) {//not found
//alert("Status Code:" + response.Status.code);
document.getElementById("place").value="not found";
}
else {//found
map.setCenter(marker.getPoint(), 16);
place = response.Placemark[0];
document.getElementById("place").value=place.address;
//document.getElementById("place").value=marker.getPoint().toUrlValue();
}
}
// Creates a marker at the given point with the given number icon and text
function createMarker(p,text) {
var marker = new GMarker(p);
if (text!=""){
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);});
}
return marker;
}
` var geocoder = null;`
` var map = null;`
function load() {//loading the map
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.enableScrollWheelZoom();
geocoder = new GClientGeocoder();
if (init_street!=""){
geocoder.getLatLng(init_street,function(point) {//set center point in map
if (point){
map.setCenter(point, zoom);
map.addOverlay(createMarker(point,init_street));
map.openInfoWindow(point,init_street);
}
});
}
map.addControl(new GLargeMapControl());
map.setMapType(G_NORMAL_MAP);
}
}`
function(data, responseCode) {
if(responseCode == 200) {
var texts = [];
var addresses = [];
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("item");
alert (markers.length);
for (var i = 0; i < markers.length; i++) {
var address=markers[i].getElementsByTagName('address').item(0).childNodes.item(0).nodeValue;
if (address!=null){
//alert (address);
var title=markers[i].getElementsByTagName('title').item(0).childNodes.item(0).nodeValue;
var link=markers[i].getElementsByTagName('link').item(0).childNodes.item(0).nodeValue;
var desc=markers[i].getElementsByTagName('description').item(0).childNodes.item(0).nodeValue;
desc=desc.substr(0,220);//limit
addresses.push(address);
texts.push("<div style='width: 200px'><a target='_blank' href='" +link+"'>"+title+"</a><br />"+desc+"</div>");
}//if
}//for
for (var i = 0; i < addresses.length; i++) {
geocoder.getLatLng(addresses[i], function (current) {
return function(point) {
if (point) map.addOverlay(createMarker(point,texts[current]));
}
}(i));
}
}//if });
I Understand the issue of needing a callback function to load the markers, but Im lost..
Any help apreciated!! ;)
Thx in advanced!!
This usually happens when fetching data with Ajax or similar. Basically when you fetch the data you need to utilize a callback function to wait for the data. If you don't there is no data to execute on. However, if you pause the execution with a alert() the data will have been fetched in the background.
Think of it as the waiting for the DOM to load before executing Javascript on the page.
I can't give you a better answer as you have not included the code that is calling the function you included.