Geo Google API

ITsolutionWizard
ITsolutionWizard used Ask the Experts™
on
I tried to find exampl c# codes to get Geo Google API and response address.
I have Lat/Lng in my database and try to get the address response back.

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Jose Gabriel Ortega CastroEE Rookie/Solution Guide/Topic Advisor and CEO Faru Bonon IT
Awarded 2018
Distinguished Expert 2018

Commented:
I think you don't need specifics @itsolutionWizard.

You can use this as a template:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace HttpClientSample
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Category { get; set; }
    }

    class Program
    {
        static HttpClient client = new HttpClient();

        static void ShowProduct(Product product)
        {
            Console.WriteLine($"Name: {product.Name}\tPrice: " +
                $"{product.Price}\tCategory: {product.Category}");
        }

        static async Task<Uri> CreateProductAsync(Product product)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync(
                "api/products", product);
            response.EnsureSuccessStatusCode();

            // return URI of the created resource.
            return response.Headers.Location;
        }

        static async Task<Product> GetProductAsync(string path)
        {
            Product product = null;
            HttpResponseMessage response = await client.GetAsync(path);
            if (response.IsSuccessStatusCode)
            {
                product = await response.Content.ReadAsAsync<Product>();
            }
            return product;
        }

        static async Task<Product> UpdateProductAsync(Product product)
        {
            HttpResponseMessage response = await client.PutAsJsonAsync(
                $"api/products/{product.Id}", product);
            response.EnsureSuccessStatusCode();

            // Deserialize the updated product from the response body.
            product = await response.Content.ReadAsAsync<Product>();
            return product;
        }

        static async Task<HttpStatusCode> DeleteProductAsync(string id)
        {
            HttpResponseMessage response = await client.DeleteAsync(
                $"api/products/{id}");
            return response.StatusCode;
        }

        static void Main()
        {
            RunAsync().GetAwaiter().GetResult();
        }

        static async Task RunAsync()
        {
            // Update port # in the following line.
            client.BaseAddress = new Uri("http://localhost:64195/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            try
            {
                // Create a new product
                Product product = new Product
                {
                    Name = "Gizmo",
                    Price = 100,
                    Category = "Widgets"
                };

                var url = await CreateProductAsync(product);
                Console.WriteLine($"Created at {url}");

                // Get the product
                product = await GetProductAsync(url.PathAndQuery);
                ShowProduct(product);

                // Update the product
                Console.WriteLine("Updating price...");
                product.Price = 80;
                await UpdateProductAsync(product);

                // Get the updated product
                product = await GetProductAsync(url.PathAndQuery);
                ShowProduct(product);

                // Delete the product
                var statusCode = await DeleteProductAsync(product.Id);
                Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})");

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }
    }
}

Open in new window


And translate it to call this instead:
https://developers.google.com/maps/documentation/geocoding/intro
https://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,
+Mountain+View,+CA&key=YOUR_API_KEY

Open in new window


of course the only thing you'd ever need is an address and your_api_key

And here's how to get it :
https://developers.google.com/maps/documentation/geocoding/get-api-key
Hello,

If I haven't misunderstood what you wanted, I think this may be along the lines of what you are looking for. You can pass this routine your longitude and latitude and it will return the address:

        private string GetAddress(string longitude, string latitude)
        {
            string address = "";
            string mykey = [YOUR_API_KEY];

            string requestUri = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&key={2}", longitude, latitude, mykey);

            WebRequest request = WebRequest.Create(requestUri);
            WebResponse response = request.GetResponse();
            XDocument xdoc = XDocument.Load(response.GetResponseStream());

            XElement formattedaddress = xdoc.Element("GeocodeResponse").Element("result").Element("formatted_address");

            if (formattedaddress != null)
                address = formattedaddress.Value;

            return address;

        }

Open in new window

Author

Commented:
Sean: The api link i confirmed is working and return xml on the browser.
but when I ran the codes, it return the alert following:

The remote server returned an error: (400) Bad Request.

You know why?
Hello ITsolutionWizard,

I noticed you accepted my answer. Where you able to resolve your 400 Bad Request error?

Sean

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial