I'm trying to plot some cities on Google's Geochart. This function works perfectly fine and will plot cities.
function drawMarkersMap() {
var newInfo = google.visualization.arrayToDataTable([
['City'],
['San Diego'],
['Los Angeles'],
['San Jose']
]);
While that's nice and all, I'm generating my cities from my database via php. So, let's just say we have this php array
<?php $city = array("San Diego", "Los Angeles", "San Jose"); ?>
Now here comes the part where I'm struggling. I can't seem to get a loop working properly so that I can output each city separately.
When I do this only the first city in the array(San Diego) will display and I understand why...I'm just showing that this method will at least print "something"
function drawMarkersMap() {
var newInfo = google.visualization.arrayToDataTable([
['City'],
['<?php foreach($city as $location){ echo json_encode($location); } ?>']
]);
//options here
}
So, I'm attempting to loop through and print each item in the array using javascript but I don't seem to have the logic correct
function drawMarkersMap() {
var newInfo = google.visualization.arrayToDataTable([
['City'],
for(i=0;i<json_encode($city).count;i++){
//some kind of print statement mixing php and javascript. I need help here please!
}
]);
Here's the entire page
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Google Visualization API Sample</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<?
$city = array("San Jose","Los Angeles","San Diego");
foreach($city as $key=>$value) {
echo "$value";
}
?>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['geochart']});
function drawMarkersMap() {
var newInfo = google.visualization.arrayToDataTable([
['City'],
['<?php echo json_encode($city); ?>']
]);
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(newInfo, {width: 556, height: 347, displayMode: 'markers', region: 'US-CA', resolution: 'provinces'});
}
google.setOnLoadCallback(drawMarkersMap);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="chart_div"></div>
</body>
</html>
json_encode()
actually outputs, not just the function in place. Your JSON is likely malformed, or not an array, but an object, which Google's functions might vomit over. – Bojangles May 18 '12 at 1:15<?php echo json_encode($city); ?>
, which is useless because it's impossible to know if the string thatjson_encode()
outputs is properly formed for the JS you plug it into. Instead of posting the PHP, please post the JSON string it outputs to the browser. – Bojangles May 18 '12 at 1:21