Cesium using local/offline tileserver (TypeScript) - reactjs

I am trying to set up a local/offline tileserver to serve Cesium's tiles for the 3D Planet/Globe. I have completed my setup for Resium and Cesium based on the following thread I created. After the necessary setup I then retrieved a Precompiled Cesium Assets provided by cesium and placed it within my Python Server. I Have also came across the following guide for Offline Cesium as well as an example for Online Cesium.
After following the guide I noticed that it wasn't working as expected and found out that createTileMapServiceImageryProvider has been deprecated, so I decided to use UrlTemplateImageryProvider instead.
Next, I began to render react cesium using the following code.
First, I did the necessary Imports
import * as cesium from 'cesium';
import * as React from 'react';
import { Entity, PointGraphics, Viewer } from 'resium';
Secondly, I created my Tile Server Properties
const tms = new cesium.UrlTemplateImageryProvider({
url: 'https://localhost:5000/{z}/{x}/{y}.png',
maximumLevel:10,
})
Once created I used it for my Viewer.
<Viewer
baseLayerPicker={ false }
geocoder={ false }
imageryProvider={ tms }
full={ false }
homeButton={ false }
fullscreenButton={ false }
vrButton={ false }
infoBox={ false }
navigationHelpButton={ false }
>
<Entity position= { cesium.Cartesian3.fromDegree(-74, 40, 100) }>
<PointGraphics pixelSize={ 10 }/>
</Entity>
</Viewer>
Even with the following settings above I noticed that my "Network" tab is not retrieving the necessary PNG Files. Which means that cesium is not even attempting to render my Planet/Globe for some reason.
Currently, there are two errors within my console which states importScripts failed for Workers/createVerticesFromHeightmap..... and TypeError: data.loaderConfig is undefined
It can be noted that geocoder and baseLayerPicker is set as false to prevent an error related to cesium ion default access token.

Related

process is undefined in React

I am building a simple React app that generates a QR code from data. I am interested in inspecting the memory usage when the QR code is generated. I am using the built process.memoryUsage() function but the app throws and exception
Uncaught TypeError: process__WEBPACK_IMPORTED_MODULE_1__.process is undefined
I have tested some different solution, i tried to rollback the react script version to "4.0.3" i tried to download the npm polyfill webpack but there is no success.
I am currently using these imports
import React, { useState, useEffect } from 'react';
import process from 'process';
import './App.css';
const QRCode = require('qrcode');
The function looks like this
let stringData = JSON.stringify(qrData);
console.log("Number of chars in data" + " " + stringData.length);
QRCode.toDataURL(stringData, function (err, url) {
if(err) return console.log("error occured")
//window.location.href = url;
})
const used = process.memoryUsage();
for (let key in used) {
console.log(`${key} ${Math.round(used[key] / 1024 / 1024 * 100) / 100} MB`);
}
}
process is a Node.js API and is not available in the browser where your React app is running, which is why you see that error. If there is an available global process object, it is being polyfilled by something in your build tools, and will not have the memoryUsage method.
There is no equivalent API for the browser, but some related APIs do exist. Note that this is an evolving space and some are non-standard, so be sure to read both the spec and documentation before considering any usage:
Device Memory API (MDN)
Performance.memory (MDN)
You are using a built in nodejs package in a react app. Node executes on the server and has access to system level resources. React runs in the browser and does not. See this article for some tips measuring performance in React.

How to access loaded script in Salesforce Lightning Web Component?

