multiple entries from csv files in java script
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
<?php
$fd = fopen ("landmarks.csv", "r");
echo "var latlngarr=new Array();";
$i=0;
echo "var markerarr=new Array();";
while (!feof ($fd)) {
$buffer = fgetcsv($fd, 4096);
echo "var latlngarr[$i] = new google.maps.LatLng($buffer[2],$buffer[3]);";
echo "var markerarr[$i] = new google.maps.Marker({
position: latlngarr[$i],
map: map,
title:$buffer[1]";
});
$i++;
}
fclose ($fd);
?>
I want to create multiple markers in开发者_高级运维 google maps..the first entry works...but the other ones, from the csv file dont work? Is there something wron with the mixed php and Javscript code?
Add quotes around strings and fix missing }
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
<?php
$fd = fopen ("landmarks.csv", "r");
echo "var latlngarr=new Array();";
$i=0;
echo "var markerarr=new Array();";
while (!feof ($fd)) {
$buffer = fgetcsv($fd, 4096);
?>
latlngarr[<?= $i ?>] = new google.maps.LatLng(<?= $buffer[2] ?>, <?= $buffer[3] ?>);
markerarr[<?= $i ?>] = new google.maps.Marker({
position: latlngarr[<?= $i++ ?>],
map: map,
title: '<?= $buffer[1] ?>'
});
<?php
}
fclose ($fd);
?>
I'm guessing that possibly the data coming out of the CSV file isn't properly quoted, particularly the title
attribute. When dynamically building Javascript from PHP, you should always use json_encode():
$b2 = json_encode($buffer[2]);
$b3 = json_encode($buffer[3]);
$title = json_encode($buffer[1]);
echo "var latlngarr[$i] = new google.maps.LatLng($b2,$b3);";
echo "var markerarr[$i] = new google.maps.Marker({
position: latlngarr[$i],
map: map,
title: $title";
});
using json_encode guarantees that whatever is in those PHP variables will be translated into syntactically correct Javascript.
精彩评论