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:
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:
- 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 or tripling the amount of data that is being sent to the client.
The Ajax request.
An example 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. This means that the size of our data isn’t slowing down the initial load time of the page.
In this example, we’re sending the AJAX request to a file called get-locations.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);
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).