I want to map a field, city, from a MySQL database into Google Maps. I found a nice script here, but haven't been able to get it to work.
If I hard code an array into locations (var locations = ['Seattle', 'New York']), it works fine. Passing this SQL array into JS is giving me problems.
I've tried a number of different things, but I'm stuck. Right now I'm trying getElementById, but no dice. Any help is appreciated! Thanks.
<?php
$server_name="localhost";
$db_user="sql_user";
$db_pass="password";
$db="mydb";
mysql_connect($server_name, $db_user, $db_pass);
mysql_select_db($db);
$sql = "SELECT city FROM posts";
$result = mysql_query($sql) or die ('Query Error: ' . mysql_error());
while ($results = mysql_fetch_array($result))
{
$city[] = $results;
}
?>
<div id="map_canvas" style="width: 600px; height: 400px"></div>
<script type="text/javascript">
var locations = document.getElementById("<?=$city?>");
var mapOpt = {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: new google.maps.LatLng(38.00, -100.00),
zoom: 3
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOpt);
var geocoder = new google.maps.Geocoder();
var index = 0;
var geocoderFunction = function () {
geocoder.geocode({ 'address': locations[index] }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
// Call the geocoder with a 100ms delay
index++;
if (locations.length > index) {
setTimeout(geocoderFunction, 100);
}
});
}
// Launch the geocoding process
geocoderFunction();
</script>
document.getElementById("<?=$city?>")some kind of special PHP syntax? Are you trying to assign the PHP array$cityto the JavaScript variablelocations?