Rails, Google maps, Javascript and JSON all at once. So I apologize if this is a simple question.
I have a rails app with a database of listings that each have a latitude and longitude. What I want to do is when the page loads, I would like to show all the listings on the map.
So I have the listings_controller.rb, application.js, index.html.erb as follows. Im using this book as a reference for my code, but the problem is its examples use Google maps version thats deprecated.
The steps I need to execute with my code are as follows:
- index.html.erb executes code in application.js
- application.js calls a function in listings_controller.rb which takes all the listings in the Listing model and converts them into a giant JSON object.
- application.js now has the JSON array of listings and parses it within a loop and extracts the name of the listing, its latitude and longitude and some other fields and passes this information to the javascript method “addMarker(latitude, longitude, description, map)”
The problem is I only know how to do parts of these steps as listed below. I was wondering if someone can fill in the holes and help me.
index.html.erb
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyATZJn-p3mhbyk9JmR8mevKAbtrx4ZzPiQ&sensor=false">
</script>
<%=javascript_include_tag 'application' %>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:80%; height:80%"></div>
</body>
</html>
listings_controller.rb
def index
@listings = Listing.order(:name)
self.all_listings_json
end
def all_listings_json
render :text=>(@listings).to_json
end
application.js
function initialize()
{
options =
{
center: new google.maps.LatLng(vlat,vlong),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), options);
//get JSON object
var markersArray = getMarkersJSON();
//pass JSON object to method and add listings in array to map
addMarkerArray( markersArray , map);
}
function getMarkersJSON()
{
//To do
}
function addMarkerArray( markersArray, map)
{
var i;
for(i = 0; i < markersArray.length ; i++)
{
//To DO
}
}
So you already have the JSON object by the time you build your map?
Then all you need to do is to run trough your object:
You can check the Google Maps documentation here:
https://developers.google.com/maps/documentation/javascript/overlays