# GeoGebraWeb1

## GeoGebra Applets (JavaScript)

Click to enlarge

This PG code shows how to write WebWork questions with interactive GeoGebra applets that run using JavaScript (not Java).

PG problem file Explanation
```DOCUMENT();
"PGstandard.pl",
"MathObjects.pl",
"AppletObjects.pl",
"unionTables.pl",
"parserNumberWithUnits.pl",
"PGcourse.pl",
);

TEXT(beginproblem());

```

Initialization: We need to include the macro file `AppletObjects.pl`.

```Context("Numeric")->variables->are(t=>"Real");

\$a = random(2,4,1);
\$b = random(5,8,1);
\$c = random(1,3,1);
\$d = random(1,3,1);
while (\$c == \$d) { \$d = random(1,3,1); }

# \$f = Formula("\$c / (1+(t-2)^2) + \$d / (1+(t-4)^2)");
\$F = Formula("\$c * arctan(t-2) + \$d * arctan(t-4) - \$c * arctan(-2) - \$d * arctan(-4)");

\$Fa = \$F->eval(t=>\$a);
\$Fb = \$F->eval(t=>\$b);
\$disp = \$Fb - \$Fa;
```

Setup: The GeoGebra applet displays a graph of `\$f` and an accumulation function that is the integral of `\$f` from 0 to a movable point x on the horizontal axis, and it also shades the region under the graph of `\$f` and gives the area of this region rounded to one decimal place. We will pass the values `\$c` and `\$d` to the GeoGebra applet later.

We define the accumulation function (antiderivative) `\$F` use it to generate the answers.

```######################################
###################################
# You can name your applet (anything reasonable :-) )
# Adjust the height and width as desired
# Paste the geogebra parameters in at the bottom of the page just above the
# command end command
# so that they don't get in the way
###################################

\$appletName = "ggbfoo";

\$applet =  GeogebraWebApplet(
code       => "geogebra.GeoGebraApplet",
archive    => "geogebra.jar",
codebase                 => findAppletCodebase("geogebra.jar"),
appletName              => \$appletName,
appletId                    => \$appletName,
submitActionAlias     => 'getAppletValues',  # default actionAlias
initializeActionAlias   => 'configure',  # default actionAlias
setStateAlias             => 'setXML',
getStateAlias             => 'getXML',
setConfigAlias           => '',
getConfigAlias           => '',
returnFieldName       => '',
width                 => 497,              # may want to modify width
height                => 361,              # may want to modify height
# mayscript             => "true",
debugMode             => 0,   # set debugMode to 0 for no debug
# to 1 to make xml representation visible
# through the applet
onInit                => 'ggbOnInit',
type                  => 'geogebraweb',
#submitActionScript    => qq{ getQE('answerBox').value = getAppletValues() },
submitActionScript => '',
params     => GEOGEBRA_PARAMS(),# paste parameters in

);

###############################################
#
#  PNG picture of GeoGebra applet for hardcopy

\$im = image( "AF7-c".\$c."-d".\$d.".png", width=>486, height=>335, tex_size=>900 );

##################################
# Setup GeogebraWebApplet --
###################################

###############################################
#
#  For persistence of GeoGebra applet state
#  when answers are submitted or page is refreshed.
#  Uses JavaScript interface to GeoGebra.

qq!
<script language="javascript">
function ggbOnInit(param) {
if (param == "\$appletName") {
ww_applet_list[param].safe_applet_initialize(2);
}
}
</script>
<noscript>For this question to work properly,
you must enable JavaScript, or use another browser
(or computer) on which JavaScript works.</noscript>
!);

#######################################################
#
#  For setting initial values in GeoGebra from WeBWorK
#  Uses JavaScript interface to GeoGebra.

TEXT( MODES(TeX=>'', HTML=><<END_SCRIPT ) );
<script language="javascript">
function setAppletCoefficients() {
if (typeof(applet)!="undefined") {
if (typeof(applet.setValue)!="undefined") {

////////////////////////////////////////////////////////////////
//  List the values of the parameters to be set in the applet here

// Set variables "c" and "d" in GeoGebra to values \$c and \$d from WebWork
applet.setValue("c", \$c);
applet.setValue("d", \$d);

} else {
setTimeout("setAppletCoefficients()", 1000);
}
} else {
setTimeout("setAppletCoefficients()",1000);
}
}
ww_applet_list["\$appletName"].setConfig = function() {setAppletCoefficients()};
</script>
END_SCRIPT

###################################
#insert applet into body  -- this does not need to be changed
# except to adjust the insertion of the reinitialize_button or
###################################
# TEXT(\$PAR,  MODES(TeX=>'geogebraweb code',
#                      HTML=>\$applet->insertAll(
#                                debug =>0,
#                                reinitialize_button => 1,
# )));
```

GeoGebra Applet Setup: We use `JavaApplet();` from `AppletObjects.pl` to configure the applet. The value of `\$appletName` can be anything reasonable. We chose the default value `ggbApplet` for applets generated by html export from GeoGebra. You will want to change the values of `width` and `height` to be the same as the values in the `<applet ... width="486" height="306" ...>` tag in the html file generated by html export in GeoGebra.

Since the GeoGebra parameters can be very lengthy, at the end of the PG file we put a new method called `GEOGEBRA_PARAMS()` that returns all of the GeoGebra applet parameters.

