0

I need to display a google map with several markers. The problem I have is to set all the markers on the map. I have a city controller and a map view. Here is the relevant code:

city_cntroller.rb

def map
    @city = City.find(params[:id])
    @mapcenter = @city.geocode
    @businesses = @city.businesses
    @numberofbusinesses = @city.businesses.count
end

map.html.haml

%script{:type => "text/javascript", :charset => "utf-8", :src => "http://maps.googleapis.com/maps/api/js?v=3.6&sensor=false&region=IN"}
%script{:type => "text/javascript"}
  function initialize() {

  var cityLatlng = new google.maps.LatLng(
  = @mapcenter[0]
  ,
  = @mapcenter[1]
  );

  var options = {
  zoom: 12,
  center: cityLatlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("map_canvas"), options);

  var businesscount = (
  = @numberofbusinesses
  )

  for (var i = 0; i <= businesscount; i++) {
  var marker = new google.maps.Marker({
  position: new google.maps.LatLng(
  = @businesses[i].latitude
  ,
  = @businesses[i].longitude
  ),
  map: map,
  });
  };
  }
%body{ :onload => "initialize()" }
  %div#map_canvas{:style => "width: 900px; height: 350px;"}

The problem is that "i" is not accepted when I try to loop through @businesses, the error message is

undefined local variable or method `i' for #<#:0xbd2d970>

How can i loop through @businesses to place all the markers on the map?

Thanks for your help!

user929062
  • 807
  • 4
  • 12
  • 33

1 Answers1

1

Your code does not work, because you are mixing server and client-side scripts. The variable exists in the browser, the @businesses data is only available to the server.

In general, you should try to export your data structure to JSON, which JavaScript can read inline, and then iterate over it on the client side.

The response JavaScript should look something like this:

// exported from rails
var businesses = [ { lat: 123, long: 632 }, { lat: 435, lon: 214 } ];

for (var i = 0; i < businesses.length; i++)
{
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(businesses[i].lat, businesses[i].lon),
        map: map
    });
}

You can read how export things to JSON in this post.

Community
  • 1
  • 1
copy
  • 3,301
  • 2
  • 29
  • 36
  • Thanks I'll try it out. But why is '@mapcenter' working? It perfectly centers the map according to '@mapcenter' from the city_controller... – user929062 Dec 21 '11 at 14:27
  • `@mapcenter[0]` is a scalar number. You can echo numbers, so they appear as a constant in the JavaScript. In your loop however, you mixed client-side and server-side variables (@businesses and i). – copy Dec 21 '11 at 15:01