Saturday, October 26, 2013

Custom Map Markers - gmaps4rails Gem

Another goal of my first project at GA was to use the location data I acquired from the image metadata, to plot thumbnails of the image on Google Map.  I was able to accomplish this using the Google Maps API documents, but my first attempt was accomplished using pure JavaScript and iterating through a nested array of images paths (using the Rails asset_path) and locations.  From this I could see that images as map markers were possible, but the challenge was to get my ruby "post" object into the JavaScript and iteratively retrieve each image's path and latitude/longitude combination.

Due to my lack of knowledge in JavaScript I implemented the Ruby Gem gmaps4rails.  In my Posts Controller I was able to utilize this Gem to create a nested array of hashes containing latitude, longitude, and image path data.

 def index
    @posts = Post.all
      @hash = Gmaps4rails.build_markers(@posts) do |post, marker|
        marker.lat post.latitude.to_f
        marker.lng post.longitude.to_f
        marker.picture({
                  :url => post.image.url(:thumb),
                  :width   => 60,
                  :height  => 60
          })
      end
  end

Now in the index view of my posts controller I call the JavaScript that targets a div with the ID of "map" and then builds the map with custom map image markers:

<script>
  handler = Gmaps.build('Google');
  handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
  markers = handler.addMarkers(<%=raw @hash.to_json %>);

  handler.bounds.extendWith(markers);
  handler.fitMapToBounds();
});

  google.maps.event.addListener(marker, 'mouseout', function(){
    infowindow.open(marker.get('map'), marker);
    });
</script>


View the project on Github: https://github.com/dtothefp/dylanthedog

No comments:

Post a Comment