>我创建了一个基于googlemaps的分支页面,其中通过自定义帖子类型和Google地图高级自定义字段对象创建地点。
唯一的问题是:如果我想在信息窗口中包含帖子的内容(以显示位置的详细信息等)并且内容不止一行 - 代码中断...
例如
这将正常工作:
Lorem ipsum dolor sit amet, id malorum numquam per
但这会破坏:
Lorem ipsum dolor sit amet,
id malorum numquam per
这是用于获取位置内容的代码:
var locations = [<?php while( $wp_query->have_posts() ){
$wp_query->the_post();
$location = get_field('google_map');
?>
//acf location's details array
['<h1><?php the_title(); ?></h1><h2><?php the_field('branch_name'); ?></h2><div id=<?php echo $post->ID; ?>><?php echo $post->post_content; ?></div>',
<?php echo $location['lat']; ?>, <?php echo $location['lng'];?>, <?php $NUM++ ?>],
<?php } ?> ];
这就是我将其发送到信息窗口的方式:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
for (var j = 0; j < markers.length; j++) {
markers[j].setIcon("<?php echo get_template_directory_uri(); ?>/images/mapmarker.png");
}
marker.setIcon("<?php echo get_template_directory_uri(); ?>/images/mapmarker-active.png");
};
})(marker, i));
以下是完整模板代码的代码共享链接:http://www.codeshare.io/zaj6n
使用 json_encode
打印包含换行符(或在 JS 中会有问题的字符,例如引号)的字符串:
echo json_encode($post->post_content);
为了避免双引号创建,json_encode用所需的值填充 PHP 数组并使用 json_encode
打印整个数组:
(未测试)
<?php
$locations=array();
while( $wp_query->have_posts() ){
$wp_query->the_post();
$location = get_field('google_map');
$locations[]=array(the_title('<h1>','</h1>',false).
'<h2>'.get_field('branch_name').'</h2>'.
'<div id="'.$post->ID.'">'.$post->post_content.'</div>',
$location['lat'],
$location['lng'],
$NUM++
);
}
echo "'nvar locations=".json_encode($locations).";'n";
?>