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?

Google Maps APIの利用メモ

Posted at

Google Maps APIの利用に気づいた点をメモする

GOOGLE_MAPS_API_KEYの保護

  • SPAのフロント側でgoogle maps apiを利用する場合、GOOGLE_MAPS_API_KEYがバレてしまう
  • GOOGLE_MAPS_API_KEYがバレても悪用されないようにリファー制限機能がgoogleにより用意されている
  • フロント側でそれのRest apiのURLを直接にfetchした場合はgoogleが介在できないので、リファー制限できない
  • フロント側でリファラー制限を効かせるには、Rest apiをやめてMaps JavaScript API(ライブラリ)を利用する

Maps JavaScript APIの利用例

  • インストール
npm i @react-google-maps/api
  • 利用例
export const useGoogleMaps = () => {
  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY!,
    language: 'ja',
    region: 'JP',
    libraries: ['geocoding'],
  });

  const isPostCodeExist = useCallback(
    (postCode: string): Promise<boolean | null> => {
      return new Promise((resolve) => {
        if (!isLoaded) return resolve(null);

        const geocoder = new google.maps.Geocoder();
        if (!geocoder) return resolve(null);

        geocoder.geocode({ address: postCode }, (results, status) => {
          if (status === google.maps.GeocoderStatus.OK) {
            resolve(results !== null && results.length > 0);
          } else if (status === google.maps.GeocoderStatus.ZERO_RESULTS) {
            // 存在しない
            resolve(false);
          } else {
            // 通信エラー
            resolve(null);
          }
        });
      });
    },
    [isLoaded],
  );

  return { isLoaded, isPostCodeExist };
};

geocoder.geocodeメソッドの第2引数のコールバック関数を利用する理由

  • ZERO_RESULTSを処理したいからである
  • 第2引数のコールバック関数を利用せずtry catchでやる場合、errorからそれを判別し難い

geocoder.geocodeメソッドの第2引数を利用しない場合の書き方

const isPostCodeExist = useCallback(
    async (postCode: string) => {
      if (!isLoaded) return null;

      try {
        const geocoder = new google.maps.Geocoder();
        if (!geocoder) return null;

        const res = await geocoder.geocode({ address: postCode});
        return res.results.length > 0;
      } catch (error) {
        console.error(error);
        // ZERO_RESULTSの場合もerrorになるので、ここで片別するしかないが、やり難い
        // 本当の通信エラーと存在しないを区別できない
        return null;
      }
    },
    [isLoaded],
  );
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?