使用json_encode从PHP数组填充Google Map Markers

时间:2021-06-04 13:38:24

When I use the hard coded javascript array as input for the map markers the markers show up just fine, so I know that the code I'm using to display the markers is good.

当我使用硬编码的javascript数组作为地图标记的输入时,标记显示得很好,所以我知道我用来显示标记的代码是好的。

My problem is when I try and convert a php multi-array using json_encode, nothing shows up on the map.

我的问题是当我尝试使用json_encode转换php多数组时,地图上没有显示任何内容。

The hard coded markers are:

硬编码标记是:

var locations = [
           ['Sausalito', 37.8590937, -122.4852507,'url'],
           ['Sacramento', 38.5815719, -121.4943996,'url'],
           ['Soledad', 36.424687, -121.3263187,'url'],
           ['Shingletown', 40.4923784, -121.8891586,'url']
       ];

and they work.

他们工作。

The php array is:

php数组是:

$locations = array(array(Sausalito, 37.8590937, -122.4852507,'url'),array(Sacramento, 38.5815719, -121.4943996,'url'));

which produces the array,

产生阵列,

Array
(
    [0] => Array
        (
            [0] => Sausalito
            [1] => 37.8590937
            [2] => -122.4852507
            [3] => url
        )
    [1] => Array
        (
            [0] => Sacramento
            [1] => 38.5815719
            [2] => -121.4943996
            [3] => url
        )
)

so no problem as yet.

所以没问题。

Now when I json_encode the above array

现在当我json_encode上面的数组

var locations = '<?php echo json_encode($locations); ?>';

it does not get read by the javascript map code. and if I print the variable

它不会被javascript地图代码读取。如果我打印变量

document.write(locations);

it shows up as

它显示为

[["Sausalito",37.8590937,-122.4852507,"url"],["Sacramento",38.5815719,-121.4943996,"url"]]

which kinda looks like the hard-coded above, but it does not get read by the map code which works with the hard-coded data.

哪种看起来像上面的硬编码,但它不会被与硬编码数据一起使用的地图代码读取。

Can anyone assist me, please, much appreciated.

请帮助我,非常感谢。

1 个解决方案

#1


1  

Remove the single-quotes, otherwise locations will be a string and not an array:

删除单引号,否则位置将是字符串而不是数组:

var locations = '<?php echo json_encode($locations); ?>';
//--------------^--------------------------------------^

#1


1  

Remove the single-quotes, otherwise locations will be a string and not an array:

删除单引号,否则位置将是字符串而不是数组:

var locations = '<?php echo json_encode($locations); ?>';
//--------------^--------------------------------------^