Search code examples
javascriptgoogle-translatetranslate

Need Help on Google Translate API


I am working on a 1 requirement where i am giving set of words in english which will be in array format as a input and output will be corresponding element in Spanish and French

for example:

Input:

["One", "Two", "Three"]

Output:

["One", "french translate One "," Spanish translate One "]
["Two","french translate Two "," Spanish translate Two "]

How can we achieve this using google translate API using javascript. Please advise


Solution

  • According to the Google Cloud Translate API FAQ page, you can only set one target language. However, you can do a work around. By making a separate API call for each targeted language and placing the results in an array, you can make it work.

    Here is an example of a solution I came up with following the APIs documentation for Node JS:

    const Translate = require('@google-cloud/translate');
    
    // Your Google Cloud Platform project ID
    const projectId = 'YOUR_PROJECT_ID';
    
    // Instantiates a client
    const translate = new Translate({
      projectId: projectId,
    });
    
    //Targated languages
    var targets = ['fr','es'];
    var result = [];
    var word;
    
    //Recursive function
    var targetLanguage = function(x)
        {
            if(x < targets.length)
            {
               translate
              .translate(word, targets[x])
              .then(results => {
                const translation = results[0];
    
                result.push(`${translation}`);
    
                //Calling the function for the next target language. 
                targetLanguage(x+1);
              })
              .catch(err => {
                console.error('ERROR:', err);
              });
            }
            else
            {
                console.log(result);
                result = [];
            }
        }
    
    //Function that takes the word to be translated
    function translateWord(originalWord)
    {
        word = originalWord;
        result.push(word);
        targetLanguage(0);
    }
    
    //Calling the function
    translateWord("One");