问题
I'm trying to only style one element in an array and apply it to pointToLayer, while the other elements in the array stay at a default parameter. Specifically, I'm trying to have the most recent earthquake point to have a radius weight of 3 while leaving the remainder earthquake points with a radius weight of 1.
Here is a picture of my legend/points on the map. As you can see Recent is identified with a larger radius weight.
I thought the best way to do this was to create a function and call it within pointToLayer under the weight attribute. My thought process to create such a function is as follows.
- Loop through the geojson which identifies the time,
feature.properties.time, and place the times in an array. - Create an
ifstatement that sees if the first element in the array is larger (most current date) and make its weight 3 while leaving the weight of the remaining elements 1.
I'm having trouble comprehending how I should structure the if statement since I only want one element of the array to have a different style then the remaining elements.
Here is the code, any help would be appreciated. The function I'm working on is called mostRecent. Thank you.
// most recent earthquake identifer
function mostRecent(time) {
var dates=[];
for (var i = 0; i < time.length; i++) {
dates.push(time[i])
}
if (dates[0] > dates[1]) {
weight = 3
} else {
weight = 1
}
return weight
}
// 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 cicrles 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
});
来源:https://stackoverflow.com/questions/59039158/styling-only-one-element-in-an-array-in-leaflets-pointtolayer