The data points on the Google Maps heatmap are not visible

We are working on developing a server side application that will utilize the Google Maps API to create weighted heat maps for visualizing data.

Check out the Google Maps API documentation for Heat Maps here

Despite successfully displaying the map, my JavaScript code seems to be having trouble showing the data points. Any suggestions on how to fix this issue?

  function initialize() {

    var mapOptions = {
      zoom: 12,
      center: new google.maps.LatLng(37.774546, -122.433523),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var heatmapData = [
      {location: new google.maps.LatLng(37.782, -122.447), weight: 0.5},
      new google.maps.LatLng(37.782, -122.445),
      {location: new google.maps.LatLng(37.782, -122.443), weight: 2},
      {location: new google.maps.LatLng(37.782, -122.441), weight: 3},
      {location: new google.maps.LatLng(37.782, -122.439), weight: 2},
      new google.maps.LatLng(37.782, -122.437),
      {location: new google.maps.LatLng(37.782, -122.435), weight: 0.5},

      {location: new google.maps.LatLng(37.785, -122.447), weight: 3},
      {location: new google.maps.LatLng(37.785, -122.445), weight: 2},
      new google.maps.LatLng(37.785, -122.443),
      {location: new google.maps.LatLng(37.785, -122.441), weight: 0.5},
      new google.maps.LatLng(37.785, -122.439),
      {location: new google.maps.LatLng(37.785, -122.437), weight: 2},
      {location: new google.maps.LatLng(37.785, -122.435), weight: 3}
    ];

    var heatmap = new google.maps.visualization.HeatmapLayer({
      data: heatMapData
    });

    heatmap.setMap(map);

  }

  function loadScript() {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=visualization&callback=initialize';
    document.body.appendChild(script);
  }

  function toggleHeatmap() {
    heatmap.setMap(heatmap.getMap() ? null : map);
  }

  function changeOpacity() {
    heatmap.set('opacity', heatmap.get('opacity') ? null : 0.2);
  }

  window.onload = loadScript;
  google.maps.event.addDomListener(window, 'load', initialize);

  initialize();

Update 1 - The error in Chrome console states:

Uncaught ReferenceError: google is not defined heatmap:68
Uncaught ReferenceError: heatMapData is not defined heatmap:45
event.returnValue is deprecated. Please use the standard event.preventDefault() instead. VM1930:45
GET https://maps.googleapis.com/maps/gen_204?ev=api_viewport&cad=host:localhost…98x0.65918,size:1920x689,relsize:1.00,token:4b2u2h59g8,src:apiv3,ts:viv6jz net::ERR_BLOCKED_BY_CLIENT VM1937:1
GET https://maps.googleapis.com/maps/gen_204?imp=smimps%3DDCyUJvj7n5l,ZvwOO2ZR5…_mlil,HRlFM3ZVJGn,Jx3V5n-JzIn,F-E4oUlMhVs%26z%3D12&cad=src:apiv3,ts:viv6n3 net::ERR_BLOCKED_BY_CLIENT VM1937:1
GET https://maps.googleapis.com/maps/gen_204?imp=smimps%3DMQc6u1JFizM,0Dl57QyKHf%26z%3D12&cad=src:apiv3,ts:viv6rc net::ERR_BLOCKED_BY_CLIENT VM1937:1
GET https://maps.googleapis.com/maps/gen_204?imp=smimps%3DOk5Wmy33jdt,Dw5TFMIYSGt%26z%3D12&cad=src:apiv3,ts:viv6tf net::ERR_BLOCKED_BY_CLIENT VM1937:1

Update 2 - The JavaScript code is encapsulated within a Jade structure:

doctype 5
html
  head
    title #{title} - picycle
    style
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
      #panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -180px;
        z-index: 5;
        background-color: #fff;

        border: 0.2px solid #999;
      }

    script(type='text/javascript')

<JS CODE FROM ABOVE>

  body

    #panel
      button(onclick='toggleHeatmap()') Toggle Heatmap
      button(onclick='changeOpacity()') Change opacity

    #map-canvas

Answer №1

Remember, Javascript is case sensitive: heatmapData is different from heatMapData

Here's how you should define it:

 var heatmapData = [

But make sure to use it correctly:

var heatmap = new google.maps.visualization.HeatmapLayer({
  data: heatMapData
});

If you see

Uncaught ReferenceError: google is not defined heatmap:68
, it means you're initializing before the API is loaded (remember, you only need to call it once in the callback)

You can remove these unnecessary lines:

  google.maps.event.addDomListener(window, 'load', initialize);

  initialize();

Answer №2

The issue arises from calling initialize towards the end of your code when google.maps has not been fully loaded yet.

Once google maps finishes loading, it also triggers another call to initialize.

Additionally, there is an unnecessary line

google.maps.event.addDomListener(window, 'load', initialize);
since a callback to initialize was already added in the loadScript method here:
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=visualization&
callback=initialize';

Therefore, it is recommended to delete these lines:

google.maps.event.addDomListener(window, 'load', initialize);

initialize();

Furthermore, remember to maintain consistency in variable names in JavaScript: heatMapData should not be confused with heatmapData

By addressing these points, the errors should be resolved. Feel free to test it out and return if the issue persists.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to retrieve values from a .json file in real-time and then perform comparisons with user input using Python

I have a JSON file structured like this: [ { "name": { "common": "Aruba", "official": "Aruba", "native": { "nld": { "official ...

An issue has arisen with AngularJS and Twitter Bootstrap, displaying an error message stating that the function element.focus

I recently implemented the angularjs twitter bootstrap datepicker and everything seemed to be working smoothly. However, I encountered an error when trying to click on the text box for the popup datepicker. This issue has left me puzzled as I am still new ...

Create an array of objects in JavaScript using JSON data

I have fetched a collection of dictionaries from my API: The data can be retrieved in JSON format like this: [{"2020-03-11 14:00:00":10.765736766809729} ,{"2020-03-11 15:00:00":10.788090128755387}, {"2020-03-11 16:00:00":10.70594897472582}, {"2020-03-11 1 ...

Height of the Accordion List

I have a code snippet below for an accordion list that I put together. I initially set the height for all the heading boxes to be uniform, but it seems like box A is displaying larger than the others. Can you help me figure out what went wrong? Any suggest ...

Incorporating middleware to handle 404 errors in Express

scenario app.use("/api/tobaccos", tobaccos); app.use(function(err, req, res, next) { console.error(err.message); }); API details: router.get("/:id", async (req, res) => { console.log("GET TOBACCO:" + req.params.id); ...

Identifying Flash content in a unique way

In my dynamic page (let's call it myFlashContainer.jsp), the Flash content changes based on the link that is clicked. The code responsible for rendering the Flash looks like this: <object height="100%" align="l" width="100%" id="player" codebase= ...

Utilize identical selectbox across various tabs

Using jQuery, I have implemented multiple tabs with different appearances. The challenge I am facing is related to a selectbox that is shared across all tabs. My goal is to synchronize the values and selected option of this selectbox among all tabs. In oth ...

Unable to retrieve data from a nested object within a JSON structure

In my React project, I have created a function component like the one below: function FetchData() { const [randomUserData, setRandomUserData] = useState(''); const url = 'https://randomuser.me/api/'; const fetchData = () => { ...

Is it causing issues having the same version of jQuery included multiple times?

Within my HTML file, referred to as x.html, I've included other HTML files as well. In x.html, I have integrated the jquery library version 1.4.1. It seems that this same version of jquery is also being included from the other HTML files. Even though ...

Contrast between pm.response.json() and parsing the responseBody using JSON.parse()

Can you explain the key distinction between const json_response = pm.response.json() and json_response = JSON.parse(responseBody) ...

Tips for refreshing jQuery to ensure it functions smoothly for subsequent tasks

I am facing an issue with running a second process under JQuery, as shown in the code snippet below: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <script type=" ...

Display outcomes for chosen checkboxes

When I call the API: $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123';, I retrieve the status results of all Order IDs and d ...

How to handle a Vue element click event through programming

In my Vue instance, I am looking to have a response triggered by a click on an uploaded thumbnail. Utilizing the Vue package called FineUploader Vue with the template layout as outlined in the documentation (refer to end of question). After uploading an i ...

Creating dynamic web content using PHP and JavaScript

I stumbled upon a tutorial on the PHP.net website within the "PHP and HTML" manual which includes an example titled Generating JavaScript with PHP. Currently, I am experimenting with a basic demo of this concept on my own to grasp the process before attem ...

Sending a Thunk to the store using Typescript

Within my primary store.ts file, the following code is present: const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); Upon initial rendering, an action is dispatched to fetchUser in ord ...

Tips for handling Promise.all and waiting for all promises to resolve in an async function in Express JS

I'm relatively new to JavaScript and especially asynchronous programming. My current project involves creating an Express+React application that shows a GitHub user's information, including a few repositories with the latest 5 commits for each. ...

InvalidType Error: The roles provided are not in the correct format, it should be a Role, Snowflake, or an Array/Collection of Roles or Snowfl

Having trouble setting up multiple select menu options on Discord.js v14. I'd like to assign more than one role to a member when multiple options are chosen in the dropdown menu. However, I'm encountering this error message: TypeError [Invalid ...

Transmitting a JavaScript file via a Node.js server

I have a NodeJS server that sends a JavaScript file to the client. However, the JavaScript file does not import the libraries it needs on the client side. I load these libraries on the client side before receiving the file. Why is the file unable to find t ...

Using Styled Components to achieve full width for input tag in relation to its parent

I am working with an input field that has a specific width set. My goal is to increase the width of this input field to 100% by selecting it from its parent component. Is there a way to achieve this without passing an explicit width prop in the styled c ...

Animating the mobile menu transition using Bootstrap CSS

Can anyone help me with animating the mobile menu when I click the menu icon? This is what I have for the menu: .overlay-menu { position: fixed; display: none; z-index : 1040; width: 100vw; height: 100vh; background: rgba(0, 0,0, 0 ...