[Java] [Rails] How to get location information using Geolocation API

less than 1 minute read

Development environment

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


The following has been implemented.

Slim introduction
Google Map display

Enable Geolocation API

Please enable the Geolocation API by following the same procedure as” Enabling the Geocoding API “in the article below.

How to calculate latitude / longitude using Geolocation API



#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 }


  let map;

  function initMap() {
    //Get location information
    navigator.geolocation.getCurrentPosition(function (position) {
    LatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

      //Display mainly the acquired location information
      map = new google.maps.Map(document.getElementById('map'), {
        center: LatLng,
        zoom: 15


If you do not disable turbolinks, the map will not switch, so be sure to disable it.

How to disable turbolinks