Utilizing Google Geochart for displaying multiple data values within the same country from JSON dataset

I am facing an issue where only the last row is being displayed in a Google Geochart for each country, despite trying to fetch data from my database via JSON. The problem is that only 'Supplier 2' is showing up, as highlighted below. I have gone through this answer and tried implementing the suggested group() method, but it gives me a console error that I cannot debug successfully: 'unexpected token }', pointing to the closing curly bracket in the declaration of var groupData.

Currently, without using the group() method, this is what shows up. I also need to display 'Supplier 1'.

https://i.sstatic.net/7BfB3.png

This is the code snippet:

function incAvailableCountry() {
$.ajax({
    url: "inc-analysis/country-available.php,
    dataType: "json"
}).done(function(jsonData){
    var data = new google.visualization.DataTable(jsonData);
    var groupData = google.visualization.data.group(
        data,
        [0, 1],
        [{
            aggregation: google.visualization.data.count,
            column, 0
        }]);
    var options = {
        width: 'auto',
        keepAspectRatio: true,
        legend: 'none'
    };

    for (var i = 0; i < data.getNumberOfRows(); i++) {
        var locationRows = groupData.getFilteredRows([{
            column: 0,
            value: data.getValue(i, 0)
        }]);
        var nameTooltip = '';
        locationRows.forEach(function(index){
            if (nameTooltip !== '') {
                nameTooltip += ', ';
            }
            nameTooltip += groupData.getValue(index, 1);
        });
        data.setValue(i, 1, nameTooltip);
    }

    var chart = new google.visualization.GeoChart(document.getElementById('incAvailableCountry'));
    chart.draw(data, options);
});}

PHP Code:

<?php include '../core/init.php';

$query = mysqli_query($conn, "(SELECT Country, Supplier
    FROM table 
    GROUP BY Supplier)
    ORDER BY Country");

$table = array();
$table['cols'] = array(
    array('label' => 'Country', 'type' => 'string'),
    array('label' => 'Supplier', 'type' => 'string')
);

