CGView.js
Examples Tutorials Docs API JSON
  • Index
  • Tutorials

  • Basic Map
  • Sequence Map
  • JSON Map
  • CGViewBuilder
  • Map Controls
  • Details

  • JSON Files
  • Meta Data
  • Map Scales
# JSON Files Typically, the JSON data for a map would be stored as a file. In JavaScript, external files can be loaded using an [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) object or the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). It is also possible to load the JSON as a JavaScript file using a script tag, however, the JSON would have to be assigned to a global variable first (see [example](#load-as-javascript) below) ## Fetch API Example ```js // Provide URL of the JSON file fetch('http://example.com/cgview.json') .then(response => response.json()) .then(json => { // Create Viewer cgv = new CGV.Viewer('#my-viewer', { height: 500, width: 500 }); // Load data cgv.io.loadJSON(json); cgv.draw(); }); ``` ## XMLHttpRequest Example ```js var request = new XMLHttpRequest(); request.open('GET', 'http://example.com/cgview.json', true); request.onload = function() { var response = request.response; const json = JSON.parse(response); // Create Viewer cgv = new CGV.Viewer('#my-viewer', { height: 500, width: 500 }); // Load data cgv.io.loadJSON(json); cgv.draw() }; request.send(); ``` ## Local Files The above examples are using server-based JSON files. Using local files is trickier. The Fetch API does not work with local files. The XMLHttpRequest can work with local files by providing a local path instead of a URL. However, file system requests are treated as cross-origin ([CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)) requests and are blocked by most browsers by default. For local development, CORS can be turned off. Each Browser has a different way of turning off CORS but a quick google search should provide the answer. ## Load as JavaScript While a local JSON file can not be loaded directly in an HTML document, it is possible to load JavaScript files. A work around is to load the JSON as a JavaScript file. This requires assigning the JSON to a global variable in the file then loading the file with a script tag. Change the JSON file from: ```json { "cgview": {...} } ``` To a JavaScript file: ```js // data.js var json = { "cgview": {...} } ``` Then load the file and add to CGView: ```html ```