简体   繁体   中英

How to implement Google Place API in C#.Net

I am developing a EPOS System in C#.NET. In My Project, i have to implement a scenario:

  1. User will enter Zip Code/ Postal Code in a Text box.
  2. Application using google places API will return City, Street and Town separately in 3 Tex box respectively. Please any one help me how to implement this scenario in C#.net.

i already created Google Project on https://console.cloud.google.com/apis/credentials/key and generate Google Place API Key for my project.

I Have searched a lot on google but all example are implemented in asp.net, but i need in C# Net. Anyone Help me. Thanks in Advance.

在此处输入图像描述

I have implemented Some how but i don't know how to read it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
namespace apidemo
{
    class Program
    {
        String response, result;
         const String apiKey= "My APi kEy";
        static void Main(string[] args)
        {
            getdata("B11 4RA");
            Console.ReadLine();
        }
        static async public void getdata(String code)
        {
            try
            {
                using (var client = new HttpClient())
                {
                   

                    var response = await client.GetStringAsync(String.Format("https://maps.googleapis.com/maps/api/place/autocomplete/json?key="+ apiKey + "&input=" +code));
               
                    Console.WriteLine(response);
                   



                }
            }
            catch (Exception ex) {
                Console.Write(ex.ToString());
            }

          
        }
   

    }
}

Output is this 在此处输入图像描述

If we look at the documentation for the Google Places API, we can see the format of the JSON that a request to the API returns. You can traverse the json object and get your required values as in below snippet.

JObject objectContainer = response.Value<JObject>("candidates");

foreach (KeyValuePair<string, JToken> tag in objectContainer)
{
    if(tag.key=="formatted_address")
        var address = tag.value;
    if(tag.key=="name")
        var name = tag.value;
}

With a simple HTTP request to the Google Places API, we can then use above code to get required fields.

using (var client = new HttpClient())
{
    var response = await client.GetStringAsync("https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=YOUR_POSTCODE&inputtype=textquery&&fields=photos,formatted_address,name,opening_hours,rating&key=YOUR_API_KEY");
    var result = JsonConvert.DeserializeObject<PlacesApiQueryResponse>(response);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM