Google multiple GeoMaps, API - javascript

How can I use multiple GeoMaps ?
If I have only one map everything is ok. If I try to add another, without loading again the geomap visualization the map doesn't load, and if I try to load them, I get an error: Uncaught TypeError: Object #<Object> has no method 'Load' The function names are the same for the both map, if I change the functions' names for the second map then I have to change the callback
google.setOnLoadCallback(drawMap);
But, if I do so I get the error posted above....
More code:
//first map
<script type="text/javascript">
google.load("visualization", "1", {"packages": ["geomap"]});
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("number", "Numar anunturi");
data.setValue(1, 0, 'Ilfov');
data.setValue(1, 1, 6);
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_chart_div");
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
}
</script>
//second map
<script type="text/javascript">
function drawMap() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("string", "pret/mp:");
data.setValue(0, 0, 'Ilfov');
data.setValue(0, 1, '50.44');
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_pret_div");
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
}
</script>

I modified your code as follows and it seems to work now, although you have to be patient for the second map to load. I'm listening for the drawingDone event on the first map before firing off the second map. My theory is that this staggering prevents the two maps from stepping on each other's data structures inside of the Visualization API. But even if I'm wrong about the cause, this at least works.
My changes could use some tidying. Sorry about that. I'm in a bit of a rush, but wanted to get the working code to you before I ran off to do other things.
<script type="text/javascript">
google.load("visualization", "1", {"packages": ["geomap"],"callback": "drawMaps"});
function drawMaps() {
drawMap1();
}
function drawMap1() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("number", "Numar anunturi");
data.setValue(1, 0, 'Ilfov');
data.setValue(1, 1, 6);
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_chart_div");
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
google.visualization.events.addListener(geomap, 'drawingDone', drawMap2);
}
function drawMap2() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("string", "pret/mp:");
data.setValue(0, 0, 'Ilfov');
data.setValue(0, 1, '50.44');
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_pret_div");
var geomap2 = new google.visualization.GeoMap(container);
geomap2.draw(data, options);
}
</script>

Related

Drawing Google pie by dynamic data

I am trying to draw a simple Google pie chart by creating a dynamic table using JavaScript.
Why my code fails?
var g;
for (g=0; g <3; g++) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Failed');
data.addColumn('number', 'Passed');
data.addRows(1);
data.setCell(0, 0, "Work?");
data.setCell(0, 1, 80);
data.setCell(0, 2, 20);
var chartName = 'piechart'+(g+1);
var chart = new google.visualization.PieChart(document.getElementById(chartName));
chart.draw(data,options);
}
3 pie charts are being drawn on my screen, but they all have one color and one slice, and not 20% 80% like in my code.
Also, I'm not getting any errors on my console.
Are you aiming for something like this?
Also if you can, consider using addRows instead of setCell
I think the problem is with your table / data structure.
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart1"></div>
<div id="piechart2"></div>
<div id="piechart3"></div>
<script>
// Load the Visualization API and the corechart package.
google.charts.load('current', {
'packages': ['corechart']
});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var g;
for (g = 0; g < 3; g++) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'PassOrfail');
data.addColumn('number', 'Percentage');
data.addRows([
['Passed', 80],
['Failed', 20],
]);
var chartName = 'piechart' + (g + 1);
var chart = new google.visualization.PieChart(document.getElementById(chartName));
chart.draw(data);
}
}
</script>

Javascript: setInterval for multiple chart updates

I'm trying to display three Google Chart Gauges on a page to represent data from three temperature sensors. I have a JS function GetCurrentTemperature that returns the three temperature values in an array. I want the gauges to update at regular intervals. I've had this working fine with a single gauge, but when I try and use setInterval for the three charts, they're not updating. The code I'm using is listed below.
function drawTemperatureGauges() {
var currentTemp = GetCurrentTemperature();
var gaugeCount = currentTemp.length;
var options = {
width: 200,
height: 200,
redFrom: 65,
redTo: 80,
yellowFrom: 50,
yellowTo: 65,
minorTicks: 5,
max: 80
};
for(var i=0; i<gaugeCount; i++) {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Temp', currentTemp[i] ]
]);
var divName = 'gauge'.concat(i+1).concat('_div');
var chart = new google.visualization.Gauge(document.getElementById(divName));
chart.draw(data, options);
setInterval(function() {
var cTemp = GetCurrentTemperature();
data.setValue(0, 1, cTemp[i]);
chart.draw(data, options);
}, 2000);
}
}
I assume it's because I'm using i inside the anonymous setInterval function. I've looked at posts related to closures and also ones that specify the use of let rather than var but I still can't work out what syntax I need.
Any pointers greatly appreciated
Bbz
did you try locking in a closure like this?
for(var i=0; i<gaugeCount; i++) {
drawGauge(i);
}
function drawGauge(i) {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Temp', currentTemp[i] ]
]);
var divName = 'gauge'.concat(i+1).concat('_div');
var chart = new google.visualization.Gauge(document.getElementById(divName));
chart.draw(data, options);
setInterval(function() {
var cTemp = GetCurrentTemperature();
data.setValue(0, 1, cTemp[i]);
chart.draw(data, options);
}, 2000);
}

How to clear chart before adding new data?

