richdata
richdata

Reputation: 3

Populating Google Map Markers from PHP array using json_encode

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.

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

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:

$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

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

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

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.

Upvotes: 0

Views: 1255

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117314

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

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

Upvotes: 1

Related Questions