How To Get GeoLocation Address By Using Google GeoLocation API In ASP.NET Web API

Now, we will create our Application. I hope, you will like this.

Background

Normally, we call Google Geolocation API, either from the Server side or from Client side, right? Today, we use the Server side. It is fully dynamic. We will use two tools, one is Postman and other one is Fiddler. Both are used to test Web API. This Google Geolocation API depends on latitude and longitude. Both will control our client. They will give the value.

Creating Database

The following query can be used to create a database in your SQL Server.

  1. CREATE DATABASE SalesTracking;  
The following query can be used to create a table in your SQL Server.
  1. CREATE TABLE [dbo].[crm_DailySalesTask](  
  2. [DailySalesTaskID] [bigintNOT NULL,  
  3. [UserID] [bigintNULL,  
  4. [BuyerName] [nvarchar](maxNULL,  
  5. [Description] [nvarchar](maxNULL,  
  6. [Achivement] [nvarchar](maxNULL,  
  7. [Latitude] [nvarchar](maxNULL,  
  8. [Longitude] [nvarchar](maxNULL,  
  9. [Address] [nvarchar](maxNULL,  
  10. [company_name] [nvarchar](maxNULL,  
  11. [CreateDate] [datetime] NULL,  
  12. CONSTRAINT [PK_crm_DailySalesTask] PRIMARY KEY CLUSTERED   
  13. (  
  14. [DailySalesTaskID] ASC  
  15. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  16. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  17. GO  
Creating web Application

Start Virtual Studio File>New>Project and click. New Project window will be shown on your monitor. Select Web and select ASP.NET Web Application (.NET Framework), give the name and click OK button. Again, a new Window will be shown on your monitor. From the following pop up, select Web API and click OK button once.

web Application

Figure: Web API Template with add folders and core references for MVC and Web API.

A project as MVC folder structure with core references will be created for you.

structure

Create Entity Data Model

Right click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the process, you can see the EDMX file and other files in your model folder. Here I gave SalesTrackingEntities for our Entity data model name. Now you can see a file with EDMX extension has been created.

Create ResponseModel Class

We will create ResponseModel class in Model folder. Actually, this class will be used for the return type. The code is given below:
  1. public class ResponseModel  
  2.   {  
  3.       public string Message { setget; }  
  4.       public bool Status { setget; }  
  5.       public object Data { setget; }  
  6.   }  
Create virtual class

We will create a virtual class in Model folder and the query is given bellow:
  1. public class vmTask  
  2.    {  
  3.        public Int64 UserID { getset; }  
  4.        public string BuyerName { getset; }  
  5.        public string Achivement { getset; }  
  6.        public string Latitude { getset; }  
  7.        public string Longitude { getset; }  
  8.        public string Address { getset; }          
  9.        public string Description { getset; }  
  10.    }  
Create API Controller

Right click on Controllers folder, add >controller, select Web API 2 Controller-Empty and give the name of the controller. Click OK once.
  1. public class TaskController : ApiController  
  2.     {  
  3.         SalesTrackingEntities _dbContext = null;  
  4.   
  5.         // constructor   
  6.         public TaskController()  
  7.         {  
  8.             _dbContext = new SalesTrackingEntities();  
  9.         }  
  10.         // for Task save  
  11.         [HttpPost]  
  12.         public ResponseModel SaveTask(vmTask _vmTask)  
  13.         {  
  14.             ResponseModel _modelObj = new ResponseModel;  
  15.             int result = SaveTaskDetails(_vmTask);  
  16.             if (result == 1)  
  17.             {  
  18.                 _modelObj.Status = true;  
  19.                 _modelObj.Message = "Task Saved";  
  20.             }  
  21.             else  
  22.             {  
  23.                 _modelObj.Status = false;  
  24.                 _modelObj.Message = "Task Saved faill";  
  25.             }  
  26.             return _modelObj;  
  27.         }  
  28.   
  29.         [HttpGet]  
  30.         // for get Task data by UserID  
  31.         public ResponseModel GetTaskList(Int64 userID)  
  32.         {  
  33.             ResponseModel _modelObj = new ResponseModel();  
  34.             List<vmTask> taskes = GetTaskDetails(userID);  
  35.             if (taskes.Count > 0)  
  36.             {  
  37.                 _modelObj.Data = taskes;  
  38.                 _modelObj.Status = true;  
  39.                 _modelObj.Message = "Data get successfully.";  
  40.             }  
  41.             else  
  42.             {  
  43.                 _modelObj.Data = taskes;  
  44.                 _modelObj.Status = false;  
  45.                 _modelObj.Message = "Data not found.";  
  46.             }  
  47.             return _modelObj;  
  48.         }  
  49.         private List<vmTask> GetTaskDetails(long userID)  
  50.         {  
  51.             List<vmTask> taskes = null;  
  52.             try  
  53.             {  
  54.                 taskes = (from ds in _dbContext.crm_DailySalesTask  
  55.                           where ds.UserID == userID  
  56.                           select new vmTask  
  57.                           {  
  58.                               UserID = ds.UserID ?? 0,  
  59.                               BuyerName = ds.BuyerName,  
  60.                               Achivement = ds.Achivement,  
  61.                               Description = ds.Description,  
  62.                               Address = ds.Address  
  63.                           }).ToList();  
  64.                 return taskes;  
  65.             }  
  66.             catch  
  67.             {  
  68.                 taskes = null;  
  69.   
  70.             }  
  71.             return taskes;  
  72.         }  
  73.         private int SaveTaskDetails(vmTask _vmTask)  
  74.         {  
  75.             crm_DailySalesTask _objSalesTask = new crm_DailySalesTask();  
  76.             int result = 0;  
  77.             string Address = "";  
  78.             try  
  79.             {   
  80.                  Int64 nextRow = _dbContext.crm_DailySalesTask.Count() + 1;  
  81.                 _objSalesTask.DailySalesTaskID = nextRow;               
  82.                 _objSalesTask.UserID = _vmTask.UserID;  
  83.                 _objSalesTask.BuyerName = _vmTask.BuyerName;  
  84.                 _objSalesTask.Description = _vmTask.Description;  
  85.                 _objSalesTask.Achivement = _vmTask.Achivement;  
  86.                 _objSalesTask.Latitude = _vmTask.Latitude;  
  87.                 _objSalesTask.Longitude = _vmTask.Longitude;  
  88.                 Address = GetAddress(_objSalesTask.Latitude, _objSalesTask.Longitude);  
  89.                 _objSalesTask.Address = Address;  
  90.                 _dbContext.crm_DailySalesTask.Add(_objSalesTask);  
  91.                 _dbContext.SaveChanges();  
  92.                 result = 1;  
  93.             }  
  94.             catch  
  95.             {  
  96.                 result = 0;  
  97.   
  98.             }  
  99.             return result;  
  100.         }  
  101.         // get Address  
  102.         private string GetAddress(string latitude, string longitude)  
  103.         {  
  104.             string locationName = "";  
  105.             string url = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false", latitude, longitude);  
  106.             XElement xml = XElement.Load(url);  
  107.             if (xml.Element("status").Value == "OK")  
  108.             {  
  109.                 locationName = string.Format("{0}",  
  110.                     xml.Element("result").Element("formatted_address").Value);  
  111.             }  
  112.             return locationName;  
  113.         }  
  114.     }  
We are going to demonstrate our TaskController. First of all I want to say that in this project, I do not use any repository pattern or any multi layer. I have done all the coding in TaskController.
  1. SalesTrackingEntities _dbContext = null
We have just pointed _dbContext instance.
  1. // constructor   
  2.        public TaskController()  
  3.        {  
  4.            _dbContext = new SalesTrackingEntities();  
  5.        }  
We have created instance of SalesTarackingEntities in TaskController constructor because it will access all the tables and use linq.
  1. // for Task save  
  2.        [HttpPost]  
  3.        public ResponseModel SaveTask(vmTask _vmTask)  
  4.        {  
  5.            ResponseModel _modelObj = new ResponseModel();  
  6.            int result = SaveTaskDetails(_vmTask);  
  7.            if (result == 1)  
  8.            {  
  9.                _modelObj.Status = true;  
  10.                _modelObj.Message = "Task Saved";  
  11.            }  
  12.            else  
  13.            {  
  14.                _modelObj.Status = false;  
  15.                _modelObj.Message = "Task Saved faill";  
  16.            }  
  17.            return _modelObj;  
  18.        }  
We use HttpPost for SaveTask method. We get vmTask object as a parameter from out world. When we will test this method, using Fiddler of Postman,  we will see, how to pass vmTask object. We call SaveTaskDetails method for saving. This method exists in TaskController.
  1. private int SaveTaskDetails(vmTask _vmTask)  
  2.     {  
  3.         crm_DailySalesTask _objSalesTask = new crm_DailySalesTask();  
  4.         int result = 0;  
  5.         string Address = "";  
  6.         try  
  7.         {  
  8.             Int64 nextRow = _dbContext.crm_DailySalesTask.Count() + 1;  
  9.            _objSalesTask.DailySalesTaskID = nextRow;  
  10.             _objSalesTask.UserID = _vmTask.UserID;  
  11.             _objSalesTask.BuyerName = _vmTask.BuyerName;  
  12.             _objSalesTask.Description = _vmTask.Description;  
  13.             _objSalesTask.Achivement = _vmTask.Achivement;  
  14.             _objSalesTask.Latitude = _vmTask.Latitude;  
  15.             _objSalesTask.Longitude = _vmTask.Longitude;  
  16.             Address = GetAddress(_objSalesTask.Latitude, _objSalesTask.Longitude);  
  17.             _objSalesTask.Address = Address;  
  18.             _dbContext.crm_DailySalesTask.Add(_objSalesTask);  
  19.             _dbContext.SaveChanges();  
  20.             result = 1;  
  21.         }  
  22.         catch  
  23.         {  
  24.             result = 0;  
  25.   
  26.         }  
  27.         return result;  
  28.     }  
We can see the method, shown above, we just save in the database, using linq and we have called GetAddress Method with two parameters. The code is given below:
  1. private string GetAddress(string latitude, string longitude)  
  2.         {  
  3.             string locationName = "";  
  4.             string url = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false", latitude, longitude);  
  5.             XElement xml = XElement.Load(url);  
  6.             if (xml.Element("status").Value == "OK")  
  7.             {  
  8.                 locationName = string.Format("{0}",  
  9.                     xml.Element("result").Element("formatted_address").Value);  
  10.             }  
  11.             return locationName;  
  12.         }  
In this method, we use Google API with the two parameters- latitude and longitude to get the address. We have used XElement class and Loaded static mehtod for geting API's response. After getting the location name, we have returned the location name.

Get task list by userID:
  1. private List<vmTask> GetTaskDetails(long userID)  
  2.         {  
  3.             List<vmTask> taskes = null;  
  4.             try  
  5.             {  
  6.                 taskes = (from ds in _dbContext.crm_DailySalesTask  
  7.                           where ds.UserID == userID  
  8.                           select new vmTask  
  9.                           {  
  10.                               UserID = ds.UserID ?? 0,  
  11.                               BuyerName = ds.BuyerName,  
  12.                               Achivement = ds.Achivement,  
  13.                               Description = ds.Description,  
  14.                               Address = ds.Address  
  15.                           }).ToList();  
  16.                 return taskes;  
  17.             }  
  18.             catch  
  19.             {  
  20.                 taskes = null;  
  21.   
  22.             }  
  23.             return taskes;  
  24.         }  
Our code is ready. Thus, we will check.

Check by Postman

For HttpPost:

HttpPost

Wow, its work is done. Let's go for HttpGet.

HttpGet

It will always work now.

Check by Fiddler

For HttpPost:

HttpPost

Output result is given below:

Output

Wow its work is done. Let's go for HttpGet.

HttpGet


Similar Articles