I am trying to display multiple markers on Google maps using data (lat and lng) from a MySQL database. When I run a foreach loop to return these markers on the map, it returns only the last row. What might be the problem?
<?php
require_once "db/db_handle.php";
$select = "SELECT * FROM map";
$data = $db->query($select);
?>
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<?php foreach ($data as $key) {
echo $key['lat'];
?>
<script>
function initMap() {
var uluru = {lat: <?php echo $key['lat']; ?>, lng: <?php echo $key['lng']; ?>};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
var contentString = '<?php echo $key['address']; ?>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
title: 'Uluru (Address)'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
</script>
<?php } ?>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMap">
</script>
</body>
</html>