Friday, May 14, 2010

Google AJAX Language API

kyawrayzan@gmail.com | My favorites | English | Sign out

Google AJAX Language API

Developer's Guide

AJAX Language API

AJAX Language API for Translation and Detection

With the AJAX Language API, you can translate and detect the language of blocks of text within a web page using JavaScript.

The API is new, so there might be some issues and slightly less than perfect documentation. Bear with us as we fill in the holes, and join the AJAX APIs developer forum to give feedback and discuss the API.

Table of Contents

Audience

This documentation is designed for people familiar with JavaScript programming and object-oriented programming concepts. There are many JavaScript tutorialsavailable on the Web.

Introduction

The "Hello, World" of the Google AJAX Language API

The easiest way to start learning about this API is to see a simple example. The following example detects the language of the given text and then translates it to English.




type="text/javascript" src="http://www.google.com/jsapi">

type="text/javascript">

google
.load("language", "1");

function initialize() {
var text = document.getElementById("text").innerHTML;
google
.language.detect(text, function(result) {
if (!result.error && result.language) {
google
.language.translate(text, result.language, "en",
function(result) {
var translated = document.getElementById("translation");
if (result.translation) {
translated
.innerHTML = result.translation;
}
});
}
});
}
google
.setOnLoadCallback(initialize);




id="text">??????????

id="translation">


You can view this example here or edit and play around with a similar example in the Code Playground.

Including the AJAX Language API on Your Page

To include the AJAX Language API in your page, utilize the Google AJAX API loader. The common loader allows you to load all of the AJAX APIs that you need, including the language API. You need to include both the Google AJAX APIs script tag and call google.load("language", "1"):

 type="text/javascript" src="http://www.google.com/jsapi">


type="text/javascript">
google
.load("language", "1");

The first script tag loads the google.load function, which lets you load individual Google APIs. google.load("language", "1") loads Version 1 of theLanguage API. Currently, the AJAX Language API is in Version 1, but new versions may be available in the future. See the versioning discussion below for more information.

API Updates

The second argument to google.load is the version of the AJAX Language API you are using. Currently the AJAX Language API is in version 1, but new versions might be available in the future.

If a significant update to the API occurs in the future, the version number will change and a notice will be posted on Google Code and the AJAX APIs discussion group. When that happens, support for both versions is expected for at least a month in order to allow you to migrate your code.

OA

The AJAX Language API team periodically updates the API with the most recent bug fixes and performance enhancements. These bug fixes should only improve performance and fix bugs, but we may inadavertently break some API clients. Please use the AJAX APIs discussion group to report such issues.

Examples

A number of examples are available in the Code Playground that you can edit and play around with to better understand how to use this API.

Language Translation

This example shows a simple translation of a JavaScript string:

google.language.translate("Hello world", "en", "es", function(result) {

if (!result.error) {
var container = document.getElementById("translation");
container
.innerHTML = result.translation;
}
});

View example (translate.html)

Language Detection

This example shows language detection of a JavaScript string. The language code is returned:

var text = "¿Dónde está el baño?";

google
.language.detect(text, function(result) {
if (!result.error) {
var language = 'unknown';
for (l in google.language.Languages) {
if (google.language.Languages[l] == result.language) {
language
= l;
break;
}
}
var container = document.getElementById("detection");
container
.innerHTML = text + " is: " + language + "";
}
});

View example (detection.html)

Detection of Unicode Font Rendering Support

Browsers and operating systems may or may not have the support for rendering particular Unicode fonts. You can detect whether the user using your web page has support for rendering the fonts of a given language in a readable way or not using the font rendering support detection API. Please note that this works correctly for Unicode fonts alone. If your web page renders using non-Unicode fonts, this function will not be useful for you. If font rendering support is not present for a given language, there are several solutions available to fix this - please rsxead this article for more information.

This example shows detection of font rendering support:

var result = google.language.isFontRenderingSupported("hi");

var resultStr = "";
if (result == google.language.FontRenderingStatus.SUPPORTED) {
resultStr
= "Rendering for " + lang + " is supported.";
} else if (result == google.language.FontRenderingStatus.UNSUPPORTED) {
resultStr
= "Rendering for " + lang + " is not supported.";
} else {
resultStr
= "Unsupported language " + lang + " for font detection API.";
}
var resultDiv = document.getElementById("displayResultsDiv");
resultDiv
.innerHTML += resultStr;

View example (fontdetection.html)

Source Detection during Translation

The following example is similar to the basic translation example but shows how to translate the text without knowing the source language. By specifying an empty string as unknown for the source language, the system detects and translates in one call.

google.language.translate("Hello world", "", "es", function(result) {

if (!result.error) {
var container = document.getElementById("translation");
container
.innerHTML = result.translation;
}
});

View example (autotranslate.html)

Branding and Google Attribution

When your application uses the Google AJAX Language APIs, it is important to communicate the Google brand to your users. Thegoogle.language.getBranding() method is designed to help with this. The method accepts an HTML DOM element or the corresponding ID, as well as optional options. The branding is attached to the provided element.

