Click here to Skip to main content
13,201,050 members (53,241 online)
Click here to Skip to main content
Add your own
alternative version

Stats

17.7K views
893 downloads
32 bookmarked
Posted 14 Aug 2016

How to Get Geolocation Address by Using Google geolocation API in ASP.NET Web API

, 7 Oct 2016
Rate this:
Please Sign up or sign in to vote.
In this article, we are going to learn how to get geolocation address by using Google geolocation API in ASP.NET Web API.

In this article, we are going to learn how to get geolocation address by using google geolocation API in ASP.NET Web API. Now we will go and create our application. I hope you will like this.

Background

Normally, we call Google geolocation API either from server side or from client side, right? Today, we use server side. It is fully dynamic. We will use two tools, one is Postman and the other one is Fiddler. Both are used for test web API. This Google geolocation API depends on latitude and longitude. Both will be controlled by our Client. They will give value.

Creating DataBase

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

CREATE DATABASE SalesTracking;

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

CREATE TABLE [dbo].[crm_DailySalesTask](
	[DailySalesTaskID] [bigint] NOT NULL,
	[UserID] [bigint] NULL,
	[BuyerName] [nvarchar](max) NULL,
	[Description] [nvarchar](max) NULL,
	[Achivement] [nvarchar](max) NULL,
	[Latitude] [nvarchar](max) NULL,
	[Longitude] [nvarchar](max) NULL,
	[Address] [nvarchar](max) NULL,
	[company_name] [nvarchar](max) NULL,
	[CreateDate] [datetime] NULL,
 CONSTRAINT [PK_crm_DailySalesTask] PRIMARY KEY CLUSTERED 
(
	[DailySalesTaskID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Creating Web Application

Start Visual Studio File>New>Project and click. New Project window will show on your monitor. Select Web and select ASP.NET Web Application (.NET Framework) and give name and click ok button once, again a new window will show on your monitor. From the following pop up, select Web API and once click ok button.

3

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.

Untitled

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 return type. Below is the code:

public class ResponseModel
  {
      public string Message { set; get; }
      public bool Status { set; get; }
      public object Data { set; get; }
  }

Create Virtual Class

We will create virtual class in model folder below is the query.

public class vmTask
   {
       public Int64 UserID { get; set; }
       public string BuyerName { get; set; }
       public string Achivement { get; set; }
       public string Latitude { get; set; }
       public string Longitude { get; set; }
       public string Address { get; set; }
       public string Description { get; set; }
   }

Create API Controller

Right click on Controllers folder, add >controller, select Web API 2 Controller-Empty and give name of controller, once click ok.

public class TaskController : ApiController
    {
        SalesTrackingEntities _dbContext = null;

        // constructor 
        public TaskController()
        {
            _dbContext = new SalesTrackingEntities();
        }
        // for Task save
        [HttpPost]
        public ResponseModel SaveTask(vmTask _vmTask)
        {
            ResponseModel _modelObj = new ResponseModel;
            int result = SaveTaskDetails(_vmTask);
            if (result == 1)
            {
                _modelObj.Status = true;
                _modelObj.Message = "Task Saved";
            }
            else
            {
                _modelObj.Status = false;
                _modelObj.Message = "Task Saved faill";
            }
            return _modelObj;
        }

        [HttpGet]
        // for get Task data by UserID
        public ResponseModel GetTaskList(Int64 userID)
        {
            ResponseModel _modelObj = new ResponseModel();
            List<vmTask> taskes = GetTaskDetails(userID);
            if (taskes.Count > 0)
            {
                _modelObj.Data = taskes;
                _modelObj.Status = true;
                _modelObj.Message = "Data get successfully.";
            }
            else
            {
                _modelObj.Data = taskes;
                _modelObj.Status = false;
                _modelObj.Message = "Data not found.";
            }
            return _modelObj;
        }
        private List<vmTask> GetTaskDetails(long userID)
        {
            List<vmTask> taskes = null;
            try
            {
                taskes = (from ds in _dbContext.crm_DailySalesTask
                          where ds.UserID == userID
                          select new vmTask
                          {
                              UserID = ds.UserID ?? 0,
                              BuyerName = ds.BuyerName,
                              Achivement = ds.Achivement,
                              Description = ds.Description,
                              Address = ds.Address
                          }).ToList();
                return taskes;
            }
            catch
            {
                taskes = null;

            }
            return taskes;
        }
        private int SaveTaskDetails(vmTask _vmTask)
        {
            crm_DailySalesTask _objSalesTask = new crm_DailySalesTask();
            int result = 0;
            string Address = "";
            try
            { 
                 Int64 nextRow = _dbContext.crm_DailySalesTask.Count() + 1;
                _objSalesTask.DailySalesTaskID = nextRow;             
                _objSalesTask.UserID = _vmTask.UserID;
                _objSalesTask.BuyerName = _vmTask.BuyerName;
                _objSalesTask.Description = _vmTask.Description;
                _objSalesTask.Achivement = _vmTask.Achivement;
                _objSalesTask.Latitude = _vmTask.Latitude;
                _objSalesTask.Longitude = _vmTask.Longitude;
                Address = GetAddress(_objSalesTask.Latitude, _objSalesTask.Longitude);
                _objSalesTask.Address = Address;
                _dbContext.crm_DailySalesTask.Add(_objSalesTask);
                _dbContext.SaveChanges();
                result = 1;
            }
            catch
            {
                result = 0;

            }
            return result;
        }
        // get Address
        private string GetAddress(string latitude, string longitude)
        {
            string locationName = "";
            string url = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},
                         {1}&sensor=false", latitude, longitude);
            XElement xml = XElement.Load(url);
            if (xml.Element("status").Value == "OK")
            {
                locationName = string.Format("{0}",
                    xml.Element("result").Element("formatted_address").Value);
            }
            return locationName;
        }
    }

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 coding in TaskController.

SalesTrackingEntities _dbContext = null;

We have just pointed _dbContext instant.

// constructor
       public TaskController()
       {
           _dbContext = new SalesTrackingEntities();
       }

We have created instant of SalesTarackingEntities in TaskController constructor because access all table and use linq.

// for Task save
       [HttpPost]
       public ResponseModel SaveTask(vmTask _vmTask)
       {
           ResponseModel _modelObj = new ResponseModel();
           int result = SaveTaskDetails(_vmTask);
           if (result == 1)
           {
               _modelObj.Status = true;
               _modelObj.Message = "Task Saved";
           }
           else
           {
               _modelObj.Status = false;
               _modelObj.Message = "Task Saved faill";
           }
           return _modelObj;
       }

We use HttpPost for SaveTask method, we get vmTask object as parameter from our world. When we test this method using fiddler of postman, then we will see how to pass vmTask object form our world. We call SaveTaskDetails method for save, this method exists in TaskController.

private int SaveTaskDetails(vmTask _vmTask)
    {
        crm_DailySalesTask _objSalesTask = new crm_DailySalesTask();
        int result = 0;
        string Address = "";
        try
        {
            Int64 nextRow = _dbContext.crm_DailySalesTask.Count() + 1;
           _objSalesTask.DailySalesTaskID = nextRow;
            _objSalesTask.UserID = _vmTask.UserID;
            _objSalesTask.BuyerName = _vmTask.BuyerName;
            _objSalesTask.Description = _vmTask.Description;
            _objSalesTask.Achivement = _vmTask.Achivement;
            _objSalesTask.Latitude = _vmTask.Latitude;
            _objSalesTask.Longitude = _vmTask.Longitude;
            Address = GetAddress(_objSalesTask.Latitude, _objSalesTask.Longitude);
            _objSalesTask.Address = Address;
            _dbContext.crm_DailySalesTask.Add(_objSalesTask);
            _dbContext.SaveChanges();
            result = 1;
        }
        catch
        {
            result = 0;

        }
        return result;
    }

We can see in the above method that we just save in database using linq and we have called GetAddress method with two parameters. This method is our main focus. Below is the code.

private string GetAddress(string latitude, string longitude)
        {
            string locationName = "";
            string url = string.Format
            ("http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false", 
            latitude, longitude);
            XElement xml = XElement.Load(url);
            if (xml.Element("status").Value == "OK")
            {
                locationName = string.Format("{0}",
                    xml.Element("result").Element("formatted_address").Value);
            }
            return locationName;
        }

In this method, we use Google API with two parameters latitude and longitude for get address. We have used XElement class and Load static method for getting API's response. After getting location name, we have returned location name.

Get Task List by userID

private List<vmTask> GetTaskDetails(long userID)
        {
            List<vmTask> taskes = null;
            try
            {
                taskes = (from ds in _dbContext.crm_DailySalesTask
                          where ds.UserID == userID
                          select new vmTask
                          {
                              UserID = ds.UserID ?? 0,
                              BuyerName = ds.BuyerName,
                              Achivement = ds.Achivement,
                              Description = ds.Description,
                              Address = ds.Address
                          }).ToList();
                return taskes;
            }
            catch
            {
                taskes = null;

            }
            return taskes;
        }

Our code is ready. So we will check.

Check by Postman

For HttpPost:

12323

Wow it's work done. OK, let's go for HttpGet.

5645645

It's always work now.

Check by Fiddler

For HttpPost:

fid1212

Our result is shown below:

ferere3434

It's work done. OK, let's go for HttpGet.

fiddler4343

Hope this will be helpful. Happy coding! :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Shamim Uddin
Software Developer Amber Software Solution Ltd.
Bangladesh Bangladesh
Hi, I am Shamim Uddin.Working with Microsoft Technologies.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralMy vote of 5 Pin
Renju Vinod11-Sep-16 20:15
professionalRenju Vinod11-Sep-16 20:15 
PraiseNice article Pin
Suvendu Shekhar Giri11-Sep-16 5:26
mvpSuvendu Shekhar Giri11-Sep-16 5:26 
GeneralMy vote of 5 Pin
Member 1269394619-Aug-16 9:21
memberMember 1269394619-Aug-16 9:21 
PraiseExcellent Pin
mahfuzbappybd16-Aug-16 7:18
membermahfuzbappybd16-Aug-16 7:18 
GeneralMy vote of 5 Pin
Shamim Uddin14-Aug-16 6:38
professionalShamim Uddin14-Aug-16 6:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171020.1 | Last Updated 8 Oct 2016
Article Copyright 2016 by Shamim Uddin
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid