简体   繁体   中英

Displaying markers on google map from mysql database using php/javascript

In my database I have lat/lng values and I'm trying to display markers on a google map. (I have my map coming up ok but can't get the markers going!).

 // Selects all the rows in the tester table.
$query = 'SELECT * FROM tester WHERE 1';
$result = mysql_query($query);

if (!$result) 
{
die('Invalid query: ' . mysql_error());
}

    while ($row = mysql_fetch_assoc($result))
    {?>
       var marker = new google.maps.Marker({
    position: <?php $row['lat']?>, <?php $row['lng']?> ,
    map: map,
    title:"Hello World!"
});   

}                

Any help would be great thanks!

我认为您需要使用“ echo”:

position: <?php echo $row['lat']?>, <?php echo $row['lng']?> ,

It gets quite complex when you start writing javascript out from PHP as its very easy to get lost in all the semi-colons.

Also I find it easier to do it all in PHP rather than keep jumping in and out of HTML-PHP-HTML-PHP etc

Try this

// Selects all the rows in the tester table.
$query = 'SELECT * FROM tester WHERE 1';
$result = mysql_query($query);

if (!$result) {
    die('Invalid query: ' . mysql_error());
}

echo '<script type="text/javascript">';

$i = 0;
while ($row = mysql_fetch_assoc($result))
    echo 'var myLatlng = new google.maps.LatLng(' . $row['lat'] ',' . $row['lng'] . ');';

    echo 'var marker' . $i . ' = new google.maps.Marker({';
    echo '  position: myLatLng ,';
    echo '  map: map,';
    echo '  title:"Hello World!"';
    echo '});';
    echo 'marker' . $i . 'setMap(map);';
    $i++;
}               


echo '<script>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM