Accessing HTML5 Geolocation via ActionScript

Read on to learn how to access the HTML5 Geolocation API using ActionScript in a web app. Using the patterns below you can get access to a visitor’s approximate location in applications that run in a desktop or laptop browser. Mobile ActionScript/Flex/AIR apps have convenient, built-in access to location via the flash.sensors.Geolocation Class. However, with a web app you have to cobble together your own code using ExternalInterface.

The key to all this is using ExternalInterface’s addCallback().  This method lets you access ActionScript from JavaScript code in the wrapper HTML file, which if you didn’t know is the .html file that is used to launch Flash Player.

There are two steps to take that make it work:

Step 1. In addCallback() set the first parameter to the name of the function you will invoke in JavaScript to send data to your ActionScript method. Set the second parameter to the name of the actual ActionScript method. ActionScript will then recognize when the method specified in the second parameter is called. Essentially this sets up a listener in ActionScript.

Step 2. Set the call() method so that it invokes a public JavaScript function. When it’s done running, then you fire off the JavaScript function specified in the first parameter of addCallback().

If that doesn’t make any sense, check out the code below to see how it all fits together. Note, you can either hard code your JavaScript in the wrapper HTML file, or you can do what I do below and inject it into the DOM at runtime using the document.insertScript pattern so you know it’s always there.

public function findLocation():void
{
	if (!Geolocation.isSupported)
	{
		const  VERIFY_GEOLOCATION:String =
			"document.insertScript = function(){" +
				"verify_geolocation = function(){"+
					"var geoEnabled = false;" +
					"if(navigator && navigator.geolocation)" +
					"{" +
					"    return geoEnabled = true;" +
					"}" +
					"else{" +
					"    return geoEnabled = false;" +
					"}"+
				"}"+
			"}";

		const  GET_GEOLOCATION:String =
			"document.insertScript = function(){" +
				"get_geolocation = function(){"+
					"var mySWF = document.getElementById('YourApplicationName');"+
					"navigator.geolocation.getCurrentPosition(function(position){"+
					"     mySWF.sendGeolocationToActionScript(position);"+
					"});"+
				"}"+
			"}";

		if(ExternalInterface.available)
		{
			//load the script into DOM
			ExternalInterface.call(VERIFY_GEOLOCATION);

			//call the JS function
			var geoEnabled:Boolean = ExternalInterface.call("verify_geolocation");

			if(geoEnabled == true){
				//Load the script into DOM
				ExternalInterface.call(GET_GEOLOCATION);

				//Step 1: set the ActionScript callback
				ExternalInterface.addCallback("sendGeolocationToActionScript",geolocationResultHandler);

				//Step 2: call the JS Function
				ExternalInterface.call("get_geolocation");
			}
		}
	}
}

//Access this Handler from JavaScript
public function geolocationResultHandler(obj:Object):void
{
	//Access the HTML5 Geolocation object properties just like you would in JavaScript
	Alert.show("Latitude: " + obj.coords.latitude + ", "Longitude: " + obj.coords.longitude );
}

Test Notes:

I compiled this code using FlashBuilder 4.6 using Apache Flex 4.6. The functionality was tested on Internet Explorer 9, Chrome 21 and Firefox 14.

References:

Adobe ActionScript Reference – ExternalInterface
Adobe Help – Accessing Flex from JavaScript

OSCON 2012 Presentation – Mastering HTML5 Geolocation

Want a fast and fun learning experience on adding location to your web apps? I’ll be sharing practical tips on how to shave days or weeks off your learning curve. The session will cover the HTML5 Geolocation API, its benefits, how it works and what doesn’t work using real-world examples covering both desktop and mobile. If you are planning on attending OSCON 2012 stop by my session and say “hi”. My session is Location, Location, Location – Mastering HTML5 Geolocation, 1:40pm Thursday, July 19th in Portland 251.

 

10 Tips for New Web Developers

If you are just getting started building web applications, these 10 tips are fundamental to learning how to build really great apps and to being successful in your new career.

1. Build at least one application on your own that wasn’t required in class and include a complex user interface component, such as a widget, and database access.

2. Understand how to use debuggers, browser debugging tools and breakpoints on IE, Chrome, Firefox and Safari for desktop and mobile.

3. Practice building your own prototype apps using the most common JavaScript libraries. The best way to learn is to roll up your sleeves and work on it. Get your curious on!

4. Understand how to use a code repository. Try posting a few of your prototypes on github.

5. Read books written by the experts. When done read some more. Learn by example.

6. Participate by asking and answering questions in industry forums such as  Stack Exchange. You’ll gain more confidence as time goes on.

7. Understand how basic coding patterns such as loops and HTTP request/response can affect website and mobile performance.

8. Learn the difference between client and server-based code.

9. Practice problem solving by testing your prototype apps against the different major browsers. You will really learn what works and what doesn’t work. In most problem solving there is no exact answer, but knowing how to come up with potential solutions will save the day.

10. Research a problem first, then ask questions. Your colleagues that have been coding for a long time know when a question wasn’t well researched beforehand. You will learn best by trying to solve it. It can be like a puzzle and you have to figure out how the pieces fit together.

11. Yep, I know I said 10 tips, so this is a bonus. Read and learn about user interface design, and if possible work with an experienced UX engineer/designer. UX, or user interface design, makes the difference between an okay app and an excellent app.