Can't import geojson value as string in google maps with firebase web - json

So, I set up my firebase to communicate with my web app which uses google maps api and my goal is this: When a user draws a shape on the map(polygon, linestring), I want to send the geoJson value of it to the firebase(currently sending it as a String), and then retrieve it back so it appears on the map for everyone(since it's getting synced from the firebase database). My problem is that when I try to retrieve the geoJson data back and add it on google maps, at the line map.data.addGeoJson(geoJsonString);(geoJsonString = geoJson value that is stored in firebase) I get an error saying:
Uncaught Jb {message: "not a Feature or FeatureCollection", name: "InvalidValueError", stack: "Error↵ at new Jb (https://maps.googleapis.com/m…tatic.com/firebasejs/4.13.0/firebase.js:1:278304)"}
For some reason google maps api doesnt accept the geoJson value even though console.log(geoJsonString); returns a valid geoJson value (checked at http://geojsonlint.com/)
Now the strange part is that if I try to import the same geoJson value manually(storing the geoJson value in a var and then map.data.addGeoJson(geoJsonString);) it works just fine.
This function syncs firebase with the web app
function gotData(data){
paths = data.val();
if(paths == null){
console.log("firebase null");
alert('Database is empty! Try adding some paths.');
}
else{
var keys = Object.keys(paths);
for(var i = 0; i < keys.length; i++){
var k = keys[i];
var geoJsonString = paths[k].geoJsonString;
console.log(geoJsonString);
map.data.addGeoJson(geoJsonString);
}
}
}
This function updates and pushes data in firebase
function updateData(){
data = {
geoJsonString: geoJsonOutput.value
}
ref = database.ref('firebasePaths');
ref.push(data);
}
In this function(which is used to store geoJson values locally in a file), I call updateData function), after a new path is drawn on the map
// Refresh different components from other components.
function refreshGeoJsonFromData() {
map.data.toGeoJson(function(geoJson) {
geoJsonOutput.value = JSON.stringify(geoJson);
updateData();
refreshDownloadLinkFromGeoJson();
});
}
Example of my firebase that contains 2 random geoJson
I can't trace where the problem is. Any ideas?

Update: I managed to fix this issue by parsing the string with JSON.parse("retrieved string from firebase"), saving it to a variable and then adding it to the map with map.data.addgeoJson(parsed variable).

We still have not faced that issue, however, we are aware of it.
Our intended solution is to use GeoFire: An open-source library for the Firebase Realtime Database that adds support for geospatial querying.
You can find the library description in here:
https://firebase.google.com/docs/libraries/
For the Web supported library:
https://github.com/firebase/geofire-js

Related

Crossfilter - Loading a JSON file from localStorage

I'm fairly new to Javascript and I'm trying to create a simple bar chart with d3.js using some data saved in the localStorage.
The data in the localStorage is acquired by the following function:
function logScore() {
var name = prompt("Please enter your name to add to the high scores list:");
var score = game.count;
var gameDate = today;
var scoreObj = { name: name, score: score, date: gameDate };
scoresArray.push(scoreObj);
window.localStorage.setItem('scoresRecord', JSON.stringify(scoresArray));
}
In a separate Javascript file, I parse the JSON object in order to store the object in an array.
var scoreData = JSON.parse(window.localStorage.getItem('scoresRecord'));
queue()
.defer(d3.json, "scoreData")
.await(makeGraph);
function makeGraph(error, scoreData) {
var ndx = crossfilter(scoreData);
var name_dim = ndx.dimension(dc.pluck('name'));
var score_dim = ndx.dimension(dc.pluck('score'));
var date_dim = ndx.dimension(dc.pluck('date'));
dc.barChart("#high-score-chart")
.width(300)
.height(150)
.margins({ top: 10, right: 50, bottom: 30, left: 50 })
.dimension(date_dim)
.group(score_dim)
.transitionDuration(500)
.x(d3.scale.ordinal())
.xUnits(dc.units.ordinal)
.xAxisLabel("Date")
.yAxisLabel("Score");
dc.renderAll();
}
Once loaded, I then try to use the data in a d3.js barchart using crossfilter, but I get the below error from the console:
https://ifd-project-simon-georgefairbairn.c9users.io/scoreData 404 (Not Found)
I think I'm loading the data correctly, but I wondered if anyone would be able to let me know if I can use crossfilter and d3.js with a JSON object stored in localStorage, and if so how?
Thanks for taking the time to read my problem - hoping someone can help!
If you're able to get the data synchronously, loading it from local storage, then you don't need queue() and d3.json
You should be able to do
var scoreData = JSON.parse(window.localStorage.getItem('scoresRecord'));
var ndx = crossfilter(scoreData);
The error you're getting indicates that d3.json is trying to do an HTTP request for the data. In this case, you don't need d3.json because JSON parsing is built into the language.
If you were using CSV data, then you might use the synchronous parse version d3.csv.parse. There is no d3.json.parse because it's provided directly by the language.

Dart / flutter: download or read the contents of a Google Drive file

I have a public (anyone with the link can view) file on my Google Drive and I want to use the content of it in my Android app.
From what I could gather so far, I need the fileID, the OAuth token and the client ID - these I already got. But I can't figure out what is the exact methodology of authorising the app or fetching the file.
EDIT:
Simply reading it using file.readAsLines didn't work:
final file = new File(dogListTxt);
Future<List<String>> dogLinks = file.readAsLines();
return dogLinks;
The dogLinks variable isn't filled with any data, but I get no error messages.
The other method I tried was following this example but this is a web based application with explicit authorization request (and for some reason I was never able to import the dart:html library).
The best solution would be if it could be done seamlessly, as I would store the content in a List at the application launch, and re-read on manual refresh button press.
I found several old solutions here, but the methods described in those doesn't seem to work anymore (from 4-5 years ago).
Is there a good step-by-step tutorial about integrating the Drive API in a flutter application written in dart?
I had quite a bit of trouble with this, it seems much harder than it should be. Also this is for TXT files only. You need to use files.export() for other files.
First you need to get a list fo files.
ga.FileList textFileList = await drive.files.list(q: "'root' in parents");
Then you need to get those files based on ID (This is for TXT Files)
ga.Media response = await drive.files.get(filedId, downloadOptions: ga.DownloadOptions.FullMedia);
Next is the messy part, you need to convert your Media object stream into a File and then read the text from it. ( #Google, please make this easier.)
List<int> dataStore = [];
response.stream.listen((data) {
print("DataReceived: ${data.length}");
dataStore.insertAll(dataStore.length, data);
}, onDone: () async {
Directory tempDir = await getTemporaryDirectory(); //Get temp folder using Path Provider
String tempPath = tempDir.path; //Get path to that location
File file = File('$tempPath/test'); //Create a dummy file
await file.writeAsBytes(dataStore); //Write to that file from the datastore you created from the Media stream
String content = file.readAsStringSync(); // Read String from the file
print(content); //Finally you have your text
print("Task Done");
}, onError: (error) {
print("Some Error");
});
There currently is no good step-by-step tutorial, but using https://developers.google.com/drive/api/v3/manage-downloads as a reference guide for what methods to use in Dart/Flutter via https://pub.dev/packages/googleapis: to download or read the contents of a Google Drive file, you should be using googleapis/Drive v3, or specifically, the methods from the FilesResourceApi class.
drive.files.export(), if this is a Google document
/// Exports a Google Doc to the requested MIME type and returns the exported content. Please note that the exported content is limited to 10MB.
drive.files.get(), if this something else, a non-Gdoc file
/// Gets a file's metadata or content by ID.
Simplified example:
var drive = new DriveApi(http_client);
drive.files.get(fileId).then((file) {
// returns file
});
However, what I discovered was that this Dart-GoogleAPIs library seemed to be missing a method equivalent to executeMediaAndDownloadTo(outputStream). In the original Google Drive API v3, this method adds the alt=media URL parameter to the underlying HTTP request. Otherwise, you'll get the error, which is what I saw:
403, message: Export requires alt=media to download the exported
content.
And I wasn't able to find another way to insert that URL parameter into the current request (maybe someone else knows?). So as an alternative, you'll have to resort to implementing your own Dart API to do the same thing, as hinted by what this OP did over here https://github.com/dart-lang/googleapis/issues/78: CustomDriveApi
So you'll either:
do it through Dart with your own HttpClient implementation and try to closely follow the REST flow from Dart-GoogleAPIs, but remembering to include the alt=media
or implement and integrate your own native-Android/iOS code and use the original SDK's convenient executeMediaAndDownloadTo(outputStream)
(note, I didn't test googleapis/Drive v2, but a quick examination of the same methods looks like they are missing the same thing)
I wrote this function to get file content of a file using its file id. This is the simplest method I found to do it.
Future<String> _getFileContent(String fileId) async {
var response = await driveApi.files.get(fileId, downloadOptions: DownloadOptions.fullMedia);
if (response is! Media) throw Exception("invalid response");
return await utf8.decodeStream(response.stream);
}
Example usage:
// save file to app data folder with 150 "hello world"s
var content = utf8.encode("hello world" * 150);
driveApi.files
.create(File(name: fileName, parents: [appDataFolder]),
uploadMedia: Media(Stream.value(content), content.length))
.then((value) {
Log().i("finished uploading file ${value.id}");
var id = value.id;
if (id != null) {
// after successful upload, read the recently uploaded file content
_getFileContent(id).then((value) => Log().i("got content is $value"));
}
});

How to Retrieve Forge Viewer objectTree?

My goal is to highlight a room by adding new geometry to the viewer based on lines I have created in revit like they do here Link
but i can not figure out how to access those lines ids.
I know what they are in revit (element_id) but not how they are mapped as dbid.
Following this Blog Post
I want to access the objectTree in my extension to find out, but it always comes back as undefined.
var tree;
//old way - viewer is your viewer object - undefined
viewer.getObjectTree(function (objTree) {
tree = objTree;
});
//2.5 - undefined
var instanceTree = viewer.model.getData().instanceTree;
var rootId = this.rootId = instanceTree.getRootId();
//- undefined
var objectTree = viewer.getObjectTree();
Can anyone tell me if its still works for them I am using the v2 of the API for the rvt conversion to svf and 2.9 of the viewer3D.js
note I can see a list of dbid if I call this
var model = viewer.impl.model;
var data = model.getData();
var fragId2dbIdArray = data.fragments.fragId2dbId ;
but have no way of mapping back to the Revit element_id
As of version 2.9 this is still working. Here's my console:
Here's a couple of things you can try:
Is viewer undefined? Are you in the correct scope when grabbing the viewer?
The document have to be loaded before you can grab the instance tree. When the document is loaded, an event called Autodesk.Viewing.GEOMETRY_LOADED_EVENT will be fired, then you can start manipulating the instance tree.
Simply do this:
viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, function () {
var instanceTree = viewer.model.getData().instanceTree;
});
For more structured code, follow this guide to add an extension.
There's a more detailed blog post on which event to listen for. It's still using the old way to get instance tree, though.
Shiya Luo was correct the viewer had not yet finished loading the geometry
in my extentions Load function I added two event listeners and made sure they both fired before trying to access the instanceTree
viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, function () {
finishedGEOMETRY_LOADED_EVENT = true;
if(finishedGEOMETRY_LOADED_EVENT && finishedOBJECT_TREE_CREATED_EVENT ){
afterModelLoadEvents(viewer);
}
});
viewer.addEventListener(Autodesk.Viewing.OBJECT_TREE_CREATED_EVENT, function () {
finishedOBJECT_TREE_CREATED_EVENT = true;
if(finishedGEOMETRY_LOADED_EVENT && finishedOBJECT_TREE_CREATED_EVENT ){
afterModelLoadEvents(viewer);
}
});

Updating a flickr image upon user input

I am trying to integrate flickr into a weather app (yahoo weather api) that I've created and decided to start by leveraging flickrGrabber (http://blog.organa.ca/?p=19) as a starting point. I have both the weather app and flickrGrabber working however updating flickrGrabber after initial load is proving very challenging for me.
The initial image is being pulled via a search term set by a variable called flickrLocationName and I am able to update the variable value successfully upon entry of a new zip code however I can't seem to get flickrGrabber to unload & reload with the new value. My flickrGrabber code is on layer documentAS. The flickrGrabber class can be found within the Src folder and var flickrLocationName gets set from the WeatherObject class which can also found in the Src folder.
You can see what I mean by visiting this link:
http://truimage.biz/WAS400/WeatherApp/Deploy/weatherApp.html
Of course my source can be downloaded here:
http://truimage.biz/WAS400/weatherApp.zip
Any help would be very much appreciated. Here is some sample code:
import flickrGrabber;
var apiKey:String = "####"; //The working API key is in the zip file
var apiSecret:String = "####"; //The working API secret is in the zip file
var flickrLocationName:String;
var grabber:flickrGrabber;
function locationImage():void
{
grabber = new flickrGrabber(1024,600,apiKey,apiSecret,flickrLocationName,false);
grabber.addEventListener("imageReady", onLoadedImage);
grabber.addEventListener("flickrGrabberError", onErrorImage);
grabber.addEventListener("flickrConnectionReady", onFlickrReady);
function onFlickrReady(evt:Event):void
{
grabber.loadNextImage();
}
function onLoadedImage(evt:Event):void
{
addChildAt(grabber.image,0);
}
function onErrorImage(evt:ErrorEvent):void
{
trace("Report error: " + evt.text);
}
}
I'm pretty sure to change the image I need to remove the
addChildAt(grabber.image,0);
and rerun the function
locationImage();
But his is my best guess.

Problem to pass a kml file to Google Earth using geoxml3 class and ProjectedOverlay class

i am trying to build a google earth view showing cities, but i stuck with the kml parser geoxml3. I have a javascript building a google map at first showing the locations i want. this works fine. I call the function from a php script providing it an address and kml file reference from database. The function builds the map, sets a flag 'map_finished' as a control flag when all ran fine and calls the build google earth view function.
// Get maps and earth from google
google.load( 'maps', '2.s', {'other_params': 'sensor=true'} );
google.load( 'earth', '1' );
//Google Earth Initializer
function initObjectEarth() {
// Check if Google Earth plugin is installed
if( gm_loaded ) {
this.ge_plugin_installed = google.earth.isInstalled();
if( this.ge_plugin_installed ) {
google.earth.createInstance( 'inmap', geSuccessCallback, geFailureCallback );
ge_loaded = true;
} else {
alert( 'Your Browser has not yet installed the Google Earth plugin.
We recommend installing it to use all features!' );
return false;
}
}
}
// Success handler
function geSuccessCallback( object ) {
this.ge = object;
this.ge.getWindow().setVisibility( true );
this.kmlParser = new geoXML3.parser();
}
// Error handler
function geFailureCallback( object ) {
alert( 'Error: ' + object );
}
The geoxml parser uses the ProjectedOverlay class. Both libraries are loaded into document head. When the parser is getting instatiated it requests a ProjectedOverlay instance. This class throws a
Error: **google.maps is undefined**
error in firebug for the following statement
ProjectedOverlay.prototype = new google.maps.OverlayView();
In my script file i have declared vars including
var gm //for google map
var ge //for google earth
gm is set in the function that builds the google map.
I wonder how to fix this issue. I tried the getProjection() thing i found in web as well as
ProjectedOverlay.prototype = new google.maps.OverlayView().prototype;
with no success. This topic is absolutely new to me and i cannot figure out how to fix it neither from the documentation of OverlayView nor from google search.
What did i forget or do wrong?
The call to the geoXML3 constructor is wrong, you must pass the google.maps object as a parameter (...hence the "google.maps is undefined" error).
this.kmlParser = new geoXML3.parser({map: gm}); // gm for google map