Monday, 19 August 2019

javascript - Import pure (regular) JSON file to Leaflet


I would like to add pure JSON file to Leaflet. Saying "pure" I mean plain JSON structure that is not GeoJSON compliant.


There are lot of examples advicing how to add GeoJSON files:


Leaflet load JSON data Load polygon JSON to Leaflet Adding Multiple JSON Layers to Leaflet Map Feature Layer from JSON file



My JSON data looks like this:


  {
"Sheet1": {
"-430524279882": {
"MDU_ID": -430524279882,
"Status": "Invoiced",
"THP": 12,
"Latitude": 52.41635,
"Longitude": -1.55227
},

"-430532279893": {
"MDU_ID": -430532279893,
"Status": "Invoiced",
"THP": 12,
"Latitude": 52.41635,
"Longitude": -1.55227
},
"-430622279798": {
"MDU_ID": -430622279798,
"Status": "Invoiced",

"THP": 12,
"Latitude": 52.41555,
"Longitude": -1.55155
},
"-430519279894": {
"MDU_ID": -430519279894,
"Status": "Invoiced",
"THP": 12,
"Latitude": 52.41635,
"Longitude": -1.55227

},
"-430558279922": {
"MDU_ID": -430558279922,
"Status": "DO NOT DESIGN - SDN",
"THP": null,
"Latitude": 52.41635,
"Longitude": -1.55227
}
...


It comes straight from Google Sheets. Unfortunately this format is not recognized by L.geoJson function:


  job2 = L.geoJson(data2, {  //layer2 Virgin Media start    
style: style2,
pointToLayer: function(feature, latlng) {
feature.properties.myKey = ''+ feature.properties.Owner +
'
; ' + feature.properties.Address
label = String(feature.properties.Owner)
if (feature.properties.Post_Survey_Home_Count >=100)
return L.circleMarker(latlng, {


How can I use this data in a similar way as GeoJSON?



Answer



In the case of plain JSON you have to iterate through it's elements, extract properties you need, convert them to desired format and then process them.


For example, for your JSON above, if you want to add markers with desired coordinates to the map, each having popup with Status property, your code could look something like this:


var myPointsLayer = L.featureGroup();
for(var key in data2.Sheet1){
var latLng = L.latLng([data2.Sheet1[key].Latitude, data2.Sheet1[key].Longitude]);
L.marker(latLng).bindPopup(data2.Sheet1[key].Status).addTo(myPointsLayer);
}

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...