Skip to content

Commit

Permalink
refactor to modern fetch approach
Browse files Browse the repository at this point in the history
  • Loading branch information
chiaweh2 committed Sep 18, 2024
1 parent 249f153 commit 1a95af2
Showing 1 changed file with 53 additions and 21 deletions.
74 changes: 53 additions & 21 deletions lmesPlotlyMapbox.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
// read geojson and create plotly plot
readTextFile("lms_choropleth_mapbox.json", function(text){
var datajson = JSON.parse(text);
lmesPlotlyMapbox(datajson);
// Using fetch() to read the JSON file
fetch('lms_choropleth_mapbox.json')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse the JSON
})
.then(dataJson => {
// create the plotly plot
lmesPlotlyMapbox(dataJson);

// auto-click the reset button to make the mapbox plot show normal view
var inputElement = document.querySelector('a[data-title="Reset view"]')
Expand All @@ -17,22 +24,10 @@ readTextFile("lms_choropleth_mapbox.json", function(text){
}
,500);
});

});

// function to read geojson
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}

})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});

// plot the plotly figure
function lmesPlotlyMapbox(datajson) {
Expand All @@ -43,4 +38,41 @@ function lmesPlotlyMapbox(datajson) {
datajson
)
}
}
}


// // read geojson and create plotly plot
// readTextFile("lms_choropleth_mapbox.json", function(text){
// var datajson = JSON.parse(text);
// lmesPlotlyMapbox(datajson);

// // auto-click the reset button to make the mapbox plot show normal view
// var inputElement = document.querySelector('a[data-title="Reset view"]')
// // first wait for 1 sec for plotly plot in modal to finish and assign the element
// setTimeout(()=> {
// inputElement = document.querySelector('a[data-title="Reset view"]')
// }
// ,1000);
// // reset button is clicked once the modal open (sufficient time out is necessary)
// $('#lmeButton').on("click", function () {
// setTimeout(()=> {
// inputElement.click()
// }
// ,500);
// });

// });

// // function to read geojson
// function readTextFile(file, callback) {
// var rawFile = new XMLHttpRequest();
// rawFile.overrideMimeType("application/json");
// rawFile.open("GET", file, true);
// rawFile.onreadystatechange = function() {
// if (rawFile.readyState === 4 && rawFile.status == "200") {
// callback(rawFile.responseText);
// }
// }
// rawFile.send(null);
// }

0 comments on commit 1a95af2

Please sign in to comment.