Learn WPF Using Google Place API

Introduction

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

In this article, we are going to

  • Create WPF Application
  • Using Google Place API
  • Configure The API

Create WPF Application

Open Visual Studio 2015

WPF

Select the File menu >New > Click Project

WPF

Select windows templates & choose the WPF Application. Then click “ok “button after fill the name & location.

After complete the solution explorer, it will load basic bundles

WPF

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

WPF

Then Drag web browser from Toolbox to Designer window 

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

Adding some extra Control for getting result. 

  1. <TextBox HorizontalAlignment="Left" Text=" "  Name="txtOrigins" Height="23" Margin="92,10,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="163"/>  
  2.         <TextBox HorizontalAlignment="Left" Text=" "  Name="txtDestinations"  Height="23" Margin="387,10,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="170" />  
  3.         <Label Content="Origins" HorizontalAlignment="Left" Margin="10,7,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="14"/>  
  4.         <Label Content="Destinations" HorizontalAlignment="Left" Margin="283,7,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="14"/>  
  5. <TextBox HorizontalAlignment="Left" Name="txtDistance" IsReadOnly="True" Height="23" Margin="92,63,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="163"/>  
  6.         <TextBox HorizontalAlignment="Left" Name="txtDuration" IsReadOnly="True" Height="23" Margin="387,63,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="170" />  
  7.         <Label Content="Distance" HorizontalAlignment="Left" Margin="21,60,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="14"/>  
  8.         <Label Content="Duration" HorizontalAlignment="Left" Margin="307,60,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="14"/>  
  9.         <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, here. Once you successfully login click here. In this site you have to click “GET a Key” button below to flow through a process where you will

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

Create and Enable API

Create a project name & click the “CREATE AND ENABLE API”

WPF

Get an API Key

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

WPF

Configure the API

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

I have checked this key using the URL and finding out what an actual result is.

WPF

I have configured the URI & Key in APP.CONFIG 

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

Code behind

First I have initiated the URL for web browser

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

Create the new class for retrieving & storing the values. 

  1. public class vmDistnce  
  2.     {  
  3.         public string durtion { get; set; }  
  4.         public double distance { get; set; }  
  5. }   

Output 1

WPF

Then I get  data from  App.config

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

Here I have used the web URL looking for UI & API URL getting the values of result. Once you  click the “Calculate” button follow the below code. 

  1. vmDistance objDistance = new vmDistance();  
  2.             try  
  3.             {  
  4.                 string DistanceApiUrl = ConfigurationManager.AppSettings["DistanceApi"];  
  5.                 string myKey = ConfigurationManager.AppSettings["ApiKey"];  
  6.                 string url = DistanceApiUrl + txtOrigins.Text + "&destinations=" + txtDestinations.Text"&mode=driving&sensor=false&language=en-EN&units=imperial&Key="+ myKey;  
  7.                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);  
  8.                 WebResponse response = request.GetResponse();  
  9.                 Stream dataStream = response.GetResponseStream();  
  10.                 StreamReader sreader = new StreamReader(dataStream);  
  11.                 string responsereader = sreader.ReadToEnd();  
  12.                 response.Close();  
  13.                 DataSet ds = new DataSet();  
  14.                 ds.ReadXml(new XmlTextReader(new StringReader(responsereader)));  
  15.                 if (ds.Tables.Count > 0)  
  16.                 {  
  17.                     if (ds.Tables["element"].Rows[0]["status"].ToString() == "OK")  
  18.                     {  
  19.                         objDistance.durtion = Convert.ToString(ds.Tables["duration"].Rows[0]["text"].ToString().Trim());  
  20.                         objDistance.distance = Convert.ToDouble(ds.Tables["distance"].Rows[0]["text"].ToString().Replace("mi""").Trim());  
  21.                     }  
  22.                 }  
  23.                 txtDuration.Text = objDistance.durtion;  
  24.                 txtDistance.Text = Convert.ToString(objDistance.distance);  
  25.             }  
  26.             catch (Exception ex)  
  27.             {  
  28.                 MessageBox.Show ("Error in calculating Distance!" + ex.Message);}   

I have added the distance mode in API URL

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

But as per our needs we can get the result from Google place api.

After the calculation, I will navigate Web URL to 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 Google Place API. If you have any queries, please tell me through the comments section. Your comments are very valuable.

Happy Coding.....

Up Next
    Ebook Download
    View all
    Learn
    View all