JSON to Map

| No Comments

Today we are going to load JSON data thats being served from our Ruby on Rails scaffold. For this lesson I'll just concentrate on reading from JSON and display it on the map. In another lesson we'll show how to setup the scaffold. Then we'll go over how to make the markers and client list clickable. For an example on what this will look like, visit http://www.ccexperts.com/dev/json-map.html or view the image below.

json-to-map.jpg


Let's dig into the code!

<script src="http://www.google.com/jsapi?key=PUTYOURAPIKEYHERE" type="text/javascript"></script>
<script type="text/javascript">

Note here we load the library API not the map API. This allows us to load whatever libraries we need. In this case we load jQuery and the Maps API.

google.load("jquery", "1.3.2");
google.load("maps", "2");

This function is called after the page fully loads and the Google API's are loaded. It starts out by building a simple map

function loaded(){
var map = new GMap(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng( 39.17165,-76.619951),9);
Now the map is loaded we use jQuery's getJSON function to call our Ruby scaffold. It's important to add the ?callback=? argument. If we didn't do this it would not work - more on that another time. $.getJSON("http://www.ccexperts.com:3000/clients?callback=?",
function(data){
$.each(data, function(i,item){
We loop over every client. $.each(item, function(j,small){
Read the lat and lng info and make a new point. Then plot that point on the map. var point = new GLatLng(small.lat,small.lng);
marker = new GMarker(point);
map.addOverlay(marker);
Now we use jQuery create a <LI> element for every client that contains the client name. We put this list inside the info <div> I already created. $("<li/>").html(small.firmname).appendTo("#info");
});
});
});
}
This tells us to call our loaded function when everything is up. google.setOnLoadCallback(loaded);
</script>

Easy enough!

As you can see it's pretty straight forward. I left plenty of room to expand on this later such as making the client list clickable to open info windows.