Route directions using geolocation+google maps api on Android 2.2 and Air 2.6

April 3rd, 2011 by Slav

Recently I’ve worked on a mobile app for the company I work for , and instead of just showing company’s address or displaying it on a map I thought.. wouldn’t it be more helpful to give user directions from wherever he is to where the company is ?
To do this, you of course, need to utilise a few APIs:

1. Google Maps API to download map tiles and draw a poly line from user’s location to destination,
2. Air’s Geolocation API to determine current users location
3. Air’s Multitouch API to let the user pan/zoom and rotate the map.

Getting the google maps to show on your display list is pretty straightforward, there’s a couple caveats though. It is now compulsory to initialise map with a sensor parameter (just a Boolean switch expressed in string format indicating whether map is used on a device with geolocating sensor.)
Also , to get it working in AIR app, you have to pass the ‘url’ parameter. I used local host for this.

		private function initMap() : void
		{
			//init map
			map = new Map3D();
	
			map.x = mapsDimensionsBox.x;
			map.y = mapsDimensionsBox.y;
			map.key = apiKey;
			map.url = "http://localhost";
			map.sensor = "true";
			
			
			map.setSize(new Point(mapsDimensionsBox.width, mapsDimensionsBox.height));
			map.addEventListener(MapEvent.MAP_READY, onMapReady);
			map.addEventListener(MapEvent.MAP_PREINITIALIZE, onMapPreinitialize);
			gfx.addChild(map);
		}

Getting user’s location is relatively simple, but it’s best to check first whether user’s device support’s it and whether it has been turned on :

	private function getGeolocation() : void
	{
		if (Geolocation.isSupported)
	         {
	            geo = new Geolocation();
	         	if (geo.muted)
	         	{
	         		alert("Please turn on the location or select a manual address input",showManualLocation);
	         	}
	         	else
	         	{
	            	geo.setRequestedUpdateInterval(100);
	            	geo.addEventListener(GeolocationEvent.UPDATE, geolocationUpdateHandler);
	         	}
	         }
	         else
	         {
	         	alert("Geolocation not supported, please input your location manualy", showManualLocation);
	         }
	}

Once we have the GeolocationEvent fired , we can determine user’s location from event.latitude and event.longitude.
However, Google maps Directions.load normally works with address format query, eg. “from 25 apple Street, NewYork to 22 Boulevard Street, San Francisco”. To get it working with LatLng you have to use this format (Thanks to Barry Hunter from Google maps forums for this tip)

private function geolocationUpdateHandler(event : GeolocationEvent) : void
{
	originLatLong = new LatLng(event.latitude, event.longitude);
	dirQuery =  "from: Start@"+originLatLong.lat()+","+originLatLong.lng()+" to: Destination@"+fbfLatLong.lat()+","+fbfLatLong.lng();
	initMap();	
}

(fbfLatLong being hardcoded LatLng destination variable)

After the geolocation is known and direction query is formulater we can get directions by calling load function:

private function requestDirections() : void
{
	//create directions
	dir = new Directions();
       dir.addEventListener(DirectionsEvent.DIRECTIONS_SUCCESS, onDirLoad);
       dir.addEventListener(DirectionsEvent.DIRECTIONS_FAILURE, onDirFail);
     
       dir.load(dirQuery);
}

Once the requested directions are computed and returned we can draw the route. I am also attaching a custom markers at the start and the end of the journey.

 
private function onDirLoad(event : DirectionsEvent) : void
{
	map.clearOverlays();

	var directions : Directions = Directions(event.directions);
	var startLatLng:LatLng=directions.getRoute(0).getStep(0).latLng;
	var endLatLng:LatLng=directions.getRoute(directions.numRoutes-1).endLatLng;
	
	createMarkers(startLatLng,true);
	createMarkers(endLatLng,false);
	
	var directionsPolyline:IPolyline = directions.createPolyline();
	map.addOverlay(directionsPolyline);			
	
	//get bound center
	var directionsBounds : LatLngBounds = directionsPolyline.getLatLngBounds();
	map.setCenter(directionsBounds.getCenter());
	
	//get the zoom level from direction bounds
	var zoomLevel:Number = map.getBoundsZoomLevel(directionsBounds); 
	map.setZoom(zoomLevel);
	map.setAttitude(map.getAttitude());
}		

