ChatGPTに指定した2地点間の直線距離を計算してもらうPythonコードを書いてもらいました。geopyを利用しています。
指示文(プロンプト):
pythonのgeopyで指定した二地点間の直線距離を計算して表示するプログラムを書いてください。指定する地点は都道府県と市区町村まで入れられるようにしてください。
回答:
以下は、geopyを使用して指定した二つの都道府県と市区町村の間の直線距離を計算し、表示するPythonのプログラムです。
from geopy.geocoders import Nominatim
from geopy.distance import great_circle
# ジオコーダーの初期化
geolocator = Nominatim(user_agent="geopy")
# 出発地の入力
start_prefecture = input("出発地の都道府県を入力してください: ")
start_city = input("出発地の市区町村を入力してください: ")
start_location = geolocator.geocode(f"{start_city}, {start_prefecture}")
if start_location is None:
print("出発地の情報を取得できませんでした。プログラムを終了します。")
exit()
# 到着地の入力
end_prefecture = input("到着地の都道府県を入力してください: ")
end_city = input("到着地の市区町村を入力してください: ")
end_location = geolocator.geocode(f"{end_city}, {end_prefecture}")
if end_location is None:
print("到着地の情報を取得できませんでした。プログラムを終了します。")
exit()
# 出発地と到着地の座標を取得
start_coordinates = (start_location.latitude, start_location.longitude)
end_coordinates = (end_location.latitude, end_location.longitude)
# 直線距離の計算
distance = great_circle(start_coordinates, end_coordinates).km
# 結果の表示
print(f"{start_prefecture} {start_city} から {end_prefecture} {end_city} までの直線距離は {distance:.2f} km です。")
このプログラムでは、出発地と到着地の都道府県と市区町村を入力し、geopyを使用してそれぞれの座標を取得します。そして、great_circle関数を使用して直線距離を計算し、結果を表示します。距離はキロメートルで表示されます。
結果:
以下のように成功しました。ただし、入力値のチェック処理がないので、不正な入力(存在しない都道府県名とか外国の地名とか)を入れるとエラーで止まります。
google mapでも確認しました。だいたいあってますね。