I am working on a web application and I am using Ruby on Rails. Our index is composed of a map and a search field. You can find the location and the map will update its markers.
I would like to use Ajax so as not to refresh the page. So I added remote: true to the form, respond_to to the controller, and the new search.js.erb. My search.js.erb displays a partial _googlemap.erb that contains a script to initialize the map.
Here is my problem. Since the map already exists, it looks like I would like to create the same object twice, which, of course, does not work, and this is terrible. I would like to update only the markers on the map with new ones. But I can’t find a way to do this.
I saw that the previous version of Gmaps4rails integrated the way to do this ( Gmaps.map.replaceMarkers(your_markers_json_array); ), but now it does not work. When I use it, I got this error: " TypeError: Gmaps.map is undefined ". I tried with " handler.replaceMarkers(); " but this time I have " TypeError: handler.replaceMarkers is not a function ".
I am new to Javascript and Rails, but I want to improve my knowledge and I really need to continue working with this web application. I searched for a solution everywhere on the Internet, but in vain.
Live site here
Please can someone tell me how can I do this and what am I doing wrong?
MANY thanks in advance
Celine
zones_controller.rb
def search respond_to do |format| format.html.none do search_params = params[:zone][:search] coordinates = Geocoder.coordinates(search_params).join(",") @zones = Zone.search( "", { "aroundLatLng" => coordinates, "aroundRadius" => 500000
search.html.erb
<div id="map" style='width: 100%; height: 700px;'> </div> <script type="text/javascript" id="map_script"> $(document).ready(function() { <%= render 'googlemap', hash: @hash %> }); </script>
_googlemap.erb
handler = Gmaps.build('Google'); handler.buildMap({ provider: { disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.TERRAIN }, internal: {id: 'map'} }, function(){ markers_json = <%= raw hash.to_json %>; markers = _.map(markers_json, function(marker_json){ marker = handler.addMarker(marker_json); handler.getMap().setZoom(4); _.extend(marker, marker_json); marker.infowindow = new google.maps.InfoWindow({ content: marker.infowindow }); return marker; }); handler.bounds.extendWith(markers); handler.fitMapToBounds(); });
search.js.erb
$('#map_script').replaceWith("<%= render 'googlemap', hash: @hash %>");