javascript - google map markers php
208
I am able to display my mp ok, but when I go to add markers it is no longer loading the map... i.e. when I add the latter php code to my initialize function it doesn't work! Any ideas??!
<script type="text/javascript">
var map = null;
function addMarker(lat, lng){
var point = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: point,
map: map
});
}
function initialize() {
var mapOptions = {
center: {lat: 54.872128, lng: -6.284874},
zoom: 15
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
<?php
$query = mysqli_query("select * from tester") or die(mysqli_error());
while($row = mysqli_fetch_array($query)){
$lat = $row['lat'];
$lng = $row['lng'];
echo ("addMarker($lat, $lng);");
?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas" style="height:600px; width:600px;
margin-top:100px; margin-bottom: 100px;
">
</div>
Answer
Solution:
You have an issue with the scope of
map
, in your initialize function you are redeclaring it inside that scope instead of populating the previous map var, remove thevar
from your function as follows:A little more explanation:
var map = null;
-> declared in global scope.var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
-> declared insideinitialize
function scope.I've found the issue, you are missing the closing bracers of your while statement: