LoginSignup
0
0

More than 1 year has passed since last update.

Next.js で緯度経度を使って Contentful 上の近隣エントリを取得する

Posted at

やりたいこと

Contentful を使ってカフェの口コミサイトのようなもの (https://www.cafeinmap.com) を作っているのですが、あるカフェの近隣カフェを取得したいと思っています。もう少し細かく書くと「あるカフェから半径Xkm以内のカフェを距離の近い順に最大N件取得したい」となります。

ちなみにフロント側はNext.jsで作っており、SSG (Server Side Generation)で呼び出される getStaticProps() 内で Contentful Content Delivery API から近隣カフェデータを取得することとします。

やり方

フロント側のコードを記載します。位置情報を利用したクエリ[near]と[within]を同時に利用するのがポイントです。

なお、contentful.js を利用して Next.js からContentfulへアクセスしています。

export const getStaticProps = async (context) => {
  /* 基準となるカフェデータ取得 */
  const entry_id = context.params.id //基準となるカフェIDはクエリパラメータで受け取る
  const data = await contentful.getEntry(entry_id)

  /* 近隣カフェデータ */
  const lat = data.fields.location.lat //基準となるカフェの緯度
  const lng = data.fields.location.lon //基準となるカフェの経度
  const radius = 10 //10km
  const near = await contentful.getEntries(
    {
      'content_type': 'cafe',
      'limit': 6,
      'sys.id[nin]': data.sys.id,  //基準となるカフェ自身は除外
      'fields.location[near]': lat + ',' + lng , //近隣絞り込み
      'fields.location[within]': lat + ',' + lng + ',' + radius //10km圏内絞り込み
    }
  )

  return {
    props: {
      cafe: data,
      near: near.items
    },
  }
}

上記のコードから実際にContentful Content Delivery APIに投げられるクエリは、curlコマンドで叩くとすれば以下のようになるはずです。

curl https://cdn.contentful.com/spaces/{space_id}/environments/{environment_id}/entries?access_token={access_token}&content_type=cafe&limit=6&sys.id[nin]={data.sys.id}&fields.location[near]={lat + ',' + lng}&fields.location[within]={lat + ',' + lng + ',' + radius}

参考

contentful.js:
https://contentful.github.io/contentful.js/contentful/9.1.5/index.html

Contentful Content Delivery API:
https://www.contentful.com/developers/docs/references/content-delivery-api/

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