September 25th, 2008 By: Wes
This tutorial will guide you through creating a map using the Google Maps API that will be dynamically populated with markers as the user zooms or scrolls around the map.
For this example, we’re going to create and use a generic
Location
model.Geocoding Your Addresses
Geocoding will translate an address into its approximate latitude and longitude.
We’ll use GeoKit, a Ruby on Rails plugin to geocode our addresses. Install it with:
Follow the instructions to obtain and install your own Google API key.
Generate the model, controller and views for our map locations:
We also need to edit the migration file for this model and add fields for the location’s latitude and longitude:
Replace the code in
app/models/location.rb
with:
That’s all there is to geocoding, now any time we create a Location it will automatically be assigned a latitude and longitude.
Adding the Google Map
In
app/views/locations/index.html.erb
add:
And in
app/views/controllers/locations_controller.rb
, change the index action to:
The index action will now respond to javascript requests with a JSON object containing the first 100 Locations inside of the map boundaries.
In your layout file, add this code inside of the
<head>
tag:
And finally, create a
public/javascripts/maps.js
file with this code:
The
updateMap()
function is run after the page initially loads and each time the user moves or zooms the map. It sends an AJAX request to the server with the maps boundaries, and the server returns a JSON object of the locations within those boundaries. After it receives the JSON object, it will add new locations to the map (it skips locations that have already been mapped) and removes locations that are no longer within the visible map boundaries.
A sample app containing all of the code can be downloaded here: map-sample-code.zip
December 11th, 2008 at 3:14 pm
December 11th, 2008 at 4:11 pm
December 11th, 2008 at 5:16 pm
December 11th, 2008 at 5:27 pm
December 12th, 2008 at 3:17 am
April 15th, 2009 at 4:15 pm
September 29th, 2009 at 2:09 pm