1. Code
  2. JavaScript

Develop a Translator App Using the Google AJAX API and JSON

Scroll to top
10 min read

In this tutorial, you will learn how to use the Google AJAX API with ActionScript 3 to create a nice looking translator application. Enjoy!


Step 1: Brief Overview

Using some of the flash.net classes, a String that communicates with the Google AJAX API, and the JSON class (part of the as3corelib) we will create a translator application in Flash CS5.


Step 2: Document Settings

Launch Flash and create a new document. Set the stage size to 600x300px and the frame rate to 24fps.


Step 3: Interface

This is the interface we'll use, a gradient background, a title or logo, an Input TextField and an Info button; there are also two panels that will be invisible at first and activated during the course of the app. Let's get building.


Step 4: Background

Select the Rectangle Tool (R) and create a 600x300 rectangle and fill it with this radial gradient: #DFE0E4 to #BDC1C8, center it on stage.


Step 5: Title/Logo

Use the Rectangle Primitive Tool to create a 100x40px rectangle, fill it with #595E64 and change the corner radius to 12.

To add the Google Logo you can use the Catull Font if you have it, or just add the text with another typeface.

There is a little detail in many elements of the interface, this is the letterpress text effect. To create it just duplicate the text (CMD + D) change its color to #212325 and move it 1px up, then right-click the darker text and select Arrange > Send Backward.

Now let's add the text to the left, use this format: Lucida Grande Regular 11pt #595E64. Again, use the letterpress effect and position the text as shown in the image.


Step 6: Separator

Create a 1px line using the Rectangle Tool and fill it with #595E64, duplicate it, change the color to #ECF1FE, and move it 1px down. You can group (CMD+G) the lines for better manipulation.


Step 7: Translate TextField Background

With the Rectangle Primitive Tool, create a 250x24px, #595E64 and 7 as corner radius. Center the shape and add the letterpress effect.

You can add a search icon too, as a detail.

Lastly, use the Text Tool (T) to create an Input Textfield with this format: Helvetica Bold, 13pt, #EEEEEE. Align the TextField to the background.


Step 8: Info Button

Select the Oval Tool (O), draw a 15x15 px oval and fill it with #919397. Use the Text Tool to add an italic i and center them.

Convert the shapes to a Button and name it infoButton.


Step 9: Language Panel

Open the Components Panel (CMD+F7) and drag a ComboBox to the stage, duplicate it and add it to to a 160x127px rounded rectangle filled with #41464A to #595E64.

Add static Text Fields to label the components and the panel.

Name the ComboBoxes fromBox and intoBox and convert all to a single MovieClip. Set the MovieClip instance name to languagePanel.

Be sure to check the position you set to the panel, as it will be animated from the starting point to the stage, in this demo y is -14.


Step 10: Results Panel

The results panel will be used to display the translated text.

Create a 600x170px rectangle using the gradient fill and add a Dynamic Textfield named txt.

Convert the shape and TextField to MovieClip and name it panel.

This completes the graphic part.


Step 11: XML

We'll use an XML file containing the languages available through Google Translate.

To get these languages we'll need an Internet Browser that can see source code (any modern browser does that), go to Google Translate site and make the source code visible. Go to the part shown in the following image and start copying.

Alternatively, copy the data shown below, though be aware that this list could be updated from time to time.

