Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Develop a Translator App Using the Google AJAX API and JSON

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

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.

<?xml version="1.0"?>
<options>
<option value="">Detect language</option>
<option value="en">English</option>
<option value="af">Afrikaans</option>
<option value="sq">Albanian</option>
<option value="ar">Arabic</option>
<option value="hy">Armenian ALPHA</option>
<option value="az">Azerbaijani ALPHA</option>
<option value="eu">Basque ALPHA</option>
<option value="be">Belarusian</option>
<option value="bg">Bulgarian</option>
<option value="ca">Catalan</option>
<option value="zh-CN">Chinese</option>
<option value="hr">Croatian</option>
<option value="cs">Czech</option>
<option value="da">Danish</option>
<option value="nl">Dutch</option>
<option value="en">English</option>
<option value="et">Estonian</option>
<option value="tl">Filipino</option>
<option value="fi">Finnish</option>
<option value="fr">French</option>
<option value="gl">Galician</option>
<option value="ka">Georgian ALPHA</option>
<option value="de">German</option>
<option value="el">Greek</option>
<option value="ht">Haitian Creole ALPHA</option>
<option value="iw">Hebrew</option>
<option value="hi">Hindi</option>
<option value="hu">Hungarian</option>
<option value="is">Icelandic</option>
<option value="id">Indonesian</option>
<option value="ga">Irish</option>
<option value="it">Italian</option>
<option value="ja">Japanese</option>
<option value="ko">Korean</option>
<option value="lv">Latvian</option>
<option value="lt">Lithuanian</option>
<option value="mk">Macedonian</option>
<option value="ms">Malay</option>
<option value="mt">Maltese</option>
<option value="no">Norwegian</option>
<option value="fa">Persian</option>
<option value="pl">Polish</option>
<option value="pt">Portuguese</option>
<option value="ro">Romanian</option>
<option value="ru">Russian</option>
<option value="sr">Serbian</option>
<option value="sk">Slovak</option>
<option value="sl">Slovenian</option>
<option value="es">Spanish</option>
<option value="sw">Swahili</option>
<option value="sv">Swedish</option>
<option value="th">Thai</option>
<option value="tr">Turkish</option>
<option value="uk">Ukrainian</option>
<option value="ur">Urdu ALPHA</option>
<option value="vi">Vietnamese</option>
<option value="cy">Welsh</option>
<option value="yi">Yiddish</option>
</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.

package
{

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.

import flash.display.Sprite;
import flash.events.KeyboardEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
import com.adobe.serialization.json.JSON;
import fl.transitions.Tween;
import fl.transitions.easing.Back;
import fl.transitions.easing.Strong;
import fl.data.DataProvider;
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.

public class Main extends Sprite
{

Step 17: Variables

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

private var srcLang:String = ""; //the source language, default is Autodetect
private var destLang:String = "it"; //default destination language, italian
private var tween:Tween; //handles animation
private var xmlLoader:URLLoader;
private var languages:XML; //will store the XML file of the languages
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.

public function Main():void
{
	loadXML("Languages.xml");
	languagePanel.intoBox.prompt = "Italian"; //Set the combobox default label to "italian" which is the default destination language
	searchTerms.addEventListener(KeyboardEvent.KEY_UP, translate); //The translate function will be run every key up
	infoButton.addEventListener(MouseEvent.MOUSE_UP, selectLanguage); //Adds the listener to the infobutton to call the language panel
}

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.

private function loadXML(src:String):void
{
	xmlLoader = new URLLoader(new URLRequest(src));
	xmlLoader.addEventListener(Event.COMPLETE, parseXML);
}

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.

private function parseXML(e:Event):void
{
	languages = new XML(e.target.data);
	setComboBoxData();
}

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.

private function setComboBoxData():void
{
	for(var i:int = 0; i < languages.children().length(); i++)
	{
		dp.addItem({label: languages.children()[i], value: languages.children()[i].@value}); //Set corresponding combobox values
	}
			
	languagePanel.fromBox.dataProvider = dp; //Set the data provider to the component
	languagePanel.intoBox.dataProvider = dp;
			
	languagePanel.fromBox.addEventListener(Event.CHANGE, comboBoxChange);//Change listeners
	languagePanel.intoBox.addEventListener(Event.CHANGE, comboBoxChange);
}

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.

private function comboBoxChange(e:Event):void
{
	if(e.target.name == "fromBox")
	{
		srcLang = e.target.selectedItem.value;
	}
	else
	{
		destLang = e.target.selectedItem.value;
	}
}

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.

private function selectLanguage(e:MouseEvent):void
{
	if(languagePanel.y == -14) //if the panel is visible
	{
		tween = new Tween(languagePanel, "y", Back.easeIn, languagePanel.y, -134, 0.3, true);//make it invisible
	}
	else //if hidden
	{
		tween = new Tween(languagePanel, "y", Back.easeOut, languagePanel.y, -14, 0.3, true); //show it
	}
}

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.

private function translate(e:KeyboardEvent):void
{
	if (searchTerms.length != 0)
	{
		var urlLoader:URLLoader = new URLLoader(new URLRequest("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + searchTerms.text + "&langpair=" + srcLang + "|" + destLang));

		urlLoader.addEventListener(Event.COMPLETE, displayTranslation); //calls the displayTranslation function after the server responds
	}
			
	if(languagePanel.y == -14)//hides the language panel if visible
	{
		tween = new Tween(languagePanel, "y", Back.easeIn, languagePanel.y, -134, 0.3, true);
	}
}

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.

private function displayTranslation(e:Event):void
{
	var translation:String = "[" + e.target.data + "]"; //the server response
	var json:Array = JSON.decode(translation) as Array; //decode the JSON string and store it as an aray

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

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

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!

Advertisement