JavaScript分析字符串并嵌入Google Charts可视化至页面的实现需求
Dynamic Google Charts Visualization & Analysis for windowData
Here's a polished implementation of your analyse function that properly integrates Google Charts, handles unique container IDs, and displays both visualizations and analysis results:
First, ensure the Google Charts library is loaded (we'll include a check in the function to avoid duplicate loads):
// Your windowData array (assuming entries are JSON strings; adjust if they're already objects) const windowData = [json1, json2, json3, json4]; // Replace with your actual JSON data function analyse(windowData) { // Load Google Charts if it's not already loaded if (typeof google === 'undefined' || typeof google.charts === 'undefined') { const script = document.createElement('script'); script.src = 'https://www.gstatic.com/charts/loader.js'; script.onload = () => initCharts(); document.head.appendChild(script); } else { initCharts(); } function initCharts() { google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(renderAllCharts); } function renderAllCharts() { windowData.forEach((item, index) => { // Parse JSON if needed (skip if items are already objects) const dataObj = typeof item === 'string' ? JSON.parse(item) : item; // Create a unique container for each chart and analysis const container = document.createElement('div'); container.className = 'chart-container'; container.innerHTML = ` <h3>Analysis #${index + 1}</h3> <div id="chart-${index}" style="width: 800px; height: 400px;"></div> <div id="analysis-${index}" class="analysis-results"></div> `; document.body.appendChild(container); // Prepare chart data (customize this based on your JSON structure) const chartData = new google.visualization.DataTable(); chartData.addColumn('string', 'Category'); chartData.addColumn('number', 'Value'); // Example: assuming your JSON has a 'data' array with {category, value} dataObj.data.forEach(row => { chartData.addRow([row.category, row.value]); }); // Chart options (customize as needed) const options = { title: `Chart for Entry #${index + 1}`, curveType: 'function', legend: { position: 'bottom' } }; // Render the chart const chart = new google.visualization.LineChart(document.getElementById(`chart-${index}`)); chart.draw(chartData, options); // Perform analysis and display results const analysisResult = analyseData(dataObj); document.getElementById(`analysis-${index}`).textContent = analysisResult; }); } // Helper function to analyze each JSON object function analyseData(dataObj) { // Customize this based on your analysis needs const totalValue = dataObj.data.reduce((sum, row) => sum + row.value, 0); const avgValue = totalValue / dataObj.data.length; return `Total value: ${totalValue.toFixed(2)}, Average value: ${avgValue.toFixed(2)}`; } } // Call the function to start analysis analyse(windowData);
Key Improvements
- Unique IDs: Uses the array index to generate unique IDs for each chart and analysis container, avoiding conflicts.
- Google Charts Loading: Handles asynchronous loading of the Google Charts library to ensure it's ready before rendering.
- JSON Handling: Checks if items are strings or objects, parsing as needed.
- Modular Structure: Separates chart initialization, rendering, and analysis into distinct functions for readability and maintainability.
- Dynamic DOM Creation: Builds containers dynamically instead of hardcoding HTML strings, making the code cleaner.
Notes
- Customize the
analyseDatafunction to match your specific analysis requirements (e.g., finding max/min values, detecting trends, etc.). - Adjust the chart type (LineChart, BarChart, PieChart, etc.) and options based on the data you're visualizing.
- Modify the container styling (width, height, classes) to fit your page layout.
内容的提问来源于stack exchange,提问作者P.W
相关产品推荐
相关产品推荐