1
2
<?xml version="1.0"?>
3
<options>
4
<option value="">Detect language</option>
5
<option value="en">English</option>
6
<option value="af">Afrikaans</option>
7
<option value="sq">Albanian</option>
8
<option value="ar">Arabic</option>
9
<option value="hy">Armenian ALPHA</option>
10
<option value="az">Azerbaijani ALPHA</option>
11
<option value="eu">Basque ALPHA</option>
12
<option value="be">Belarusian</option>
13
<option value="bg">Bulgarian</option>
14
<option value="ca">Catalan</option>
15
<option value="zh-CN">Chinese</option>
16
<option value="hr">Croatian</option>
17
<option value="cs">Czech</option>
18
<option value="da">Danish</option>
19
<option value="nl">Dutch</option>
20
<option value="en">English</option>
21
<option value="et">Estonian</option>
22
<option value="tl">Filipino</option>
23
<option value="fi">Finnish</option>
24
<option value="fr">French</option>
25
<option value="gl">Galician</option>
26
<option value="ka">Georgian ALPHA</option>
27
<option value="de">German</option>
28
<option value="el">Greek</option>
29
<option value="ht">Haitian Creole ALPHA</option>
30
<option value="iw">Hebrew</option>
31
<option value="hi">Hindi</option>
32
<option value="hu">Hungarian</option>
33
<option value="is">Icelandic</option>
34
<option value="id">Indonesian</option>
35
<option value="ga">Irish</option>
36
<option value="it">Italian</option>
37
<option value="ja">Japanese</option>
38
<option value="ko">Korean</option>
39
<option value="lv">Latvian</option>
40
<option value="lt">Lithuanian</option>
41
<option value="mk">Macedonian</option>
42
<option value="ms">Malay</option>
43
<option value="mt">Maltese</option>
44
<option value="no">Norwegian</option>
45
<option value="fa">Persian</option>
46
<option value="pl">Polish</option>
47
<option value="pt">Portuguese</option>
48
<option value="ro">Romanian</option>
49
<option value="ru">Russian</option>
50
<option value="sr">Serbian</option>
51
<option value="sk">Slovak</option>
52
<option value="sl">Slovenian</option>
53
<option value="es">Spanish</option>
54
<option value="sw">Swahili</option>
55
<option value="sv">Swedish</option>
56
<option value="th">Thai</option>
57
<option value="tr">Turkish</option>
58
<option value="uk">Ukrainian</option>
59
<option value="ur">Urdu ALPHA</option>
60
<option value="vi">Vietnamese</option>
61
<option value="cy">Welsh</option>
62
<option value="yi">Yiddish</option>
63
</options>

Paste the text in your XML editor and save it as Languages.xml. Don't forget to add the <options> </options> tags at the beginning and end respectively, this way we can get the full language name using xml.children()[elementNumber] and the abbreviation value using xml.children()[elementNumber].@value. See Dru Kepple's tutorial on XML in AS3 for more information.


Step 12: New ActionScript Class

Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder.


Step 13: Package

The package keyword allows you to organize your code into groups that can be imported by other scripts, it's recommended you name them starting with a lowercase letter and use intercaps for subsequent words for example: myClasses. It's also common to name them using your company's website: com.mycompany.classesType.myClass.

In this example, we're using a single class, so there isn't really a need to create a classes folder.

