[GIS] Create map using Leaflet and JSON

jsonleafletmaps

I have a question in order to developing a web app using dynamic maps with JSON files. I'm using Visual Studio 2015 with MVC 5.

At this moment i have developed complete app but I'm unable to draw points (with Lat and Lng) in a Leaflet map from a JSON File.

My JSON file is similar to:

[{
"latitud": 43.526523590087891,
"longitud": -5.6150951385498047
}, {
"latitud": 43.511680603027344,
"longitud": -5.6671133041381836
},
 .
 //More Lat-Lng Points
 .
{
"latitud": 43.526451110839844,
"longitud": -5.6140098571777344
}]

Currently, I'm using a example of heatmap but is imposible for me represent markers when i try to get coordinates from my JSON file.

Any help?

Best Answer

You have a JSON but Leaflet really likes geoJSONs, so you should convert the JSON to geoJSON first, or directly load a geoJSON. So for your example, if you have:

var data =[{
"latitud": 43.526523590087891,
"longitud": -5.6150951385498047
}, {
"latitud": 43.511680603027344,
"longitud": -5.6671133041381836
},
 .
 //More Lat-Lng Points
 .
{
"latitud": 43.526451110839844,
"longitud": -5.6140098571777344
}]

You can restructure the JSON to a geoJSON:

var jsonFeatures = [];

data.forEach(function(point){
    var lat = point.latitud;
    var lon = point.longitud;

    var feature = {type: 'Feature',
        properties: point,
        geometry: {
            type: 'Point',
            coordinates: [lon,lat]
        }
    };

    jsonFeatures.push(feature);
});

var geoJson = { type: 'FeatureCollection', features: jsonFeatures };

And last but not least, you can add your new geoJSON to the map:

L.geoJson(geoJson).addTo(map);

A full code example to display your points on a map would look like this:

var map = L.map('map',{
}).setView([43.526523590087891, -5.6150951385498047], 12);

L.tileLayer('http://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.{ext}', {
    attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    subdomains: 'abcd',
    ext: 'png'
}).addTo(map);

var data = [{
"latitud": 43.526523590087891,
"longitud": -5.6150951385498047
}, {
"latitud": 43.511680603027344,
"longitud": -5.6671133041381836
},
{
"latitud": 43.526451110839844,
"longitud": -5.6140098571777344
}]

var jsonFeatures = [];

data.forEach(function(point){
    var lat = point.latitud;
    var lon = point.longitud;

    var feature = {type: 'Feature',
        properties: point,
        geometry: {
            type: 'Point',
            coordinates: [lon,lat]
        }
    };

    jsonFeatures.push(feature);
});

var geoJson = { type: 'FeatureCollection', features: jsonFeatures };

L.geoJson(geoJson).addTo(map);

Hope this solves your problem! Cheers