Thursday, 9 August 2018

Generating Google Maps Markers With PHP

On too many occasions, I’ve come across people using PHP loops to print out large amounts of JavaScript data. In particular, it seems to be common among developers who are attempting 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 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:
  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 / 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.

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 (and JSON actually stands for JavaScript Object Notation).
Using this method, you can significantly reduce the load time of your page (differences will obviously depend on the number of locations you intend on plotting). It is also a cleaner solution, as you have successfully kept your JavaScript and PHP decoupled from one another.

0 comments:

Post a Comment