// attach a "powered by Google" branding

<div id='branding'> div>
...
google
.language.getBranding('branding');

The branding can be customized using CSS and comes in a 'vertical' and 'horizontal' base formats. An example showing the various formats and CSS customization is below.

View example (branding.html)

Additional Examples

Here are two addional samples that allow some interaction. The first does language detection with a pre-canned text string but allows other text as input. It also displays confidence and reliability factors. Also, you can play around with similar examples in the Code Playground.

View example (detect.html)

The second additional sample does translation. However, it also allows interaction similar to the sample above.

View example (translate.html)

API Details

Supported Languages

The Google AJAX Language API currently supports the following languages. The technology is constantly improving and the team is working hard to expand this list, so please check back often. You can also visit Google Translate to view an up-to-date list of supported languages.

  • Afrikaans
  • Albanian
  • Amharic
  • Arabic
  • Armenian
  • Azerbaijani
  • Basque
  • Belarusian
  • Bengali
  • Bihari
  • Breton
  • Bulgarian
  • Burmese
  • Catalan
  • Cherokee
  • Chinese (Simplified and Traditional)
  • Corsican
  • Croatian
  • Czech
  • Danish
  • Dhivehi
  • Dutch
  • English
  • Esperanto
  • Estonian
  • Faroese
  • Filipino
  • Finnish
  • French
  • Frisian
  • Galician
  • Georgian
  • German
  • Greek
  • Gujarati
  • Haitian Creole
  • Hebrew
  • Hindi
  • Hungarian
  • Icelandic
  • Indonesian
  • Inuktitut
  • Irish
  • Italian
  • Japanese
  • Javanese
  • Kannada
  • Kazakh
  • Khmer
  • Korean
  • Kurdish
  • Kyrgyz
  • Lao
  • Latin
  • Latvian
  • Lithuanian
  • Luxembourgish
  • Macedonian
  • Malay
  • Malayalam
  • Maltese
  • Maori
  • Marathi
  • Mongolian
  • Nepali
  • Norwegian
  • Occitan
  • Oriya
  • Pashto
  • Persian
  • Polish
  • Portuguese
  • Punjabi
  • Quechua
  • Romanian
  • Russian
  • Sanskrit
  • Scots Gaelic
  • Serbian
  • Sindhi
  • Sinhalese
  • Slovak
  • Slovenian
  • Spanish
  • Swahili
  • Swedish
  • Sundanese
  • Syriac
  • Tajik
  • Tamil
  • Tatar
  • Telugu
  • Thai
  • Tibetan
  • Tonga
  • Turkish
  • Ukranian
  • Urdu
  • Uzbek
  • Uighur
  • Vietnamese
  • Welsh
  • Yiddish
  • Yoruba

Supported Language Translation Pairs

The Google AJAX Language API currently detects all languages listed above. A subset of those languages are translatable and are listed below. Any two languages from the following list can be translated. To test if a language is translatable, utilize google.language.isTranslatable(languageCode);

  • Afrikaans
  • Albanian
  • Arabic
  • Belarusian
  • Bulgarian
  • Chinese (Simplified and Traditional)
  • Catalan
  • Croatian
  • Czech
  • Danish
  • Dutch
  • English
  • Estonian
  • Filipino
  • Finnish
  • French
  • Galician
  • German
  • Greek
  • Hebrew
  • Hindi
  • Hungarian
  • Icelandic
  • Indonesian
  • Irish
  • Italian
  • Japanese
  • Korean
  • Latvian
  • Lithuanian
  • Macedonian
  • Malay
  • Maltese
  • Norwegian
  • Persian
  • Polish
  • Portuguese
  • Romanian
  • Russian
  • Spanish
  • Serbian
  • Slovak
  • Slovenian
  • Swahili
  • Swedish
  • Thai
  • Turkish
  • Ukrainian
  • Vietnamese
  • Welsh
  • Yiddish

Flash and other Non-Javascript Environments

For Flash developers, and those developers that have a need to access the AJAX Language API from other Non-JavaScript environments, the API exposes a simple RESTful interface. In all cases, the method supported is GET, and the response format is a JSON encoded result with embedded status codes. Forgoogle.language.translate, the POST method is available. Applications that use this interface must abide by all existing terms of use. An area to pay special attention to relates to correctly identifying yourself in your requests. Applications MUST always include a valid and accurate http referer header in their requests. In addition, we ask, but not require, that each request contains a valid API Key. By providing a key, your application provides us with a secondary identification mechanism that is useful should we need to contact you in order to correct any problems.

Developers are also encouraged to make use of the userip parameter to supply the IP address of the end-user on whose behalf you are making the API request. Doing so will help distinguish this legitimate server-side traffic from traffic which doesn't come from an end-user.

The easiest way to start learning about this interface is to try it out. Using the command line tool curl or wget execute the following command:

curl -e http://www.my-ajax-site.com \         'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20world&langpair=en%7Cit' 

