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.
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.
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;
public TaskController()
{
_dbContext = new SalesTrackingEntities();
}
[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]
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;
}
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.
public TaskController()
{
_dbContext = new SalesTrackingEntities();
}
We have created instant of SalesTarackingEntities
in TaskController
constructor because access all table and use linq.
[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
:
Wow it's work done. OK, let's go for HttpGet
.
It's always work now.
Check by Fiddler
For HttpPost
:
Our result is shown below:
It's work done. OK, let's go for HttpGet
.
Hope this will be helpful. Happy coding! :)