It’s important to centre and zoom the map so that the whole journey is visible on the map.
OnDirFail is called when the given coordinates couldn’t be resolved, and then it’s probably best option to give user a chance to input the address manually.
Tested on Android 2.2 on Desire HD with Air 2.6 runtime.

Posted in AIR, Android, AS3, flash, Mobile

15 Responses

  1. Morris

    Wery Cool! Source Code Please :)

  2. Andre D. Woodley Jr.

    Great info. Do you anything about programming maps on the ios device. Im using yahoo maps but its really slow.

    If possible could you provide something on that.

    Thanks,
    Andre D. Woodley Jr.

  3. Slavomir Durej

    Andre, I haven’t tried this on ios, but even using this approach (with Google maps API) on HTC Desire HD is fairly slow, ESPECIALLY when using mobile data internet. And of course GPS detection isn’t very fast either, especially the initial position detection. On my device it can take up to 5 minutes to get the accurate location info :(

  4. Andre D. Woodley Jr.

    Dang, its understandable. Your still a beast.

    In the mean time I will look into some information for it and If you dont mind post anything I find on optimizing and programming on ios.

    Side question (im everywhere in thought), I was wondering if you knew of a code I could use for android programming in flash that could change the size of my screen and objects for any mobile device its on?

  5. Slavomir Durej

    Andre: Sure, post it, I’ll be glad to hear what you have found out!

    as for your second question , I recommend reading Paul Trani’s blog post on mobile optimisation : http://www.paultrani.com/blog/index.php/2011/03/1562/ and you might find some useful code samples here as well :
    http://www.adobe.com/devnet/air/samples_actionscript.html

  6. Loy

    Where would I put all this line of code and do i need to import anything example… import android.widget.*; and what permissions do i need to add in the Manifest.

  7. blog backlinks

    Good day! I just found your web site: FlashPad

  8. site

    Those are our favorite ways for any speedy spring cleaning.

    Modern carpet cleaning procedures won’t upset the delicate fibers of the carpets and may actually enable them to look new longer. You should never higher temperatures to completely clean the stains.

  9. internet marketing jobs nyc

    This shows you truly know what you’re talking about and are secure enough to be able to share with others without fearing that you are jeopardizing your career. Sometimes the spur of the moment captures are more powerful than anything we could write up. Focusing on SEO will help you generate significant traffic from search engines.

  10. http://odinandroid.com

    At this moment I am ready to do my breakfast, afterward
    having my breakfast coming over again to read
    more news.

  11. Stryker hip injury lawsuit

    Hi there! Do you use Twitter? I’d like to follow you if that would be okay.
    I’m absolutely enjoying your blog and look forward to new posts.

  12. smokeless cigarettes forum

    Heey There. I foound your blog using msn. This is a really well
    written article. I will make sure to bookmark it and return to read more of your useful info.
    Thanks for tthe post. I’ll definitely return.

  13. webpage

    I have seen other professionals install landscaping fabric over areas that
    were only sod cut but not killed with an herbicide. There are many basic elements in
    landscape backyard design that should be incorporated
    into your landscape design. When climbing up trees, surgeons are hunting
    for a handful of things like, dead wood, splits, and cracked
    limbs, that will most definitely split under large snow or wind.

  14. backlinks

    Unquestionably consider that which you said. Your favorite
    reason seemed to be on the internet the simplest
    factor to consider of. I say to you, I definitely get irked while other people think about worries that they plainly don’t recognise about.

    You managed to hit the nail upon the top and also defined out the whole thing without having side-effects ,
    people can take a signal. Will likely be back to get
    more. Thanks

  15. ios 7 activation

    I am really impressed with your writing skills as well as with the layout on your blog.
    Is this a paid theme or did you customize it yourself?
    Either way keep up the nice quality writing, it is rare to see a nice blog like this one nowadays.