$rows = array();
while ($r1 = mysqli_fetch_assoc($query)) {
    $temp = array();
    $temp[] = array('v' => (string)$r1['Country']);
    $temp[] = array('v' => (string)$r1['Supplier']);
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;

JSON Result:

{"cols":[
{"label":"Country","type":"string"},
{"label":"Supplier","type":"string"}],"rows":[
{"c":[{"v":"Spain"},
{"v":"Supplier 1"}]},
{"c":[{"v":"Spain"},
{"v":"Supplier 2"}]}]}

HTML Code:

<script src="https://www.google.com/jsapi"></script>
<script>google.charts.load('current', {'packages': ['geochart'], 'mapsApiKey': 'key...'});</script>
<div id="incAvailableCountry"></div>

Answer №1

When using the group method, ensure that column is followed by a colon : instead of a comma ,.

var groupData = google.visualization.data.group(
    data,
    [0, 1],
    [{
        aggregation: google.visualization.data.count,
        column: 0
    }]);

Updated code:

var groupData = google.visualization.data.group(
  data,
  [0, 1],
  [{
    aggregation: google.visualization.data.count,
    column: 0,
    type: 'number'
  }]
);

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

Incomplete data retrieval issue encountered during .ajax call

I am having trouble retrieving all 4 key|value pairs from a page that displays an object as text in the body and pre tag. It seems to be missing one pair - any ideas why? Just a heads up, I've tweaked some of the URLs and data in the JSON output for ...

Triple the Charts: Highcharts Vue Component combines three dynamic charts into one powerful visual tool

looking for help with creating a complex chart Hello, I have a task of creating what seems to be 3 charts in one design. I am able to create the two scattered charts, but the column charts are proving to be challenging. Thanks to Wojciech Chmiel, I manage ...

Vue text failed to display the variable. Any ideas on why?

While working with a library, I encountered the issue of having "Close {{myVar}}" displayed on the screen. Can anyone guide me on how to use template literals in Vue? I have experience with React JSX. <template> <a-alert message="Info Tex ...

Executing npm / http-server script

I'm currently working on a shell script that will compile an Angular app using the "ng build" command and then launch a web server to host the app from the dist folder. The web server will be started with the "http-server" command, which needs to be i ...

Converting a JavaScript string containing an `import` statement into a browser-compatible function

Can my vue application transform the given string into a callable function? const test = 'import { pi } from "MathPie"; function test() { console.log(pi); } export default test;' The desired output format is: import { pi } from "M ...

Redirecting in Next.js without the use of a React component on the page

I need to redirect a page using HTTP programmatically only. The following code achieves this: export const getServerSideProps: GetServerSideProps = async (context) => { return { redirect: { destination: '/', permanent: false, ...

Using an array to dynamically input latitude and longitude into a weather API call in PHP

I am currently working on a leaflet map project that showcases the top 10 cities in a selected country. The markers are added dynamically based on the coordinates provided in the $latLng array. For example, when Australia is chosen from the select field, t ...

What are the fundamental steps for setting up AJAX with a mongoDB server?

I need help with making an AJAX request to pull data from my database. I am looking for a simple example to check if a user exists before creating a new one. Currently, I am using mlabs and trying to understand how to access it through JavaScript. This p ...

The AngularJS array data is not displaying correctly

I am having trouble displaying comments array data in HTML properly. The data appears the same as it is in the comments array. What could be causing this issue? How should I proceed? <ul class="media-list" ng-controller="dishDetailController as menuCt ...

Encountering a no-loops/no-loops eslint error in node.js code while attempting to utilize the for and for-of loops

While working on my nodejs application, I have encountered an issue with es-lint giving linting errors for using 'for' and 'for-of' loops. The error message states error loops are not allowed no-loops/no-loops. Below is the snippet of c ...

Can you explain the concept of F-Bounded Polymorphism in TypeScript?

Version 1.8 of TypeScript caught my attention because it now supports F-Bounded Polymorphism. Can you help me understand what this feature is in simple terms and how it can be beneficial? I assume that its early inclusion signifies its significance. ...

Why does the getComputedStyle function return null for IE11 and Edge when using Kendo React Grid within a Popout window, while it works fine in Chrome, Opera, and Firefox?

Check out my stackblitz demo where I am experimenting with rendering a Kendo React Grid inside a popout window using the react-popout-component. The demo runs smoothly in Chrome, Opera, and Firefox, but encounters issues in Edge and IE11 due to a null valu ...

Tips on extracting code differences from code inspector

Utilizing the Chrome code inspector is extremely valuable, but I often find it challenging to track the modifications made to CSS and HTML live. This becomes particularly cumbersome when there are multiple tags being modified. Are there any Chromium exten ...

The tally of seconds within a year has been altered

I have developed a function that converts inputted seconds into an output format of Years, Days, Hours, Minutes, and Seconds for the user. While I am still refining the various outputs and improving the syntax, I am currently focused on identifying a calcu ...

Transfer information from the ajax success event to an external else/if statement

I am encountering an issue when trying to transfer the appropriate result from my ajax success function to an external function for further use. Currently, I am using user input to query a data source via ajax and receiving the object successfully. The re ...

How to adjust transparency in Three.js objects

Currently, I am developing a scene where certain elements are loaded from a JSON file. While I am able to toggle the visibility of each individual object, I now find myself wanting to adjust the opacity/transparency of an individual object. The objects in ...

Why won't my AngularJS checkbox stay checked?

In my application, I have the following code: <input type="checkbox" ng-checked="vm.eduToEdit.test" /> {{vm.eduToEdit.test}} <input type="checkbox" ng-model="vm.eduToEdit.test"> The value of vm.eduToEdit.test is displaying t ...

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

Guide on waiting for AWS assumeRole before proceeding with defining the module

I'm currently working on a module that needs to export functions and variables, but before it can do that, it must switch user roles. Here is the code snippet I've come up with. What I need is for the anonymous async function to execute first, an ...

What is the process for determining the default character length in a <p> tag based on its height and width?

I'm trying to determine the default length for the <p> tag in HTML. It should be displayed based on the height and width of the <p> tag. For example: Consider the following code snippet, <p style="height:300px;width:200px;"> </ ...