```Context()->texStrings;
BEGIN_TEXT
\{
ColumnTable(
"The figure shows an interactive graph of velocity \( v(t) \), in
meters per second, where time \( t \) is measured in seconds.  You can
change the value of \( t \) in the graph by clicking and dragging
the red dot along the horizontal \( t \)-axis.
\$BR
\$BR
(a) What is the displacement between \( t = 0 \) seconds
and \( t = \$a \) seconds?
\$BR".
ans_rule(20).
\$BR
\$BR
(b) What is the displacement between \( t = 0 \) seconds
and \( t = \$b \) seconds?
\$BR".
ans_rule(20).
\$BR
\$BR
(c) What is the displacement between \( t = \$a \) seconds
and \( t = \$b \) seconds?
\$BR".
ans_rule(20).
,
\$BCENTER.
\$BBOLD."Graph of velocity \( y = v(t) \)".\$EBOLD.\$PAR.
\$ECENTER
,
indent => 0, separation => 30, valign => "TOP"
);
\}
END_TEXT
Context()->normalStrings;
```

Main Text: The problem text section of the file is mostly as we'd expect. We make use of a `ColumnTable()` and the string concatenation operator `.` a lot. The code that is special here is ``` MODES(HTML=>\$applet->insertAll(debug=>0, reinitialize_button=>0, includeAnswerBox=>0,), TeX=>\$im)``` which says to display the `\$applet` in HTML mode and the PNG picture file defined by `\$im` in TeX mode.

```ANS( NumberWithUnits("\$Fa","m")  ->cmp(tolerance=>0.11, tolType=>'absolute') );
ANS( NumberWithUnits("\$Fb","m")  ->cmp(tolerance=>0.11, tolType=>'absolute') );
ANS( NumberWithUnits("\$disp","m")->cmp(tolerance=>0.21, tolType=>'absolute') );
```

```sub GEOGEBRA_PARAMS {
my \$result = {
showResetIcon=>"false" ,
enableRightClick=>"false" ,
enableLabelDrags=>"false",
showToolBar=>"false",
showAlgebraInput=>"false",
useBrowserForJS=>"true",

};

\$result;
}

COMMENT('Uses GeoGebraWeb (JavaScript), so it should work on computers and tablets.');

ENDDOCUMENT();
```

GeoGebra Applet Parameters: When you export your GeoGebra drawing pad via File -> Export -> Dynamic worksheet as Webpage (html), you get an html file with source code you can paste directly in here below the commented lines `# The GeoGebra "source code" ...`. The parameter named `ggbBase64` is actually the source code for the GeoGebra worksheet, and it was so long that we couldn't include it right here and have the source code and comments both visible at the same time (the `ggbBase64` parameter is given in full near the bottom of the page). Using an applet parameter to include your `filename.ggb` file directly is a bad idea for security reasons and has been prohibited in WeBWorK.

### Steps to construct the GeoGebra applet:

2. From the menu bar at the top of GeoGebra, select `View -> Grid`
3. In the Input textbox at the bottom of GeoGebra, type `c=1 (Enter)` and `d=3 (Enter)` to create Free Objects
4. In the Input textbox at the bottom of GeoGebra, type `f=Function[c/(1+(x-2)^2)+d/(1+(x-4)^2),-10,10]` to create a Dependent Object
5. From the graphical tool bar near the top of GeoGebra, click the New Point tool (it has a point and the letter A on it and is second from the left)
6. Put the pointer over the x-axis and click. You should see a new Dependent Object `A = (?,0)` listed in the Algebra View
7. From the menu bar at the top of GeoGebra, select `Options -> Point Capturing -> Off`
8. In the algebra view in the left column of GeoGebra, right-click on the point you created and select Object Properties. Set the color and style as you like, then from the Basic tab select Show Label and Value
9. In the Input textbox at the bottom of GeoGebra, type `a = Integral[f(x),0,x(A)]` to create a dependent object. You will see a shaded region representing the area under the curve. The syntax `x(A)` gets the value of the x-coordinate of the point A.
10. In the algebra view in the left column of GeoGebra, right-click on the integral you created and select Object Properties. Set the color and style as you like.
11. From the graphical toolbar near the top of GeoGebra, choose the Insert Text tool by clicking (it is labeled ABC and is obtained by clicking and holding on the icon that is second from the right until a drop down menu appears).
12. Click the mouse somewhere on the drawing pad and a new window with a text box will appear. Type `"Signed area = " + a` in the text box and click OK.
13. From the graphical toolbar near the top of GeoGebra, choose the Move tool (it has a mouse pointer on it and is the leftmost icon)
14. Click and drag the "Signed area = ..." text to a desired location.
15. Right-click on the "Signed area = ..." text and select Object Properties. Change the color and font size as desired, then from the Basic tab select Fix Object
16. As before, use the Insert Text tool to write instructions, etc.
17. Close the algebra view by going to the menu bar at the top of GeoGebra and selecting `View -> Algebra View`
18. From the graphical toolbar near the top of GeoGebra, choose the Move Drawing Pad tool (it has perpendicular two-headed arrows and is the rightmost icon).
19. Click and drag on the drawing pad to move your picture up the the top left corner.
20. Resize the GeoGebra window so that the drawing pad is as small as possible while still displaying the drawing well.
21. From the menu bar at the top of GeoGebra, select `File -> Save`.
22. From the menu bar at the top of GeoGebra, select `File -> Export -> Dynamic Worksheet as Webpage (html)`. -- or use Shift-Command-m to copy this to the clipboard
23. View the html source code by opening the html file in a text editor. Copy the parameter `<param name="ggbBase64" value="UEsD...stuff omitted...">` and paste it into your WebWork PG file near the bottom where it says `GEOGEBRA_PARAMS`. Also, get the width and height of the applet from the html source code and put those numbers in your WebWork PG file within the `JavaApplet()` method.
24. From the menu bar at the top of GeoGebra, select `File -> Export -> Graphics View as Picture (png, eps)` and save it as a PNG file. Change the values of the parameters c and d and repeat this process until you have generated one picture for every possible value of c and d you will use in your WebWork question.
25. Upload your PNG picture files to the same directory as your WebWork PG file on the WebWork server.