0

I have a Google map that I want to link to a database to display many markers dynamically using PHP and MySQL.

My code below

<?php
//This creates an array from the database and allows us to use it later in the jquery
//CREATE SQL STATEMENT
$sql_locations = "SELECT * FROM tbllocations";

//CONNECT TO MYSQL SERVER
require('test-connection.php');

//EXECUTE SQL STATEMENT
$rs_locations = mysqli_query($vconnection, $sql_locations);

//CREATE AN ASSOCIATIVE ARRAY
$rs_locations_rows = mysqli_fetch_assoc($rs_locations);
$place = $rs_location_rows['place'];
$city = $rs_location_rows['city'];
$long = $rs_location_rows['long'];
$lat = $rs_location_rows['lat'];
?>
<div id="map_wrapper">
    <div id="map_canvas" class="mapping"></div>
</div>


<style>

#map_wrapper {
    height: 400px;
}

#map_canvas {
    width: 100%;
    height: 100vh;
}


</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>

jQuery(function($) {
    // Asynchronously Load the map API 
    var script = document.createElement('script');
    script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
    document.body.appendChild(script);
});

function initialize() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };

    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);

    // Multiple Markers
    var markers = [


       <?php do{?>

        ['<?php echo $place . ", " . $city;?>', <?php echo $long . "," . $lat;?>],

        <?php } while($rs_location_rows = mysqli_fetch_assoc($rs_location))?>

        ['Palace of Westminster, London', 51.499633,-0.124755]


        //['London Eye, London', 51.503454,-0.119562],
        //['Palace of Westminster, London', 51.499633,-0.124755]
    ];

    // Info Window Content
    var infoWindowContent = [
        ['<div class="info_content">' +
        '<h3>London Eye</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>' +        '</div>'],
        ['<div class="info_content">' +
        '<h3>Palace of Westminster</h3>' +
        '<p>The Palace of Westminster is the meeting place of the House of Commons and the House of Lords, the two houses of the Parliament of the United Kingdom. Commonly known as the Houses of Parliament after its tenants.</p>' +
        '</div>']
    ];

    // Display multiple markers on a map
    var infoWindow = new google.maps.InfoWindow(), marker, i;

    // Loop through our array of markers & place each one on the map  
    for( i = 0; i < markers.length; i++ ) {
        var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
        bounds.extend(position);
        marker = new google.maps.Marker({
            position: position,
            map: map,
            title: markers[i][1]
        });

        // Allow each marker to have an info window    
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infoWindow.setContent(infoWindowContent[i][0]);
                infoWindow.open(map, marker);
            }
        })(marker, i));

        // Automatically center the map fitting all markers on the screen
        map.fitBounds(bounds);
    }

    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
        this.setZoom(16);
        google.maps.event.removeListener(boundsListener);
    });

}



</script>

The problem is that I get all of the markers variables from the associative array in php and they display if I echo them. However as I pass them through the jquery function in a do while loop, it only displays two of the markers on the map instead of all of the markers.

My theory is that I have not written my for loop inside my jquery correctly and this is causing the code to only display two markers.

4
  • What does the code the browser sees look like? Are you getting any javascript errors? It looks to me like your latitude and longitude are reversed (is longitude, latitude; should be latitude, longitude) Commented Nov 11, 2015 at 14:23
  • No Errors in the Javascript console, just for some reason it wont pick up the full array of markers Commented Nov 11, 2015 at 14:26
  • What does the "full array of markers" look like in the output? (or at least some of the values). Which two markers are you getting on the map? Commented Nov 11, 2015 at 14:31
  • There must be an error: ['<?php echo $place . ", " . $city;?>', <?php echo $long . "," . $lat;?>] gives you [ "place, city", "long, lat" ] BUT you need [ "place, city", long, lat] in your code Commented Nov 11, 2015 at 15:20

1 Answer 1

2

I would guess, the problem is that you define the variables $place, $city, $long once and you never override it.

So maybe you have more than two markers but all except ['Palace of Westminster, London', 51.499633, -0.124755] are the same markers.

UPDATE: working example, commented out your sql stuff, and wrote some coordinates in the marker array. You have to adjust your infoWindowContentif you have this information in your Database you can also add this to the php $markerarray or create a new one like the $markerin this example.

