Antonin Mrchd Antonin Mrchd - 1 year ago 77
Ruby Question

Generate marker with rails, ajax and Mapbox

I want my users be able to generate markers on their own maps (on their profile page), when they create a post and enter a country.
For now, I'm able to create a post, to choose a country, and save longitude and latitude using geocoder gem, but I am not able to generate the marker using ajax call, here is my codes :

users_controller.rb (show method):

def show
@post_all = @user.posts
@geojson =
@post_all.each do |pos|
@geojson << {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [pos.longitude, pos.latitude]
properties: {
name: pos.title,
:'marker-color' => '#d9534f',
:'marker-symbol' => 'circle',
:'marker-size' => 'medium'
respond_to do |format|
format.json { render json: @geojson } # respond with the created JSON object

my application.js file :

L.mapbox.accessToken = "pk.eyJ1IjoiYW50b3RvIiwiYSI6ImNpdm15YmNwNTAwMDUyb3FwbzlzeWluZHcifQ.r44fcNU5pnX3-mYYM495Fw";
var map ='map').setView([48.856614, 2.3522219000000177], 4);
var style = L.mapbox.styleLayer("mapbox://styles/antoto/civn0z51d00002ko4tmlch2zn").addTo(map);
var marker = L.marker([48.856614, 2.3522219000000177], {
icon: L.mapbox.marker.icon({
'marker-color': '#d9534f'

dataType: 'json',
url: '/#{:id}/show.json',
success: function(data) {
geojson = $.parseJSON(data)
error: function(data) {
console.log(data + ' error')

I think that there are problems in my URL in the ajax call, but when a create the geojson I don't know what url to use.

Answer Source

I believe your application.js file is the issue here. You have this line url: '/#{:id}/show.json', where you are expecting(?) rails would interpolate your current user_id value for you...

Instead I think the better solution would be making a function called grabUserData(user_id), and making the url line for the ajax call url: '/' + user_id + '/show.json',...

Call this JS function from somewhere in your html where you have the user_id in question from rails dumped out to your page.

var thisID = <%= %>; grabUserData(thisID);