Antonin Mrchd Antonin Mrchd - 9 days ago 6
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 = Array.new()
@post_all.each do |pos|
@geojson << {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [pos.longitude, pos.latitude]
},
properties: {
name: pos.title,
address: pos.country,
:'marker-color' => '#d9534f',
:'marker-symbol' => 'circle',
:'marker-size' => 'medium'
}
}
end
respond_to do |format|
format.html
format.json { render json: @geojson } # respond with the created JSON object
end
end


my application.js file :

$(document).ready(function(){
L.mapbox.accessToken = "pk.eyJ1IjoiYW50b3RvIiwiYSI6ImNpdm15YmNwNTAwMDUyb3FwbzlzeWluZHcifQ.r44fcNU5pnX3-mYYM495Fw";
var map = L.mapbox.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'
})
})
.bindPopup('hello')
.addTo(map);
map.scrollWheelZoom.disable();

$.ajax({
dataType: 'json',
url: '/#{:id}/show.json',
success: function(data) {
geojson = $.parseJSON(data)
console.log(data)
map.featureLayer.setGeoJSON(geojson)
},
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

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 = <%= current_user.id %>; grabUserData(thisID);

Comments