[英]How to make if else statement on getJSON to load different leaflet markers
How to check condition (==) array from json and make statement if else to load different leaflet markers.如何检查 json 中的条件(==)数组并声明 if else 以加载不同的 leaflet 标记。
$.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();
});
});
//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.
Hope it helps.希望能帮助到你。
You could save the icon in a previously defined var like markerIcon
and then use it later as it will have the expected value:您可以将图标保存在先前定义的变量中,例如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();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.