Skip to content Skip to sidebar Skip to footer

Convert Javascript To Json?

I'm working with leaflets and I've noticed that many examples use a separate js file where a variable is set to a JSON stream. How would I be able to modify the following example s

Solution 1:

To read JSON data from a file you can use the fetch function (read more).

Here is an example:

fetch('http://example.com/movies.json')
    .then(function(response) {
        return response.json();
    })
    .then(function(myJson) {
        // Do something with the JSON data
        console.table(myJson);
    });

In your case:

function doSomething(geoJsonData) {
    var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    });

    var map = L.map('map')
            .addLayer(tiles);

    var markers = L.markerClusterGroup();

    var geoJsonLayer = L.geoJson(geoJsonData, {
        onEachFeature: function (feature, layer) {
            layer.bindPopup(feature.properties.address);
        }
    });
    markers.addLayer(geoJsonLayer);

    map.addLayer(markers);
    map.fitBounds(markers.getBounds());
}

fetch('http://myserver.com/myfile.json')
    .then(function(response) {
        return response.json();
    })
    .then(doSomething)
    .catch(function(err) {
        // In case of error, display the error message
        console.error(err);
    });

Notice that I put your code inside a callback function, as the fetch function is asynchronous.


Solution 2:

You can store the geoJSON variable in a separate .js file and import it into the main logic .js file. Try pasting your var geoJsonData in a file called geoJsonData.js, then at the bottom of that file add "module.exports = geoJsonData;". Then on your logic file (ie scripts.js), you can import the variable as is by adding "var geoJsonData = require("./geoJsonData.js"); at the top. Then your call to add the points to the map would be

function geoJsonMarkers() {  
$.getJSON(geoJsonData, function (data) {
        // this adds the GeoJSON layer to the map once the file is loaded
        L.geoJson(data).addTo(mymap);
}
}

Solution 3:

I know it can be done with $.getJSON, but I would prefer using L.geoJson, if possible.

You seem to not realize that these 2 functions provide different steps of your workflow, as illustrated by the 2 other answers.

You may be misled by other libraries that provide utility functions which perform both steps for you.

jQuery's $.getJSON is to fetch / retrieve data from your server.

Once you have the resulting JS object, you feed it into Leaflet's L.geoJSON factory to have it converted into Leaflet layers.


Post a Comment for "Convert Javascript To Json?"