Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Google Translator API v2 Implementation

0.00/5 (No votes)
25 Dec 2011 1  
This is a very simple implementation of Google Translator API v2 implementation. It is a simple HTML file and makes use of jQuery for client side operations.

Introduction

These days, Google is busy in shutting down their free goodies/services that were available. Language Translation service is one among them which was shut down completely from Dec 01, 2011. Now Google has come up with Translation API V2 which is a paid version of Translation Service. Many apps which were dependent on the free version of service have been affected and some have opted for the paid version as some are in the process of shifting the providers. There’s one freebie from Microsoft too Bing Translation APIs. Anyways, I won’t be getting into Bing here but rather concentrate on the Google Language Translator API v2.

Background

This is a very simple and easy to understand implementation of API which is built on simple HTML page and makes use of jQuery to get much of the client side related activities done.

Note: Before I continue, I would like to stress that this article makes an assumption that you have a valid Google API v2. This video provides all the guidance required to get a Google API key.

Using the Code

To make it simple, I have segmented the article content into 3 portions:

Supported Languages – This portion would concentrate on listing the languages which are supported by Google Translator.

The API provides the list of codes for the supported languages but by default doesn’t provide the name of the languages. In case of requirement of the language name, we can pass in additional parameter Target and specify the language code in which we want the language name to be provided in. For e.g., if we specify the code as ‘zh-CN’ it would provide the language names in ‘Chinese Simplified’ and if it's ‘en’ it would list out the names in ‘English’.

Code functionality for loading all the supported Languages by Google API 
function loadLanguages() {
   var apiurl = "https://www.googleapis.com/language/translate/v2/languages?key=" + 
    apiKey<span class="Apple-tab-span" style="white-space: pre; ">        
    </span> + "&target=en";

            $.ajax({
                url: apiurl,
                dataType: 'jsonp',
                success: function (data) {
                    var languages = data.data.languages;
                    $.each(languages, function (index, language) {
                        $('#selSourceLanguage').append('<option value="' + 
            language.language + '">' + language.name + '</option>');
                        $('#selTargetLanguage').append('<option value="' + 
            language.language + '">' + language.name + '</option>');
                    });
                    $("select#selSourceLanguage").val('en');
                    $("select#selTargetLanguage").val('en');
                },
                error: function (x, e) {
                    alert('Error occurred while loading the Google Supported Languages');
                }
            });
 }

Detect Language – This portion would be concentrating on detecting the language of the text that’s been provided by the end user for translation. API would make use of its internal AI to identify the language and notify it to the end user. In case it's not possible, it would notify as Unknown.

Code functionality for auto detecting the language of the text to be translated 
function detectLanguage() {
   var text = $.trim($('#txtOrgText').val());
   if (text.length > 0) {
     var apiurl = "https://www.googleapis.com/language/translate/v2/detect?key=" + 
    apiKey <span class="Apple-tab-span" style="white-space: pre; ">    
    </span>+ "&q=";

       $.ajax({
          url: apiurl + encodeURIComponent(text),
          dataType: 'jsonp',
          async: false,
          success: function (data) {
                 var obj = data.data.detections[0];
                 $('#selSourceLanguage').val(obj[0].language);
                 langSource = obj[0].language;
                 $('#divDetectedLanguage').html("The automatically detected language is: 
        " <span class="Apple-tab-span" style="white-space: pre; ">            
        </span>+ $('#selSourceLanguage option:selected').text());
                 $.unblockUI();
          <span class="Apple-tab-span" style="white-space: pre; ">    </span>},
          error: function (x, e) {
                 $('#divDetectedLanguage').html
        ("Error occurred while detecting the current 
        <span class="Apple-tab-span" style="white-space: pre; ">            
        </span>text language");
                 $.unblockUI();
                }
              });
      }
      else {
         $('#divDetectedLanguage').html("No Text for Translation was provided");
         $.unblockUI();
      }
 }

Translation – This would be our ultimatum. Get the text translated into language (supported by Google API) as required.

Code functionality to translate the text 
 $('#btnTranslate').click(function (e) {
     e.preventDefault();

     var text = $.trim($('#txtOrgText').val());
     $('#divTranslated').html("");
     if (text.length > 0) {
         var langSource = $('#selSourceLanguage').val();
         var langTarget = $('#selTargetLanguage').val();

         if (langSource === "" || langTarget === "") {
             alert("Select Source Language and Target Language");
         }
         else if (langSource === langTarget) {
             alert("Source Language and Target Language cannot be same");
         }
         else {
              $.blockUI({ css: {
              border: 'none',
              padding: '15px',
              backgroundColor: '#000',
              '-webkit-border-radius': '10px',
              '-moz-border-radius': '10px',
              opacity: .5,
              color: '#fff'
             }
         });
     var apiurl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + 
    "                       &source=" + langSource + "&target=" + langTarget + "&q=";

     $.ajax({
        url: apiurl + encodeURIComponent(text),
        dataType: 'jsonp',
        async: false,
        success: function (data) {
        <span class="Apple-tab-span" style="white-space: pre; ">    
        </span> if (langSource === langTarget) {
                     $('#divTranslated').html(text);
                 }
                 else if (langSource != "") {
                  try {
                       $('#divTranslated').html(data.data.translations[0].translatedText);
                  }
                  catch (e) {
                       $('#divTranslated').html(text);
                  }
             }
             $('#divTranslated').css({ "border": "1px solid #7F9DB9" });
             $('#divTranslated').css({ "padding": "4 4 4 4" });

             $('#lblTranslation').css({ "color": "black" });
             $.unblockUI();
            },
           error: function (x, e) {
              alert('Error occurred while translating the text');
              $.unblockUI();
           }
         });
        }
      }
      else {
          alert("Nothing was entered to translate");
          $.unblockUI();
        }
     });
    $.unblockUI();
});

The process followed in this article implementation is very simple. UI for the implementation is self-explanatory. We have a text box where the end user can key in the text which he/she wishes to be translated. There are 2 drop downs which are pre-loaded with the list of languages supported for translation by Google API and 2 buttons which perform the action as indicated ‘Detect’ and ‘Translate’.

Once text is provided, the user can make use of the ‘Detect’ button and use the Google API service which tries to detect the language of the language and set the Detected Language as the Source Language. If in case Google Service is unable to detect the language, it would set the source language as Unknown. And at any point of time, the user can manually select the source language and the target language and use the ‘Translate’ option to get the translation done.

Points of Interest

This is a very basic implementation and can be improved upon.

History

You can find the implementation of Google Translator which used the earlier version of Google API here.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here