When loading an external library in a Lightning Web Component, I can't seem to access the actual script.
Instead, I can only find the reference to the static resource by checking the resolved import string.
phone.js:
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import JsSIP from '#salesforce/resourceUrl/jssip';
// import * as JsSIP from 'jssip';
export default class Phone extends LightningElement
{
...
async connectedCallback() {
console.log(JsSIP); // This resolves to the static resource location inside the connected org in a string.
loadScript(this, JsSIP + '/jssip.js')
.then(() => {
console.log(JsSIP.version); // This is only accessing the resource reference, not the actual script; so result is *undefined*.
...
}
So my question is: "How to access the loaded script instead of the resource reference?".
I've followed the guides here and here and found this GitHub issue that seems to be dealing with the same referencing problem. The solution however is not apparent for my specific case.
Any help with this would be much appreciated!
I think your library creates a "global" object called JsSIP once it finishes loading. And the name clashes with the name for the file reference. Can you name it import jssip or jsSipLibrary or something and see what happens?
Put debugger; statement into then and enable debugging in Setup -> debug mode. Open the page with browser's console (F12 most of the time)

Is there a way to track a user active time spent in the React web application via Google Analytics?

Let's say an user with user_id(1000) and email(user101#example.com) logged into the reactjs based web application and browsed a few pages for 2mins and then moved to other application tabs/windows for 30mins and came back to the web application and browsed the app for 5more mins on April 1st 2021.
I would like track/get this user's time spent report in the Google Analytics report saying user101#example.com with user_id(1000) has spent 7mins on April 1st 2021. Is there a way to track the same via GA if possible with react-ga, if it is possible how can we do it?
As of now with react-ga I'm tracking the userid property like the below:
ReactGA.set({userId});
If it is not possible via Google Analytics, is there any service provider that has this kind of feature?
Note: I have gone through existing q/a but unable to find/figure out the solution.
I was able use another tracker Riveted, which by it's definition:
Riveted helps fix this by measuring the amount of time users are
actively engaged (e.g., clicking, scrolling, using the keyboard) and
then reporting the data to Google Analytics in frequent intervals.
More on it's page.
While Riveted is written with a direct global variable, we need to work around to make it available for the react project using exports-loader.
Here is what I could achieve:
Get the riveted.js locally as a file
Ensure to install the exports-loader via npm install exports-loader --save
Import the same with the location of revited.js as:
import riveted from 'exports-loader?exports=riveted!./riveted.js';
After you have initialised ReactGA.initialize(configs);
If you check the source code of riveted, you will notice it's using the same ga object of window.ga and thus the google analytics once initialised via ReactGA.initialize should be enough.
The react-ga provides an ability to extend ga. They state ga can be accessed via ReactGA.ga() method. This gives developers the flexibility of directly using ga.js features that have not yet been implemented in ReactGA. No validations will be done by ReactGA as it is being bypassed if this approach is used.
Then the ga allows writing a custom plugin
So with all that here is what the code looks like:
import React, { PureComponent } from 'react';
import ReactGA from '../../src';
import riveted from 'exports-loader?exports=riveted!./riveted.js';
export default class App extends PureComponent {
constructor(props, context) {
super(props, context);
this.state = {
reactGaInitialised: false,
configs: [DEFAULT_CONFIG]
};
}
initReactGA = (event) => {
const { configs } = this.state;
ReactGA.initialize(configs);
// Send initial test view
ReactGA.pageview('test-init-pageview');
function TrackerCustomPlugin() {
this.riveted = riveted;
}
TrackerCustomPlugin.prototype.init = riveted.init;
let ga = ReactGA.ga();
ga('provide', 'riveted', TrackerCustomPlugin);
ga('require', 'riveted');
ReactGA.plugin.execute('riveted', 'init', {
reportInterval: 10, // Default: 5
idleTimeout: 20, // Default: 30
nonInteraction: true // Default: true
});
};
Here is how the events are sent to GA from my local:
And the GA Dashboard showing Time Spent:

Cant open local html file with WebView on React Native canOpenURL: failed for URL

2020-01-29 20:32:22.470194+0300 Myapp[8905:2391245]
-canOpenURL: failed for URL: "file:///private/var/containers/Bundle/Application/146EA027-7A**/Myapp.app/assets/src/assets/policy.html" - error: "This app is not allowed to query for scheme file"
I am getting this error on xCode console output on real device. On simulator, everything works fine.
Here is my simple full code:
import React, { Component } from 'react';
import { WebView } from 'react-native-webview';
const PolicyHTML = require('../assets/policy.html');
export default class PolicyScreen extends React.Component {
render() {
return (
<WebView
source={PolicyHTML}
style={{flex: 1}}
/>
);
}
}
Couldn't find much solution about that online, what am i missing ?
The solution for me was just add originWhitelist={['*']} in the <WebView> component and then iOS would load HTML correctly.
I was having the same issue, i am using webview and wanted to load my local html file in that webview, which works perfectly fine in Android but was not in IOS device. After a lot of research i ended up with the following solution.
I have placed my html file in the following path:
MyReactNativeProjectFolder>app>views>monthly>trip.html
Where monthly is my custom folder that i created myself and has a local html file called trip.html.
And in the view, lets say MyView.js, where i want to call my html file i used the following syntax:
<WebView originWhitelist={['*']} source={require('./monthly/trip.html')} ref={( webView1 ) => this.webView1 = webView1} />
MyView.js is in the follwing path:
MyReactNativeProjectFolder>app>views>MyView.js
If you are not getting any error on simulator then this shall fix your problem, otherwise try changing the html file path as I have mentioned above, that is in the views folder, and try again.
I hope this may resolve the error Unable to open URL file:///private/var/containers/Bundle/Application/146EA027-7A/Myapp.app/assets/src/assets/policy.html
I don't know is this can be considered as proper solution but here how i solved it;
I am not sure but as my thinking Xcode is not allowing some codes on html files, so I thought about that found some websites on google which converts to html files to 'clean html file' and removes the unnecessary codes. After cleaning I replaced the new clean file with old one and it worked.
Hope it helps (Especially in Privacy Policy Files).

Setting up PDF.js to work with Meteor + Reactjs project (want to use text layer)

I've been working on a project using Meteor and React, which needs a PDF viewer with the ability to select text.
I'm currently trying to achieve this with Mozilla's PDF.js, but am having some trouble getting started. I'm a long time reader, first time asker at stackoverflow.
I've installed PDF.js with npm.
npm install pdfjs-dist --save
Now I'm trying to modify the example from pdf.js's github project here to create a React component that will render a PDF from a supplied file path and include a text layer.
imports/ui/components/PDF/PDFText.jsx
import React from 'react';
require ('pdfjs-dist/build/pdf.combined');
require ('pdfjs-dist/web/compatibility');
export default class PDFText extends React.Component {
renderPDF() {
PDFJS.workerSrc = '/node_modules/pdfjs-dist/build/pdf.worker.js';
const container = document.getElementById('pdf-container');
const scale = 1;
const pageNumber = 1;
PDFJS.getDocument(this.props.file).then(function(pdf) {
return pdf.getPage(pageNumber).then(function(page) {
var pdfPageView = new PDFJS.PDFPageView({
container: container,
id: pageNumber,
scale: scale,
defaultViewport: page.getViewport(scale),
textLayerFactory: new PDFJS.DefaultTextLayerFactory()
});
pdfPageView.setPdfPage(page);
return pdfPageView.draw();
});
});
}
render() {
this.renderPDF()
return (
<div id='pdf-container'></div>
);
}
}
If I include this component in page I get the following error:
Uncaught (in promise) TypeError: PDFJS.DefaultTextLayerFactory is not a constructor
The next thing I tried was including 'pdfjs-dist/web/pdf_viewer' in my code, as this is where DefaultTextLayerFactory is declared. I modified the code above to add the following line above the class declaration:
require ('pdfjs-dist/web/pdf_viewer');
When I run the code now, I get a different error.
Uncaught TypeError: Cannot read property 'PDFJS' of undefined
at Object.<anonymous> (modules.js?hash=9dd20a3…:114918)
at __w_pdfjs_require__ (modules.js?hash=9dd20a3…:114838)
at Object.<anonymous> (modules.js?hash=9dd20a3…:117449)
at __w_pdfjs_require__ (modules.js?hash=9dd20a3…:114838)
at Object.<anonymous> (modules.js?hash=9dd20a3…:118157)
at __w_pdfjs_require__ (modules.js?hash=9dd20a3…:114838)
at module.exports (modules.js?hash=9dd20a3…:114884)
at modules.js?hash=9dd20a3…:114887
at webpackUniversalModuleDefinition (modules.js?hash=9dd20a3…:114811)
at pdf_viewer.js (modules.js?hash=9dd20a3…:114818)
I'm really unsure what is going on here. I noticed that the function complaining refers to webpack - which I haven't been using.
I've also tried including the following check at the start of my code (this is taken from pageviewer.js in the github link above).
if (!PDFJS.PDFViewer || !PDFJS.getDocument) {
alert('Please build the pdfjs-dist library using\n' +
' `gulp dist`');
}
My code does in fact trigger that alert (PDFJS.PDFViewer is undefined) but the message doesn't seem correct as I installed the built pdfjs-dist library using npm. That message seems for people who cloned the repo. There isn't a gulp file in the pdfjs-dist directory - which makes sense.
I'm sure part of thep problem is that I'm experimenting with a lot of new tools here. This is my first time working with meteor, react, node, and pdf.js, so apologies in advance if I've made an obvious rookie mistake.
For the record I've tried a few other libraries, including:
mikecousins/react-pdf-js (worked reasonably well for simply displaying a pdf with no text layer).
peerlibrary/meteor-pdf.js (I hit some errors with this one as well, and I didn't pursue it too much further as the repo hasn't been touched in a couple of years).
Hopefully that's enough information for someone to spot the issue. My theory is that there's some other set up step I need to do to get this working for meteor or react (and that's why it hasn't been obvious from the "getting started" in the PDF.js website.
Also, I'm not locked in to PDF.js, so if the easiest solution to my problem is to use something else, I'd be happy to try that.
Thanks for your time

Resources