Typically, they will grab a bunch of long / lat values from their database and then print them out like so:
The code above will work fine if you’re only displaying a small amount 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 end having to pursue another solution.
OK, so what’s the best way to load multiple markers from a database?
Typically, you want to take the following steps:
- Load the page and the map.
- 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.
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 / tripling the amount of data that is being sent to the client.
The Ajax Request
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. Therefore, the size of our data isn’t adversely affecting the initial load time of the page.
<?php //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);