2

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 load on a map using filters. However, in reality, the amount of points to be mapped exceeds 50,000 (the example here only shows 2). What I want to know is how I can just load the data coming from a file in the same directory called placesgj.geojson, where the 50,000 data entries will be written in geojson format, to the variable placez instead of writing them manually there like in the example. The rest of the code is ommited for tidyness, and irrelevant for the functionality. Thanks in advance!

var placez = {
    "type": "FeatureCollection",
    "features": [{
        "type": "Feature",
        "properties": {
            "icon": "theatre"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [-77.038659, 38.931567]
        }
    }, {
        "type": "Feature",
        "properties": {
            "icon": "music"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [-77.007481, 38.876516]
        }
    }]
};
map.on('load', function() {
    // Add a GeoJSON source containing place coordinates and information.
    map.addSource("placer", {
        "type": "geojson",
        "data": placez
    });
    placez.features.forEach(function(feature) {
        var symbol = feature.properties['icon'];
        var layerID = 'poi-' + symbol;
ElBuenMarvin
  • 51
  • 1
  • 4
  • Why don't you just read your local file ? https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file Then parse it. Don't worry about the size of the string you'll get https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length – PopHip May 03 '19 at 09:30

3 Answers3

2

Use the Fetch API to read the file.

function fetchJSON(url) {
  return fetch(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);
            });

});
Nuhman
  • 1,172
  • 15
  • 22
  • Tried doing this but I couldn't get it to work. Kept getting an error message for "Uncaught TypeError: Cannot read property forEach of undefined". Still works pasting the 50,000 lines of text though, so I guess I got that going for me. Will keep looking. – ElBuenMarvin May 05 '19 at 02:54
  • @FranciscoVG I've updated my answer, please check it out. Also make sure the geojson file is having the right extension/type, and its path is passed correctly for the `fetchJSON` method. – Nuhman May 06 '19 at 00:49
1

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

 function loadJSONFile(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...

Pavan
  • 632
  • 5
  • 9
  • I'm getting an error message saying: "Uncaught ReferenceError: placez is not defined at...". The code works fine when copy-pasting the 50-lines of text content to the text editor, so I'll keep looking into this. – ElBuenMarvin May 05 '19 at 03:10
1

As mentioned before, you can check the Fetch API

An example using Leaflet API to load a Layer:

        fetch('http://localhost:8081/geoserver/basesEspaciales00/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=basesEspaciales00%3Aanimal2022ipa&maxFeatures=50&outputFormat=application%2Fjson')
  .then(response => response.json())
  //.then(data => console.log(data))
  .then (response => response)
  //.then (response => console.log (response))
  .then (response => mapa(response));
  
  function mapa(rta){
  var a = rta;
    var animalLayer = L.geoJSON(a, {

        filter: function (feature, layer) {
            if (feature.properties) {
                // If the property "underConstruction" exists and is true, return false (don't render features under construction)
                return feature.properties.underConstruction !== undefined ? !feature.properties.underConstruction : true;
            }
            return false;
        },

        onEachFeature: onEachFeature
    }).addTo(map);
  }