Generating Google Maps markers with PHP.

On too many occasions, I’ve come across developers using PHP loops to print out large amounts of JavaScript data.

This seems to be particularly common among coders who are trying to generate multiple markers for the Google Maps API.

Typically, they will grab a bunch of long / lat values from their database and then print them out like so:

<script type="text/javascript">
    <?php foreach($locations as $location){ ?>
        var location = new google.maps.LatLng(<?php echo $location['lat']; ?>, <?php echo $location['lng']; ?>);
        var marker = new google.maps.Marker({
            position: location,
            map: map
        });
    <?php } ?>
</script>

The code above will work fine if you’re only displaying a small number of markers.

However, as the number of markers begins to grow in size, the loop starts to become more and more wasteful.

The first thing you’ll notice is that your page will begin to load more slowly. This is simply because of the fact that you are printing more and more data.

Another problem that comes with this approach is the lack of extensibility.

If, in the future, you are forced to add InfoWindows or other features that interact with your markers, then the code above will become more and more difficult to maintain. The size of the data being printed out will grow, and you’ll inevitably have to pursue another solution.

What is the best way to load multiple markers from a database?

Typically, you will want to take the following steps:

  1. Load the page and the map.
  2. After the page has loaded, carry out an AJAX request to a PHP file that will return the locations in a format such as JSON or XML.
  3. Loop through the locations using JavaScript.

Using the steps above will allow your page to load much more quickly. It will also allow you to add Events and Controls to your map without doubling or tripling the amount of data that is being sent to the client.

The Ajax request.

An example Ajax request:

<script type="text/javascript">

    //When the Window finishes loading...
    $(window).load(function () {

        //Carry out an Ajax request.
        $.ajax({
            url: 'get-locations.php',
            success:function(data){
                //Loop through each location.
                $.each(data, function(){
                    //Plot the location as a marker
                    var pos = new google.maps.LatLng(this.lat, this.lng); 
                    new google.maps.Marker({
                        position: pos,
                        map: map
                    });
                });
            }
        });

    });

</script>

As you can see, we’re using JQuery to send an AJAX request to get-locations.php.

Because we’ve used the load event, this request will only be sent after the page has loaded. This means that the size of our data isn’t slowing down the initial load time of the page.

get-locations.php

In this example, we’re sending the AJAX request to a file called get-locations.php.

This is the page that will retrieve our locations from the database and then print them out in JSON format so that our JavaScript can retrieve and interpret the data.

In case you didn’t already know, JSON and JavaScript go together like bread and butter:

//Using PDO in this example.
require 'pdo-connection.php';

//Get our locations from the database.
$sth = $pdo->prepare("SELECT `lat`, `lng` FROM `locations`");
$sth->execute();
$locations = $sth->fetchAll(PDO::FETCH_ASSOC);

//Encode the $locations array in JSON format and print it out.
header('Content-Type: application/json');
echo json_encode($locations);

Using this method, you can significantly reduce the load time of your page (differences will obviously depend on the number of locations that you intend on plotting).

It is also a cleaner solution, as you have successfully kept your JavaScript and PHP separate from one another.

One thought on “Generating Google Maps markers with PHP.

Comments are closed.