The error message "Google Heatmap API - visualization_impl.js:2 Uncaught (in promise) TypeError: Cannot read property 'NaN' of undefined" was encountered while using the

I'm currently working on a project that involves utilizing a JSON data structure like the one shown below:

 [
    {               
        "lat": 53.1522756706757,
        "lon": -0.487157731632087,
        "size": 63,
        "field": "TestField",
        "variety": "TestVariety",
        "count": 1
    }
]

This JSON will contain additional entries with different locations and count values. However, I am encountering an error titled above when implementing the following code.

    let map;
let testField = new google.maps.LatLng(53.150, -0.488);

let options = {
    zoom: 6,
    center: testField,
    mapTypeId: 'satellite',
};
function createMap(data) {
    let mapElement = document.getElementById('map');
    let geometry, weighted, count, heatData;
    let heatmap, points;
    map = new google.maps.Map(mapElement, options);

    heatData = [];
    for (var i = 0; i < data.length; i++) {
        geometry = data[i];
        weighted = {};
        count = data[i].count;
        weighted.location = new google.maps.LatLng(
              data.lat,
              data.lon);
        weighted.weight = count
        heatData.push(weighted);
    }

    points = new google.maps.MVCArray(heatData);
    console.log(data);   

    heatmap = new google.maps.visualization.HeatmapLayer({
        data: points,
        opacity: 0.9,
        radius: 20
    });

    heatmap.setMap(map);
}

    $(function () {
      $.ajax({
          type: "GET",
          url: "field_example.json",
          dataType: "json",
          success: createMap
      });
    });

It seems like there is a concept that eludes me in this process, and any assistance would be greatly appreciated.

Answer №1

If you encounter the error message:

TypeError: Cannot read property 'NaN' of undefined
, it is likely due to the fact that both data.lat & data.lon are undefined. One way to resolve this issue is by substituting data.lat with geometry.lat and data.lon with `geometry.lon` (or utilizing data[i] instead of data).

for (var i = 0; i < data.length; i++) {
   var weighted = {};
   count = data[i].count;
   weighted.location = new google.maps.LatLng(
     data[i].lat,
     data[i].lon);
   weighted.weight = count
   heatData.push(weighted);
}
heatmap = new google.maps.visualization.HeatmapLayer({
   data: heatData
});

Check out a proof of concept fiddle here

Code Snippet:

// This example requires the Visualization library. Include the libraries=visualization
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=visualization">

var map, heatmap;

function initMap() {
  let map;
  let testField = new google.maps.LatLng(53.150, -0.488);

  let options = {
    zoom: 6,
    center: testField,
    mapTypeId: 'satellite',
  };
  var data = [{
    "lat": 53.1522756706757,
    "lon": -0.487157731632087,
    "size": 63,
    "field": "TestField",
    "variety": "TestVariety",
    "count": 1
  }]

  function createMap(data) {
    let mapElement = document.getElementById('map');
    let count, heatData;
    let heatmap, points;
    map = new google.maps.Map(mapElement, options);

    heatData = [];
    console.log(data.length);
    for (var i = 0; i < data.length; i++) {
      var weighted = {};
      count = data[i].count;
      weighted.location = new google.maps.LatLng(
        data[i].lat,
        data[i].lon);
      weighted.weight = count
      heatData.push(weighted);
    }

    points = heatData;
    console.log(points);

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

    heatmap.setMap(map);
  }
  createMap(data);
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?v=3.41&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=visualization&callback=initMap">
</script>

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

Implementing a click event on a button within an infowindow on Google Maps in Angular

I've successfully set up the infowindow on my Google Maps and I'm looking to include a button inside it. Here's the code I used: InitializeMap() { this.map = new google.maps.Map(document.getElementById('map'), { zoom: 10, cen ...

"Can you tell me the method for obtaining an array within an Angular

Within the realm of PHP, there exist certain elements within an array: $this->data['messages']['ms'][] = 'Line1'; $this->data['messages']['ms'][] = 'Line2'; along with a method that return ...

Tips for dynamically changing the body class based on the page in a remix

I am trying to set parameters for the body class in root.jsx, which will change based on the page being viewed. I want to assign different values to the class in each route - for example, in _index it should be "company homepage", and in the restaurants ro ...

What caused the sudden malfunction in the extended Express Request?

Currently, I am utilizing Node v12 along with Express v4.16.4 and Typescript version 3.8.3 within VSCode. This particular snippet of code has remained unchanged for almost 8 months and is utilized in all our routers. export interface ICustomRequest exten ...

Converting the length attribute of a table to a string does not yield any

After grappling with this bug for some time now, I've come up empty-handed in my search for a solution online. Expected Outcome: Upon pressing the create row button, I anticipate a new row being added at the bottom of the table. This row should cons ...

Dynamic Rendering of Object Arrays in Table Columns using JavaScript

In the process of developing an appointment slot selection grid, I have successfully grouped all appointments by dates. However, I am facing challenges in displaying this array of Objects as a clickable grid with columns. The current output can be viewed h ...

Using React to create an onScroll event listener within a mapped array

I am currently working on a setup where scrolling over an image mapped from an array updates the state with that image's coordinates, which in turn updates a Google Map. <CloudinaryContext cloudName="hcjmhcjf" fetchFormat="auto"> <div clas ...

Launching the Skeleton feature in NextJS with React integration

I have been working on fetching a set of video links from an Amazon S3 bucket and displaying them in a video player component called HoverVideoPlayer. However, during the loading process, multiple images/videos scale up inside a Tailwind grid component, ca ...

Create a query string using JavaScript and combine multiple parameters into a single param

I am facing a challenge where I need to construct a query string in JavaScript and nest various parameters within one of the parameters. In PHP, I can achieve this using the http_build_query function. However, when attempting to do the same in JavaScript, ...

Having trouble navigating through multiple layers of nested array data in react js

I need help understanding how to efficiently map multiple nested arrays of data in a React component and then display them in a table. The table should present the following details from each collection: title, location, description, and keywords. Below ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

Vue JS: Easily Calculate the Total Sum of All Columns

An example of a query in the backend controller public function show($id) { $structural = DB::table('attendance')->where('payroll_daily_id',$id) ->where('assignment','STRUCTURAL') -&g ...

Run a script on a specific div element exclusively

Up until this point, we have been using Iframe to load HTML and script in order to display the form to the user. Now, we are looking to transition from Iframe to DIV, but we are encountering an issue with the script. With Iframe, the loaded script is onl ...

Using JavaScript to set attribute values in Python Selenium, these values are cleared after each update

Assuming : for i in list('{}'.format(value)): self.browser.execute_script( "arguments[0].setAttribute('value', '{}');".format(i.replace('&b ...

Extracting the chosen content from a textarea using AngularJS

Greetings! I am currently experimenting with an example that involves displaying values in a text area. You can find the code on Plunker by following this link: Plunker Link <!DOCTYPE html> <html> <head> <script src="https://aj ...

How can I implement jQuery Ajax to handle multiple elements on a single webpage?

I recently created a page where users can add items to their "favorites" list using the following JavaScript code: $(function(){ $('.doit-01234').click(function (e) { e.preventDefault(); $.ajax({ url: "https://www.domain. ...

Access in-depth data by clicking on a map to get detailed information

Recently, I took on the challenge of managing a golf club website after the original creator had to step away. One urgent issue I need to address is fixing a malfunctioning flash animation that provides information about each hole on the course. My plan is ...

What is the method for creating a function using the const keyword in JavaScript?

I trust you are doing well. Recently, I have embarked on a coding journey and encountered an interesting challenge. The task requires me to create a function that outputs specific weather conditions for different countries to the console: The weather in ...

The JSON was found to be invalid but was later verified as valid using an online tool

Unfortunately, the invalid json response body error is caused by an unexpected issue in another section of my code. Apologies for any inconvenience. I have encountered an issue with receiving an invalid json response body error on my client while using fe ...

Enhanced coding experience with JavaScript completion and ArangoDB module management

Exploring New Horizons After more than a decade of using Eclipse for Java development, I have decided to delve into the realms of javascript and arangodb due to high demand. My current task involves developing multiple microservices to run within arangodb ...