This tutorial shows you how to get a users location within a Flex application using the free GeoCity GeoLocation service.
VIEW THE DEMO
DOWNLOAD THE SOURCE CODE
GeoLocation enables you to create localised applications based on a users current position. Google Gears offers a very accurate GeoLocation service for JavaScript, but there aren't many free services that support Flash/Flex. However the free MaxMind GeoCity service, which is designed for JavaScript, can be made to work with Flex.
This tutorial extends the Google Maps tutorial, and then uses the location found by the GeoCity service to display the users current position on a map.
The GeoIP class is used to convert the JavaScript output from the GeoCity service into XML which can then be easily read in Flex. This class is originally from this blog post here.
The GeoIP class works by first calling the GeoCity service using the URL http://j.maxmind.com/app/geoip.js. If you open up this link in your browser you will see that you get a response like:
function geoip_country_code() { return 'AU'; }
function geoip_country_name() { return 'Australia'; }
function geoip_city() { return 'Sydney'; }
function geoip_region() { return '02'; }
function geoip_region_name() { return 'New South Wales'; }
function geoip_latitude() { return '-33.8833'; }
function geoip_longitude() { return '151.2167'; }
function geoip_postal_code() { return ''; }
These functions can be called directly from JavaScript, but since we are not using JavaScript this information needs to be parsed into a format that is more suitable. Because the format of the results are fixed, they can easily be turned into XML. The GeoIP class uses some regular expressions to pull out the important information and format it into an XML document like this:
<maxmind>
<geoip_country_code value="AU"/>
<geoip_country_name value="Australia"/>
<geoip_city value="Sydney"/>
<geoip_region value="02"/>
<geoip_region_name value="New South Wales"/>
<geoip_latitude value="-33.8833"/>
<geoip_longitude value="151.2167"/>
<geoip_postal_code value=""/>
</maxmind>
Thanks to the built in support for XML in Flex, reading the information from an XML object is very simple, as we will see.