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
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
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
app/views/controllers/locations_controller.rb, change the index action to:
In your layout file, add this code inside of the
And finally, create a
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