Search code examples
ruby-on-railsruby-on-rails-4gmaps4rails

gmap4rails zoom in based on current_user's location


I'm using the new gmaps4rails with rails 4.1 I have succeeded in showing all markers on the map although the map zooms out to show the whole world with all markers. I would like the map to start off zoomed in within a certain radius of the current_user. How would I go about that? Thank you

my view:

<div style='width: 100%;'>
  <div id="big_map" style='width: 100%; height: 500px;' data-lat= "<%= current_user.latitude %>" data-lng= "<%=current_user.longitude %>"></div>
</div>

<script type="text/javascript">
    handler = Gmaps.build('Google');
    handler.buildMap({ provider: {}, internal: {id: 'big_map'}}, function(){
      markers = handler.addMarkers(<%= raw(@hash.to_json) %>);
      handler.bounds.extendWith(markers);
      handler.fitMapToBounds();
    });
</script>

my action:

  def map
    if user_signed_in?
      @users = User.where('latitude IS NOT NULL').all
      @hash = Gmaps4rails.build_markers(@users) do |user, marker|
      marker.lat user.latitude
      marker.lng user.longitude
    end
    else
      redirect_to new_user_registration_url
    end
  end

Solution

  • var currentUserPosition = <%=raw [ current_user.latitude, current_user.longitude].to_json %>;
    var handler = Gmaps.build('Google');
    handler.buildMap({ provider: {}, internal: {id: 'big_map'}}, function(){
      var markers = handler.addMarkers(<%= raw(@hash.to_json) %>);
      handler.map.centerOn(currentUserPosition);
    
      // if you want to set the zoom level
      // handler.getMap().setZoom(10)
    
      // if you want to adapt on current user, no need to do this
      // handler.bounds.extendWith(markers);
      // handler.fitMapToBounds();
    });