This command performs a Language Translation(/ajax/services/language/translate), for Hello World (q=hello%20world) from English to Italian (langpair=en%7Cit). The response has a Content-Type of text/javascript; charset=utf-8. You can see from the response below that theresponseData is identical to the properties described in the Result Objects documentation.

{"responseData": {

"translatedText":"Ciao mondo"
},
"responseDetails": null, "responseStatus": 200}

In addition to this response format, the protocol also supports a classic JSON-P style callback which is triggered by specifying a callback argument. When this argument is present the JSON object is delivered as an argument to the specified callback.

callbackFunction(

{"responseData": {
"translatedText":"Ciao mondo"
},
"responseDetails": null, "responseStatus": 200})

And finally, the protocol supports callback and context arguments. When these URL arguments are specified, the response is encoded as a direct JavaScript call with a signature of: callback(context, result, status, details, unused). Note the slight difference in the following command and response.

curl -e http://www.my-ajax-site.com \   'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20world&langpair=en%7Cit&callback=foo&context=bar' 

This command performs a Language Translate and is identical to the previous call, BUT has been altered to pass both callback and context. With these arguments in place, instead of a JSON object being returned, a JavaScript call is returned in the response and the JSON object is passed using the resultparameter.

foo('bar', {"translatedText":"Ciao mondo"}, 200, null)

Code Snippets

The AJAX Search API documentation includes a small collection of code snippets that demonstrate access to the service from Flash, Java, and Php. The language specific part of this is uniform across all of the AJAX APIs so instead of repeating the snippets, please view via this link.

For complete documentation on this interface, please visit the class reference manual.

Troubleshooting

If you encounter problems with your code:

  • Look for typos. Remember that JavaScript is a case-sensitive language.
  • Use a JavaScript debugger. In Firefox, you can use the JavaScript console or the FireBug extension. In IE, you can use the Microsoft Script Debugger.
  • Search the AJAX APIs discussion group. If you can't find a post that answers your question, post your question to the group along with a link to a web page that demonstrates the problem.

AJAX Language API for Transliteration

With the AJAX Language API for Transliteration, you can enable transliteration on any editable element on your web page. This helps your users type in any language using an English keyboard.

What is transliteration? Transliteration is the process of phonetically converting a word written in one script into another. Transliteration should not be confused with translation, which involves a change in language while preserving meaning. With transliteration, it is the sound of the words that are converted from one alphabet to the other.

Table of Contents

Audience

This documentation is designed for people familiar with JavaScript programming and object-oriented programming concepts. There are many JavaScript tutorialsavailable on the Web. You should also be familiar with transliteration from a user's point of view. See the Indic transliteration or Arabic transliteration pages for how to use transliteration. Please see this article for more details.

This conceptual documentation is not complete and exhaustive; it is designed to let you quickly start exploring and embedding transliteration in your page.

Introduction

The "Hello, World" of the Google AJAX Language API for Transliteration

The easiest way to start learning about this API is to see a simple example. The following example enables transliteration in a textarea with language as Hindi, so that users can type in Hindi using an English keyboard. The user can also switch between typing English and Hindi using 'ctrl+g' as a shortcut. For information on selecting a different language, see the API class reference.




http-equiv="Content-Type" content="text/html; charset=utf-8"/>
type="text/javascript" src="http://www.google.com/jsapi">

type="text/javascript">

// Load the Google Transliteration API
google
.load("elements", "1", {
packages
: "transliteration"
});

function onLoad() {
var options = {
sourceLanguage
:
google
.elements.transliteration.LanguageCode.ENGLISH,
destinationLanguage
:
[google.elements.transliteration.LanguageCode.HINDI],
shortcutKey
: 'ctrl+g',
transliterationEnabled
: true
};

// Create an instance on TransliterationControl with the required
// options.
var control =
new google.elements.transliteration.TransliterationControl(options);

// Enable transliteration in the textbox with id
// 'transliterateTextarea'.
control
.makeTransliteratable(['transliterateTextarea']);
}
google
.setOnLoadCallback(onLoad);



Type in Hindi (Press Ctrl+g to toggle between English and Hindi)


id="transliterateTextarea" style="width:600px;height:200px">

View example in Code Playground

Including the Transliteration API on Your Page

AJAX Transliteration API is packaged under the "elements" module. To include the Google Transliteration API in your page, first you need the Google AJAX APIs script tag:

 type="text/javascript" src="http://www.google.com/jsapi">

This script tag will load the google.load function, which lets you load the individual Google APIs. For loading Google Transliteration API, calls to google.loadlook like this:

 type="text/javascript">

google
.load("elements", "1", {
packages
: "transliteration"
});

This loads Version 1 of the Transliteration API. Currently the Transliteration API is in Version 1, but new versions might be available in the future. See the versioning discussion below for more information.

API Updates

The second argument to google.load is the version of the AJAX Language API you are using. Currently the Transliteration API is in version 1, but new versions might be available in the future.