I am using the Google Visualization API. A chart is generated based on values from an ajax call function drawchart().
The user then inputs values in textboxes and this point is added on the chart also (function addUserPoint()). function addUserPoint2() is autogenerated and is also added onto the map. The result of adduserpoint and adduserpoint2 have a line between them.
My issue: If the user adds a new point again, the chart adds those values and the previously added points stay on the chart. I want to get rid of the results of adduserpoint and adduserpoint2 before adding a new point. How can I achieve this?
var chartData;
var options2;
function addUserPoint() {
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
var aa= $("#wbtotala").text();
var bb= $("#wbtotalb").text();
chartData.addRow([
parseFloat(bb),
null,
parseFloat(aa)
]);
myLineChart.draw(chartData, options2);
}
function addUserPoint2(){
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
myLineChart.draw(0,0, options2);
var aa2 = fweight;
var bb2= fcg;
chartData.addRow([
parseFloat(bb2),
null,
parseFloat(aa2)
]);
myLineChart.draw(chartData, options2);
}
function drawchart() {
document.getElementById('addPoint').addEventListener('click', addUserPoint, false);
document.getElementById('addPoint').addEventListener('click', addUserPoint2, false);
chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Sli');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < chartdatax.length; i++) {
chartData.addRow([parseFloat(chartdatax[i]), parseFloat(chartdatay[i])]);
};
options2 = {
height: 500,
hAxis: {
title: 'AB',
gridlines: {
count: 20
}
},
vAxis: {
title: 'CD',
gridlines: {
count: 15
}
},
chartArea: {top:40, width: "70%", height: "75%"},
legend: { position: 'none' },
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('myChart2'));
myLineChart.draw(chartData, options2);
}
Use the Below Command.Here data is the DataTable Variable.
var data = new google.visualization.DataTable();
Set chartData to an empty object in addUserPoint();
function addUserPoint() {
charData = {};
if (chartData.getNumberOfColumns() === 2) {
...
}
}
This makes sure that anytime you add a new Data, it clears the previous data and you have a fresh new dataset ;)

Google Geomap API change region option onClick()

This piece of code draws a map with the Google Geomap API
<script type="text/javascript">
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = new google.visualization.DataTable();
data.addColumn('string','iso'); //e.g.: mx
data.addColumn('number','population'); //e.g.: 114
data.addRows([["mx",114],["ec",14],["ve",28]]);
var options = {
region: '005',
width: '511px',
height: '280px',
showLegend: true
};
var geomap = new google.visualization.GeoMap(document.getElementById('map'));
geomap.draw(data,options);
};
</script>
The region that is selected by default is 005 (South America). These are other available regions:
013 - (Central America)
150 - (Europe)
How can I change the region of the already drawn map dinamically? Something like this:
Europe
I know that the map will have to be redrawn, but i'm kind of stuck in the region property modification step. Any ideas will help. Thanks!
If you already have the data, I give you a snippet I use in my own app. Easier to understabd rather than long explanations I guess. Hope it helps.
In my case, I wanted to display numbers by country in the same region.
geomap = new google.visualization.GeoMap(document.getElementById('geo_chart'));
google.visualization.events.addListener( geomap, 'regionClick',
function(e)
{
var dataLocal = new google.visualization.DataTable();
var grouped_cities;
if (e['region'] == "0")
return;
options['colors'] = [0xaacdf8, 0x164177]; //orange colors
options['dataMode'] = 'markers';
options['region'] = e['region'];
options['showZoomOut'] = true;
if ( previous_region != e['region'] )
{
var indexes = dataFull.getFilteredRows([{column: 0, value: e['region']}]);
dataLocal.addRows(indexes.length);
dataLocal.addColumn('string', 'City');
dataLocal.addColumn('number', 'Views');
for ( i=0; i<indexes.length; i++ )
{
dataLocal.setValue(i, 0, dataFull.getValue(indexes[i], 2));
dataLocal.setValue(i, 1, dataFull.getValue(indexes[i], 3));
}
grouped_cities = google.visualization.data.group( dataLocal, [0],[{'column': 1, 'aggregation': google.visualization.data.sum, 'type': 'number'}]);
previous_region = e['region'];
}
geomap.draw(grouped_cities, options);
delete grouped_cities;
delete dataLocal;
}
);

OpenLayers => feature is null

This is my GeoJSON result. PasteBin
But when I load it, the result I get in firebug is feature is null. Why's that, are there any errors in my result? The coords in the JSON is written in projection WGS84, and in the code I also have set the externalProjection as WGS84. So why do I get the return "feature is null"?
The code I use to manage my map is :
$(document).ready(function() {
var wgs84 = new OpenLayers.Projection('EPSG:4326');
var layer = null;
var map = new OpenLayers.Map('map',{projection: wgs84});
layer = new OpenLayers.Layer.OSM( "Simple OSM Map");
var baseProjection = layer.projection;
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(10,10), 4);
map.events.register("moveend", null, function(){
if(map.zoom == 10)
{
var bounds = map.getExtent();
console.log(bounds);
var ne = new OpenLayers.LonLat(bounds.right,bounds.top).transform(map.getProjectionObject(),wgs84);
var sw = new OpenLayers.LonLat(bounds.left,bounds.bottom).transform(map.getProjectionObject(),wgs84);
var vectorLayer = new OpenLayers.Layer.Vector();
map.addLayer(vectorLayer);
$.getJSON('ajax.php?a=markers&type=json&sw=('+sw.lon+','+sw.lat+')&ne=('+ne.lon+','+ne.lat+')',function(data){
//$.getJSON('test.json',function(data){
var geojson_format = new OpenLayers.Format.GeoJSON({
'externalProjection': wgs84,
'internalProjection': baseProjection
});
vectorLayer.addFeatures(geojson_format.read(data));
});
}
});
});
Your sample OpenLayer code is working correctly, the problem is in your GeoJSON: you misspelled coordinates as "coordninates"

Categories

Resources