setData and setCategory highcharts from rails - ruby-on-rails

I'm using highcharts 3.0.1 with ruby on rails.
basically i have finally this javascript ( in an ajax/remote request) :
var chart = $('#my_bar_div').highcharts();
chart.xAxis[0].setCategories(["cat1", "cat2", "cat4"]);
chart.series[0].setData([6.0,7.0,8.0]);
ruby version _updatechart.js.erb:
var chart = $('#my_bar_div').highcharts();
chart.xAxis[0].setCategories(<%= #qids.to_s.html_safe %>);
chart.series[0].setData(<%= #average_values.to_json %>);
i'm going back from 6 to 3 categories/rows, I use a vertical column chart:
#bar = LazyHighCharts::HighChart.new('column') do |f|
f.series(:name=>'Punkte',:data=> #average_values )
f.title({ :text=>"Auswertung Fragen " + #theobjects.name })
### Options for Bar
f.options[:chart][:defaultSeriesType] = "bar"
f.plot_options({:series=>{:stacking=>"normal"}, :bar => { :dataLabels => { :enabled => true }}})
f.options[:xAxis] = {:plot_bands => "none", :title=>{:text=>""}, :categories => #qids}
f.options[:yAxis] = {:title => { :text =>'Punkte', :align =>'high'}, :labels => { :overflow => 'justify' } }
end
it resizes the categories, but does not redraw the columns, I tried almost everything without success.
Maybe you got any ideas?
Thanks, Patrick

Fixed example: http://jsfiddle.net/BCRyP/4/
1) "plotBands": "none" -> remove that or use {}
2) Use the same variable's name:
var chart;
$(document).ready(function () {
var chart = new Highcharts.Chart(options);
jQuery("#button").on("click", function () {
chart.xAxis[0].setCategories(["Wie geht es?", "How is your mam?"], true);
chart.series[0].setData([5.5, 6.0], true);
});
});

Related

antd Table with switch component

Is it possible to get row information by switching the switch in ant design table?
https://codesandbox.io/s/mmvrwy2jkp
Yes, the second argument of the render function is the record.
you can do this
{
title: 'switch',
dataIndex: 'age',
key: 'age',
render: (e, record) => (< Switch onChange={() => handleSwitchChange(record)} defaultChecked={e} />)
}
This is how I dealed with the switch component on each row item when using Ant design. Maybe this could give you some hints.
Table Columns
const COLUMN =
{
title: 'Status',
key: 'status',
dataIndex: 'status',
// status is the data from api
// index is the table index which could be used to get corresponding data
render: (status, record, index) => {
const onToggle = (checked) => {
status = checked;
onActiveUser(index, status);
};
return (
<Space>
<Switch defaultChecked={status} onChange={onToggle} />
</Space>
);
},
},
const onActiveUser = (index, status) => {
axios.patch({ id: users[index].id }, { is_active: status })
.then((response) => {
console.log(response);
})
.catch(() => {
console.log('Failed!');
});
};

Ruby on Rails, Gmaps4rails v 2.1.0 handler.addMakers(items,options) how do I put on options for dragging?

After facing the
undefined method gmaps at the line
with the code line :
<%= gmaps("markers" => {"data" => #json, "options" => { "draggable" => true } } ) %>
That does not seem to work in Gmaps4rails 2.1.0
Detailed problem and answer for it in here.
What I am asking in here is , provided the answer in the previous link, for me to be able to make the marker draggable, how should I write this method ?
1 : handler.addMarker(<%= raw #hash.to_json %>,<% {draggable => :true }%>)
or
2 : handler.addMarker(<%= raw #hash.to_json %>,<% "draggable" => true }%>)
or
What?
It just seems to not work, and the map does not load, also I'd like to know where to put it in the code,
handler = Gmaps.build('Google');
// here ?
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
// or Here ?markers = handler.addMarkers(<%= raw #hash.to_json %>,<%"draggable" => true %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
Update #1 : Solved
I found the answer on github, it requires a bit of time reading through the doc, but hey , It's worth taking a look at , in the end, it is exactly the answer to this question.
Answer
Pass google options as a second argument:
handler.addMarkers([
{
lat: 0,lng: 0,
picture: {
url: "/logo.png",
width: 36,
height: 36
},
infowindow: "hello!"
},
]
{
draggable: true
}
);
doc here: https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Js-Methods

How to integrate spiderfier js with gmaps4rails gem ? (Multiple markers on same lat,lng )

I'm struggling a bit trying to integrate spiderfier https://github.com/jawj/OverlappingMarkerSpiderfier with https://github.com/apneadiving/Google-Maps-for-Rails
In my map.html.haml:
= gmaps(:markers => {:data => #map, :options => { "rich_marker" => true, :raw => '{ animation: google.maps.Animation.DROP }' } }, :map_options => { :draggable => true, :auto_zoom => false, :zoom => 9, :disableDefaultUI => false, :scrollwheel => true, :disableDoubleClickZoom => true, :custom_infowindow_class => "province" })
- content_for :scripts do
:javascript
Gmaps.map.infobox = function(boxText) {
return {
content: boxText
,disableAutoPan: false
,maxWidth: 0
,pixelOffset: new google.maps.Size(-140, -50)
,alignBottom: true
,zIndex: 999
,hideCloseButton: false
,boxStyle: {
background: "white"
,width: "280px"
,padding: "10px"
,border: "1px solid #b2b2b2"
,arrowStyle: 0
,arrowPosition: 50
,arrowSize: 20
}
,infoBoxClearance: new google.maps.Size(10, 10)
,isHidden: false
,pane: "floatPane"
,enableEventPropagation: false
}};
This works fine, but how would one integrate spiderfier https://github.com/jawj/OverlappingMarkerSpiderfier#how-to-use ?
This is an old question using an old version of Gmaps 4 Rails, however to anyone that is interested in working with both libs in their latest versions, here's how to do it.
This example is based off the documentation sample code
handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
markers = handler.addMarkers([
{
"lat": 0,
"lng": 0,
"picture": {
"url": "https://addons.cdn.mozilla.net/img/uploads/addon_icons/13/13028-64.png",
"width": 36,
"height": 36
},
"infowindow": "hello!"
}
]);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
// Create a OverlappingMarkerSpiderfier instance
var oms = new OverlappingMarkerSpiderfier(handler.getMap(), {
keepSpiderfied: true
// Other options you need
});
// Track each marker with OMS
_.each(markers, function(marker) {
oms.addMarker(marker.getServiceObject());
});
});
The important thing here is to get down to the native Google objects that Gmaps4Rails wraps inside its own classes.
If you need click events on your markers, add a single handler to oms as it is explained in the doc.

afterSetExtremes callback for highcharts

I'm creating a highchart using the lazy_highcharts gem. I'd like to make use of the afterSetExtremes callback to regenerate some other data on the page on zooming. I've tried several ways, currently trying:
#chart = LazyHighCharts::HighChart.new('graph') do |f|
f.chart(:zoomType =>'x', :defaultSeriesType => 'spline')
f.x_axis(:type=> 'datetime', :events => {:afterSetExtremes => "functon(event){alert('something')}"} )
end
But that gives me the error
Uncaught TypeError: Object functon(event){alert('something')} has no method 'apply'
in the javascript console when I zoom the chart. I assume this has something to do with the generator not correctly setting up the callback function, setting it as a string instead of interpreting it as a function.
I've also tried to set it on my chart object via javascript after creation, but so far have had no luck with that. A few attempts below
chart_my_id4.xAxis.events = {setExtremes: function(event) {
alert('set extremes');
}};
chart_my_id4.xAxis[1].events = {setExtremes: function(event) {
alert('set extremes');
}};
No luck there either.
Any insight appreciated, thank you.
Not too familiar with ... ruby, but I took a look at the source on github and they do the following when they set functions into attributes:
:formatter => "function() { return this.x; }".js_code
It would be worth a try to add that .js_code and see if it works so you end up with:
#chart = LazyHighCharts::HighChart.new('graph') do |f|
f.chart(:zoomType =>'x', :defaultSeriesType => 'spline')
f.x_axis(:type=> 'datetime', :events => {
:afterSetExtremes => "functon(event){alert('something')}".js_code
})
end
I'm not familiar with that gem, but in standard Highcharts 3.0 you can add event in that way:
chart.yAxis[0].update({
events: {
afterSetExtremes: function(){
alert('x');
}
}
});
You can do this like that :
LazyHighCharts::HighChart.new('graph') do |f|
...
f.xAxis(:events => { :afterSetExtremes => after_set_extremes_function})
end
-
def after_set_extremes_function
%|function(e) {
chart = Highcharts.charts[0];
chart.showLoading('Loading data...');
$.getJSON("/path_to_your_action?start="+Math.round(e.min)+"&end="+Math.round(e.max), function(data) {
chart.series[0].setData(data);
chart.hideLoading();
}
}
);
}|.js_code
end

Flot won't Plot (Ruby)

I'm playing around with FLOT with Ruby and I'm having a hard time passing the code to javascript; I know my javascript isn't reading the data correctly from Ruby. I need some syntax help.
o={};
o= {'label' => "A", 'data' => #example.collect{|x| [Time.utc(x.date).to_i, x.num]}}
render :text => o.to_json
I have successfully rendered the output as such:
{"label":"A","data":[[1281225600,1.31],[1281225600,1.31],[1281225600,1.25]]}
The HTML outputs this data only.
My javascript is as follows:
var obj = jQuery.parseJSON(text);
var options = {
lines: { show: true },
points: { show: true },
xaxis: { mode: "time", timeformat: "%m/%d/%y", minTickSize: [1, "day"]}
};
var data = obj;
$.plot(placeholder,[data],options);
}
What you are missing is that Ruby puts out timestamps in the Unix format (i.e. seconds since the epoch 1281225600). Flot requires javascript timestamps, which count the milliseconds since the epoch, i.e. 1281225600*1000.
So in your Ruby code, your best bet is to do something like this:
o={};
o= {'label' => "A", 'data' => #example.collect{|x| [Time.utc(x.date).to_i*1000, x.num]}}
render :text => o.to_json
Or if you prefer, you could loop over the obj.data and do the multiplication on the Javascript side:
for (i=0;i<obj.data.length;i++){
obj.data[i] = obj.data[i]*1000;
}
Ok I got it....
Ruby code:
#o={};
#o= {'label' => "A", 'data' => #example.collect{|x| [Time.utc(x.date).to_i, x.num]}}
Java code:
$(function () {
var obj = <%= #o.to_json %>;
var options = {
lines: { show: true },
points: { show: true },
xaxis: { mode: "time", timeformat: "%m/%d/%y", minTickSize: [1, "day"]}
};
var data = obj;
$.plot(placeholder,[data],options);
});

Resources