florian
florian

Reputation: 1001

Add markers from rails database

I'm creating a map with Google Maps API to reference restaurants based on their location. Each restaurant in my database (sqlite3) has a title, a description and two coordinates (latitude, longitude). I can successfully create entries in my database but struggle to find a solution to call in JS each restaurant's coordinates from the database.

Different solutions have been proposed on Stackoverflow of which this one, another and a last one, but none of the answers my question as I'm working exclusively with JS and Ruby (on rails).

Would you have suggestions ?

Upvotes: 0

Views: 1044

Answers (3)

hedin
hedin

Reputation: 1024

First, you need to read this example from Goolge Maps Javascript API and play with this code:

<!DOCTYPE html>
<html>
<head>
<style>
   #map {
    height: 400px;
    width: 100%;
   }
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
  function initMap() {
    var uluru = {lat: -25.363, lng: 131.044};
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: uluru
    });
    var marker = new google.maps.Marker({
      position: uluru,
      map: map
    });
  }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&callback=initMap">
</script>
</body>
</html>

As you can see here, you need to

  • create your own GOOGLE_MAPS_API_KEY here
  • create div with id;
  • connect Google's javascript, which when will load, will load also js-function initMap()
  • define initMap-function with map and marker settings.

Next step: getting data from database and passing to JavaScript.

I used gon gem for transferring data from backend to frontend:

in controller:

# app/controllers/application_controller.rb
def root
  gon.locations = Location.all
end

in layout:

<!-- app/views/layouts/application.html.erb -->
<head>
<%= include_gon %>
<!-- ... -->
</head>

in view:

<!-- app/views/application/root.html.erb -->
<script>
  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: { lat: gon.locations[0].lat, lng: gon.locations[0].lng }
    });

    for(var i = 0; i < gon.locations.length; i++){
      new google.maps.Marker({
        position: { lat: gon.locations[i].lat, lng: gon.locations[i].lng },
        title: gon.locations[i].name,
        map: map
      });
    }
  }
<script>

But, if you don't want use gon gem for passing data from backend to frontend, you can do this by plain rails:

# app/controllers/application_controller.rb
def root
  @json_data = {
    locations: {
      # ...
    },
    # ...
  }.to_json
end

<!-- views/posts/edit.html.erb -->
<script>
  var json_data = JSON.parse('<%= raw(escape_javascript(@json_data)) %>');
</script>

Also, I created rails demo application, you can play with it.

  • This commit doing all job, to write 'ICE' word by markers on Antarctica. enter image description here
  • See these files for more details:
    • app/controllers/application_controller.rb
    • app/views/application/root.html.erb
    • app/views/layouts/application.html.erb
  • I used this online service to create coordinates for 'ICE' word

Upvotes: 3

pip36
pip36

Reputation: 126

One way you could try is by using json. For example in the controller.

class RestaurantsController < ApplicationController
  def show
    @restaurant = Restaurant.find(params[:id])

    respond_to do |format|
      format.html
      format.json {render json: @restaurant}
    end

  end
end

Then the restaurant can be accessed in javascript (I'll use JQuery)

 $.getJSON("show_page_url.json", function(data){
   //data will contain the @restaurant object 
   //so data.latitute should return the value
}

Maybe this helps. I used it for a simple project I did recently, but maybe there are better methods.

Upvotes: 2

wesley6j
wesley6j

Reputation: 1403

To make variables in your rails app accessible for js code, you need to save these values in rendered html and later your js code can take values from html. You can use gon so you don't have to write the solution yourself. Here are the steps to get it working:

  1. install the gem 'gon'.
  2. add <%= Gon::Base.render_data %> to your layout.
  3. set variable: gon.push(restaurants: restaurants).
  4. in your js code, read data and pass it to your map.

Upvotes: 1

Related Questions