If a significant update to the API is done in the future, the version number will be changed and a notice posted on Google Code and the AJAX APIs discussion group. When that happens, support both versions is expected for at least a month in order to allow you to migrate your code.

The AJAX Language API team periodically updates the API with the most recent bug fixes and performance enhancements. These bug fixes should only improve performance and fix bugs, but might inadvertently break some API clients. Please use the AJAX APIs discussion group to report such issues.

Examples

Transliteration in Rich Text Editors

Transliteration can be used for editors which support rich text editing such as an editable Div or IFrame or an editable field created using the Closure library or Yahoo! UI Library.




http-equiv="Content-Type" content="text/html; charset=utf-8"/>
type="text/javascript" src="http://www.google.com/jsapi">
</span><span class="pln" style="color: rgb(0, 0, 0); ">Transliteration in Rich Text Editor</span><span class="tag" style="color: rgb(0, 0, 136); ">
type="text/javascript">

// Load the Google Transliteration API
google
.load("elements", "1", {
packages
: "transliteration"
});

function onLoad() {
var options = {
sourceLanguage
:
google
.elements.transliteration.LanguageCode.ENGLISH,
destinationLanguage
:
[google.elements.transliteration.LanguageCode.HINDI],
shortcutKey
: 'ctrl+g',
transliterationEnabled
: true
};

// Create an instance on TransliterationControl with the required
// options.
var control =
new google.elements.transliteration.TransliterationControl(options);

// Enable transliteration in the editable DIV with id
// 'transliterateDiv'.
control
.makeTransliteratable(['transliterateDiv']);
}
google
.setOnLoadCallback(onLoad);



Type in Hindi (Press Ctrl+g to toggle between English and Hindi)


id="transliterateDiv" contenteditable="true" style="width:600px;height:200px;border:1px solid;overflow-y:scroll">


View example (richedittransliteration.html)

An example of transliteration integrated into Closure Library's Rich Text Editor can be found here.

Transliteration Control with Single Language

This example is very similar to the basic example shown in the Introduction section, but it displays a control for switching between English and Hindi typing modes. It also enables transliteration in two textfields.




http-equiv="Content-Type" content="text/html; charset=utf-8"/>
type="text/javascript" src="http://www.google.com/jsapi">

type="text/javascript">

// Load the Google Transliteration API
google
.load("elements", "1", {
packages
: "transliteration"
});

function onLoad() {
var options = {
sourceLanguage
: 'en', // or google.elements.transliteration.LanguageCode.ENGLISH,
destinationLanguage
: ['hi'], // or [google.elements.transliteration.LanguageCode.HINDI],
shortcutKey
: 'ctrl+g',
transliterationEnabled
: true
};
// Create an instance on TransliterationControl with the required
// options.
var control =
new google.elements.transliteration.TransliterationControl(options);

// Enable transliteration in the textfields with the given ids.
var ids = [ "transl1", "transl2" ];
control
.makeTransliteratable(ids);

// Show the transliteration control which can be used to toggle between
// English and Hindi.
control
.showControl('translControl');
}
google
.setOnLoadCallback(onLoad);



Type in Hindi (Press Ctrl+g to toggle between English and Hindi)

id='translControl'>


Title : type='textbox' id="transl1"/>

Body
id="transl2" style="width:600px;height:200px">

View example (singlelangtransliteration.html)

Transliteration Control with Multiple Languages

This example is very similar to the above example, but displays a control in which the destination language can be chosen. In this example, the destinationLanguageoption is used to specify the initial value of the destination language and also list the languages to be supported on the page. For example, if you were interested in having the default destination language on your page be Telugu and also in having Tamil and Malayalam as options in the language dropdown menu, you could specifydestinationLanguage as ['te', 'ta', 'ml'].




http-equiv="Content-Type" content="text/html; charset=utf-8"/>
type="text/javascript" src="http://www.google.com/jsapi">

type="text/javascript">

// Load the Google Transliteration API
google
.load("elements", "1", {
packages
: "transliteration"
});

function onLoad() {
var options = {
sourceLanguage
: 'en',
destinationLanguage
: ['hi','kn','ml','ta','te'],
shortcutKey
: 'ctrl+g',
transliterationEnabled
: true
};

// Create an instance on TransliterationControl with the required
// options.
var control =
new google.elements.transliteration.TransliterationControl(options);

// Enable transliteration in the textfields with the given ids.
var ids = [ "transl1", "transl2" ];
control
.makeTransliteratable(ids);

// Show the transliteration control which can be used to toggle between
// English and Hindi and also choose other destination language.
control
.showControl('translControl');
}
google
.setOnLoadCallback(onLoad);




Type in Indian languages (Press Ctrl+g to toggle between English and Hindi)

id='translControl'>


Title : type='textbox' id="transl1"/>

Body
id="transl2" style="width:600px;height:200px">

View example (multilangtransliteration.html)

Transliteration with Custom Control

