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>
883

Answer

Solution:

You have an issue with the scope ofmap, 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:

map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); //Note i've removed the "var" keyword from this line.

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.

var marker = new google.maps.Marker({
    position: point,
    map: map // -> NULL because it will look for map in the parent scope.
});

I've found the issue, you are missing the closing bracers of your while statement:

<?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);");
    } //Missing!!!
?>

People are also looking for solutions to the problem: php - Microsoft CRM 2013: relate Account and Contact entities AFTER import

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.