0
0

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

Google Places APIで駅周辺の病院情報を取得してみた。

Last updated at Posted at 2022-01-24

はじめに

こんにちは、山田です。
今回は、作成中のアプリでGoogle Places APIを使用したので、使用方法について記載していきます。

前提条件

APIキーを取得していること。

取得手順

以下にコードを記載する。
例として、西馬込駅周辺の病院情報を取得していきます。

function searchPlaceHospital($keyword) {
  $api_key = "自分のAPIキーを入力";  #1
  $keyword = urlencode($keyword);  #2
  $url = "https://maps.googleapis.com/maps/api/place/textsearch/json?&language=ja&query={$keyword}&key={$api_key}";  #3
  $json = file_get_contents($url);  #4
  $result = json_decode($json, true);  #5
  $lat = $result["results"][0]["geometry"]["location"]["lat"];  #6
  $lng = $result["results"][0]["geometry"]["location"]["lng"];  #7
  $url2 = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={$lat},{$lng}&radius=1000&language=ja&type=hospital&key={$api_key}";  #8
  $json2 = file_get_contents($url2);  #9
  $test =json_decode($json2, true);  #10
	return  $test;  #11
  }

$hospital = searchPlaceHospital("西馬込駅");  #12

$hospital_count = count($hospital["results"]);  #13

for ($i=0; $i<$hospital_count; $i++){  #14
 echo ($hospital["results"][$i]["name"]);
 echo '<br>';
}

①:$api_keyに自分のAPIキーを入れる。
②:unlencode($keyword)にてURLとして使用できない文字や記号を、使用できる文字の特殊な組み合わせで表すように変換する。
③:language=jaにて日本語を設定。query=に検索したい言葉を入力する。今回は、西馬込駅が入る。
④:file_get_contentsにてURLの情報を取得。
⑤:json_decodeにてJSON エンコードされた文字列を受け取り、それをPHPの変数に変換。
⑥:検索した場所の経度を取得。
⑦:検索した場所の緯度を取得。
⑧:location={$lat},{$lng}にて経度、緯度の場所を指定。radiusにて、半径どれくらいの情報を取得するのか指定。今回は、radius=1000で半径1kmの情報を取得。type=hospitalで病院の情報を取得。
⑨:file_get_contentsにてURLの情報を取得。
⑩:json_decodeにてJSON エンコードされた文字列を受け取り、それをPHPの変数に変換。
⑪:return 文により値を返す。
⑫:searchPlaceHospitalを実行。今回は引数に西馬込駅を指定。
⑬:countを用い要素をカウント。
⑭:for文を用い値を出力し、情報が取得できている確認。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?