This is an advanced example which shows how to create your own custom control to control the transliteration. It uses a checkbox for toggling between English and Hindi typing modes and a dropdown to change the destination language. It also registers event handlers for various events that can be raised by the TransliterationControl. See the API class reference for details on the possible events.




http-equiv="Content-Type" content="text/html; charset=utf-8"/>
type="text/javascript" src="http://www.google.com/jsapi">

type="text/javascript">

// Load the Google Transliteration API
google
.load("elements", "1", {
packages
: "transliteration"
});

var transliterationControl;
function onLoad() {
var options = {
sourceLanguage
: 'en',
destinationLanguage
: ['ar','hi','kn','ml','ta','te'],
transliterationEnabled
: true,
shortcutKey
: 'ctrl+g'
};
// Create an instance on TransliterationControl with the required
// options.
transliterationControl
=
new google.elements.transliteration.TransliterationControl(options);

// Enable transliteration in the textfields with the given ids.
var ids = [ "transl1", "transl2" ];
transliterationControl
.makeTransliteratable(ids);

// Add the STATE_CHANGED event handler to correcly maintain the state
// of the checkbox.
transliterationControl
.addEventListener(
google
.elements.transliteration.TransliterationControl.EventType.STATE_CHANGED,
transliterateStateChangeHandler
);

// Add the SERVER_UNREACHABLE event handler to display an error message
// if unable to reach the server.
transliterationControl
.addEventListener(
google
.elements.transliteration.TransliterationControl.EventType.SERVER_UNREACHABLE,
serverUnreachableHandler
);

// Add the SERVER_REACHABLE event handler to remove the error message
// once the server becomes reachable.
transliterationControl
.addEventListener(
google
.elements.transliteration.TransliterationControl.EventType.SERVER_REACHABLE,
serverReachableHandler
);

// Set the checkbox to the correct state.
document
.getElementById('checkboxId').checked =
transliterationControl
.isTransliterationEnabled();

// Populate the language dropdown
var destinationLanguage =
transliterationControl
.getLanguagePair().destinationLanguage;
var languageSelect = document.getElementById('languageDropDown');
var supportedDestinationLanguages =
google
.elements.transliteration.getDestinationLanguages(
google
.elements.transliteration.LanguageCode.ENGLISH);
for (var lang in supportedDestinationLanguages) {
var opt = document.createElement('option');
opt
.text = lang;
opt
.value = supportedDestinationLanguages[lang];
if (destinationLanguage == opt.value) {
opt
.selected = true;
}
try {
languageSelect
.add(opt, null);
} catch (ex) {
languageSelect
.add(opt);
}
}
}

// Handler for STATE_CHANGED event which makes sure checkbox status
// reflects the transliteration enabled or disabled status.
function transliterateStateChangeHandler(e) {
document
.getElementById('checkboxId').checked = e.transliterationEnabled;
}

// Handler for checkbox's click event. Calls toggleTransliteration to toggle
// the transliteration state.
function checkboxClickHandler() {
transliterationControl
.toggleTransliteration();
}

// Handler for dropdown option change event. Calls setLanguagePair to
// set the new language.
function languageChangeHandler() {
var dropdown = document.getElementById('languageDropDown');
transliterationControl
.setLanguagePair(
google
.elements.transliteration.LanguageCode.ENGLISH,
dropdown
.options[dropdown.selectedIndex].value);
}

// SERVER_UNREACHABLE event handler which displays the error message.
function serverUnreachableHandler(e) {
document
.getElementById("errorDiv").innerHTML =
"Transliteration Server unreachable";
}

// SERVER_UNREACHABLE event handler which clears the error message.
function serverReachableHandler(e) {
document
.getElementById("errorDiv").innerHTML = "";
}
google
.setOnLoadCallback(onLoad);




Type in Indian languages (Press Ctrl+g to toggle between English and Hindi)

id='translControl'>
type="checkbox" id="checkboxId" onclick="javascript:checkboxClickHandler()">
Type in
id="languageDropDown" onchange="javascript:languageChangeHandler()">


Title : type='textbox' id="transl1"/>

Body
id="transl2" style="width:600px;height:200px">

id="errorDiv">


View example (customtransliteration.html)

Transliteration Using the Low-Level API

The low-level API for transliteration uses the AJAX Language API (and not the elements package that is used by the rest of the transliteration APIs). To include the AJAX Language API in your page, utilize the Google AJAX API loader and follow the instructions specified here.

This example shows a simple transliteration of a JavaScript string:

google.language.transliterate(["Namaste"], "en", "hi", function(result) {

if (!result.error) {
var container = document.getElementById("transliteration");
if (result.transliterations && result.transliterations.length > 0 &&
result
.transliterations[0].transliteratedWords.length > 0) {
container
.innerHTML = result.transliterations[0].transliteratedWords[0];
}
}
});

View example (transliterate.html)

API Details

Supported Languages