Result: I get all of the defined markers. If this works try to remove the comment //from the stuff you need, If you still have problems, try this in your foreach for debugging:

foreach( $rs_locations as $rs_location ) {
  var_dump( $rs_location );
  ......

Working example:

//This creates an array from the database and allows us to use it later in the jquery
//CREATE SQL STATEMENT
$sql_locations = "SELECT * FROM tbllocations";

//CONNECT TO MYSQL SERVER
//<---------   require('test-connection.php');
//EXECUTE SQL STATEMENT
//<---------   $rs_locations = mysqli_query($vconnection, $sql_locations);

$markers = array(
    // your example['Palace of Westminster, London', 51.499633,-0.124755]
    array(
        'Palace of Westminster, London',
        51.499633,
        -0.124755
    ),
    array(
        'Westminster Abbey, London',
        51.4992453,
        -0.1272561
    ),
    array(
        'QEII Centre, London',
        51.4997296,
        -0.128683
    ),
    array(
        'Winston Churchill Statue, London',
        51.5004308,
        -0.1275243
    ),
    array(
        'Fitzroy Lodge Amature Boxing Club, London',
        51.4954215,
        -0.1154758
    ),
    array(
        'Balham Boxing Club, London',
        51.4419539,
        -0.1336075
    )
);

// use this for your code
//foreach( $rs_locations as $rs_location ) {
//  $markers[] = array(
//      "{$rs_location['place']}, {$rs_location['city']}",
//      $rs_location['long'],
//      $rs_location['lat']
//  );
//}
?>
<div id="map_wrapper">
    <div id="map_canvas" class="mapping"></div>
</div>


<style>

    #map_wrapper {
        height: 400px;
    }

    #map_canvas {
        width: 100%;
        height: 100vh;
    }


</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>

    function initialize() {
        var map;
        var bounds = new google.maps.LatLngBounds();
        var mapOptions = {
            mapTypeId: "roadmap",
            center: new google.maps.LatLng(52.791331, -1.918728), // somewhere in the uk BEWARE center is required
            zoom: 3,
        };

        // Display a map on the page
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
        map.setTilt(45);

        // Multiple Markers
        var markers = <?php echo json_encode( $markers ); ?>;

        // Info Window Content
        var infoWindowContent = [
            ['<div class="info_content">' +
            '<h3>London Eye</h3>' +
            '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>' + '</div>'],
            ['<div class="info_content">' +
            '<h3>Palace of Westminster</h3>' +
            '<p>The Palace of Westminster is the meeting place of the House of Commons and the House of Lords, the two houses of the Parliament of the United Kingdom. Commonly known as the Houses of Parliament after its tenants.</p>' +
            '</div>']
        ];

        // Display multiple markers on a map
        var infoWindow = new google.maps.InfoWindow();
        var marker, i;

        // Loop through our array of markers & place each one on the map
        for (i = 0; i < markers.length; i++) {
            var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
            bounds.extend(position);
            marker = new google.maps.Marker({
                position: position,
                map: map,
                title: markers[i][0]
            });

            // Allow each marker to have an info window
            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infoWindow.setContent(infoWindowContent[i][0]);
                    infoWindow.open(map, marker);
                }
            })(marker, i));

            // Automatically center the map fitting all markers on the screen
            map.fitBounds(bounds);
        }

        //Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {
            this.setZoom(10);
            google.maps.event.removeListener(boundsListener);
        });

    }
    google.maps.event.addDomListener(window, 'load', initialize);


</script>

EDIT: removed duplicate div <div id="map_canvas"></div> from my example

Sign up to request clarification or add additional context in comments.

3 Comments

This does the same thing :) only the two markers show up, yet in my database there are 5 rows. Would it be in this loop?
// Display multiple markers on a map var infoWindow = new google.maps.InfoWindow(), marker, i; // Loop through our array of markers & place each one on the map for( i = 0; i < markers.length; i++ ) { var position = new google.maps.LatLng(markers[i][1], markers[i][2]); bounds.extend(position); marker = new google.maps.Marker({ position: position, map: map, title: markers[i][1] });
updated my answer with a working example, changes some stuff due to the google maps api, to get it work on my server

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.