Sunday, May 23, 2010

WSO2 Mashup Server - Google Maps API Key Mashup

If you are using Google Maps in your web site, you need to get an API key from Google.com. In order to do that, you need to login using an existing Google account, accept their terms and policies and finally you will be able to get the Google Maps API key. Although this is the usual procedure, if they provide a web service for it, it will be much useful in places where you want to get the key at runtime.

As an example, WSO2 Mashup Server has a Twitter Maps Mashup which shows recent tweets in a Google map. In order to have the proper functionality of this mashup independent of the domain where the server is running, it needs to dynamically generate an API key for that domain and use it within the Twitter map mashup. That was the original motivation towards this mashup.

You will need to deploy the following mashup in the WSO2 Mashup Server 2.0.2 or a newer one.
getAPIKey.inputTypes = { "username" : "string", "password" : "string", "url" : "string" };
getAPIKey.output = "string";
function getAPIKey(username, password, url) {
    var client = new HttpClient();
    var code = client.executeMethod("GET", "https://www.google.com/accounts/Login");
    if (code == 200) {
        var galx = client.cookies[0].value;
        var content = [
            { name : "Email", value : username },
            { name : "Passwd", value : password },
            { name : "signIn", value : "Sign in" },
            { name : "GALX", value : String(galx) },
            { name : "dsh", value : "5537526595243201224"},
            { name : "rmShown", value : "1"},
            { name : "PersistentCookie", value : "yes"}
        ];
        code = client.executeMethod("POST", "https://www.google.com/accounts/LoginAuth", content);
        if (code == 302 || code == 200) {
            code = client.executeMethod("GET", "http://code.google.com/apis/maps/signup/createkey", [
                { name : "referer", value : url }
            ]);
            if (code == 200) {
                var response = eval('(' + client.response + ')');
                client.releaseConnection();
                return response.generated_key;
            } else {
                client.releaseConnection();
                return new XML("" + code + "" + client.statusText + "");
            }
        } else {
            client.releaseConnection();
            return new XML("" + code + "" + client.statusText + "");
        }
    } else {
        client.releaseConnection();
        return new XML("" + code + "" + client.statusText + "");
    }
}

1 comment: