Ads

Wednesday, April 11, 2012

Google Geocode in Titanium Application

In my Titanium Application I have tried to use reverseGeocoder to find the current address (Street, City, State, Zip and Country) from the latitude and longitude.

But Ti reverseGeocoder does not return the exact address from the current latitude and longitude at all the time. It works only in few locations only.

So that I have move to Google Geocode API

Here is my sample code for how to use Google Geocode API in Titanium Application to get Street, City, State, Zip and Country value using latitude and longitude.

var addrUrl = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng="+latitude+","+longitude;
/* web-service call */
var addrReq = Titanium.Network.createHTTPClient();
addrReq.open("GET",addrUrl);
addrReq.send(null);
 
addrReq.onload = function()
{
    var response = JSON.parse(this.responseText);
 
    if(response.status == "OK"){
        var resLen = response.results[0].address_components.length;
        for(var i=0; i < resLen; i++) {
            switch (response.results[0].address_components[i].types[0])
            {
                case "street_number":
                    Ti.API.info("street number : "+response.results[0].address_components[i].long_name);
                    break;
                case "route":
                    Ti.API.info("street name : "+response.results[0].address_components[i].long_name);
                    break;
                case "locality":
                    Ti.API.info("city name : "+response.results[0].address_components[i].long_name);
                    break;
                case "administrative_area_level_1":
                    Ti.API.info("state name : "+response.results[0].address_components[i].long_name);
                    break;
                case "postal_code":
                    Ti.API.info("zip code : "+response.results[0].address_components[i].long_name);
                    break;
                case "country":
                    Ti.API.info("country name : "+response.results[0].address_components[i].long_name);
                    break;
                }
        }
    }else{
        showAlert('','Unable to find Address');
    }
 
};

3 comments:

  1. Hey, congratulations for your website! I was using kitchensink app to geolocation, is better to use your sample instead? And how can I test my GEolocation app in ios? Do I have to be a apple developer? May i use a jailbroken iphone? If yes, how? Thanks a lot!

    ReplyDelete
  2. This is fantastic, thank you so much!

    ReplyDelete