google mapのapiから周辺のカフェを取得したときのメモ
api keyを取得する
まずはgoogle cloud platformからapi keyを取得します。今回はwebアプリで取得するのでPlaces APIに加えてMaps JavaScript APIも有効にします。下記ドキュメントを参考にkeyを取得
作成したプロジェクトのダッシュボードで画像のように表示されていればOK

有効なAPIにPlaces APIとMaps JavaScript APIが確認できます。
次に、api keyにアクセス制限を掛けます。
認証情報 -> 作成したapi keyを選択
- アプリケーションの制限 : HTTPリファラーを選択
- webサイトの制限 : 使用するサイトのドメインを指定 (localで動かす場合はlocalhost/*)

これでapi keyの準備が出来ました。
place libraryを読み込み
では、実際にwebアプリケーション側でapiを呼び出すために、place libraryを読み込みます。
index.htmlのhead内に以下を追加
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
YOUR_API_KEYを先ほど取得したkeyに置き換えてください。
ついでに、index.htmlのbody内に以下を追加
<div id="map" style="height: 500px;"></div>
このdivの中にgoogleマップが表示されます。
place libraryの関数を使用して近くのカフェを取得
以下関数を作成します。
let map: google.maps.Map;
let service: google.maps.places.PlacesService;
let infowindow: google.maps.InfoWindow;
export const initMap = () => {
const sendai = new google.maps.LatLng(38.26039273442388, 140.88246968423428);
map = new google.maps.Map(document.getElementById('map') as HTMLElement, {
center: sendai,
zoom: 16
});
infowindow = new google.maps.InfoWindow();
const request: google.maps.places.TextSearchRequest = {
query: '検索文字列',
type: 'cafe',
location: sendai
};
service = new google.maps.places.PlacesService(map);
service.textSearch(
request,
(results: google.maps.places.PlaceResult[] | null, status: google.maps.places.PlacesServiceStatus): void => {
if (status === google.maps.places.PlacesServiceStatus.OK && results) {
const len = results.length;
for (let i: number = 0; i < len; i++) {
createMarker(results[i]);
}
}
}
);
};
const createMarker = (place: google.maps.places.PlaceResult) => {
if (!place.geometry || !place.geometry.location) return;
const marker = new google.maps.Marker({
map,
position: place.geometry.location,
title: place.name
});
marker.addListener('click', () => {
infowindow.setContent(place.name || '');
infowindow.open(map, marker);
});
};
initMapを任意の場所で呼び出してあげると、仙台駅付近のカフェを取得できます。
new google.maps.LatLngに渡す座標を変えると場所の変更ができます。
検索文字列を変えると文字列によるクエリを追加できます。
type: ‘cafe‘,をtype: ‘restaurant’に変えると付近のレストランを取得できます。
取得できる場所のtypeの種類をもっと知りたい方はgoogleの公式ドキュメントを確認してください。

正しく実行できると、以下のようにピンが表示され、ピンをクリックすると場所の名前が表示されます。