1

I'm trying to build an offline navigation.

I have two versions of my program: online and offline.

  1. I create an object based on a google maps request

  2. I want to "store" this object somehow

  3. I want to access this object in the offline version of the program.

If I do console.log(object) google chrome gives me the object, but I cant just copy it and paste in the offline version.

Any ideas how to "export" the object?

lornz
  • 306
  • 5
  • 16

2 Answers2

2
  1. Stringify your object -> JSON.stringify( yourObject );

  2. Save your file as JSON ( you can use library like : https://github.com/eligrey/FileSaver.js/ )

  3. Upload this JSON to your offline app

  4. Parse it -> JSON.parse( youJsonFile.json )

Damien
  • 3,915
  • 1
  • 17
  • 18
  • @lornz see also http://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it? – xmojmr Aug 19 '14 at 15:49
  • I just need to store the object one time and then I wont have to touch the online version ever again. So I thought about JSON.stringify too. I did: JSON.stringify(myObject) and printed it with console.log. Then I copied that string into the offline version and tried to parse it. But that gives me an error "error: SyntaxError: Unexpected token f SyntaxError: Unexpected token f at Object.parse (native)" – lornz Aug 20 '14 at 06:51
  • Can you paste here your stringified object ? – Damien Aug 20 '14 at 08:33
0

I guest you use HTML5 for you task? In the case answer is yes, is ease save local data for your use in offline mode. You can read this tutorial for localStorage object Local Storage in HTML5

Now, the next code help you to save online data in local storage, and access this in offline:

function init() {
   var googleMapObject = null;

   // This is first status verification
   if (navigator.onLine) {
      googleMapObject = anyMethodToGetData();

      // Save remote object in local storage
      localStorage['googleMapsObject'] = JSON.stringify(googleMapObject);
   } else {
      // In offline mode, return local storage data
      if (localStorage['googleMapsObject']) {
         googleMapObject = JSON.parse(localStorage['googleMapsObject']);
      }
   }

   return googleMapsObject;
}

The init method is call in load/ready event. If you need detect change in online/offline state, use online/offline events.

Regards!!

Carlos Guzman
  • 363
  • 5
  • 11
  • I thought about that too. But I need to transfer the offline version to another device. So the local storage of my browser won't be avaible. – lornz Aug 20 '14 at 06:47