The Transliteration API currently supports transliteration from the English version of the Latin alphabet to the scripts of the following languages:

  • AmharicNew!
  • Arabic
  • Bengali
  • GreekNew!
  • Gujarati
  • Hindi
  • Kannada
  • Malayalam
  • Marathi
  • Nepali
  • Persian
  • Punjabi
  • RussianNew!
  • SanskritNew!
  • SerbianNew!
  • Tamil
  • Telugu
  • TigrinyaNew!
  • Urdu

Customizing the visible components

The transliteration control that is displayed using the showControl method can be styled to blend into your web page by extending the CSS classes defined in the default CSS file. The default CSS file is loaded automatically on the google.load() call, and it defines the styles for the control and the transliteration suggestions menu that pops out when you click or edit a transliterated word. If you do not want to load the default CSS, set "nocss" to true.

google.load("elements", "1", {packages: "transliteration", "nocss" : true});

The language selection menu, the button indicating the language selected by the user and the suggestion menu are enclosed in div elements marked with specific CSS classes. You can define overriding CSS rules that are applied to these elements in order to style them according to your page. Please refer to this documented transliteration CSS file for details of the default CSS loaded with the transliteration API package. The following is a listing of CSS classes that are useful for customization:

  • goog-transliterate-indic-language-menu and goog-transliterate-indic-language-menu-highlight are used in the language selection menu.
  • goog-transliterate-indic-suggestion-menu and goog-transliterate-indic-suggestion-menu-highlight are used in the suggestion menu that shows up for correcting transliterations.
  • goog-transliterate-indic-button and goog-transliterate-indic-button-checked are used in the button which indicates the language chosen by the user.

For example, defining goog-transliterate-indic-suggestion-menu's background-color parameter, allows the displayed suggestion menu's background to be changed from the default #F0A000 value to the new value.

Support for Right-to-Left Languages

For right-to-left writing systems like Arabic, the API, by default, automatically adjusts the direction of the textarea, according to the direction of the writing system being used and the content of the textarea. (The direction of a textarea is set in HTML and JavaScript with direction, which can have the value 'ltr' or 'rtl'. It affects the cursor and textarea alignment.)

View Arabic transliteration example (arabictransliteration.html)

Browser Compatibility

The Transliteration API is supported by Firefox 1.5 and higher on Windows and Linux, and Internet Explorer 6.0 and higher on Windows (preferably Windows XP). The Transliteration API can be loaded without errors in almost every browser, so you can safely load it before checking for compatibility.

Different applications sometimes require different behaviors for users with incompatible browsers. The Transliteration API provides a global methodgoogle.elements.transliteration.isBrowserCompatible() to check compatibility, but it does not have any automatic behavior when it detects an incompatible browser. Most of the examples in this document do not check for browser compatibility, nor do they display an error message for older browsers. Clearly, real applications should do something more friendly with incompatible browsers, but we have omitted such checks to make the examples more readable.

HTML Content Type

The Transliteration API handles a lot of UTF-8 text and hence it is necessary to set the content-type of your page to UTF-8 by adding this meta tag . Without this meta tag, the Transliteration API will not work properly in your web page.

Troubleshooting

If you encounter problems with your code:

  • Look for typos. Remember that JavaScript is a case-sensitive language.
  • Use a JavaScript debugger. In Firefox, you can use the JavaScript console or the FireBug extension. In IE, you can use the Microsoft Script Debugger.
  • Search the AJAX APIs discussion group. If you can't find a post that answers your question, post your question to the group along with a link to a web page that demonstrates the problem.

AJAX Language API for Virtual Keyboard

With the AJAX Language API for Virtual Keyboard, you can enable the onscreen keyboard on any textfield or textarea in your webpage. This will help your website users to type in any language using their familiar keyboard layouts.

What is a virtual keyboard? A virtual keyboard is used to translate the input from one keyboard layout to another.

  • It allows users to type their own languages on foreign keyboards, when they're traveling abroad, or living in a country where their language is not official, and the like.
  • For disabled users that cannot use a physical keyboard, onscreen keyboard provides an alternative way to type by mouse clicking.
  • Another major use for an on-screen keyboard is for bi- or multi-lingual users, who continually need to switch between different character sets and/or alphabets.

Table of Contents

Audience

This documentation is designed for people familiar with JavaScript programming and object-oriented programming concepts. There are many JavaScript tutorialsavailable on the Web.

This conceptual documentation is not complete and exhaustive; it is designed to let you quickly start exploring and embedding virtual keyboard in your page.

Introduction

The "Hello, World" of the Virtual Keyboard API

The easiest way to start learning about this API is to see a simple example. The following example enables Virtual Keyboard in a textarea with Russian keyboard layout, so that users can type in Russian by using an English physical keyboard or by using mouse. The user can also hide/show the virtual keyboard by clicking the +/- buttons on the onscreen keyboard. For information on selecting a different layout, see the API class reference




http-equiv="Content-Type" content="text/html; charset=utf-8"/>
type="text/javascript" src="http://www.google.com/jsapi">
type="text/javascript">

// Load the Google Onscreen Keyboard API
google
.load("elements", "1", {
packages
: "keyboard"
});

