我對服務器進行 API 呼叫以獲取資料
const api_url = "https://my_urlxxx"
addMyData()
.then(response => {
//console.log('Working!');
})
.catch(error => console.log(error.message));
async function addMyData() {
const response = await fetch(api_url);
const data = await response.json();
然后我將 JSON 轉換為 Leaflet.js 的 GeoJSON
geojson['type'] = 'FeatureCollection';
geojson ['features'] = [];
for (i = 0; i < data.length; i ) {
x = data[i].location.coordinate.longitude;
y = data[i].location.coordinate.latitude;
console.log('get ', data[i].itemId); //find the error...
console.log('get ', data[i].openingHours);
console.log('get ', data[i].openingHours.services[0]);
console.log('get ', data[i].openingHours.services[0].openDay); // error = undefined
var newFeature = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [x,y]
},
"properties": {
"status": data[i].status,
"itemId": data[i].itemId,
"name": data[i].name,
"openingMonday": days(data[i].openingHours.services[0].openDay) ' ' num2time(data[i].openingHours.services[0].openTime) '\u2014' num2time(data[i].openingHours.services[0].closeTime)
}
}
geojson ['features'].push(newFeature);
}
//console.log(JSON.stringify(geojson));
loadData (geojson);
};
function loadData(MyGeoJSONData) {
MyLayer = L.geoJson(MyGeoJSONData, {
pointToLayer: function (feature, latlng) {
if (feature.properties.status != "1") {
return new L.shapeMarker(latlng, {
radius: 4,
color: '#252525', //#d53e4f
fillOpacity: 0.3,
weight: 2,
shape: 'circle'
})
}
},
問題是每個專案都沒有“openingHours”的值。這使得錯誤“未定義”,我無法檢索資料以顯示在 Leaflet 地圖上。如何在創建 GeoJSON 之前傳遞或忽略這些值,或者將它們過濾掉?
這是openingHours的JSON檔案的一部分,JSON串列中的某些專案可能會丟失整個部分,我無法通過這個...
"openingHours": {
"services": [
{
"closeDay": "Monday",
"closeTime": "2359",
"openDay": "Monday",
"openTime": "0000"
},
{
"closeDay": "Tuesday",
"closeTime": "2359",
"openDay": "Tuesday",
"openTime": "0000"
},
{
"closeDay": "Wednesday",
"closeTime": "2359",
"openDay": "Wednesday",
"openTime": "0000"
},
{
"closeDay": "Thursday",
"closeTime": "2359",
"openDay": "Thursday",
"openTime": "0000"
},
{
"closeDay": "Friday",
"closeTime": "2359",
"openDay": "Friday",
"openTime": "0000"
},
{
"closeDay": "Saturday",
"closeTime": "2359",
"openDay": "Saturday",
"openTime": "0000"
},
{
"closeDay": "Sunday",
"closeTime": "2359",
"openDay": "Sunday",
"openTime": "0000"
}
],
"specialDates": [
]
},
uj5u.com熱心網友回復:
你不需要在這里過濾,你可以檢查三元組并回傳一個空字串(或任何你可能需要的),如果它不存在:
"openingMonday": data[i]?.openingHours? days(data[i].openingHours.services[0].openDay) ' ' num2time(data[i].openingHours.services[0].openTime) '\u2014' num2time(data[i].openingHours.services[0].closeTime): ''
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/412332.html
標籤:
