[英]Unclear why I'm getting a strange result when trying to add JSON features to an array
I'm working on a function in leaflet that changes the style weight
of the most recent object in a JSON response.我正在处理传单中的一个函数,该函数更改 JSON 响应中最新对象的样式
weight
。 That's beside the point though, because I can't properly get the JSON objects into an array.不过,这不是重点,因为我无法正确地将 JSON 对象放入数组中。
When I run console.log(dates)
in order to see if they were pushed to the dates
array I return this in the console.当我运行
console.log(dates)
以查看它们是否被推送到dates
数组时,我在控制台中返回它。 A bunch of empty arrays, amounting to the number of dates in the JSON response.一堆空数组,相当于 JSON 响应中的日期数。
When I run console.log(time)
to ensure I am in fact reaching the correct json feature I receive the dates (epoch format) as expected, but can not understand why they will not be pushed into the array dates
.当我运行
console.log(time)
,以确保我其实到达正确的JSON功能,我收到预期的日期(纪元格式),但不明白为什么他们不会推入阵dates
。 Any ideas?有任何想法吗?
Function功能
//most recent earthquake identifer
function mostRecent(time) {
var dates=[];
for (var i = 0; i < time.length; i++) {
dates.push(time[i])
}
console.log(dates)
return true
}
Javascript Javascript
// adds geojson feed of earthquakes from USGS url (must create a function to layer it on leaflet)
$.getJSON('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson', function(earthQuakes) {
var points = L.geoJSON(earthQuakes, {
filter: eqFilter,
onEachFeature: function (feature, layer) { // binds data in geosjon to a popup
var eqDate = new Date(feature.properties.time); // converts epoch date
layer.bindPopup(
'<b>Location: </b>' + feature.properties.place + '<br>' +
'<b>Magnitude: </b>' + feature.properties.mag + '<br>' +
'<b>Depth: </b>' + feature.geometry.coordinates[2] + 'km' + '<br>' +
'<b>Time: </b>' + eqDate.toGMTString() + '<br>' +
'<br><center><a href=' + feature.properties.url + '>USGS Details</a></center>',
)
},
pointToLayer: function(feature, latlng){ // changes default icons to circles and styles accordingly
return new L.CircleMarker(latlng, {
radius: circleSize(feature.properties.mag),
fillColor: getColor(feature.properties.mag),
color: "#000",
weight: mostRecent(feature.properties.time),
opacity: 1,
fillOpacity: 0.5,
});
}
}).addTo(map);
map.fitBounds(points.getBounds()); // pans to points
});
Make the dates
variable a global variable.使
dates
变量成为全局变量。 You're actually resetting the dates
array on every function call.您实际上是在每次函数调用时重置
dates
数组。 Refactor it to something like this将它重构为这样的东西
var dates = [];
function mostRecent(time) {
dates.push(time);
console.log(dates);
return true
}
It should be working.它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.