1
2
package
3
{

Step 14: JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

JSON.org

The JSON class will be needed to decode the server response, you can get it as part of the as3corelib at its download page.


Step 15: Import Directive

These are the classes we'll need to import for our class to work, the import directive makes externally defined classes and packages available to your code.

1
2
import flash.display.Sprite;
3
import flash.events.KeyboardEvent;
4
import flash.net.URLLoader;
5
import flash.net.URLRequest;
6
import flash.events.Event;
7
import com.adobe.serialization.json.JSON;
8
import fl.transitions.Tween;
9
import fl.transitions.easing.Back;
10
import fl.transitions.easing.Strong;
11
import fl.data.DataProvider;
12
import flash.events.MouseEvent;

Step 16: Declare and Extend the Class

Here we declare the class using the class definition keyword followed by the name that we want for the class, remember that you have to save the file using this name.

The extends keyword defines a class that is a subclass of another class. The subclass inherits all the methods, properties and functions, that way we can use them in our class.

1
2
public class Main extends Sprite
3
{

Step 17: Variables

These are the variables we'll use, read the comments in the code to find out more about them.

1
2
private var srcLang:String = ""; //the source language, default is Autodetect

3
private var destLang:String = "it"; //default destination language, italian

4
private var tween:Tween; //handles animation

5
private var xmlLoader:URLLoader;
6
private var languages:XML; //will store the XML file of the languages

7
private var dp:DataProvider = new DataProvider(); //stores an array of languages to pass to the comboBox

Step 18: Constructor

The constructor is a function that runs when an object is created from a class. This code is the first to execute when you make an instance of an object or runs using the Document Class.

1
2
public function Main():void
3
{
4
	loadXML("Languages.xml");
5
	languagePanel.intoBox.prompt = "Italian"; //Set the combobox default label to "italian" which is the default destination language

6
	searchTerms.addEventListener(KeyboardEvent.KEY_UP, translate); //The translate function will be run every key up

7
	infoButton.addEventListener(MouseEvent.MOUSE_UP, selectLanguage); //Adds the listener to the infobutton to call the language panel

8
}

Step 19: Load XML

This function loads the XML passed in the src parameter (which was called in the constructor). It adds a listener to execute the parseXML() function when the load is complete.

1
2
private function loadXML(src:String):void
3
{
4
	xmlLoader = new URLLoader(new URLRequest(src));
5
	xmlLoader.addEventListener(Event.COMPLETE, parseXML);
6
}

Step 20: Handle XML

After the XML is fully loaded, we use the XML instance to convert the data to a valid XML object and after that we call the setComboBoxData() function.

1
2
private function parseXML(e:Event):void
3
{
4
	languages = new XML(e.target.data);
5
	setComboBoxData();
6
}

Step 21: Set ComboBox Data

This code loops through the values in the XML file, sets the full language name as the ComboBox label and the value parameter as the ComboBox value.

It also adds the corresponding event listeners to detect the change of language.

1
2
private function setComboBoxData():void
3
{
4
	for(var i:int = 0; i < languages.children().length(); i++)
5
	{
6
		dp.addItem({label: languages.children()[i], value: languages.children()[i].@value}); //Set corresponding combobox values

7
	}
8
			
9
	languagePanel.fromBox.dataProvider = dp; //Set the data provider to the component

10
	languagePanel.intoBox.dataProvider = dp;
11
			
12
	languagePanel.fromBox.addEventListener(Event.CHANGE, comboBoxChange);//Change listeners

13
	languagePanel.intoBox.addEventListener(Event.CHANGE, comboBoxChange);
14
}

Step 22: Detect ComboBox Changes

When the language in the ComboBox is changed, we check which component was changed (from or into) and change the corresponding variable, this way when the translate() function is executed it will automatically use the new values.

1
2
private function comboBoxChange(e:Event):void
3
{
4
	if(e.target.name == "fromBox")
5
	{
6
		srcLang = e.target.selectedItem.value;
7
	}
8
	else
9
	{
10
		destLang = e.target.selectedItem.value;
11
	}
12
}

Step 23: Show Language Panel

By default, the language panel is hidden.The following function is executed when the user clicks in the infoButton, it shows or hides the language panel.

1
2
private function selectLanguage(e:MouseEvent):void
3
{
4
	if(languagePanel.y == -14) //if the panel is visible

5
	{
6
		tween = new Tween(languagePanel, "y", Back.easeIn, languagePanel.y, -134, 0.3, true);//make it invisible

7
	}
8
	else //if hidden

9
	{
10
		tween = new Tween(languagePanel, "y", Back.easeOut, languagePanel.y, -14, 0.3, true); //show it

11
	}
12
}

Step 24: Translate

The core function. To perform the translation Google gives us an AJAX API that we need to call to then receive the translated text.

This is the string we use:

http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + searchTerms.text + "&langpair=" + srcLang + "|" + destLang

After the q= term we must include the text we want to translate; after the langpair parameter, the abbreviation of the languages we are using separated by a "|" character. To automate this process we use the variables declared before in the class.

This function is executed after a KEY_UP event.

1
2
private function translate(e:KeyboardEvent):void
3
{
4
	if (searchTerms.length != 0)
5
	{
6
		var urlLoader:URLLoader = new URLLoader(new URLRequest("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + searchTerms.text + "&langpair=" + srcLang + "|" + destLang));
7
8
		urlLoader.addEventListener(Event.COMPLETE, displayTranslation); //calls the displayTranslation function after the server responds

9
	}
10
			
11
	if(languagePanel.y == -14)//hides the language panel if visible

12
	{
13
		tween = new Tween(languagePanel, "y", Back.easeIn, languagePanel.y, -134, 0.3, true);
14
	}
15
}

Step 25: Display Translation

When the server responds with the translated text we call this function. As the server doesn't responds in plain text, it's time to use the JSON class we downloaded from the as3CoreLib.

1
2
private function displayTranslation(e:Event):void
3
{
4
	var translation:String = "[" + e.target.data + "]"; //the server response

5
	var json:Array = JSON.decode(translation) as Array; //decode the JSON string and store it as an aray

6
7
	tween = new Tween(panel,"y",Strong.easeOut,panel.y,140,1,true); //bring up the translate panel

8
9
	panel.txt.text = json[0].responseData.translatedText; //display the translated text in the textfield

10
}

You are probably wondering why we used an array to store the server string, this is because the JSON string received from the server contains separated types of data, you can see it in the following string:

{"responseData": {"translatedText":"this is the text translated"}, "responseDetails": null, "responseStatus": 200}

As we are only interested in the translated text, we have to convert the JSON data into an array and then get the value of the property translatedText from that array.


Step 26: Document Class

We're done with the class, to use it, just go back to the FLA file and add Main to the Class field in the Properties Panel.


Conclusion

It could be a really nice touch to use a Translator in your application without leaving it, try implementing it in your own app.

Thanks for reading this tutorial, I hope you've found it useful!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.