Issue with creating a chart using JSON data in Google Geo Charts

I have integrated a google geo chart into my application. I am following the example provided in this link using database data.

https://developers.google.com/chart/interactive/docs/gallery/geochart?hl=en

The data array looks like this:

var data = google.visualization.arrayToDataTable([
        ['City',   'Population', 'Area'],
        ['Rome',      2761477,    1285.31]])

in that format.

I am structuring my data similarly to the data variable but the chart is not displaying.

var arr=[];

         $.ajax({
            type: 'POST',
            url: "LiveMap",
            dataType: "json",
            success: function (response) {

               for (var i = 0; i < response.length; i++) {
                   var temp=[];
                  var str=response[i].split(':');
                  temp[0]=str[0];
                  temp[1]=parseInt(str[1]);
                  temp[2]=parseInt(str[2]);

                  arr[i]=temp;
               }
            }

         });

     google.load('visualization', '1', {'packages': ['geochart']});
     google.setOnLoadCallback(drawMarkersMap);

      function drawMarkersMap() {
          var data = new google.visualization.DataTable();
    data.addColumn("string","City");
    data.addColumn("number","Population");
    data.addColumn("number","Area");
    data.addRows(arr);
      var options = {
        region: 'IT',
        displayMode: 'markers',
        colorAxis: {colors: ['green', 'blue']}
      };

      var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    };
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 300px; height: 300px;"></div>
  </body>
</html>

The response from the ajax call is as follows:

 result.put("Bhopal:300:200");
      result.put("Hyderabad:300:200");
      result.put("Vizag:300:200");
      result.put("Mysore:300:200");
      result.put("Delhi:300:200")

;

Answer №1

Ensure to place the code below after the for loop:

google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawMarkersMap);

Here is an example:

$.ajax({
            type: 'POST',
            url: "LiveMap",
            dataType: "json",
            success: function (response) {

               for (var i = 0; i < response.length; i++) {
                   var temp=[];
                  var str=response[i].split(':');
                  temp[0]=str[0];
                  temp[1]=parseInt(str[1]);
                  temp[2]=parseInt(str[2]);

                  arr[i]=temp;
               }
               google.load('visualization', '1', {'packages': ['geochart']});
               google.setOnLoadCallback(drawMarkersMap);
            }

         });

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

Upon the creation of a new Post and attempting to make edits, the field is found to be blank

<template> <div class="card m-3"> <div class="card-body"> <Form method="post" @submit="submitData" :validation-schema="schema" ref="myForm" v-slot="{ errors, ...

Error message "Error: listen EADDRINUSE" is reported by node.js when calling child_process.fork

Whenever the 'child_process.fork('./driver')' command is executed, an error occurs: Error: listen EADDRINUSE at exports._errnoException (util.js:746:11) at Agent.Server._listen2 (net.js:1156:14) at listen (net.js:1182:10) ...

Using expressJS and MongoDB to create a secure login and registration system

I am interested in adding a login/register function to my expressJS API. Currently, I am only inserting the password and email into my database. I would like this function to first check if a user with this email is already in the database - if yes, then s ...

Kendo's data-bind onclick feature functions properly on web browsers but fails to work on mobile devices

As a newcomer to Kendo and JavaScript, I may be missing something obvious... In one of my list entries, I have a simple call like this: <li style="margin: 0.5em 0 0.5em 0"> <a href="#transaction-details" data-bind="click: onB ...

Having difficulty with Angular's ng-options feature in a Select element

I'm currently tackling an issue with using ng-options to iterate through an array of objects and display specific properties in a select element. Upon querying the api/admin endpoint, I receive JSON data containing details of all users holding the ad ...

Encountering Laravel Vue.js error regarding converting an array to a string

I previously posted without receiving any helpful replies, so I'm reaching out again. I'm attempting to create a basic table to retrieve data from a mongodb database using a query builder in Laravel and display it with a Vue component. However, w ...

Resolving the issue: "How to fix the error "Credentials are not supported if the CORS header 'Access-Control-Allow-Origin' is '*' in React?"

Recently, I encountered some CORS issues while using a third party API in my front-end application. After reaching out to the API maintainers, they lifted the CORS control by adding a * to Access-Control-Allow-Origin, which seemed like the perfect solution ...

Replicating the existing div content into a textarea

I wanted to create a tool for my workplace as a learning project in html, CSS and JS. It's a timer that tracks how long I spend on tasks. Currently, I have the timer resetting itself but I'm facing an issue where the paused time is not being log ...

Safari failing to load JavaScript on live website

While JavaScript functions correctly both locally and in production on Chrome, I am facing issues when trying to run it on Safari. Despite having JavaScript enabled on Safari and it working fine locally, it fails to work on the production environment. This ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

Efficient Checkbox Implementation in ActiveAdmin for Rails 3.1

This query actually encompasses two related inquiries. Enabling "Select all" functionality - In the realm of formtastic, which is used by Active_admin to render forms, how can I implement a button that selects all checkboxes present on the page? While ...

Navigate divs with varying z-index values

I want to change the z-index of 3 divs by toggling them using jQuery, but I'm not sure how to do it. What I want is to click a button that relates to a specific div and increase the z-index of that div so the content inside it is shown. Currently, all ...

What is the reason for the `Function` type not functioning properly when trying to input a function as a parameter in a higher-order function?

Looking to create a function that requires the following inputs: an array a filter logic function (predicate function) In JavaScript, you can use the following code successfully: const myFilter = (func, arr) => arr.filter(func) const myArr = [1, 2, 3, ...

Does the PHP include function act as an HTTP request?

After coming across an article highlighting the negative impact of using excessive HTTP requests on server speed, I started wondering about the performance implications of PHP includes. Specifically, I'm curious if sending 4 AJAX requests compared to ...

Guide to concealing List elements from the Search Filter when the search input field is emptied

I am facing a challenge with an HTML list of items. Here is the structure: <ul id="fruits"> <li><a href="#">Mango</a></li> <li><a href="#">Apple</a></li> <li><a href="#">Grape</a>& ...

Using JavaScript regular expressions to validate currency without relying on jQuery

Looking for a solution to create a money mask for an input field without using jquery in my application. Is it possible to achieve this using regular expressions with 'on key up' events, for example? Below is the code snippet: <tr> & ...

After a period of activity, requests to Node.js with Express may become unresponsive

My server is running smoothly but after some time, it stops responding to requests. When I try to load the page, it gives me a "couldn't establish connection" error message. Here is my app.js: var express = require('express'); var path = r ...

AJAX: The form submission without refreshing the page only functions for the first attempt

My current issue involves using AJAX to submit a form without refreshing the page. The problem arises when I try to submit the form more than once, as the on('submit') function stops working after the initial submission. This defeats the purpose ...

Encountering a ng-select2 Error with Angular version 4.1.3

I have recently installed the ng-select2 package, but I encountered an error when trying to compile my code using 'ng serve'. Node version: 8.10.0 NPM version: 6.0.0 Another list item Operating System: Windows 7 ERROR in d:/PATH-TO-PROJECT-F ...

Do I need to provide my email and password while using the Firebase signInWithGoogle()?

After attaching the signInWithGoogle() method to a button within the form, instead of opening a popup window as expected, it prompts me to fill in the email and password fields. Below is the configuration file: import firebase from 'firebase/app' ...