Reputation: 432
i have case like this. i have hardcode javascript variable like this :
var features = [{
position: new google.maps.LatLng(-8.702709, 115.224461),
type: 'info',
title: 'Pusat Informasi Kota',
category: 1
}, {
position: new google.maps.LatLng(-8.704432, 115.230249),
type: 'parking',
title: 'Tempat Parkir Avaliable',
category: 2
}, {
position: new google.maps.LatLng(-8.704442, 115.231239),
type: 'library',
title: 'perpustakaan kota',
category: 3
}, {
position: new google.maps.LatLng(-8.702909, 115.230149),
type: 'parking',
title: 'ini parkir',
category: 2
}];
in future, i want to store that data on a table. problem is, i try to make table like image below
and i was store the data on php array variable $data_location.
do you have idea if i want to change $data_location array into features variable ? i have try to use json_encode but i think i shouldn't work.
var features = <?php echo json_encode($data_location);?>;
i try to print_r($data_location); this is the result :
<html><head>
<title>Styling the Base Map</title>
</head><body>Array
(
[0] => stdClass Object
(
[id] => 1
[type] => info
[category] => 1
[title_info] => Pusat Informasi Kota'
[name] => Pusat Informasi Kota'
[lat] => -8.70271
[long] => 115.224
)
[1] => stdClass Object
(
[id] => 2
[type] => parking
[category] => 2
[title_info] => Tempat Parkir Avaliable
[name] => parkir 1
[lat] => -8.70443
[long] => 115.23
)
[2] => stdClass Object
(
[id] => 3
[type] => library
[category] => 3
[title_info] => perpustakaan kota
[name] => Perpus 1
[lat] => -8.70444
[long] => 115.231
)
)
</body></html>
do you have any suggestion?
-thank you in advance-
Upvotes: 0
Views: 91
Reputation: 2995
First of all fetch all the records from database and create a new php array from the results according to your requirement and then json_encode that array in your script...
You can do something like this, I hope that you can understand this code easily..
<?php
$data_locations =array();
$result = mysql_query('SELECT * FROM your_table');
while($row = mysqli_fetch_array($result))
{
$arr['position'] = 'new google.maps.LatLng('.$row['lat'].' , '.$row['long'].')';
$arr['type'] = $row['type'];
$arr['title'] = $row['title_info'];
$arr['category'] = $row['category'];
$data_locations[] = $arr;
}
?>
And in your script json encode $data_locations
array..
<script>
var features = <?php echo json_encode($data_locations);?>;
</script>
Upvotes: 1
Reputation: 66
You can turn a JSON string into a JavaScript object by using JSON.parse.
Something like
var features = JSON.parse( <?php echo json_encode($data_location);?> );
may work, if the output of echo json_encode($data_location)
is valid JSON.
Upvotes: 1