I'm using the google maps JSON output:
http://maps.googleapis.com/maps/api/directions/json?origin=Sheffield&waypoints=london&sensor=falseI have managed to plot a route but the problem is that the route is very rough and doesn't follow the road like I want it to.
self.createRoute = function(){ var url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Sheffield&waypoints=london&sensor=false', xhr = Titanium.Network.createHTTPClient(); xhr.onload = function(e){ var mapObj = JSON.parse(this.responseText), points = [], steps = mapObj.routes[0].legs[0].steps; for (x in steps) { if (steps.length > 1) { var lat = steps[x].start_location.lat, lon = steps[x].start_location.lng, lat2 = steps[x].end_location.lat, lon2 = steps[x].end_location.lng; var startObj = {latitude:lat,longitude:lon}, endObj = {latitude:lat2,longitude:lon2}; points.push(startObj, endObj); } } var route = { name:"bonVoyage", points:points, color:"blue", width:6 }; self.mapView.addRoute(route); }; xhr.open('GET',url); xhr.send(); }How can I get a more detailed route? Is this all I will ever get? The json that is output from google doesn't seem to have that many points in it so could this be it?
Thanks, James
2 Answers
You can Download a Module from the market for Free which will do it for you.
Search for google directions
The directions returned from Google includes what looks like a meaningless string called points, this contains the complete path in a very compressed format, some googling will tell you how its done and it is quite clever.
To decode it I use the following code:
polyline = JSON.parse(xhr.responseText).routes[0].overview_polyline.points; polyPoints = decodeLine(polyline); polyLineOverlayDef = { name: "Directions", points : polyPoints, color : "red", width:2 * scale, }; mapView.addRoute(polyLineOverlayDef); function decodeLine (encoded) { var len = encoded.length; var index = 0; var array = []; var lat = 0; var lng = 0; while (index < len) { var b; var shift = 0; var result = 0; do { b = encoded.charCodeAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = encoded.charCodeAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1)); lng += dlng; array.push({longitude:lng * 1e-5, latitude:lat * 1e-5}); } return array; }
Your Answer
Think you can help? Login to answer this question!