Rails Against The Machine

Just a mind dump. Why are you even reading this?

Tuesday, 7 October 2008

 

Google maps directions without markers

Ok, suppose you want to display a route on the map generated by google's route planning algorithm. But you don't want the way points to appear you just want to draw the polyline. Also you want to do some processing server side first. For example if you are just interested in getting the distance between two points rather than actual directions for use in some crazy as program you are writing.

In your controller do something like this.

require "json"
require 'net/http'
class MapController < ApplicationController

def index
def get_response v
Net::HTTP.get_response(URI.parse(v))
end
data=get_response 'http://maps.google.com/maps/nav?q=from:%20berlin%20to:%20london&output=js&hl=es'
@result = data.body
end



end


btw: if you had do JSON.parse(data.body) you can extract parameters from the returned json object as a hash to use however you want.

In your view you do something like this.
1)Set the javascript variable 'route' equal to the @results instance variable.
2)Create a new polyline from the polyline subobject.

<head>
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAABigEsKG95vfiiA8xoEc_lRTSLFpLV9kZAti9u7YqBb88417uPxSs1hcTAggwKX8F0qh_mSZL8Y-_Rw"></script>
<%= javascript_tag "var route = #{@result}" %>
<script type="text
/javascript">
google.load(
"maps", "2.x");

// Call this function when the page has been loaded
function initialize() {
if (GBrowserIsCompatible()) {
var myCopyright = new GCopyrightCollection(
");
myCopyright.addCopyright(new GCopyright('Demo', new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)),0,'©2007 Google'));

var map = new GMap2(document.getElementById(
"map"));
map.addControl(new GSmallMapControl());
map.setCenter(new GLatLng(51.53608560178475, -0.06591796875), 6);//

var polyline = new GPolyline.fromEncoded(route.Directions.Polyline);
map.addOverlay(polyline);

}
}
google.setOnLoadCallback(initialize);
</script>
</head>

<div id=
"map" style="width: 500px; height: 300px"></div>


You can be a bit more sophisticated if you like and play with the polygons attributes individualy

var thing_to_draw=route.Directions.Polyline
var polyline = new GPolyline.fromEncoded({
color: "#df2518",
weight: 4,
opacity: 0.8,
points: thing_to_draw.points,
levels: thing_to_draw.levels,
zoomFactor:thing_to_draw.zoomFactor,
numLevels: thing_to_draw.numLevels
});

Archives

July 2007   August 2007   September 2007   December 2007   January 2008   February 2008   March 2008   April 2008   June 2008   July 2008   August 2008   October 2008   November 2008   January 2009  

This page is powered by Blogger. Isn't yours?

Subscribe to Comments [Atom]