apneadiving / Google-Maps-for-Rails

Enables easy Google map + overlays creation in Ruby apps
https://apneadiving.github.io/
MIT License
2.27k stars 382 forks source link

How to add search bar to gmaps4rails #524

Closed CTam8 closed 8 years ago

CTam8 commented 8 years ago

In my app I am using gmaps4rails gem and google maps api v3. What I want to do is to add a search bar similar to what its like in google maps so that I can find markers in a specific area. When I complete a search,all the markers disappear. This can be seen in my images attached. Why is that happening and how do I fix it?

index.html.erb

<script type="text/javascript" src="//maps.google.com/maps/api/js?key=i-enter-my-api-key-here&sensor=false&amp;libraries=geometry,places"></script>
<script src="//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js"></script>

<html>
<body>

  <div id="map-container">
    <input id="pac-input" class="controls" type="text" placeholder="Search Box" />
    <div id="all_markers" class="map-canvas"></div>
  </div>

<script>

    var handler = Gmaps.build('Google');
    handler.buildMap({ internal: {id: 'all_markers'}}, function(){
      var markers = handler.addMarkers(<%=raw @hash.to_json %>);
      handler.bounds.extendWith(markers);
      handler.fitMapToBounds();
    });

  // Create the search box and link it to the UI element.
  var map = new google.maps.Map(document.getElementById('all_markers'))
  var input = document.getElementById('pac-input');
  var searchBox = new google.maps.places.SearchBox(input);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

  // Bias the SearchBox results towards current map's viewport.
  map.addListener('bounds_changed', function() {
  searchBox.setBounds(map.getBounds());
  });

  // Listen for the event fired when the user selects a prediction and retrieve
  // more details for that place.
  searchBox.addListener('places_changed', function() {
  var places = searchBox.getPlaces();

  // For each place, get the icon, name and location.
  var bounds = new google.maps.LatLngBounds();
  places.forEach(function(place) {
    if (!place.geometry) {
      console.log("Returned place contains no geometry");
      return;
    }

    if(place.geometry.viewport) {
      // Only geocodes have viewport.
      bounds.union(place.geometry.viewport);
    } else {
      bounds.extend(place.geometry.location);
    }
  });
  map.fitBounds(bounds);
});

</script>

</body>
</html>
screen shot 2016-08-02 at 10 41 04 pm 2 screen shot 2016-08-02 at 10 41 33 pm 2
devlvng commented 5 years ago

Hi there, just interested but how were you able to solve the disappearing markers?

My code is similar to yours, albeit with an infowindow, but when I perform a search, the markers disappear completely.