[C#][WPF] TmapAPI를 이용해 주소 검색 결과를 AutoCompleteBox로 받아오기

ESOLOGY·2021년 9월 10일
2
post-thumbnail

🙋‍♀️계획

TextBlock에 입력한 검색어와 연관된 주소 목록을 AutoCompleteBox에 채워서 보여주기!

준비

Reference

AutoCompleteBox를 위해 두 개의 Reference가 필요=> System.Windows.Controls.Input.Toolkit, WPFToolkit

Model

https://json2csharp.com/를 이용해 Response 받은 JSON 문서를 Model Class로 변환해주기

MainWindow.xaml

<Window x:Class="TmapApiPOITest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TmapApiPOITest"
        xmlns:System_Windows_Controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
        mc:Ignorable="d"
        Title="MainWindow" Height="400" Width="400">
  <Grid>
    <Border BorderBrush="Black" BorderThickness="1" Height="30" HorizontalAlignment="Center" Width="300" VerticalAlignment="Top" Margin="0 50">
      <!-- Populating: 자동완성과 관련된 메소드, 
           MinimumPopulateDelay: 타이핑을 마치고 Populating 실행되기까지의 시간(milliseconds),
           ValueMemberPath: 검색창 입력된 단어와 연관시킬 property명,
           SelectionChanged: AutoCompleteBox의 아이템이 선택되면 실행될 메소드,
           FilterMode: ItemsSource의 아이템이 검색어와 어느정도 일치해야 AutoCompleteBox의 아이템이 될 수 있는지 -->
      <System_Windows_Controls:AutoCompleteBox x:Name="txtSearchKeyword" Populating="txtSearchKeyword_Populating" MinimumPopulateDelay="500"
                                               ValueMemberPath="Name" FontWeight="Normal" SelectionChanged="txtSearchKeyword_SelectionChanged" FilterMode="None">
        <System_Windows_Controls:AutoCompleteBox.ItemTemplate>
          <!-- AutoCompleteBox 결과창의 형식 -->
          <DataTemplate>
            <Grid Margin="3" Width="280">
              <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
              </Grid.RowDefinitions>
              <Grid.ColumnDefinitions>
                <ColumnDefinition Width="30"/>
                <ColumnDefinition />
                <ColumnDefinition Width="Auto"/>
              </Grid.ColumnDefinitions>
              <Image Source="Images/marker_gray.png"/>
              <TextBlock Text="{Binding Name}" Grid.Column="1" TextTrimming="CharacterEllipsis"/>
              <TextBlock Text="{Binding LowerBizName}" Grid.Column="2" HorizontalAlignment="Right" Foreground="LightGray"/>
              <TextBlock Text="{Binding NewAddressList.NewAddress[0].FullAddressRoad}" Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="1" Foreground="Gray" TextTrimming="CharacterEllipsis"/>
            </Grid>
          </DataTemplate>
        </System_Windows_Controls:AutoCompleteBox.ItemTemplate>
      </System_Windows_Controls:AutoCompleteBox>
    </Border>
  </Grid>
</Window>

MainWindow.xaml.cs

using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using TmapApiPOITest.Model;

namespace TmapApiPOITest
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();
    }

    private void txtSearchKeyword_Populating(object sender, PopulatingEventArgs e)
    {
      e.Cancel = true; //이벤트를 현 지점에서 끊어줌
      string Uri = $"https://apis.openapi.sk.com/tmap/pois?version=1&format=json&callback=result&appKey=발급 받은 API 키&searchKeyword={txtSearchKeyword.Text}&resCoordType=EPSG3857&reqCoordType=WGS84GEO&count=10";
      HttpWebRequest request = WebRequest.Create(Uri) as HttpWebRequest;
      request.Method = "GET";
      request.ContentType = "application/json;charset=utf-8";
      request.Accept = "*/*";
      try
      {
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
          using (StreamReader sr = new StreamReader(response.GetResponseStream()))
          {
            string jsonData = sr.ReadToEnd();
            SearchPoiInfoRoot SearchPoiInfoRoot = JsonConvert.DeserializeObject<SearchPoiInfoRoot>(jsonData); //jsonData 객체화
            if(SearchPoiInfoRoot != null)
            {
              txtSearchKeyword.ItemsSource = SearchPoiInfoRoot.SearchPoiInfo.Pois.Poi;
            }
            txtSearchKeyword.PopulateComplete(); //Populating 완료
          }
        }
      }
      catch
      {

      }
    }

    private void txtSearchKeyword_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      Poi selectedPoi = txtSearchKeyword.SelectedItem as Poi;
      MessageBox.Show(selectedPoi.Name);
    }
  }
}
profile
👩‍💻

1개의 댓글

comment-user-thumbnail
2022년 3월 22일

좋은 자료 올려주셔서 너무 감사합니다. 혹시 json 파일은 어떻게 해야되는지 몰라 자료 올려주실수 있나요?ㅠㅠ

답글 달기