LoginSignup
3
5

More than 3 years have passed since last update.

【Rails】Geolocation APIを用いて位置情報を取得する方法

Posted at

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

前提

下記実装済み。

Slim導入
Google Map表示

Geolocation APIを有効化

下記記事の「Geocoding APIを有効化」と同様の手順で、Geolocation APIを有効化して下さい。

Geolocation APIを用いて緯度経度を算出する方法

実装

~.html.slim
#map style='height: 500px; width: 500px;'

- google_api = "https://maps.googleapis.com/maps/api/js?key=#{ ENV['GOOGLE_MAP_API'] }&callback=initMap".html_safe
script{ async src=google_api }

javascript:

  let map;

  function initMap() {
    // 位置情報を取得
    navigator.geolocation.getCurrentPosition(function (position) {
    LatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

      // 取得した位置情報を中心に表示
      map = new google.maps.Map(document.getElementById('map'), {
        center: LatLng,
        zoom: 15
      });
    });
  }

注意

turbolinksを無効化しないと地図が切り替わらないので、必ず無効化しておきましょう。

turbolinksを無効化する方法

3
5
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
3
5