我目前正在与ACF和CPT建立一个DealLocator。
为了让经销商在地图上购物,我想使用MAPlace JS。当手动将数组添加到locations变量时,这可以很好地工作。
从我的CPT传递数据时,会引发错误:
未捕获的TypeError:无法分配给字符串的只读属性“0”。
这是传递的JSON数组:
[{
"lat":"52.5164364",
"lng":"6.073328800000013",
"title":"Company Name",
"zoom":8,
"icon":"http:\\/\\/www.google.com\\/mapfiles\\/markerA.png"
},{
"lat":"53.3354151",
"lng":"6.5032264999999825",
"title":"Company Name 2",
"zoom":8,
"icon":"http:\\/\\/www.google.com\\/mapfiles\\/markerA.png"
}]
这是通过以下脚本传递的:
add_action(\'wp_enqueue_scripts\', function() {
global $post;
$args = array(
\'post_type\' => \'dealers\'
);
$mapposts = get_posts($args);
$location_array = array();
foreach($mapposts as $mappost) : setup_postdata($mappost);
$location = get_field(\'maps_location\', $mappost->ID);
$location_array[] = array(
\'lat\' => $location[\'lat\'],
\'lng\' => $location[\'lng\'],
\'title\' => get_the_title($mappost->ID),
\'zoom\' => 8,
\'icon\' => \'http://www.google.com/mapfiles/markerA.png\'
);
$location_json = json_encode($location_array);
wp_localize_script(\'sage/main.js\', \'locationJSON\', $location_json);
endforeach;
}, 110);
在JS文件中,如下所示:
console.log(locationJSON);
new Maplace({
// eslint-disable-next-line no-undef
locations: locationJSON,
controls_type: \'list\',
controls_on_map: false,
}).Load();
在控制台上。log它如上所述显示JSON,因此代码传递正常。
但是代码在Maps脚本中不起作用,这是下面的错误。
Uncaught TypeError: Cannot assign to read only property \'0\' of string \'[{"lat":"52.5164364","lng":"6.073328800000013","title":"Company Name","zoom":8,"icon":"http:\\/\\/www.google.com\\/mapfiles\\/markerA.png"},{"lat":"53.3354151","lng":"6.5032264999999825","title":"Company Name 2","zoom":8,"icon":"http:\\/\\/www.google.com\\/mapfiles\\/markerA.png"}]\'
at b._init (maplace.min.js:12)
at b.Load (maplace.min.js:12)
at Object.init (common.js:15)
at Router.fire (Router.js:30)
at Router.loadEvents (Router.js:45)
at HTMLDocument.<anonymous> (main.js:25)
at i (jquery-1.12.4.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.12.4.min.js:2)
at Function.ready (jquery-1.12.4.min.js:2)
at HTMLDocument.K (jquery-1.12.4.min.js:2)
b._init @ maplace.min.js:12
b.Load @ maplace.min.js:12
init @ common.js:15
fire @ Router.js:30
loadEvents @ Router.js:45
(anonymous) @ main.js:25
i @ jquery-1.12.4.min.js:2
fireWith @ jquery-1.12.4.min.js:2
ready @ jquery-1.12.4.min.js:2
K @ jquery-1.12.4.min.js:2
我已经找了好几个小时了,但我无法解决这个问题。
有什么想法吗?