Displaying Highcharts inside an infowindow by sending an AJAX request through Google Maps

After exploring the demo available here, I successfully created a map using data from my MySQL table.

Now, my goal is to include a HighChart in the infowindow. However, despite several attempts, I am unable to make it appear. Ultimately, I aim to retrieve chart data from the same table that contains the marker information.

If you have any suggestions or tips on how to achieve this, please feel free to share them.

You can view the page here. The objective is to display unemployment rates in different cities compared to the national average.

<!DOCTYPE html>
 <html>
<head>
<title>Employment</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Styles -->
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="http://map.itp.ca/css/style.css" rel="stylesheet">

<script type="text/javascript">
 $(function () {
    $('#chart_joblessness').highcharts({
        chart: {
            type: 'bar',
            backgroundColor:'rgba(255, 255, 255, 0.1)'
        },
        title: {
            text: ''
        },
        xAxis: {
            categories: ['Total Workforce', 'Youth', 'Women', 'Imigrants']
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Percentage'
            }
        },
        legend: {
            reversed: true
        },
       plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true
                }
            }
        },
            series: [{
            name: 'ICT Jobs',
            data: [2.7, 4.4, 3.1, 2.8]
        }, {
            name: 'Canada',
            data: [7, 13, 6, 7.9]
         }]
    });
});
 </script>  

<script src="http://map.itp.ca/charts/js/highcharts.js"></script>
<script src="http://map.itp.ca/charts/js/modules/exporting.js"></script>    

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?   sensor=true"></script>
<script type="text/javascript">
//<![CDATA[

var customIcons = {
  LargeUrban: {
    icon: 'img/chart-pin.png'
  },
  Medium: {
    icon: 'img/chart-pin.png'
  },
  Small: {
    icon: 'img/chart-pin.png'
  }
};


function load() {
  var map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(47.899754, -90.137494),
    zoom: 5,
    mapTypeId: 'roadmap'
 });




  var infoWindow = new google.maps.InfoWindow;

  // Change this depending on the name of your PHP file
  downloadUrl("phpsqlajax_genxml2.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("city");
      var type = markers[i].getAttribute("type");
      var population = markers[i].getAttribute("population");
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      var html = '<div id="content">'+
        '<h2 id="firstHeading" class="firstHeading">' + name + '</h2>'+
        '<div id="bodyContent">'+
        '<p><b>ICT Employment</b>, ' + population + ' </p>' +
        '<div id="chart_joblessness" style="z-index:9999; min-width: 500px; max-width: 600px; height: 230px;"></div>'+
        '<p><a href="#" class="btn btn-primary" role="button">Additional City Data</a>  '+
                    '<a href="#" class="btn btn-primary" role="button">Another Button</a></p>'+
                    '</div>';

      var icon = customIcons[type] || {};
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        icon: icon.icon
      });
      bindInfoWindow(marker, map, infoWindow, html);
    }
  });
}

function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
    map.setCenter(marker.getPosition());
  });
}

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);when making an AJAX request
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function doNothing() {}

//]]>

<body  onload="load()">

    <div class="contact">
    <div class="map" id="map"></div>
    </div>

</body> 

Answer №1

My experience with Google Charts has been great: https://developers.google.com/chart/?hl=es.

I noticed that you are working with JSON in your code, so if you're using PHP, you can easily utilize the json_encode and json_decode functions to handle the JSON data. Simply query the database for the information you need, then structure it into a JSON format.

Here is some documentation on the JSON PHP functions: http://www.php.net/manual/en/book.json.php

I hope this advice proves useful to you.

Best of luck with your project.

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

Node.js can be used to easily set the values of HTML elements

After successfully setting up a node.js connection to my mysql database and being able to retrieve and input data using connection.query(), I now want to display the database information on my HTML elements. Is there an equivalent of getElementById for t ...

Converting php array submitted from a form using ajax

I have a form on my website that collects user input and sends it to an email address using php. The form includes a checkbox input where users can select multiple options, which are then stored in an array. However, when the form is submitted, the email r ...

Creating a string of DIV elements with PHP and mySQL - is it possible?

I am in the process of creating a well-formatted product list using data from an SQL database. The goal is to have my website display a store layout with small boxes containing brief information about each product that, when clicked, will open up detailed ...

How can we retrieve a jQuery selector from a $.get() function

When utilizing $.get() to fetch data, it successfully retrieves the entire HTML page. I am looking for a way to use selectors on the fetched data in order to extract specific information from elements, similar to how I would use $('.someclass') ...

