Playing with OpenStreetMap and Cloudmade

I’ve been doing some research into using maps in a web application, and I wanted to check out the different providers that are available.  Since hearing that Apple was moving away from the Google Maps API in iPhoto, I was curious to give it a try myself.

Since OpenStreetMap is a “free” alternative for mapping data, I looked around and CloudMade.com was the first provider with an API that I was able see an easy way to use.  It works very similar to Google Maps, and has a similar javascript API.

Here’s how I added it to a simple Rails 3 app…

First, I created a new controller “app/controllers/maps_controller.rb” and put an index function in:

class MapsController < ApplicationController
  def index
  end
end

Next, I created a separate javascript doc “app/assets/javascript/maps.js”:

$(document).ready(function(){ /*code here*/ 
    var cloudmade = new CM.Tiles.CloudMade.Web({key: 'my_key'});
    var map = new CM.Map('map_canvas', cloudmade);

    
     var geocoder = new CM.Geocoder('my_key');
  
    geocoder.getLocations('Durham, NC', function(response) {
      var southWest = new CM.LatLng(response.bounds[0][0], response.bounds[0][1]),
	      northEast = new CM.LatLng(response.bounds[1][0], response.bounds[1][1]);
      map.zoomToBounds(new CM.LatLngBounds(southWest, northEast));
      
    });
   
    map.addControl(new CM.LargeMapControl());
});

Next, I created the maps index view “app/views/maps/index.html.rb” with a link to the open maps javascript library and the maps javascript doc:

<% content_for(:head) do %>
<%= javascript_include_tag "http://tile.cloudmade.com/wml/latest/web-maps-lite.js", :maps %>
<% end %>

<script>
  user = <%= current_user %>
</script>

<br />
<br />
<div id="map_sidebar">Top Restaurants </div>
<div id="map_canvas"></div>

Finally, modify the routes.rb file to allow localhost:8080/maps to be directed to my new controller and view:

  match "/maps" => "maps#index"

Add this all up and we get a nice map showing on our page:

The only weird thing I noticed is that there are some issues when zooming in.  After a certain point, the tiles stop loading:

If you’re interested in learning more, the CloudMade tutorials show pretty much how to do everything in easy steps here.

Tagged , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *