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

https://i.sstatic.net/rwJBw.png

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 Facebook Javascript SDK to enable login and trigger re-authentication using React Web and Typescript within a component

As a newcomer to stack overflow, I welcome any suggestions on how I can improve my question. I'm in need of guidance concerning logging a user into facebook and requiring them to authenticate their profile or select another profile manually, rather t ...

Covering a doughnut shape with a twisting spiral

I want to achieve a hula hoop covered in tape effect using three.js. The 3D model should look similar to the image below. https://i.sstatic.net/lj9cR.jpg I have been able to create the hoop in 3D space using TorusGeometry and pan around, but I am strugg ...

A comparison between preg_match and stripos functions in PHP

In order to analyze product descriptions and identify various characteristics/product options, the input data follows this structure: // INPUT DATA TABLE STRUCTURE: PRODUCT_CATEGORY [0], PRODUCT_NUMBER[1], DESCRIPTION OF AN OPTION [2]. THE INPUT DATA TABLE ...

Unable to successfully interact with Paypal button using selenium automation

I'm facing an issue with Selenium where I am unable to click on the PayPal button. Despite trying various methods recommended in the Selenium documentation, the button remains unresponsive. I even attempted using the standard findElement method, but ...

In search of a solution to effectively narrow down data within an Azure API request

I'm currently facing an issue with extracting data from an azure environment. When I make an API call, I receive a JSON response containing around 60 lines of data, but I only require 4 specific lines. To optimize performance, reduce unnecessary load, ...

Serialization and deserialization of empty arrays into dictionaries/objects

Currently, I am developing a Silverlight 3 application that needs to connect with a PHP 5.2.13 server application. For this task, we are utilizing JSON.NET, but I have encountered some challenges with Dictionaries. As part of my experiments, I am attempti ...

iPad is playing the incorrect file when using .play(). Any ideas on how to fix this issue?

Currently, I am developing a web application that involves a div element with dynamic text content that changes based on user interactions. To enhance the user experience, I decided to incorporate audio elements by creating an array containing correspondin ...

How to incorporate text into the white circle object using three.js

View the current state of my project on this JS Fiddle. I am looking to incorporate rotating text, whether in 3D or 2D. The text should rotate in sync with the white circle. I am open to any method that achieves the desired outcome. Below is the provided c ...

What impact does setting a variable equal to itself within a Dom Object have?

Within my code example, I encountered an issue with image sources and hrefs in a HTML String named tinymceToHTML. When downloading this html String, the paths were set incorrectly. The original image sources appeared as "/file/:id" in the String. However, ...

Leveraging JavaScript to identify web browsers

I am looking to implement a feature on my website where if the visitor is using Internet Explorer 8.0 or an earlier version, they will receive an alert prompting them to upgrade their browser before proceeding. For users with other browsers, the page will ...

Introduce regex in the middle

If I have a string in JavaScript like so: "test test hello test test" I understand how to replace 'hello' with 'byebye': replace("hello","byebye"); However, what is the most efficient method to add 'byebye' immediately afte ...

Converting personal injury claims into configuration maps with the help of jq

Here is my input: { "apiVersion": "apps/v1", "kind": "Deployment", "spec": { "template": { "spec": { "containers": [ { "volum ...

Guidelines for showcasing validation summary on an ASP.NET webpage with the help of Javascript

My asp.net form contains multiple required fields that need validation. I am looking to display a summary of all validations at the end of the form. Valid input controls have already been checked, now I just need the summary. Here is an example code s ...

Issue with React Hot Toast not displaying properly due to being positioned behind the <dialog>

The Challenge of Toast Notifications Visibility with <dialog> Element tl;dr When utilizing the native dialog.showModal() function, the <dialog> element appears to consistently remain on top, which causes toast notifications to be obscured by ...

"Creating a duplicate of an element by utilizing the `next`

I have a dilemma involving two divs within a section of my project - one div is dynamically created while the other exists statically. My goal is to transfer the non-dynamically created div into the one that is generated dynamically. let adContainer = $ ...

Troubleshooting Vue 3: Dealing with Synchronization Issues Between Keyboard Input and

I am currently working on a Vue 3 autocomplete component and I've come across a strange issue that I can't quite figure out. The component emits two events: "update:search" to update the search variable in the parent component, and "change" whic ...

Obtain an individual item from the reducer array

I am working on a company reducer that will store an array of companies. To optimize performance, I aim to fetch only the necessary company object from my API when a user navigates to /company/name. This way, if a user visits the same company page multiple ...

Python is not triggering the custom object_hook function in JSON parsing

I have created a custom hook in Python that successfully works when the input string is a valid dictionary, but it fails to work with a valid list. For example, [1,2] is a valid JSON format. However, when I pass this to json.loads along with my custom hoo ...

Tracking the progress bar as files are being uploaded via AJAX using HTML5

Currently, I have a progress bar that increments based on the number of files and their sizes. I am looking to implement an overall progress bar to display while uploading files to the server using AJAX and HTML5. Each file is uploaded individually to th ...

Enhance the efficiency of parsing JSON data

I am looking to extract and analyze the JSON data provided by this API (taken from their sample page): I have created a parsing method that takes quite some time (several seconds on my Galaxy A5) to process the extensive data: This is the approach I have ...