Skip to content Skip to sidebar Skip to footer

How Can I Assign The Contents Of A Geojson File To A Variable In Javascript?

The code shown already works, but I want to clean it up. It declares a variable called placez which contains information in geojson format for the next part of the code to read and

Solution 1:

This is a case of loading JSON file in to a javascript object. It can be done in Pure Java Script using XMLHttpRequest.

functionloadJSONFile(callback) {   

    var xmlobj = new XMLHttpRequest();

    xmlobj.overrideMimeType("application/json");

    xmlobj.open('GET', 'placesgj.geojson', true); // Provide complete path to your json file here. Change true to false for synchronous loading.

    xmlobj.onreadystatechange = function () {
          if (xmlobj.readyState == 4 && xmlobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xmlobj.responseText);
          }
    };

    xmlobj.send(null);  
 }

call the loadJSONFile function by passing a call back function as below:

loadJSONFile(function(response) {
    var placez = JSON.parse(response);
 });

// Continue with your map.on('load', .. code here...

Solution 2:

Use the Fetch API to read the file.

functionfetchJSON(url) {
  returnfetch(url)
    .then(function(response) {
      return response.json();
    });
}

Assuming placesgj.geojson is in the same directory:

var data = fetchJSON('placesgj.geojson')
            .then(function(data) { 

        // do what you want to do with `data` here...
        data.features.forEach(function(feature) {
                console.log(feature);
                var symbol = feature.properties['icon'];
                console.log(symbol);
            });

});

Post a Comment for "How Can I Assign The Contents Of A Geojson File To A Variable In Javascript?"