如何从json检查条件(==)数组,并在其他情况下执行语句以创建其他变量。
$.getJSON("<?=base_url() ?>home/sekolah_json", function(data){
$.each(data, function(i, field){
var longitude = parseFloat(data[i].longitude);
var latitude = parseFloat(data[i].latitude);
var nama = (data[i].nama_sekolah);
L.icon = function (options) {
return new L.Icon(options);
};
var marker = (data[i].jenjang);
//how to write if else on this line of code
if (marker == 'sd'){
var redIcon = new L.icon({iconUrl: '<?=base_url() ?>assets/leaflet/images/sd1.png', iconSize:[30,30]});
}else{
var blueIcon = new L.icon({iconUrl: '<?=base_url() ?>assets/leaflet/images/smp1.png', iconSize:[30,30]});
}
// help me
L.marker([longitude, latitude], {icon: marker}).addTo(map)
.bindPopup(nama, {autoClose: false, autoPan: false})
.openPopup();
});
});
您可以将图标保存在先前定义的变量中,例如markerIcon
,然后稍后使用它,因为它将具有预期的值:
$.getJSON("<?=base_url() ?>home/sekolah_json", function(data){
$.each(data, function(i, field){
var longitude = parseFloat(data[i].longitude);
var latitude = parseFloat(data[i].latitude);
var nama = (data[i].nama_sekolah);
var marker = (data[i].jenjang);
var markerIcon;
if (marker == 'sd') {
markerIcon = new L.Icon({iconUrl: '<?=base_url() ?>assets/leaflet/images/sd1.png', iconSize:[30,30]});
} else {
markerIcon = new L.Icon({iconUrl: '<?=base_url() ?>assets/leaflet/images/smp1.png', iconSize:[30,30]});
}
L.marker([longitude, latitude], {icon: markerIcon}).addTo(map)
.bindPopup(nama, {autoClose: false, autoPan: false})
.openPopup();
});
});
//how to write if else on this line of code
//create blueIcon by default
var icon = new L.icon({iconUrl: '<?=base_url() ?>assets/leaflet/images/smp1.png', iconSize:[30,30]});
//if marker is 'sd' then update same variable for Red Icon
if (marker == 'sd'){
icon = new L.icon({iconUrl: '<?=base_url() ?>assets/leaflet/images/sd1.png', iconSize:[30,30]});
}
//Now you can 'icon' variable below as per requirement.
希望有帮助。