Introduction

In this article, we will learn WPF using Google Place API with the WPF control web browser in Visual Studio 2015.

In this article, we are going to:

  • Create a WPF Application.
  • Using Google Place API.
  • Configure the API.

Create a WPF Application

Open Visual Studio 2015

WPF

Select the File menu >New > Click Project.
WPF

Select Windows templates, and choose the WPF Application. Then click “ok “after filling in the name and location.

After you complete the solution explorer, it will load basic bundles.
WPF

Open the ManiWindow.xaml file and Change it from <Grid> to <DockPanel>. It will load based on resolution.
WPF

Then drag a web browser from the Toolbox to the Designer window.

<DockPanel Height="262" VerticalAlignment="Top" Margin="-1,94,-0.4,0">
            <WebBrowser  Name="Wb" Margin="0,0,0,-113" />
</DockPanel>

Adding some extra controls to get a result.

<TextBox HorizontalAlignment="Left" Text=" "  Name="txtOrigins" Height="23" Margin="92,10,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="163"/>
        <TextBox HorizontalAlignment="Left" Text=" "  Name="txtDestinations"  Height="23" Margin="387,10,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="170" />
        <Label Content="Origins" HorizontalAlignment="Left" Margin="10,7,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="14"/>
        <Label Content="Destinations" HorizontalAlignment="Left" Margin="283,7,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="14"/>
<TextBox HorizontalAlignment="Left" Name="txtDistance" IsReadOnly="True" Height="23" Margin="92,63,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="163"/>
        <TextBox HorizontalAlignment="Left" Name="txtDuration" IsReadOnly="True" Height="23" Margin="387,63,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="170" />
        <Label Content="Distance" HorizontalAlignment="Left" Margin="21,60,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="14"/>
        <Label Content="Duration" HorizontalAlignment="Left" Margin="307,60,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="14"/>
        <Button Content="Calculate" HorizontalAlignment="Left" Name="btnFind" Margin="585,7,0,0" VerticalAlignment="Top" Width="75" Height="29" Background="#FFA61195" FontWeight="Bold" Foreground="#FFF7F2F2" FontSize="14" Click="btnFind_Click"/>

Using Google Place API

If you’re going to use Google API, you must sign up for a Gmail account. Once you successfully login click here. In this site, you have to click the “GET a Key” button to flow through a process where you will:

  • Create or select a project.
  • Enable the API.
  • Get an API Key.

Create and Enable the API

Create a project name and click the “CREATE AND ENABLE API.”
WPF

Get an API Key

In this process, you are getting keys ready to use in your application, so copy the key and click the “FINISH” Button.
WPF

Configure the API

I have checked this key using the URL below, and found out what the actual result is.

https://maps.googleapis.com/maps/api/distancematrix/xml?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key=YOUR_API_KEY
WPF

I have configured the URI and Key in APP.CONFIG.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
    </startup>
  <appSettings>
    <add key="DistanceApi" value="http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" />
    <add key="ApiKey" value="AIzaSyCo9WJ7uQJIIrJVm1dDFCZwu9o1GJ8oQoM" />
  </appSettings>
</configuration>

Code Behind

First, I have initiated the URL for a web browser.

Wb.Navigate("https://www.google.co.in/maps");

Create the new class for retrieving and storing the values.

public class vmDistnce
    {
        public string durtion { get; set; }
        public double distance { get; set; }
}

Output 1

WPF

Then I get data from App.config.

string DistanceApiUrl = ConfigurationManager.AppSettings["DistanceApi"];
string myKey = ConfigurationManager.AppSettings["ApiKey"];

Here, I have used the web URL to look for the UI and API URL and used it to get the values of this search’s result. Once you click the “Calculate” button, follow the below code.

vmDistance objDistance = new vmDistance();
            try
            {
                string DistanceApiUrl = ConfigurationManager.AppSettings["DistanceApi"];
                string myKey = ConfigurationManager.AppSettings["ApiKey"];
                string url = DistanceApiUrl + txtOrigins.Text + "&destinations=" + txtDestinations.Text"&mode=driving&sensor=false&language=en-EN&units=imperial&Key="+ myKey;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                WebResponse response = request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader sreader = new StreamReader(dataStream);
                string responsereader = sreader.ReadToEnd();
                response.Close();
                DataSet ds = new DataSet();
                ds.ReadXml(new XmlTextReader(new StringReader(responsereader)));
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables["element"].Rows[0]["status"].ToString() == "OK")
                    {
                        objDistance.durtion = Convert.ToString(ds.Tables["duration"].Rows[0]["text"].ToString().Trim());
                        objDistance.distance = Convert.ToDouble(ds.Tables["distance"].Rows[0]["text"].ToString().Replace("mi", "").Trim());
                    }
                }
                txtDuration.Text = objDistance.durtion;
                txtDistance.Text = Convert.ToString(objDistance.distance);
            }
            catch (Exception ex)
            {
                MessageBox.Show ("Error in calculating Distance!" + ex.Message);}

I have added the distance mode in the API URL, as follows:

“&mode=driving&sensor=false&language=en-EN&units=imperial&Key=”

But, per our users’ needs, we can get the result from Google Place API.

After the calculation, I will navigate the Web URL to the web browser.

Wb.Navigate("https://www.google.co.in/maps/dir/"+txtOrigins.Text +"/"+txtDestinations.Text);

Run the application or Click (F5)

Output 2

WPF

Visit my WPF article links given below.

Conclusion

In this article, we have learned WPF, using the Google Place API. If you have any queries, please tell me through the comments section. Your comments are very valuable.

Happy Coding!

Advertisements