Google Map Apiを利用してみる
諸事情により、Wep APIを利用するコーディングを試すことになったので、メモる
Google Cloud Platformの登録
Google Map Apiを利用するためにはGoogle Cloud Platformへの登録が必要、クレジットカード必須。 https://cloud.google.com 登録を完了すると、デフォルトのプロジェクトが生成される。
認証キーを生成する。
サイドメニューから「APIとサービス→認証情報」へ
認証情報を作成から、APIキーを選択し、認証キーを作成する。
APIキーの制限設定画面からはアプリケーション制限からHTTPやIPアドレスでの制限をかけれるらしい、とりあえず、テストだけにはなしで問題なし
Google Map Apiを有効にする。
サイドメニューから「APIとサービス→ライブラリー」へ
「Maps JavaScript API」を探して、「有効」にする。
管理画面へ移動
これで、Javascript用Map Apiが利用可能になった。
用件によって「Geocoding API」や「Places API」の有効化が必要になる。
Map APIを利用して座標の地図を表示してみる。
HTML
googleのapiが読まれたタイミングでinitMapが実行され、表示される
<div id="map" style="height:500px;width:500px;"></div> <script> function initMap() { var MyLatLng = new google.maps.LatLng(34.7088812,135.4881584); var Options = { zoom: 15, //地図の縮尺値 center: MyLatLng, //地図の中心座標 mapTypeId: 'roadmap' //地図の種類 }; var map = new google.maps.Map(document.getElementById('map'), Options); } </script> <script src="http://maps.google.com/maps/api/js?key={API_KEY}&language=ja&callback=initMap"></script>
Geocoding APIを利用して、住所から座標を取得する方法
もともとこれをやって見るための準備だったので、これを有効にする。 これにより、Web APIからのResponseを取得する様にしてみる。
.NETのコンソールプロジェクトを作成し、必要なパッケージを追加する。
先ずはパッケージの追加 + Microsoft.AspNet.WebApi.Client + Newtonsoft.Json
レスポンス用クラスを宣言(Google GeocodeからのレスポンスのJson型)
public class MyResponse { public List<AddressComponent> results { get; set; } public string status { get; set; } } public class AddressComponent { public List<address_components> address_components { get; set; } public string formatted_address { get; set; } public Geometry geometry { get; set; } public string place_id { get; set; } public List<string> types { get; set; } } public class Geometry { public Bounds bounds { get; set; } public Point location { get; set; } public string location_type { get; set; } public Bounds viewport { get; set; } } public class Bounds { public Point northeast { get; set; } public Point southwest { get; set; } } public class Point { public decimal lat { get; set; } public decimal lng { get; set; } } public class address_components { public string long_name { get; set; } public string short_name { get; set; } public List<string> types { get; set; } }
実行プログラム
class Program { static HttpClient _client = new HttpClient(); static List<String> _list = new List<string>(); static Dictionary<String,string> _result = new Dictionary<String, string>(); static void Main(string[] args) { _list.Add("東京タワー"); _list.Add("543-0001"); RunAsync().GetAwaiter().GetResult(); foreach (var item in _result) { // JsonからNewtonsoft.Jsonを利用してDeserializeしている。下のresult3と結果は同じ var conv = Newtonsoft.Json.JsonConvert.DeserializeObject<MyResponse>(item.Value); Console.WriteLine($"{item.Key}=X:{conv.results[0].geometry.location.lat},Y:{conv.results[0].geometry.location.lng}"); } Console.ReadLine(); } static async Task<String> GetResultAsync(string address) { //Json形式で返す様にしている。 HttpResponseMessage response = await _client.GetAsync(new Uri($"https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={API_KEY}")); var result = response.EnsureSuccessStatusCode(); var result2 = await response.Content.ReadAsStringAsync(); //Jsonの文字列を取得する。 var result3 = await response.Content.ReadAsAsync<MyResponse>(); //Deserializeした結果を受け取る return result2; } static async Task RunAsync() { // BaseAddressは指定しているが、今回は毎回Full Urlを送っているため、何でも良い(はず) _client.BaseAddress = new Uri("https://maps.googleapis.com/maps/api/geocode/"); _client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); try { foreach (var item in _list) { var result = await GetResultAsync(item); _result.Add(item, result); } } catch (Exception e) { Console.WriteLine(e.Message); } } }
テスト用コードがいっぱい残っているが、とりあえず、ここまで