DEV Community

Cover image for How to use the Browser Geolocation API with StimulusJS and Rails
Yaroslav Shmarov
Yaroslav Shmarov

Posted on • Originally published at blog.corsego.com on

3

How to use the Browser Geolocation API with StimulusJS and Rails

Task: get users coordinates from browser, redirect to page with coordinates in params:

geolocation-api-search.gif

To request users’ location, we will use Web/API/Geolocation/getCurrentPosition with StimulusJS.

Create stimulus controller:

rails g stimulus geolocation
Enter fullscreen mode Exit fullscreen mode
// app/javascript/controllers/geolocation_controller.js
import { Controller } from "@hotwired/stimulus"

const options = {
  enableHighAccuracy: true,
  maximumAge: 0
};

// Connects to data-controller="geolocation"
export default class extends Controller {
  static values = { url: String }

  search() {
    navigator.geolocation.getCurrentPosition(this.success.bind(this), this.error, options);
  }

  success(pos) {
    const crd = pos.coords;
    // redirect with coordinates in params
    location.assign(`/locations/?place=${crd.latitude},${crd.longitude}`)
  }

  error(err) {
    console.warn(`ERROR(${err.code}): ${err.message}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

Finally, a button to get location:

<div data-controller="geolocation">
  <button data-action="geolocation#search">search near me</button>
</div>
Enter fullscreen mode Exit fullscreen mode

💡 Interestingly, if you use this.success instead of this.success.bind(this), stimulus targets will not work within the success function.

Get address from coordinates

Get address (city, street...) based on coordinates using geocoder , and search near the address:

# app/javascript/controllers/geolocation_controller.js
- location.assign(`/locations/?place=${crd.latitude},${crd.longitude}`)
+ location.assign(`/locations/?coordinates=${crd.latitude},${crd.longitude}`)
Enter fullscreen mode Exit fullscreen mode
# app/controllers/locations_controller.rb
  def index
+    if params[:coordinates].present?
+      place = Geocoder.search(params[:coordinates])
+      params[:place] = place.first.address
+    end

    if params[:place].present?
      @locations = Location.near(params[:place], params[:distance] || 10, order: :distance)
    else
      @locations = Location.all
    end
  end
Enter fullscreen mode Exit fullscreen mode

That’s it! Now you can get Geolocation with Javascript and use it within a Rails app!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay