ここで役立つ “現在の条件” サービス、場所ごとの現在の大気質指数値と汚染物質濃度を提供する「過去の条件」サービス、およびイメージとして特定の地域の現在の条件を提供する「ヒートマップ」サービスの3つの API ツールがあります。
以前は、Python で Google マップの API を呼び出すために素晴らしいgooglemapsパッケージを使用していましたが、これらの新しい API はまだサポートされていません。驚くべきことに、公式のドキュメント以外では、これらの新しいツールを使用している人々の例や、それらを呼び出すために設計された事前存在の Python パッケージはほとんど見つかりませんでした。もし他に知っている人がいれば、喜んで訂正いたします!
そこで、自分自身の簡単なツールを作成しました。この記事では、それらがどのように機能し、どのように使用するかについて説明します。これが、Python でこれらの新しい API を試してみたい人や、始める場所を探している人に役立つことを願っています。このプロジェクトのすべてのコードはこちらで見つけることができ、時間の経過とともに機能を追加し、大気の質データを使用した何らかのマッピングアプリケーションを作成する予定です。
2. 特定の場所の現在の大気質を取得する
さあ、始めましょう!このセクションでは、Google マップで特定の場所の大気質データを取得する方法について説明します。まず、Google Cloud アカウントを通じて生成できる API キーが必要です。90日間の無料トライアル期間がありますが、それ以降は使用した API サービスに対して料金が発生しますので、コール数を増やす前に価格ポリシーをご確認ください!
Google Cloud API ライブラリのスクリーンショット。大気質 API をアクティブにすることができます。画像は筆者の生成です。
現在の状況を取得するには、詳細はこちらのPOSTリクエストが必要です。私たちは< a href=”https://github.com/googlemaps/google-maps-services-python”>googlemapsパッケージからインスピレーションを受けて、一般化できる方法でこれを行います。最初に、 requestsを使用して呼び出しを行うクライアントクラスを作成します。目標は非常に簡単です-以下のようなURLを構築し、ユーザーのクエリに固有のリクエストオプションをすべて含めたいのです。
{'dateTime': '2023-10-12T05:00:00Z', 'regionCode': 'us', 'indexes': [{'code': 'uaqi', 'displayName': 'Universal AQI', 'aqi': 60, 'aqiDisplay': '60', 'color': {'red': 0.75686276, 'green': 0.90588236, 'blue': 0.09803922}, 'category': 'Good air quality', 'dominantPollutant': 'pm10'}, {'code': 'usa_epa', 'displayName': 'AQI (US)', 'aqi': 39, 'aqiDisplay': '39', 'color': {'green': 0.89411765}, 'category': 'Good air quality', 'dominantPollutant': 'pm10'}], 'pollutants': [{'code': 'co', 'displayName': 'CO', 'fullName': 'Carbon monoxide', 'concentration': {'value': 292.61, 'units': 'PARTS_PER_BILLION'}, 'additionalInfo': {'sources': 'Typically originates from incomplete combustion of carbon fuels, such as that which occurs in car engines and power plants.', 'effects': 'When inhaled, carbon monoxide can prevent the blood from carrying oxygen. Exposure may cause dizziness, nausea and headaches. Exposure to extreme concentrations can lead to loss of consciousness.'}}, {'code': 'no2', 'displayName': 'NO2', 'fullName': 'Nitrogen dioxide', 'concentration': {'value': 22.3, 'units': 'PARTS_PER_BILLION'}, 'additionalInfo': {'sources': 'Main sources are fuel burning processes, such as those used in industry and transportation.', 'effects': 'Exposure may cause increased bronchial reactivity in patients with asthma, lung function decline in patients with Chronic Obstructive Pulmonary Disease
def historical_conditions( client, location, specific_time=None, lag_time=None, specific_period=None, include_local_AQI=True, include_health_suggestion=False, include_all_pollutants=True, include_additional_pollutant_info=False, include_dominant_pollutant_conc=True, language=None,): """ このAPIのドキュメントはこちらを参照してください https://developers.google.com/maps/documentation/air-quality/reference/rest/v1/history/lookup """ params = {} if isinstance(location, dict): params["location"] = location else: raise ValueError( "Location argument must be a dictionary containing latitude and longitude" ) if isinstance(specific_period, dict) and not specific_time and not lag_time: assert "startTime" in specific_period assert "endTime" in specific_period params["period"] = specific_period elif specific_time and not lag_time and not isinstance(specific_period, dict): # 注意:時刻は「ズール」形式である必要があります。 # 例:datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%dT%H:%M:%SZ") params["dateTime"] = specific_time # 時間のラグ期間(時間単位) elif lag_time and not specific_time and not isinstance(specific_period, dict): params["hours"] = lag_time else: raise ValueError( "Must provide specific_time, specific_period or lag_time arguments" ) extra_computations = [] if include_local_AQI: extra_computations.append("LOCAL_AQI") if include_health_suggestion: extra_computations.append("HEALTH_RECOMMENDATIONS") if include_additional_pollutant_info: extra_computations.append("POLLUTANT_ADDITIONAL_INFO") if include_all_pollutants: extra_computations.append("POLLUTANT_CONCENTRATION") if include_dominant_pollutant_conc: extra_computations.append("DOMINANT_POLLUTANT_CONCENTRATION") if language: params["language"] = language params["extraComputations"] = extra_computations # ページサイズはここでデフォルト値100に設定されています params["pageSize"] = 100 # page tokenは必要に応じてrequest_postメソッドで埋められます params["pageToken"] = "" return client.request_post("/v1/history:lookup", params)
from itertools import chainimport pandas as pddef historical_conditions_to_df(response_dict): chained_pages = list(chain(*[response_dict[p]["hoursInfo"] for p in [*response_dict]])) all_indexes = [] all_pollutants = [] for i in range(len(chained_pages)): # タイムスタンプのいずれかがデータが欠落している場合に必要なこのチェックがあります。これは時々起こります。 if "indexes" in chained_pages[i]: this_element = chained_pages[i] # 時間を取得 time = this_element["dateTime"] # すべてのインデックス値を取得してメタデータを追加 all_indexes += [(time , x["code"],x["displayName"],"index",x["aqi"],None) for x in this_element['indexes']] # すべての汚染物値を取得してメタデータを追加 all_pollutants += [(time , x["code"],x["fullName"],"pollutant",x["concentration"]["value"],x["concentration"]["units"]) for x in this_element['pollutants']] all_results = all_indexes + all_pollutants # "長いフォーマット"のデータフレームを生成 res = pd.DataFrame(all_results,columns=["time","code","name","type","value","unit"]) res["time"]=pd.to_datetime(res["time"]) return res
Google Maps Air Quality APIの最終的なユースケースであるヒートマップタイルの生成に入りましょう。これらのタイルは現在の空気のクオリティを視覚化するための強力なツールであり、特にFoliumマップと組み合わせると効果的です。ただし、これに関するドキュメントは少なく、残念なことです。
最後までお読みいただきありがとうございます!ここでは、PythonでGoogle Maps Air Quality APIを使用して、さまざまな興味深いアプリケーションで使用できる結果を提供する方法を探求しました。将来的には、air_quality_mapperツールについて別の記事を追加する予定ですが、ここで説明したスクリプトが独自の価値を持つことを願っています。常にさらなる開発のための提案は大歓迎です!
We will continue to update VoAGI; if you have any questions or suggestions, please contact us!