function onLoad() {
var kbd = new google.elements.keyboard.Keyboard(
[google.elements.keyboard.LayoutCode.RUSSIAN],
['t1']);
}

google
.setOnLoadCallback(onLoad);



Type in Russian


id="t1" style="width: 600px; height: 200px;">

You can play around with a similar example in the Code Playground.

Including the Virtual Keyboard API on Your Page

AJAX Virtual Keyboard API is packaged under the "elements" module. To include the Google Virtual Keyboard API in your page, first you need the Google AJAX APIs script tag:

 type="text/javascript" src="http://www.google.com/jsapi">

This script tag will load the google.load function, which lets you load the individual Google APIs. For loading Google Virtual Keyboard API, calls to google.loadlook like this:

 type="text/javascript">

google
.load("elements", "1", {
packages
: "keyboard"
});

This loads Version 1 of the Virtual Keyboard API. Currently the Virtual Keyboard API is in Version 1, but new versions might be available in the future. See theversioning discussion below for more information.

API Updates

The second argument to google.load is the version of the AJAX Language API you are using. Currently, the Virtual Keyboard API is in version 1, but new versions might be available in the future.

If a significant update to the API is done in the future, the version number will be updated and a notice posted on Google Code and the AJAX APIs discussion group. When that happens, support for both versions is expected for at least a month in order to allow you to migrate your code.

The AJAX Language API team periodically updates the API with the most recent bug fixes and performance enhancements. These bug fixes should only improve performance and fix bugs, but may inadvertently break some API clients. Use the AJAX APIs discussion group to report such issues.

Examples

Show/Hide Keyboard

The following example shows how to hide or show the keyboard in your code. When a virtual keyboard is hidden, the user types using the physical keyboard layout.




http-equiv="Content-Type" content="text/html; charset=utf-8"/>
type="text/javascript" src="http://www.google.com/jsapi">
type="text/javascript">

// Load the Google Onscreen Keyboard API
google
.load("elements", "1", {
packages
: "keyboard"
});

var kbd; // A Keyboard object.

function onLoad() {
// Create an instance on Keyboard.
kbd
= new google.elements.keyboard.Keyboard([
google
.elements.keyboard.LayoutCode.POLISH],
['t1']);
}

// If the keyboard is visible, hide it.
// If the keyboard is invisible, show it.
function toggleVisible() {
var button = document.getElementById("btVisible");
if (kbd.isVisible()) {
kbd
.setVisible(false);
document
.getElementById('btVisible').value = "Show";
} else {
kbd
.setVisible(true);
document
.getElementById('btVisible').value = "Hide";
}
}

google
.setOnLoadCallback(onLoad);



This is a demo for setVisible/isVisible.


type="button" onclick="toggleVisible()" id="btVisible" value="Hide">

type="text" id="t1" style="width: 600px; height: 200px;">

You can play around with a similar example in the Code Playground.

Switch Keyboard Layout

The following example is similar to the basic example shown in the Introduction section, but it shows how to switch layout for a virtual keyboard in your code:




http-equiv="Content-Type" content="text/html; charset=utf-8"/>
type="text/javascript" src="http://www.google.com/jsapi">
type="text/javascript">

// Load the Google Onscreen Keyboard API
google
.load("elements", "1", {
packages
: "keyboard"
});

var kbd; // A Keyboard object.

function onLoad() {
// Create an instance on Keyboard.
kbd
= new google.elements.keyboard.Keyboard([
google
.elements.keyboard.LayoutCode.RUSSIAN],
['t1']);
}

google
.setOnLoadCallback(onLoad);



This is a demo for setLayout/getLayout.


type="text/javascript">

type="button" onclick="kbd.setLayout('ru')" value="Russian" />

type="button" onclick="kbd.setLayout('hi')" value="Hindi" />

type="button" onclick="kbd.setLayout('th')" value="Thai" />

type="button" onclick="kbd.setLayout('ar')" value="Arabic" />

type="button" onclick="kbd.setLayout('pl')" value="Polish" />

type="button" onclick="kbd.setLayout('fa')" value="Persian" />

type="text" id="t1" style="width: 600px">

You can play around with a similar example in the Code Playground.

Render Keyboard Menu

The following example enumerates the supported keyboard layouts, and draws a layout menu on the page:




http-equiv="Content-Type" content="text/html; charset=utf-8"/>
type="text/javascript" src="http://www.google.com/jsapi">
type="text/javascript">

// Load the Google Onscreen Keyboard API
google
.load("elements", "1", {
packages
: "keyboard"
});

var kbd; // A Keyboard object.

