Blog Post Icon
Blog
04/26/2016

How to create a heatmap layer on Google Maps using JQuery and PHP

Hello!

There was a scenario not too long ago where we were required to create a heatmap layer on top of a Google map to plot latitude/longitude coordinates. I thought I’d share the process through which we pull the coordinate data from a MySQL database and plot it into the google map as a heatmap layer.

We chose to go with a pre-built jQuery library to handle most of the work interacting with the Google Map api and drawing the heatmap layer itself. For this we chose heatmap.js. From heatmap.js’ website, it is a “lightweight, easy to use JavaScript library to help you visualize your three dimensional data!”.

What we’re ultimately trying to do is build a simple PHP page that pulls all the coordinate from a MySQL table, prepares it into a json array and then plots all the points as a heatmap over top a google map location.

The location we chose was Trinity Bellwoods in Toronto. We want to plot a bunch of reported coordinate points on the map so you can see heavily “reported” areas in the park in such a way that you can visually discern areas of the park that are more reported than others.

Pull the data from MySQL

This is obvious! What we want to do is build a simple data array by completing a MySQL query against our database. Here is the SQL query that we will be using :

$sql = "SELECT latitude,longitude from reports order by created_at DESC;";

Simple, right? Well lets take that to the next step and connect to our database and execute the query :

    try {
        $db = connect_db();
                $result = $db->query($sql);
        while ( $row = $result->fetch_array(MYSQLI_ASSOC) ) {
                    $data[] = $row;
                }
        $db = NULL;
                $data_json = json_encode($data);
    } catch(PDOException $e) {
            echo '{"error":{"text":'. $e->getMessage() .'}}';
        }

If you echo the $data_json variable, you’ll likely see something like this :

{"latitude":"45.646008","longitude":"-59.414391"},{"latitude":"33.647446","longitude":"-49.413498"},{"latitude":"13.664890","longitude":"-88.420975"} ..

The heatmap.js library is capable of taking an additional integer to weight each plotted coordinate as a “count”. If you are able to count existing coordinates and then mark the duplicates with a count(*). As implied, the count variable will add weight to each coordinate that is greater than one. So if you have a coordinate that was reported 10 times, then it will appear more pronounced in the heatmap overlay.

Use Heatmap.js to build and plot the map

The heatmap.js library provides quite a few examples, including an example to interact directly with Google maps for your heatmap. I will walk you through creating the heatmap page. First you’ll want to load the libraries :

    
    
    

Next thing you want to do is create a div container for the map canvas. This should be full height / width on the screen, but can be adjusted through CSS to accommodate whatever layout you’re looking for.

Below the map canvas is where most of the manipulation happens. The first thing you want to do is declare the focal point of your map. In our case it is Trinity Bellwoods park in Toronto.

var myLatlng = new google.maps.LatLng(43.648062, -79.414115);

As far as how zoomed out we want to be, we pass standard google map options :

        var myOptions = {
          zoom: 17,
          center: myLatlng
        };

The heatmap library takes options with respect to scale, radius, and which fields to parse for latitude, longitude and count in the data variable.

        heatmap = new HeatmapOverlay(map,
          {
            // radius should be small ONLY if scaleRadius is true (or small radius is intended)
            "radius": 17,
            "maxOpacity": 1,
            // scales the radius based on map zoom
            "scaleRadius": false,
            // if set to false the heatmap uses the global maximum for colorization
            // if activated: uses the data maximum within the current map boundaries.
            //   (there will always be a red spot with useLocalExtremas true)
            "useLocalExtrema": true,
            // which field name in your data represents the lat - default "lat"
            latField: 'latitude',
            // which field name in your data represents the lng - default "lng"
            lngField: 'longitude',
            // which field name in your data represents the data value - default "value"
            valueField: 'count'
          }
        );

The in-line comments should help explain what each field is used for. Typically the default options should be good enough for first-time use. Finally we want to prep the testData variable which will contain the data array that we prepped with the PHP/MySQL query :

        var testData = {
          max: 8,
          data : 
        };

You can see that I am simply echoing the $data_json variable via php. Now the last thing we need to do is trigger the heatmap :

heatmap.setData(testData);

If everything goes well, you’ll have a working heatmap!

At Shift8, we cater to all sorts of businesses in and around Toronto from small, medium, large and enterprise projects. We are comfortable adapting to your existing processes and try our best to compliment communication and collaboration to the point where every step of the way is as efficient as possible.

Our projects are typically broken into 5 or 6 key “milestones” which focus heavily on the design collaboration in the early stages. We mock-up any interactive or unique page within your new website so that you get a clear picture of exactly how your design vision will be translated into a functional website.

Using tools like Basecamp and Redpen, we try to make the process simple yet fun and effective. We will revise your vision as many times as necessary until you are 100% happy, before moving to the functional, content integration and development phases of the project.

For the projects that are more development heavy, we make sure a considerable amount of effort is spent in the preliminary stages of project planning. We strongly believe that full transparency with a project development plan ensures that expectations are met on both sides between us and the client. We want to ensure that the project is broken into intelligent phases with accurate budgetary and timeline breakdowns.

Approved design mock-ups get translated into a browse-ready project site where we revise again and again until you are satisfied. Client satisfaction is our lifeblood and main motivation. We aren’t happy until you are.

Need Web Design?

Fill out the form to get a free consultation.

shift8 web toronto – 416-479-0685
203A-116 geary ave. toronto, on M6H 4H1, Canada
© 2023. All Rights Reserved by Star Dot Hosting Inc.

contact us
phone: 416-479-0685
toll free: 1-866-932-9083 (press 1)
email: sales@shift8web.com

Shift8 Logo