Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Google Geocoding service from C# code

Tags:

c#

google-api

I have one class library in C#. From there I have to call Google service & get latitude & longitude.

I know how to do it using AJAX on page, but I want to call Google Geocoding service directly from my C# class file.

Is there any way to do this or are there any other services which I can use for this.

like image 435
vaibhav shah Avatar asked Apr 29 '13 08:04

vaibhav shah


People also ask

Is geocoding API Google free?

The Geocoding API uses a pay-as-you-go pricing model. Geocoding API requests generate calls to one of two SKUs depending on the type of request: basic or advanced.

Will Google provide Google map service and geocoding service without a key?

no they will work without key also but till a limit after that you need to pay and api keys are use d to monitor your usages.


1 Answers

You could do something like this:

string address = "123 something st, somewhere"; string requestUri = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?key={1}&address={0}&sensor=false", Uri.EscapeDataString(address), YOUR_API_KEY);  WebRequest request = WebRequest.Create(requestUri); WebResponse response = request.GetResponse(); XDocument xdoc = XDocument.Load(response.GetResponseStream());  XElement result = xdoc.Element("GeocodeResponse").Element("result"); XElement locationElement = result.Element("geometry").Element("location"); XElement lat = locationElement.Element("lat"); XElement lng = locationElement.Element("lng"); 

You will also want to validate the response status and catch any WebExceptions. Have a look at Google Geocoding API.

like image 61
Chris Johnson Avatar answered Oct 11 '22 01:10

Chris Johnson