とろろこんぶろぐ

かけだしR&Dフロントエンジニアの小言

nuxtで位置情報取得するサービスを作る

概要

nuxtのSSRモードで位置情報取得は行えないので、SSRを行わないようにする。

具体的には、 <no-ssr> で囲むことで該当箇所がCSRになるので、 getCurrentPosition をクライアント側で呼び出すことができる。

該当するコード

<template>
  <div>
    <no-ssr>
      <section class="container">
         ...
      </section>
    </no-ssr>
  </div>
</template>

<script>
function getCurrentPositionPromise(options) {
  return new Promise(function(resolve, reject) {
    navigator.geolocation.getCurrentPosition(resolve, reject, options);
  });
}

async function getLocation() {
  if (navigator.geolocation) {
    try {
      const result = await getCurrentPositionPromise();
      return result;
    } catch (e) {
      console.error(e);
      throw e;
    }
  } else {
    console.log("can not get a location data in this browser.");
    throw null;
  }
}

export default {
  name: "Home",
  async mounted() {
    try {
      const position = await getLocation();
      console.log("getLocation", position);
      ...
    } catch (e) {
      console.error(e);
    }
  },
};
</script>

参考

ja.nuxtjs.org