How to display all location markers in google map via Google api in rails

796 views Asked by At

I have added few locations using Geocoder gem. Now I want to display all of them in the google map using Google Api. So far after a lot of google and SO search, I have this code in my index.html.erb:

let locations = [
  ['<%= @location[0].address %>', '<%= @location[0].latitude %>','<%= @location[0].longitude %>'],
  ['<%= @location[1].address %>', '<%= @location[1].latitude %>','<%= @location[1].longitude %>'],
  ['<%= @location[2].address %>', '<%= @location[2].latitude %>','<%= @location[2].longitude %>']
];

let map = new google.maps.Map(document.getElementById('map'), {
  zoom: 7,
  center: new google.maps.LatLng('<%= request.location.latitude %>', '<%= request.location.longitude %>'),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

let infowindow = new google.maps.InfoWindow();

let marker, i;

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

Here I want the location be added dynamically from the database and show it in the map. I have tried using google-maps4rails gem but it didn't give me any result so I tried using Google api. Any suggestion? Thank you :)

1

There are 1 answers

1
Michael Geary On

Your latitude and longitude values are quoted strings. These need to be numbers. Take the quotes out around these.

Also you can simplify the code by putting the loop body in its own function. Then you don't need the hard to understand function-that-returns-a-function. An easy way to do this is to use forEach which calls a function for each loop iteration. Note how this makes the code simpler and easier to understand:

let locations = [
  ['<%= @location[0].address %>', <%= @location[0].latitude %>,<%= @location[0].longitude %>],
  ['<%= @location[1].address %>', <%= @location[1].latitude %>,<%= @location[1].longitude %>],
  ['<%= @location[2].address %>', <%= @location[2].latitude %>,<%= @location[2].longitude %>]
];

let map = new google.maps.Map(document.getElementById('map'), {
  zoom: 7,
  center: new google.maps.LatLng('<%= request.location.latitude %>', '<%= request.location.longitude %>'),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

let infowindow = new google.maps.InfoWindow();

locations.forEach( function( location ) {
  let marker = new google.maps.Marker({
    position: new google.maps.LatLng(location[1], location[2]),
    map: map
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(location[0]);
    infowindow.open(map, marker);
  });
}