Sunday, April 7, 2013

Using Google Geocoding API-v3 to extract latitude/longitude values of an address in C#.NET

Geocoding is the process of converting addresses into geographic coordinates (latitudes and longitudes). These coordinates  can be  used to place markers on a map. The Google Geocoding API is a direct way to access these services via an HTTP (HTTPS is recommended if you are dealing with sensitive data) request. This HTTP request must be of the following form:

"http://maps.googleapis.com/maps/api/geocode/output?parameters"



Output may be either json or xml (In Google Geocoding v2 they allowed csv also, but they have removed it in v3). Required parameters are 'address' (address that you want to geocode) and 'sensor' (indicates whether or not the request comes from a device with a location sensor).

XML output:





I wrote a simple code to send a API Request and retrieve the XML file and parse it and get the latitude/longitude values. The Send backed XML contains two important elements. 


1.) <status> - describe the status of the result-whether it's success or not.

2.) <result> - contains informations of the address including latitude/longitude values.

c# code:


string location = "1600+Amphitheatre+Parkway,+Mountain+View,+CA";
float[] position =new float[2];
position = getLatLongForAddress(location);
System.Diagnostics.Debug.Write("Lattitude:"+position[0]+"Location:"+position[1]);

public float[] GetLatLongForAddress(string location)
{

  string result = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=true", location);
            

  var doc = XDocument.Load(result);
  string status = doc.Element("GeocodeResponse").Element("status").Value;

  //no errors occurred; the address was successfully parsed and at least one            
    geocode was returned.   
             
      if(status.Equals("OK"))
      {
         var point = doc.Element("GeocodeResponse").Element("result").
Element("geometry").Element("location");

         string lat = point.Element("lat").Value;
         string lng = point.Element("lng").Value;
         latLong[0] = (float)Convert.ToDouble(lat);
         latLong[1] = (float)Convert.ToDouble(lng);
                 
         }
         else if (status.Equals("ZERO_RESULTS")) 
         {
            //geocode was successful but returned no results
             throw new ApplicationException("No maps found for this address");
            
         }
         else if (status.Equals("REQUEST_DENIED")) 
         {
            //request was denied
            throw new ApplicationException("Request Denied");
            
         }
         else if (status.Equals("INVALID_REQUEST")) 
         {
             //address is missing
             throw new ApplicationException("Address not found");
         }
         else if (status.Equals("UNKNOWN_ERROR")) 
         {
             //the request could not be processed due to a server error
     //throw new ApplicationException("Unknown Error. Try agian.");
      GetLatLongForAddress(location);
         }       

    return latLong;
}


Similarly you can get the json output and get the latitude/longitude values.

If you wan't learn more details about Google Geocoding API, have a peek at their documentation.

"https://developers.google.com/maps/documentation/geocoding"

Sunday, March 11, 2012

Detecting and refactoring bad smells in code using JDeodorant plugin for Eclipse


I came across this tool when I was doing an assignment for my final year subject -Advanced Software Architecture and Design.

So what are bad smells in code?
Bad smells are warning signs in your own code that possibly indicates a deeper design problem. You can find a detail description about different types of bad smells and how to re-factor them in here.

JDeodorant
JDeodorant is an Eclipse plugin that identifies bad smells, and resolves them by applying appropriate refactorings.JDeodorant only detects four types of bad smells.They are,
  1. God Class
  2. Long method
  3. Type checking
  4. Feature Envy
Installing JDeodorant plugin in Eclipse
Download JDeodorant Eclipse plugin  and extract its contents into Eclipse  plugins directory. Then close the Eclipse IDE and open it again. Now you can see a menu item named 'Bad Smells' appear in the menu bar. Also you can install the plugin through JDeodorant Update site by using Eclipse Install New Software feature (Help-->Install New Software).

Procedure of detecting bad smells
As an example, first I am going to show you how to identify a God class and how re-factor it by the means of extracting. 

Step 1 -
First of all, select god class from Bad smell menu item. A view will pop up along side with the console view.


Step 2 -
Select the project or the package in the project in which you want to find out the God classes and then click the identification button in the god class view.Then three progress bar windows will appear. After parsing java objects and identifying extract class re-factoring opportunities, God Class view table will be populated.The results will be grouped by source classes. 

Step 3 -
When you click on the results, it will expand and show you extract opportunities. Double click on a row will show you the suggestive re-factoring  in the respective class.


Step 4 -
If you want to apply suggestive re-factoring, then click “Apply Refactoring” button in the God Class view. An input window will pop out. Then give a name to the extract class in the input field and click preview button. Here you can see all the suggestive changes that are going to be introduced in the code and a comparison between the original and the re-factored source class files.


Step 5 -
Choose what ever changes you want apply and click OK. The new extracted class will open in the editor. If you don't want to keep the changes, select Undo Extract Class from the Edit Menu item. It will undo all the changes in the code.

Identifying other bad smells also similar to this process. Now you know the basics,  I am sure you can figure it out by your own. Anyway if you encounter any problems in dealing with them, following links might come handy.

Finally I hope this will be helpful if you ever need to identify bad smells in your code.There are quite few other bad smell detectors available in the Internet. You can check out them.  

Important: In large projects (20 MB or large) JDeodorant may throw Heap size OutOfMemoryError. This can be solved by setting up VM Arguments in the eclipse.ini file (configuration file) with the following parameters:
-vmargs
-Xms128m
-Xmx1024m
-XX:PermSize=128m

And if you ever encounter a StackOverflow error try turning off the system paging file and start detecting again.