nodeの中で google map apiキーを使う方法
(APIのGoogleコンソール上での有効化やNodeの基本的なインストール等は完了しているという前提です)
プロジェクトの package に @googlemaps/google-maps-services-js をインストールして、
プロジェクトフォルダに適当に置いた index.js に下記を記述します。
( なお、Google の Geocoding APIのジオコーディングの結果は、API利用規約上、用途によっては利用が禁止されている場合があります。ジオコーディングの結果を大量にCSV出力して保存し、自分が作ったwebアプリで利用する等の使い方は、この禁止事項に引っ掛かる可能性があります。
参照:https://groups.google.com/g/Google-Maps-API-Japan/c/hAlBYFDnzso?pli=1
)
(下記はコンセプト例)
index.js
js
1const {Client} = require("@googlemaps/google-maps-services-js");
2const client = new Client({});
3
4client
5 .geocode({
6 params: {
7 address: "東京都中央区1-1-1",
8 key: "APIキーを指定",
9 },
10 timeout: 1000, // milliseconds
11 })
12 .then((r) => {
13 console.log(r.data.results[0].geometry.location);
14 })
15 .catch((e) => {
16 console.log(e.response.data.error_message);
17 });
実行
PS Z:\gmaptest> node index.js
出力結果例
{ lat: 35.6790837, lng: 139.783026 }
筆者の環境:
Node.js ver 14.15.3 ・ Windows 10・ VSCode 上のpowershell にて確認
参考:
Node.js Client for Google Maps Services
https://github.com/googlemaps/google-maps-services-js
Google Maps Platform - Geocoding Service
https://developers.google.com/maps/documentation/javascript/geocoding