[英]Loop in php the posts and add a class to polygon (leaflet)
我正在使用Wordpress,正在浏览我的文章,并为每篇文章创建一个案例并添加一个类。 案例名称和类名称取自每个帖子所附的自定义字段。
但是,发生的事情是,如果我有2条与某个国家(例如澳大利亚)有关的文章,则循环将显示“为澳大利亚的此类课程找到了一篇文章,设置了一个案例并添加了其类别”。 但是,如果我有2条与澳大利亚有关的文章,则已经为其创建了案例,因此我将无法添加第二类,因为它会跳过它。 因此我认为我做错了,我不应该使用switch case
。
这个想法是检查country custom field
与sovereignt property within the geoson
的sovereignt property within the geoson
之间是否匹配,这样,如果有任何文章与某个国家相关,则我可以绘制国家/地区多边形,但是如果我有两个与一个国家/地区相关的文章,则可以绘制多边形只画了一次,但是上面有类问题。
geojson = L.geoJson(statesData, {
style: style,
style: function(feature) {
<?php
query_posts(array(
'post_type' => 'post',
'showposts' => -1
));
?>
switch (feature.properties.sovereignt) {
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
case '<?php the_field("country"); ?>': return {className: '_<?php the_field("year"); ?>'};
<?php endwhile; endif;?>
}
},
onEachFeature: onEachFeature
}).addTo(map);
我从传单文档中获得的开关案例示例
您做错的是每两行混合使用PHP和JavaScript。 这是《灾难食谱》,因为您必须考虑两种不同语言的执行。 虽然看起来可行,但很快就会变得混乱。
相反,请稍微分离一下逻辑,然后控制周围的变量:
<?php // Preprocess some data ?>
var something = <?php echo JSON_encode(some_clearly_defined_data); ?>
do_something_with_the_data();
即:
<?php
classesForCountries = [];
while (have_posts()) {
classesForCountries[ post.country ] += post.className + ' ';
}
?>
// Now this should look something like {"Australia": "2006 2010 "}
var classNameMap = <?php echo JSON_encode(classesForCountries); ?>;
geojson = L.geoJson(statesData, {
style: function(feature) {
// Now the logic is a simple hashmap look-up
var classes = classNameMap[feature.properties.sovereignt];
if (classes) {
return {className: classes};
}
},
}).addTo(map);
看起来不干净吗? 当您可以将PHP和JS混合在一起时,应该使代码易于阅读和理解。 创建可以检查的变量和状态。 编写您将来的自己想阅读的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.