はじめに
こんにちは、山田です。
今回は、作成中のアプリで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文
を用い値を出力し、情報が取得できている確認。