0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

緯度・経度の一括取得

Posted at

前回スクレイピングをした東京都のカーディーラー住所リストを使って地図にプロットしたいと思います。

地図にプロットするために、Google Geocoding APIを使って緯度・経度をcsvファイルの列に追加します。
GeocodingのWEBサイトにいってAPIキーの取得が必要です。

元のファイルはGoogle Driveにおいています。
次回は実際に地図にプロットしていきます。

from google.colab import drive
drive.mount('/content/drive')

import requests
import csv

api_key = "APIキー"
input_csv_file = '/content/drive/ファイルパス/元のファイル名.csv'
output_csv_file = '/content/drive/ファイルパス/新しいファイル名.csv'

with open(input_csv_file, 'r', encoding='shiftjis') as csv_file:
    csv_reader = csv.reader(csv_file)
    data = list(csv_reader)

with open(output_csv_file, 'w', encoding='shift_jis', newline='') as new_csv_file:
    csv_writer = csv.writer(new_csv_file)

   csv_writer.writerow(["Shop Name", "Address", "Latitude", "Longitude"])

    for row in data[1:]:
        shop_name, address_tokyo = row[0], row[1]

        encoded_address = requests.utils.quote(address_tokyo)

       url = f"https://maps.googleapis.com/maps/api/geocode/json?address={encoded_address}&key={api_key}"
        response = requests.get(url)
        geocoding_data = response.json()

        if geocoding_data["status"] == "OK" and len(geocoding_data["results"]) > 0:
            location = geocoding_data["results"][0]["geometry"]["location"]
            latitude = location["lat"]
            longitude = location["lng"]
        else:
            latitude = ""
            longitude = ""

       csv_writer.writerow([shop_name, address_tokyo, latitude, longitude])

スクリーンショット 2023-10-29 222542.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?