2

I'm doing google maps on ruby on rails. I'm trying to implement dynamic marker text on the map.

I find a way to add marker text in java script. How can I pass my controller data( string data retrieved from database) to java?I've searched other posts but cant understand their answer.

The javascript in html is

 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&amp;sensor=false"></script>
 <script type="text/javascript" src="../src/markerwithlabel.js"></script>
 <script type="text/javascript">
 function initMap() {

 var latLng = new google.maps.LatLng(49.47805, -123.84716);
 var homeLatLng = new google.maps.LatLng(49.47805, -123.84716);

 var map = new google.maps.Map(document.getElementById('map_canvas'), {
   zoom: 12,
   center: latLng,
   mapTypeId: google.maps.MapTypeId.ROADMAP
 });

 var marker1 = new MarkerWithLabel({
   position: homeLatLng,
   draggable: true,
   raiseOnDrag: true,
   map: map,
   labelContent: *"text"*,
   labelAnchor: new google.maps.Point(22, 0),
   labelClass: "labels", // the CSS class for the label
   labelStyle: {opacity: 0.75}
 });
 </script>

I want to replace this "text" to a variable called text,which copies @somestring from my controller,say gmaps_controller.rb

I have tried add text: "<%= @somestring %>" I put it just under var homelatlng,but no working.

I also have tried

$(document).ready(function(){
var text='<%=j @somestring%>'
})

I put this in a individual javascript tag after

<script type="text/javascript" src="../src/markerwithlabel.js"></script>

also not working.

Is there any otherway to pass data to controller?please tell me in detail Im quite a newbie. thanks in advance

infused
  • 24,000
  • 13
  • 68
  • 78
asdjkag
  • 448
  • 1
  • 7
  • 23
  • I provide an example here: https://github.com/apneadiving/Google-Maps-for-Rails – apneadiving Aug 19 '14 at 07:16
  • Can you kindly share, what does this render in the view? – Babar Aug 19 '14 at 07:24
  • @apneadiving I have read many times,try to follow http://apneadiving.github.io/ to add text to marker.but this special one is coffee script, I've tried many places to add this coffee script(tried other javascript they works!),it just not working T.T have to turn to other method.this marker with label works. – asdjkag Aug 19 '14 at 07:24
  • @Babar when I try add those 2, the map display but no marker no text.seems it goes wrong either because the text value is null or syntax error – asdjkag Aug 19 '14 at 07:26
  • In the github example, he is creating a json in the controller and sending that to the view, have you tried that? – Babar Aug 19 '14 at 07:29
  • @wen you can use html5 data attributes to pass values from view to javascript – Mandeep Aug 19 '14 at 07:29
  • @wen get rid of the quotes around the embedded rails code for a chnage. I remember I once ran into a problem like that, but can't remember how I solved it. let me look up the code. – Babar Aug 19 '14 at 07:38
  • Well, I did not sue the quotes, and it assigns a normal string to the variable. – Babar Aug 19 '14 at 07:42
  • @Babar so u mean the link's jason part works? – asdjkag Aug 19 '14 at 07:48

3 Answers3

2

how to pass data from controller to javascript in html

You can't access ruby variables in your assets. Your best bet would be to use html5 data attributes to pass data from your controller or rather i should say view to javascript. Lets suppose you have html element like this:

= link_to "some text", some_path, id: "some_id", data: {value: @some_value}  #where @some_value is set in your controller

and then access it like this in javascript

$(document).ready(function(){
  var text =  $("#some_id").data("value");
  // now text will contain some_value
});
Mandeep
  • 9,093
  • 2
  • 26
  • 36
  • Is this html5 supported by most browsers? – asdjkag Aug 19 '14 at 07:50
  • @wen yeah they do. I have tested them for ie9 and this [question](http://stackoverflow.com/questions/2412947/do-html5-custom-data-attributes-work-in-ie-6) suggests they work for older versions as well :) – Mandeep Aug 19 '14 at 07:54
  • @wen you'll have to use data attribute on some element like i have used in a link and then access it in javascript – Mandeep Aug 19 '14 at 08:06
1

Use gon gem.

step 1: add gem'gon' in your gemfile

step 2: run bundle install

step 3: add <%= include_gon %> in your view's header tag

step 4: add gon.yourpassdata="sometext" in your controller

step 5:get your data from your view,say alert(gon.yourpassdata)

done!

0

more clearer way to show map + dynamic marker on map + dynamic infowindow + clickable infowindows....Just pass the required object and include the places js from google map...this code is ready to work.here i dynamically add markers to the map with infowindows using $.each and push it into the array

i raised the similar question here

in your controller...

def show_nearby_locations_to_guest
@nearbys = Place.near("#{params[:address]}", 5,:order => "distance",:units => :km).paginate(:page => params[:page], :per_page => 10)
end

_show_nearby_locations_to_guest.js.erb

in this js.erb(to update view with new map with dynamic markers keeping in mind you have this selector(anyother also) on the page you cliked),here i have a EMPTY map and replacing it with NEW map FILLED with dynamic markers

$("#map-canvas").html("<%= escape_javascript(render(:partial => 'show_nearby_locations_to_guest')) %>");

_show_nearby_locations_to_guest.html.erb

<%= javascript_tag do%>
/////use global variable instead of using data-attribute as my resultset can have 100+ records
window.nearbys= <%=raw @nearbys.to_json %>;
<%end%>


<script type="text/javascript">
var pinColor = "000000";
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
function initialize() {
// Display a map on the page
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
map.setTilt(45);
//emtpy array to add dynamic markers
var markers=[];
//emtpy array to add dynamic infowindows 
var infoWindowContent=[];
$.each(nearbys, function(index) {
markers.push([nearbys[index]['title'], nearbys[index]['latitude'],nearbys[index]['longitude']]);
infoWindowContent.push(['<div class="info_content" >' +
'<h3'+nearbys[index]['title']+'</h3>' +
'<p><i>'+nearbys[index]['about']+'</i></p>' +
'<p><a href="/places/show/'+nearbys[index]['id']+'" data-remote="true" title="view more">view more</a></p>' +
'</div>']);
});
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow({ maxWidth: 320 }), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="+markers[i][0].charAt(0).toUpperCase()+"|FE7569|" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: pinImage
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}//initialize ends
$(document).ready(function(){
$('#map-canvas').html("<p class='text-center text-alert'><b><i>Loading map...</i><i class='fa fa-spinner fa-spin fa-2x'></i></b></p>");
//load the map after 2 seconds so that the same code can work on modals as well
setTimeout('initialize()', 2000);
Community
  • 1
  • 1
Milind
  • 4,535
  • 2
  • 26
  • 58
  • Is this window.nearbys= <%=raw @nearbys.to_json %>; copy data from controller ? what is this window? I feel urs most likely to work but I copy those to my code not working. – asdjkag Aug 20 '14 at 02:43
  • @wen... window.variable..is just a way to store values global to the page..just like you store in data-attribute=your_values...so you store it in global variable which is available to entire page and then acces it as you do usually.. give it a try... – Milind Aug 20 '14 at 08:55
  • window.nearbys= <%=raw @nearbys.to_json %>; where should I put this code?I tried window.nearbys="hi" and put alert(window.nearbys) ,it shows no message,nor does alert(nearbys) .seems not working this part? – asdjkag Aug 21 '14 at 08:05
  • @wen always remember to put ruby code in <%= javascript_tag do%> your ruby code getting set in js .... <%end%> when you are in html.erb file instead of inside – Milind Aug 21 '14 at 08:41
  • can I know whats inside your show_nearby_locations_to_guest file? I have problem separate display marker and map T.T – asdjkag Aug 25 '14 at 07:15
  • hi @wen...i have updated my answer..they all are regular methods reponding to js with a view of samw name `show_nearby_locations_to_guest` (change it to the name you want) – Milind Aug 25 '14 at 09:05