1
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 5 years have passed since last update.

Node.js の async/await のサンプル

Posted at

Node.js の async/await のサンプルを書いてみました。
次のプログラムを書き換えました。
ライブラリーは、node-fetch を使いました。
緯度経度から都市の名前を得る (Node.js)

reverse_geo.js
# ! /usr/bin/node
//
//	reverse_geo.js
//
//					May/04/2018
//
// ------------------------------------------------------------------
function parser_results(dict_aa)
{
	var unit_out = {}
	unit_out['city'] = ""
	unit_out['pref'] = ""

	const components = dict_aa['results'][0]['address_components']
	for (var it in components)
		{
		const unit_aa = components[it]
		if (unit_aa['types'][0] == "locality")
			{
			unit_out.city = unit_aa['short_name']
			}
		else if (unit_aa['types'][0] == "administrative_area_level_1")
			{
			unit_out.pref = unit_aa['short_name']
			}
		}

	return unit_out
}

// ------------------------------------------------------------------
async function get_city_pref_proc(pos)
{
	const lat = pos[0]
	const lon = pos[1]

	api_key="***************************************"
	url_aa="https://maps.googleapis.com/maps/api/geocode/json?latlng="
	url=url_aa + lat + "," + lon + "&language=ja&key=" + api_key
//	console.error(url)


	const fetch = require("node-fetch")
	response = await fetch(url)
	const data = await response.json()

	var unit_aa = parser_results(data)

	unit_aa['lat'] = lat
	unit_aa['lon'] = lon

	return	unit_aa
}

// ------------------------------------------------------------------
async function main_proc()
{
	console.error("*** 開始 ***")

	const array_in = [[43.08,141.35],
			[36.56,139.88],
			[35.91,139.66],
			[35.68,139.76],
			[35.16,136.90],
			[34.70,135.50],
			[33.59,130.42],
			[31.56,130.56],
			[26.21,127.68]
			]
	array_aa = []

	for (var it in array_in)
		{
		const pos = array_in[it]
		array_aa.push(await get_city_pref_proc(pos))
		}

	console.error("array_aa.length = " + array_aa.length)

	array_aa.forEach(function(unit)
	{
	console.log(unit.lat,unit.lon,unit.city,unit.pref)
	})

console.error("*** 終了 ***")
}

// ------------------------------------------------------------------

main_proc()

// ------------------------------------------------------------------

実行結果

$ ./reverse_geo.js 
*** 開始 ***
array_aa.length = 9
43.08 141.35 '札幌市' '北海道'
36.56 139.88 '宇都宮市' '栃木県'
35.91 139.66 'さいたま市' '埼玉県'
35.68 139.76 '千代田区' '東京都'
35.16 136.9 '名古屋市' '愛知県'
34.7 135.5 '大阪市' '大阪府'
33.59 130.42 '福岡市' '福岡県'
31.56 130.56 '鹿児島市' '鹿児島県'
26.21 127.68 '那覇市' '沖縄県'
*** 終了 ***
1
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
1
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?