Leveraging a combination of AngularJS directives within a single div element

Why can't I use multiple directives in the same div tag in AngularJS? The product names from the module are not displayed with the following HTML code: <!DOCTYPE html> <html ng-app="gemStore"> <head> <title></ti ...

Using jQuery, target the specific elements that have certain data attributes assigned to them

Is there a way to target elements with a specific data attribute and a unique class using jQuery? For instance, I want to select these elements: <div data-roomid="55" data-status="NoData"></div> <div data-roomid="55" data-status="Open"> ...

Can the $_SESSION[balance] be updated automatically?

On each login, I retrieve the value of $_SESSION[balance] from a MySQL database. Is there a way to update this value in the client's browser every 5 minutes without refreshing the page? Could AJAX be used for this purpose? I apologize if my question ...

Is it possible to access the chrome://webrtc-internals/ variables through an API in JavaScript?

I couldn't find any information about how to access the logged variables in chrome://webrtc-internals/ on google. There is not even a description of the graphs available there. I am specifically interested in packetsLost, googCurrentDelayMs, and goo ...

Transfer specific columns from a MongoDB table to MySQL using AWS DMS

In my mongodb database, I have a schema called reports and a collection called totals. The keys in this collection are structured as follows: { "_id" : { "dt" : "2018-12-02", "dt2" : "2018-04-08", "nu ...

Uh-oh, the Next.js fetch didn't go as planned. The error message

Currently, I am using Next.js 14 for my project. Suddenly, there has been an issue where some images are not loading on my local setup. However, the images load fine on the preview and production branches on Vercel. Upon checking my console, I noticed th ...

Encountering issues while attempting to transmit several files to backend in React/NestJS resulting in a BAD REQUEST error

My goal is to allow users to upload both their CV and image at the same time as a feature. However, every time I attempt to send both files simultaneously to the backend, I encounter a Bad Request error 400. I have made various attempts to troubleshoot th ...

The JavaScript form submission is not sending any data via POST request

Here is the form I am utilizing to send data to gamelobby.php <form id="game_form" method="POST" action="/gamelobby.php"> <input type="text" id="plr_name"></input> <input type="hidden" value="" id="table_name"></input> ...

Searching through text in Node JS using Mongoose for Full-Text queries

I am facing an issue while attempting to perform a full-text search on an array of strings using Mongoose. The error message I receive is as follows: { [MongoError: text index required for $text query] name: 'MongoError', message: 'text ...

What can be done to stop the event handler from executing?

My goal is to verify a user's authentication every time they click on a button. If the user happens to be logged out and tries to click on a button, they should be redirected back to the home page. The issue I'm facing is that the code after the ...

Problem with the WP Rocket helper plugin that excludes JS scripts from Delay JS only at specific URLs

Looking for assistance with a helper plugin that excludes scripts from "Delay Javascript Execution"? You can find more information about this plugin here. The specific pages where I want to exclude slick.min.js and jquery.min.js are the home page and tabl ...

The element fails to receive the class when it is being clicked

Currently, I am in the process of developing a Joomla website and I am working on implementing an accordion feature for the category descriptions based on the placement of H3 headings in the WYSIWYG editor. Here is the basic function I have so far (althou ...

What is the best way to save the city name received from geolocation into a variable and then make an AJAX request?

<script> new Vue({ el: '#fad' , data: { data: {}, }, mounted() { var self = this; navigator.geolocation.getCurrentPosition(success, error); function success(position) { var GEOCO ...

The update feature seems to be malfunctioning within the MEAN Stack environment, specifically with node.js and angular js

Looking for some assistance as a beginner in the mean stack. I'm trying to update a record using the update function, but it's not working as expected. I need to update a specific object based on its ID, however, I'm encountering issues wit ...

What error am I making in the Date calculator for the select box using Javascript/jQuery?

$(.dateselboxes) .change( function(){ var y; y=$("#year").val(); var m; m=$("#month").val(); var d; // check for leap year var isLeapYear; if(y%4==0) { if(y%100==0) { if(y%400==0) {isLeapYear=true;} else {isLeapYear=false;} } ...

Drop and drag to complete the missing pieces

Here is a drag and drop fill in the blanks code I created. The challenge I'm facing is that I want users to be able to correct their mistakes by moving words to the right place after receiving points. <!DOCTYPE HTML> <html> <head&g ...