// Draw a list of keyboard layouts in their native languages.
// User can click any of them to switch to that keyboard layout.
function drawMenu() {
html
= ["
    "];
    for (var i in google.elements.keyboard.LayoutCode) {
    var code = google.elements.keyboard.LayoutCode[i];
    var name = google.elements.keyboard.getLayoutName(code);
    html
    .push("
  • , code, "\")'>",
    name
    , "
  • "
    );
    }
    html
    .push("
"
);
document
.getElementById("menu").innerHTML = html.join('');
}

function onLoad() {
kbd
= new google.elements.keyboard.Keyboard(
[google.elements.keyboard.LayoutCode.RUSSIAN],
['t1']);

drawMenu
();
}

google
.setOnLoadCallback(onLoad);



This is a demo for LayoutCode and getLayoutName.


id="menu">


id="t1" style="width: 600px; height: 200px;">

Two Groups of Keyboard settings

The following example is similar to the basic example shown in the Introduction section. But it has two Keyboard objects to control two groups of text fields each. There are four text fields on the page. Two of them use a Thai virtual keyboard and the other two use an Arabic virtual keyboard.




http-equiv="Content-Type" content="text/html; charset=utf-8"/>
type="text/javascript" src="http://www.google.com/jsapi">
type="text/javascript">

// Load the Google Onscreen Keyboard API
google
.load("elements", "1", {
packages
: "keyboard"
});

function onLoad() {
var kbd1 = new google.elements.keyboard.Keyboard(
[google.elements.keyboard.LayoutCode.THAI],
['th1', 'th2']);

var kbd2 = new google.elements.keyboard.Keyboard(
[google.elements.keyboard.LayoutCode.ARABIC],
['ar1', 'ar2']);
}

google
.setOnLoadCallback(onLoad);



Type in Thai and Arabic


id="th1" style="width: 300px; height: 80px;">
id="ar1" style="width: 300px; height: 80px;">
id="th2" style="width: 300px; height: 80px;">
id="ar2" style="width: 300px; height: 80px;">

You can play around with a similar example in the Code Playground.

API Details

Supported Layouts

The Virtual Keyboard API currently supports the following keyboard layouts:

  • Albanian
  • Arabic
  • Armenian - Eastern
  • Armenian - Western
  • Basque
  • Belarusian
  • Bengali - PhoneticNew!
  • Bosnian
  • Brazilian PortugueseNew!
  • Bulgarian
  • Catalan
  • Croatian
  • Czech
  • Czech - QWERTZ
  • DanishNew!
  • DutchNew!
  • Devanagari - PhoneticNew!
  • English
  • EstonianNew!
  • EthiopicNew!
  • Finnish
  • FrenchNew!
  • Galician
  • Georgian - QWERTY
  • Georgian - Typewriter
  • German
  • Greek
  • Gujarati - PhoneticNew!
  • Gurmukhi - PhoneticNew!
  • Hebrew
  • Hindi
  • Hungarian - 101
  • IcelandicNew!
  • ItalianNew!
  • Kannada - PhoneticNew!
  • Kazakh
  • Kyrgyz
  • LithuanianNew!
  • LatvianNew!
  • Macedonian
  • Malayalam - PhoneticNew!
  • MalteseNew!
  • Mongolian - Cyrillic
  • Montenegrin
  • NorwegianNew!
  • Oriya - PhoneticNew!
  • Persian
  • Polish
  • Romani
  • RomanianNew!
  • Russian
  • Sanskrit - PhoneticNew!
  • Serbian - Cyrillic
  • Serbian - Latin
  • Slovak
  • Slovak - QWERTY
  • Slovenian
  • Spanish
  • SwedishNew!
  • Tamil - PhoneticNew!
  • TatarNew!
  • Telugu - PhoneticNew!
  • Thai
  • Turkish - F
  • Turkish - Q
  • Ukrainian - 101
  • Uzbek - Latin
  • Uzbek - Cyrillic PhoneticNew!
  • Uzbek - Cyrillic TypewritterNew!

We plan to gradually release more keyboard layouts in the near future. Stay tuned and come back to check this document for up-to-date information.

Browser Compatibility

The Virtual Keyboard API is supported by Firefox 3 and higher on Windows and Linux, and Internet Explorer 6.0 and higher on Windows (preferably Windows XP). The Virtual Keyboard API can be loaded without errors in almost every browser, so you can safely load it before checking for compatibility.

Troubleshooting

If you encounter problems with your code:

  • Look for typos. Remember that JavaScript is a case-sensitive language.
  • Use a JavaScript debugger. In Firefox, you can use the JavaScript console or the FireBug extension. In IE, you can use the Microsoft Script Debugger.
  • Search the AJAX APIs discussion group. If you can't find a post that answers your question, post your question to the group along with a link to a web page that demonstrates the problem.

5 comments:

  1. Thank you for an additional great post. Exactly where else could anybody get that kind of facts in this kind of a ideal way of writing? I have a presentation next week, and I’m around the appear for this kind of data.
    python Training institute in Pune
    python Training institute in Chennai
    python Training institute in Bangalore

    ReplyDelete
  2. Thanks for sharing valuable information, keep us posted more. wanted to learn more about other language then visit: Python Training in Nanded
    Best IT Training Provider

    ReplyDelete
  3. The blog is really very informative and useful.
    Click here">Java course in Pune

    ReplyDelete

Newer Post Older Post Home

Blog Archive