LACATION BASED SERVICE

advertisement
LACATION-BASED SERVICE
-A Mobile Implementation
Approach
by
Lynn Li (ID:2048854)
A thesis submitted in partial fulfilment of the
requirements for the degree of
Bachelor of Applied Science
University of Otage
2006
Abstract
Supervisor:
Dr. Paul Werstein
A thesis presented on the different aspects of location-based services (LBS),
discussing how these location-based tasks are achieved, with a software
implementation on mobile phone called UniFind. The concept and
development of location-based services are rapidly growing with positioning
technologies and network upgrading. With the help of APIs (Application
Program Interface) and powerful mobile handsets, location-based tasks can
now be handled by cell phones.
TABLE OF CONTENTS
List of Figures ...................................................................................................................... ii
List of Tables .........................................................................................................................
Acknowledgements............................................................................................................ iii
1 Introduction ...................................................................................................................... 1
1.1 Aims and Purposes................................................................................................ 1
1.2 Problems Presented .............................................................................................. 2
1.3 Report Outline ....................................................................................................... 2
2 Backgroud
2.1 GSM Localization.................................................................................................. 4
2.1.1 Network Architecture .................................................................................. 4
2.1.2 Positioning Methods .................................................................................... 5
2.2 Location-based Applications ............................................................................. 13
2.2.1 Service Models ........................................................................................... 13
2.2.2 Location API ............................................................................................... 14
3 Related Projects .............................................................................................................. 18
3.1 Telia: Yellow Page Near You & BotFighters (1999) .................................... 18
3.2 AT&T: Find Friends (2002) .............................................................................. 19
3.3 Japan: EZ Navi Walk (2003) ............................................................................. 20
2.4 Others ................................................................................................................... 22
2.5 Situations & Trends ............................................................................................ 23
4 Proposed Solutions........................................................................................................ 25
4.1 Positioning ............................................................................................................ 25
4.2 Symbian and Location API ............................................................................... 28
5 Implementation - uniFind ............................................................................................ 29
5.1 Project Description ............................................................................................. 29
5.2 Project Design ...................................................................................................... 30
5.3 Project Architecture ............................................................................................ 30
6 Results .............................................................................................................................. 33
6.1 Testing ................................................................................................................... 33
6.1.1 Simulation Environment ............................................................................ 33
6.1.2 Procedure and Errors ................................................................................. 37
6.1.3 User Interface Flow..................................................................................... 47
6.2 Analysis.................................................................................................................. 48
6.3 Comments............................................................................................................. 49
7 Findings and Discussions ............................................................................................. 52
4.1 Findings ................................................................................................................. 52
4.2 Market Outlook ................................................................................................... 52
4.3 Conclusion ............................................................................................................ 53
Reference ............................................................................................................................ 55
Appendix: Codes of Unifind........................................................................................... 59
i
LIST OF FIGURES
Number
Page
Figure 2.1: Adding LBS to the GSM Network ...................................................... 4
Figure 2.2: ToA ............................................................................................................ 6
Figure 2.3: E-OTD ...................................................................................................... 8
Figure 2.4: Typical GPS Positioning System ........................................................ 10
Figure 2.5: A-GPS Principles ................................................................................... 11
Figure 2.7: D-GPS ..................................................................................................... 11
Figure 1.6: General Location API MIDlet model ............................................... 15
Figure 3.1: Sonera location-based services ............................................................ 19
Figure 3.2: EZ Navi Walk ........................................................................................ 22
Figure 4.1: No lost of data ....................................................................................... 26
Figure 4.2: 50% GPS data loss ................................................................................ 27
Figure 4.2: 67% GPS data loss ................................................................................ 27
Figure 5.1: Unifind: Use Case Diagram ................................................................. 30
Figure 3.2: Unifind: Class Diagram ........................................................................ 31
Figure 6.1: S60 3rd Edition Emulator .................................................................... 33
Figure 6.2: tool colletions available for application developers......................... 35
Figure 6.3: Simulation PSY Route Dialog ............................................................. 36
Figure 6.4: Simulation PSY Configurator .............................................................. 36
Figure 6.5: Define the Route ................................................................................... 37
Figure 6.6: Use the Defined Route in the Emulator .......................................... 38
Figure 6.7: Privacy Confirmations .......................................................................... 39
Figure 6.8: Waiting for the First Location Update .............................................. 39
Figure 6.9: At the Start Point X............................................................................... 40
Figure 6.10: Save Current Location ........................................................................ 42
Figure 6.11: List the Landmarks.............................................................................. 42
Figure 6.12: Save the New Landmark to the Store ............................................ 43
Figure 6.13 Landmark Screen .................................................................................. 43
Figure 6.14 Update Landmark................................................................................. 44
Figure 6.15 Remove Landmark ............................................................................... 44
Figure 6.16 At End Point Y .................................................................................... 45
Figure 6.17 Proximity Testing ................................................................................. 46
ii
Figure 6.18 Landmark Found .................................................................................. 46
Figure 6.19 UniFind: screen flow............................................................................ 47
Figure 6.20 UniFind: Sequence Diagram (setup) ................................................ 48
iii
LIST OF TABLES
Number
Page
Table 2.1: GPS Error Sources ................................................................................... 9
Table 2.2: Accuracy of Positioning Methods........................................................ 12
iv
ACKNOWLEDGMENTS
I wish to express sincere appreciation to Dr. Paul Werstein and Dr. Zhiyi Huang, for
their assistance on hardware, and guidance on writing the dissertation.
I am grateful to Mr Bryan Johnston and Professor Martin K Purvis, for without their
understanding the dissertation could not be done.
I would also like to extend my thanks to Doug and Janette, for their constant “you can
do it”.
Last but far from the least, I must mention Computer Science student Bjorn Wells,
whose idea and reference suggestions provided much of the groundwork of the report.
v
1. INTRODUCTION
Location-Based Services (LBS) are widely used in answering three questions: Where am
I? What is around me? How do I get there?
The location-based services determine the location of the user by using one of several
technologies for pinpointing the position, and then use the location and other
information to provide personalized applications and services (Mahmoud, 2004). For
example, in the city of Dunedin, the service could provide recommended tourist
attractions, restaurants and promotions currently on within the city.
Many researches have been carried out through recent years, and are applied to a variety
of fields. These include location based information, tracking, gaming and emergencies,
and are especially useful to people who do not know where they are. The use of
location-based services falls into following categories:
1. Location is used as a filter to provide information only to the geographically
targeted population. For example, if the user is in Dunedin, the information of
Christchurch can be filtered out.
2. Human senses and abilities can be enhanced with location-based services.
Even if the friend is a block away from the user within the city or township, the
user is able locate the friend. Mountains, walls and distance are not obstacles any
more with location-base services.
3. Dynamic and mobile data collection is possible. Take the example from the
professional domain – moving agents can request location-based services to
deliver dynamic data (e.g. temperature, humidity etc.) to the server.
Nowadays, location-based services have become popular among cell phone service
providers. There are several reasons behind this trend. First of all, cell phones are now
so powerful and affordable that people are carrying them all the time, and this makes
them valuable tool for advertising and servicing. Secondly, with different localizing
techniques, the location of a handset can be easily determined with different levels of
accuracy and cost.
1
1.1 Aims and Purpose
The research is to investigate important aspects of location-based services, focusing on
the implementing location-based services on mobile handsets. The report will look into
the integration of hardware and software, determine how the service task is
accomplished, and compare different methods and implementations.
UniFind, is the logo I have used for location service within the university campus. The
goal of this project is to enable students to find their own location and target locations
using mobile phones. In order to do this, location Application Program Interfaces
(APIs) from Mobile Information Device Profile 2.0 (MIDP2.0) is used in conjunction
with a proper positioning method.
Hopefully this research can serve as a starting point for future research in locationbased services and mobile programming.
1.2 Problems Presented
The positioning signal needs to be converted and handled by mobile phones, which
require the software to communicate with the location provider and the cell itself. The
receiver packages the signals in an acceptable format to the host operating system. The
operating system then provides usable information which can be displayed on the
screen. The mobile phone has to be powerful enough to handle such calculations and
communications.
In the campus area, lecture theatres are built within close proximity to each other,
therefore, high positioning accuracy is required. Indoor propagation of the positioning
signals is required, since the student sometimes need to move from one room to
another in one building. The indoor channel is characterized by higher path losses and
sharper changes in the mean signal level. Proper method is needed to eliminate
multipath fading.
1.3 Report Outline
Chapter 1 provides the objectives and structure of the report. Chapter 2 covers the
theoretical background for localisation. Chapter 3 reviews recent progress on locationbased services, reasons behind their success/failure are discussed. Chapter 4 gives the
2
proposed solution to the problems presented, based on the comparison of these
previous discussions. Chapter 5 details the implementation of this project. Chapter 6
focuses on describing the testing environment and results, and gives analysis on the
flow of the program. Chapter 7 is dedicated to general conclusions and comments on
commercializing and possible future work.
3
2. BACKGROUND
2.1 Global System for Mobile communication (GSM) Localization
While 3G (Third Generation) is currently being advertised for use, experiments on 4G
(Fourth Generation) are still at laboratory stage. GSM (Global System for Mobile
communication) is still the most widely used digital mobile phone system in New
Zealand. GSM localization is the use of multilateration to determine the location of
GSM mobile phones, usually with the intent to locate the user (Wikipedia, 2006).
2.1.1 Network Achitecture
According to the study (Intel Corporation, 2006), four elements need to be added to the
existing GSM network in order to provide location-based services. These elements are
Location Service Client (LSC), Gateway Mobile Location Centre (GMLC), Location
Measurement Unit (LMU) and Serving Mobile Location Center (SMLC)
Figure 2.1: Adding LBS to the GSM Network (Source: Intel Corp, “Adding Location-based Services to
Existing Architecturesxisting”, bitpit IT Information, Feb 2006)
4
Location Measurement Unit (LMU) is the client’s application which either initiates or
responds to the location-based services queries. Gateway Mobile Location Centre
(GMLC) connects Location Service Client (LSC) to the mobile network. It can either
communicate with a mobile switching center (MSC) on location information, or request
routing information from the Home Location Register (HLR).
Location Measurement Unit (LMU) is linked to the Base Station Subsystem (BSS). it
records positioning measurements to support location-based services.
Serving Mobile Location Center (SMLC) controls several Location Measurement Units
(LMUs), in order to receive radio interface timing measurement information. Based on
the received information, the postion of a mobile handset can be determined, plus an
indication of the accuracy of the positioning information.
2.1.2 Positioning Methods
Mobile positioing in general is the process of determining the location of a mobile
terminal. The accuracy of the mobile location mainly depends on the positioning
method used, and there are several methods available to meet different user
requirements. These are as follows:
Cell Identification – “Cell ID” is a parameter presented in SIM card and GSM
network. With SMLC (Serving Mobile Locaiton Centre), Cell ID can be used to identify
the location of the Base Station Subsystem (BSS). Depending on the number of BSS
found, accuracy may vary from 100 metres in an urban are, to 5 kilometres or more in a
rural situation. It is the most common method in use, which is already sufficient for
most location-based services. Interestingly, in spite of its sufficiency, it is also the most
inaccurate and method. Quality of the data can be enhanced by additional calculations
such as Timing Advance (TA). The TA is based on the existing Timing Advance
parameter, which corresponds to the length of time a signal from the mobile phone
takes to reach the base station. It is used to synchronize the TDMA (Time Division
Multiple Access) frames from the mobile to the base station. TA is used to assist all
positioning mechanisms and as a fall-back procedure.
Enhanced Cell Identification – Similar to Cell Identification. Position accuracy in a
rural area is increased to 550 metres.
5
Time of Arrival (ToA) – Used with Cell Identification. This positioning method
utilizes the fact that radio waves travel at the speed of light and the distance can,
therefore, be calculated from the propagation delay. A known signal sent from the
mobile and received at three or more measurement units. The known signal is the
access bursts generated by having the mobile perform an asynchronous handover. This
method can be performed without modification to existing mobiles.
As illustrated below, additional measurement units (LMUs) are needed within the
vicinity of the mobile to measure the signal arrival time. As the geographical coordinates
of the LMUs are known, the mobile position can then be calculated using hyperbolic
triangulation. The Serving Mobile Location Center (SMLC) is then used to calculate
Time Difference of Arrival (TDOA) values by pair-wise subtracting the ToA values.
The mobile position is then calculated via hyperbolic triangulateration assuming that: a)
the geographical coordinates of the measurement units are known, and b) the timing
offset between the measurement units involved in the measurement are known, e.g. by
the use of absolute GPS time at the measurement units, or by using reference
measurement units situated at known locations to determine Real Time Difference
(RTD)values (Veijalainen & Gross, 2002). The accuracy of ToA positioning is about
100 to 200 meters depending on the area and the number of available measurement
units.
Figure 2.2 ToA (Source: K. Raja, W.J. Buchanan, and J. Munoz.“We Know Where You Are”. IEE
Communications Engineer. June 2004)
6
Angle of Arrival (AoA) – Multiple Location Measurement Units (LMUs) calculate the
AoA of the cell phone's signal, then Servicing Mobile Location Center (SMLC)
combines the infomation to determine the location of the handset.
Different from ToA, AoA measures the Time Difference of Arrival (TDOA) at
individual elements of a antenna array, the phase difference of antenna array can then
be calculated in order to determine AoA.
The accuracy is about 1 to 2 kilometers depending on the area and the number of
measurement units. This method can be performed without modification to existing
mobiles.
Enhanced Observed Time Difference (E-OTD) – This is similar to ToA, but, the
position is estimated by the cell handset instead of the base station. The E-OTD
positioning method is developed from the Observed Time Difference (OTD) feature.
For unsynchronized networks, the signals are also received by a fixed measuring point
(LMU) whose location is known. The position of the mobile terminal is determined by
deducing the geometrical components of the time delays to a terminal from the base
stations.
For synchronized networks, the mobile terminal, measures relative time of arrival of the
signals from several base stations. For OTD measurements synchronization, normal
and dummy bursts can be used. When the transmission frames of base stations are not
synchronized, the network needs to measure the Real Time Differences (RTD) between
them. In order to obtain accurate triangulation, OTD measurements and, for nonsynchronized base stations, RTD measurements are needed for at least three
geographically distinct base stations (Virrantaus ,Veijalainen, Markkula, Katasonov,
Garmash, Tirri & Terziyan, 2001).
As shown in Figure 2.3, in “handset-based” mode, the handset makes the measurement
therefore, all necessary data is available in the mobile terminal; in “assisted” mode, the
handset reports the measured information to the Servicing Mobile Location Centre
(SMLC),
the network, then uses these measured E-OTD values to calculate the
location. Measurements are performed by the handset without any additional hardware.
7
The measurement accuracy varies from 50 to 200 metres, depending on the number of
available Location Measurement Units (LMUs).
Figure 2.3 E-OTD (Source: K. Raja, W.J. Buchanan, and J. Munoz. “We Know Where You Are”. IEE
Communications Engineer, June 2004)
Global Positioning System (GPS) – A constellation of 24 satellites (21 orbiting
operational satellites plus 3 active backup satellites) are used to triangulate a receiver’s
position.
Similar to other triangulation methods, GPS determines the location by calculating
lengths of time that signals take to reach the receiver, from different satellites orbiting
the earth. GPS has now been integrated in some Code Division Multiple Access
(CDMA) networks in order to provide positioning service.
A timestamp is contained in each packet of the GPS location data in order to record the
satellite’s position in space. This information is used by the GPS receiver to work out
the distance between itself and the satellites, thereby triangulating its position (Grewal,
Weill & Andrews, 2001).
Accuracy of GPS mainly depends on the quality of the unit and the satellite signals. On
average, GPS system provides the global coordinates within 10 metres of a specific
8
position (Wormley, 2004). The table below shows sources, which can introduce errors
to GPS.
Table 2.1 GPS Error Sources (Source: Bjorn Wells, Intergrating a GPS Receiver With an Inertial Measurement
Unit Using a Kalman Filter, Bachelor thesis, Otago University)
UERE is the typical one standard deviation errors of the error sources listed.
Mathematically, it is the combined error of URE2 (User Range Error) and UEE2 (User
Equipment Errors):
UERE  URE 2  UEE 2
(2.1)
Although GPS is able to provide speed data, it is not very accurate, because GPS
calculates the velocity using Doppler Effect (2.2) instead of dividing distance by time.
The Doppler effect formula is shown below, where f’ is the observed frequency, f is the
emitted frequency, v0 is the velocity of the observer, v is the velocity of the wave (speed
of sound travels in air =340 m/s, speed of light travels in the air = 3x108 m/s), and vs is
the velocity of the source (the thing emitting the light/sound). No component in this
equation is associate of the errors listed in Table 2.1. The receiver calculates the speed
based on the assumption that the received data are 100% accurate.
f ' (
v  v0
)f
v  vs
(2.2)
Operating at 1Hz, GPS provides data once per second. If someone travels at high speed,
the distance between data points can be quite large (38.9 metres at the speed of
140Km/hour).
9
Several drawbacks of GPS are: lines of sight to the satellites are required, devices must
be equipped with a GPS receiver to decode the GPS signals – which means extra cost
involved, accuracy depends on the clarity of the sky, the warm-up time is comparably
long – it can take as long as ten minutes or more for the receiver to lock.
Figure 2.4 Typical GPS Positioning System (Source: Source: 3GPP LCS Specifications)
Assisted GPS (A-GPS) – Both A-GPS and D-GPS (Differential GPS) are based on
the idea of establishing a GPS reference network (or a wide-area differential GPS
network) whose receivers have clear views of the sky and can operate continuously.
As shown in Figure 2.5, A-GPS uses the mobile phone network as the reference
network to assist the GPS system. The assistance data from the reference network is
transmitted to the handset to increase performance of the GPS sensor.
When the position is calculated at the handset, it is called mobile-based solution, but if
the calculation is done at the network, it is called mobile-assisted solution. If
implemented properly, the assisted-GPS method should be able to: 1). reduce the power
consumption and overcome the warm-up problem since a GPS receiver is built in the
base station. The base station is always on and will be located in the position where the
satellites can be “seen”. 2). Increase the sensor sensitivity, enabling the position
information to be provided indoors and in harsh environments (e.g. bushes, skyscrapers
etc.).
10
Figure 2.5 A-GPS Principles (Source: Nokia Corporation. 2005. White Paper. Capitalizing On The
Location-Based Services Opportunity)
Differential GPS (D-GPS) – If Assisted GPS (A-GPS) is more focused on
performance, D-GPS targets accuracy improvement. The accuracy is increased by using
a network of fixed ground based reference stations to broadcast the difference between
the positions indicated by the satellite systems and the known fixed positions. These
stations broadcast the difference between the measured satellite pseudoranges and
actual (internally computed) pseudoranges, and receiver stations may correct their
pseudoranges by the same amount (Wikipedia, 2006). As shown in Figure 2.6, the
differential station serves as a fixed ground based reference to inform the user on the
positioning difference indicated by the satellite systems.
Figure 2.6 D-GPS (source: Egypt Marine DGPS)
11
Cell Broadcast – Also know as Short Message Service (SMS) – Call Broadcast (CB).
Unlike SMS, it is a one-to-many service with a geographic focus. It is popular in China
for delivering weather and advertising information.
Short-range Positioning Beacons – As indicated by Mahmoud (2004), in relatively
small areas, such as a single building, a local area network can provide locations along
with other services. For example, appropriately equipped devices can use Bluetooth for
short-range positioning.
These large number of positioning methods can be divided into two broad categories:
network-based and terminal-based. The first category, network-based positioning, is
made up of methods that reach from relatively simple Cell Identification methods to
more complex methods like ToA (Time of Arrival). The latter category, the terminalbased positioning methods, allows locating the terminal without the help of the mobile
communication network (for example, the GSM or CDMA network). GPS is the most
prominent member of that category (Haiges, 2003).
Hybrid methods exist beside those two categories. The term “hybrid” indicates to unite
network-based and handset-based methods. For example, terminal-assisted (networkbased) Enhanced Observed Time Difference (E-OTD) is used for higher accuracy.
Another example is A-GPS which can be used to locate indoor users and speed up the
initialization time. The accuracy of some popular methods are listed in Table 2.2 below
(Rel.99 is the Abbreviation for Release 1999):
Satellite positioning (reflections)
GPS
10 (-30)m GSM, Rel.99
DGPS
1-10 (-30)m
A-GPS
1-10 (-30)m GSM, Rel.99
Cellular positioning
CoO
0,2-10km GSM, Rel.99
AoA
0,1-2km
ToA
100-200m GSM, Rel.99
E-OTD
50-200m GSM, Rel.99
Table 2.2 Accuracy of Positioning Methods (Source: GSM & UMTS Standardization, 3GPP)
12
2.2 Location-based Applications
Although there has been talk of location-based services in the mobile domain for some
time, it is only in recent years that R&D (Research & Development) have been widely
carried out to truly support on location-base software. Models and theories have been
rapidly developed to accelerate the innovation.
According to Intel Corp (2006), two things need to be confirmed at the beginning of
any location-based applications:
1. The Mobile handsets support the use of these location-based service mechanisms
(e.g. location API, GPS units, etc.).
2. Positioning information provided by the mobile network meets the accuracy
requirements of the application.
2.2.1 Service Models
The study shows that location-based applications can be segmented into two models:
“push” and “pull” (Intel Corp, 2006):
The “Pull” services are used by subscribers to retrieve area information. Examples of
this type of location-based services being deployed includes driving directions, which
provides the user with turn-by-turn directions from the current location to the desired
destination; map applications enabling the user to view maps on his phone detailing his
current location; and City Guides providing information on finding locations of local
ATMs, restaurants, stores, and attractions.
Client-server model belongs to this category. The client initiates the communication
with the server whenever it wants a service, and the server waits passively for the
requests. Once the requests arrive, the server becomes active and processes these
requests. The client-server model is well suited for mobile applications which require
intensive computation power. As heavy computation can be handled by the server, the
requirements for clients are lowered, and little amount of work parameter or response
data is transmitted over the network. However, the client must be willing to generate a
separate request each time the service is needed, and be willing to wait for the
transmission to complete.
13
The transmission starts from the time the request is sent from the client and ends when
the results arrive from the server. Client-server model is not well suited for services
which are used frequently by the client, or which provides the most recent status of
some information (e.g. currency exchange rates), because in the former case, big
amounts of overhead are accumulated each time the client makes a request. As a result,
the server could become bottle-necked due to the amount of requests and responses. In
the latter case, the client has to poll the server each time to get the updates, and possibly
a large portion of the polls end with old data. If the polling is not done frequently, the
information could become outdated, and consequently may cause loss to client (e.g.
stocks go down).
Both of these cases can cause the server to saturate which is a common phenomenon in
the client-server network. Agents can be used to regulate the traffic and reduce the
number of requests sent directly to the server. The agent layer situated between the
server and the client can manage to cache the data, but it is not a foolproof situation,
since the updates might be more frequent in the server than reflected into the cache.
The “Push” model is one in which information is proactively sent to subscriber, where
no particular request needs to be answered. “Opt-in” mobile advertising is emerging as
an effective way to send discounts, promotions, and contests to consumers who give
their permission to receive such alerts.
2.2.2 Location API
The Location API (JSR 179) was accepted by the Executive Committee for Micro
Edition of the Java Community Process in June 2003. It provides an abstract interface
for access to location-based information, such as the current coordinates of the mobile
terminal independent from the underlying positioning method used (Haiges, 2003).
Before this, the access of current location of the terminal requires special signal
processing for mobiles and embedded systems. With the modern platforms support key
location APIs, location-based applications can be developed without knowing the
underlying positioning mechanism.
In addition, the APIs shadow the hardware, therefore the application can run on any
platform supporting the APIs, without changing the code. For example, if the
positioning method changed from CoO (Cell of Origin) to GPS, the program can still
14
contact the “LocationProvider” for the location data, however, the quality of the
information can be very different.
Figure 2.7 General Location API MIDlet model (Source: Nokia Corp. 2006. MIDP: Location API
Developer's Guide.)
Location API (package javax.microedition.location) needs the CLDC 1.1 (Connected
Limited Device Configuration 1.1) (or later version) as an underlying configuration.
Main location APIs are illustrated on Figure 2.7. LandmarkStore deals with landmark
management, Landmarks (not illustrated) allow the classification of locations and save
them to a landmark database on the mobile handset. The database uses the RMS
(Record Management System) that is part of the underlying profile, the MIDP (Mobile
Information Device Profile). LocationListener and Proximity Listener can be registered
on Custom MIDlet in order to receive events from LocationProvider. The nonblocking
LocationListener will receive location information at regular intervals after registration.
Another way to get location information is to block a request by using the getLocation()
method from the LocationProvider. The LocationProvider is a Singleton class that is
the starting point for a request to the location service. It can receive a criteria object as a
parameter to determine the needs of the location request (for example, desired accuracy,
whether to use non-free location providers, etc.).
There are two categories of Criteria (not shown on the graph): soft criteria and hard
criteria. Hard criteria specify whether the speed has to be determined, the format of the
location data and the maximum cost per request. Soft criteria define accuracy (both
vertical and horizontal), the levels of power consumption and the timeout value.
15
Location information is encapsulated in Location (not shown) objects, and is used by
the LocationProvider to reply to requests. It includes a Coordinates and an AddressInfo
object. Coordinates class represents coordinates as latitude-longitude-altitude values.
AddressInfo class holds textual address information about a location (e.g. country, city,
building, description). The table below shows the short definition of the location API
classes.
class
Short definition
Criteria
Used for the selection of the location provider.
LocationProvider
Represents a source of the location information
LocationListener
Listener that receives events associated with a
particular LocationProvider.
ProximityListener
Listener to events associated with detecting
proximity to registered coordinates.
AddressInfo
Holds textual address information about a
location.
Coordinates
Represents coordinates
altitude values.
as
latitude-longitude-
Location
Represents the standard set of location
information (time-stamped coordinates, speed,
accuracy, course, etc.)
LocationException
Is thrown when a location API-specific error has
occurred.
QualifiedCoordinates Represents coordinates as latitude-longitudealtitude values that are associated with an accuracy
value.
Landmark
Represents a known position with a name.
LandmarkStore
Methods for persistent landmark store
management (store, delete, and retrieve
landmarks).
Represents the physical orientation of the device.
Orientation
Table 2.3 Classes in Location APIs
Three main purposes of the API (Application Program Interface) are determined by
past researches (Nokia, 2006):
1. Obtaining information about the location of a device.
16
2. Creating, editing, storing, and retrieving landmarks are made possible.
3. Obtaining the orientation of a device is made possible if the orientation is
supported by the device.
Floating point numbers supported in CLDC 1.1 (Connected Limited Device
Configuration 1.1), are necessary for coordinates (longitude and latitude) representation.
Furthermore, the utilization of the security concept of MIDP 2.0 (Mobile Information
Device Profile 2.0) is recommended in the JSR. If an application wants to make use of
the Location API, the user will be prompted for the permissions. He or she can decide
to give those permissions to use the Location API on a per-usage basis for the duration
of the current session or in general. This inhibits the abuse of this API, as every location
request might involve costs to the user.
17
3. RELATED PROJECTS
Location-base services began as a result of government mandates that have required
mobile operators to be able to locate users for emergency services. The US Federal
Communications Commission (FCC) adopted Wireless Enhanced 911 (E911) rules in
1996 to improve the effectiveness and reliability of wireless 911 services by providing
911 dispatchers with additional information on wireless 911 calls. The program is
divided into two phases - Phase I and Phase II. Phase I requires carriers, upon valid
request by a local Public Safety Answering Point (PSAP), to report the telephone
number of a wireless 911 caller and the location of the antenna that received the call
(Federal Communications Commission, 2006). Phase II rules require wireless carriers to
begin providing more precise Automatic Location Identification (ALI), subject to
certain conditions and schedules (implementation beginning October 1, 2002). For the
revised Phase II ALI Accuracy Standards, handset-based solutions are required to
provide an accuracy of 50 meters for 67 percent of calls, or 150 meters for 95% of calls.
The requirements for network-based solutions are 100 meters for 67 percent of calls, or
300 meters for 95% of calls.
Similar to the Enhanced 911 rule, Enhanced112 initiative is adopted in Europe, and
later on, similar requirements are included in 3G licensing terms. LBS then rapidly
extended from professional field of use (monitoring goods and vehicles), to everyday
mobile world. This chapter will look at a few examples of location-base services which
appeared through the years, discussing their strengths and weaknesses, and making
comments on the trends in future markets.
3.1 Telia: Yellow Page Near You (YPNU) & BotFighters (1999)
Swedish operator Telia Mobile is one of the first mobile providers to launch commercial
LBS: Gula Sidorna Nära Dig (Yellow Page Near You), a typical “pull” type mobile
yellow page service.
According to Telia (2006), using either WAP or SMS, users text inquiries to number
“4400”, directions can then be sent to a user's mobile phone to find the nearest Italian
restaurant, dry cleaner or subway station, or whatever business or service they might be
looking for. Up to 6 SMS or 5 WAP messages can be replied. Fully realizing the
18
potential of mobile positioning, Telia Mobile has since introduced a dozen of “Near
You” services, such as Rätt Väg Nära Dig (Right Way Near You), Hemnet Nära Dig
(Beds Near You) etc.. These “Near You” services have had an uptime of 99.97 % since
launch, and they are still popular.
Figure 3.1 Sonera location-based services
Telia has also introduced LBS into the game field. BotFighters is a mobile game
application. It is like a virtual paintball that your mobile phone acts both “radar” to
detect opponents, and a “laser” weapon to attack them. Short-ranged beacon is involve
in this positioning.
The simplicity of YPNU contributed greatly to the success. No extra application or
positioning units need be installed, and mobile users are familiar with WAP and SMS so
it is easy enough to use. Telia has lauched other more complicated LBS, such as
Närmaste Resurs (Next Resource), Telia Friend Finder and Visa Position. With higher
requirements and longer instructions, they are not as popular as YPNU.
3.2 AT&T: Find Friends (2002)
AT&T Wireless introduced “Find Friends” in 2002, as a part of the company's mMode
plan. The service is limited to those who have upgraded to the company's newest
phones and its mMode service plans, which count usage in kilobytes of data
19
transmitted, not minutes. These plans range from an extra $2.99 a month for minimal
users of multimedia services to $19.99 for heavy users (Hanrahan, 2003).
“Find Friends” first ask the user’s permission to be tracked by other people. Once the
permission has been granted, a person can choose to be "invisible" to specific or all
users, through the menus. If a friend is “visible”, his/her approximate location can be
identified. Once the friend is located, the customer can elect to call that person, send a
message, or arrange a meeting. If the two choose to meet, “Find Friends” provides the
customer with a directory of nearby restaurants, bars, coffee shops, and bookstores. The
customer then chooses where and when to meet, and sends a meeting request to the
friend, who can RSVP and easily get directions to the meeting place.
Unfortunately, the feedbacks are not very good. According to Hanrahan (2003), two
people tested the service using a Panasonic GU 87 a Motorola T720. First, they were
constantly waiting for connections, and then on the Panasonic, crucial functions
frequently change meanings and places. “A taxi dropped me off at the intersection, but
Katherine was nowhere in sight, which we had expected. Cell towers can be many
blocks apart -- or miles apart in a rural area. Find Friends simply identifies the closest
tower, which the company made clear. After several text messages back and forth, I
found her at a restaurant just a few blocks away”, wrote Hanrahan.
Cingular bought out AT&T Wireless in 2004, and the “Find Friends” service is no
longer in the mMode plans (Cingular, 2006).
“Find Friends” is failed because:
1. The positioning ability does not match the performance requirements.
According to Hanrahan, “Find Friends” simply “identifies the closest tower”, which
means Cell ID is used in positioning. The accuracy varies from 100 metres (in the city)
to 5 kilometres or worse (in rural area). If the delay requirements are low, it is very
hard to find friends with these parameters.
2. Extra applications cause UI and API support problems on different phone.
Hanrahan recalled: “Getting a cutting-edge phone doesn't mean more-reliable signals
or fast Web access; we were constantly waiting for connections. The Motorola's
20
screen is straightforward, with three main buttons: Exit, Main Menu and Select.
There's a thumb pad for scrolling and for switching between screens. The Panasonic
has the same number of buttons, but crucial functions frequently change meanings
and places, which led me to accidentally delete text messages. On both phones, it
often isn't clear how to return to the main menu. It's less irritating to turn off the
phone and restart. ”
Applications should be tested on a variety of phones before launch; separate versions
could be built for certain phones if necessary. However, users are still required to
learn the instruction before use.
3. High requirements to users.
Firstly, “Find Friends” is limited to those who have upgraded to the company's
newest phones, which means users and their friends both need to upgrade. Secondly,
both users and their friends need to be on the company’s mMode plans, which count
usage in kilobytes of data transmitted. Hanrahan commented, “they are fun, but so
far are a little impractical; and they have complicated, costly rate plans.”
3.3 Japan: EZ Navi Walk (2003)
EZ Navi Walk is launched by KDDI (a Japanese information and communication
company) in October 2003. Launched from the EZ Navi icon from the mobile menu, it
provides continuous location guidance on a real time basis. The navigation flow is
shown in FigureXXX below. With easy operation, the current position can be displayed
on the map. The “Odekake Menu” (outing menu) enables users to navigate to their
desired destinations. In addition, as the route navigation begins, primarily with voice but
also using text, vibrations and icons, users are notified where to turn. There are four
components in the outing Menu: “Map search” provides the ability to easily search for
the locations from the current position, postal code, address, phone number, name,
station name and categories. “Total Navi” provides navigation guidance as well as traffic
information. The “Going Home” menu gives guidance from current location to users’
home. With “My Spot” menu users can register up to 20 landmarks. With “Current
position mails” users can let their friends and families know where they are by mail.
They receive location maps from their friends who have EZ Navi Walk compatible
21
handsets, they can navigate easily to the locations based on the positioning data in the
mail text (KDDI Corp, 2003).
Two pricing plans are available. The 315 yen (≈4.02NZD) monthly plan includes all
features mentioned previously, while the 210 yen (≈2.68NZD) excludes the traffic
information. There will be a free trial period, and users will be able to access the data
free of charge for the first 15 days. Communication fees will be charged separately.
Figure 3.2 EZ Navi Walk (Source: KDDI news archive)
3.4 Others
Previous projects are all “pull” service examples, “push” services are normally been
used as an advertising media. “Push” services are common in China; mobile users get
messages with information on weather, local discounts, news and jokes. When you
move from one city to another, once the boarder is crossed, a welcome message will
appear on your phone, followed with motel information.
22
Another category of use is some location-aware web contents – if typing the urls is not
considered as a request. One typical example is the personalized Google homepage. It
provides weather and news based on user’s location. The difference is that, it uses IP
addresses as the positioning mechanism.
The main attraction of these “push” services is that, both parties are benefited from
these simple applications: users get free information, while companies promote their
products with reduced cost.
3.5 Situations & Trends
Growth barriers of location-based services have been overcome by government
regulations, changing markets, technologies and growing awareness among consumers
during recent years. Location-based services are now about to take-off and are rapidly
becoming more common on mass-market mobile devices.
The Study (Rao & Minakakis, 2003) shows, location-based services have been driven by
the “push” technology. Professional market, which is characterized by the high entry
barrier and restricted demand (to large corporations), is still dominated by a few
automatic vehicle location vendors. Consumer market on the other hand, despite its
expanding volicity, shows little evidence that users are willing to pay premiums.
Location-based services in the mass market are normally applied as ”add-on” services.
The estimated revenue of location-based services in Europe is approximately $5.2
billion in 2005 (Source: Mobile-Zoom, Professional Location-Based Services in Europe).
Trends of mobile location-based services during recent years are reviewed by the ARC
Group. During year 2002 to 2003, the first generation of location-based applications
focused on deploying the technology to the fields of gaming, community interaction,
and proximity traffic information. However, only mobile handset features were limited
at that time. The location-based tasks were accomplished by using mainly WAP
(Wireless Application Protocol), Voice/SMS (Short Message Service), Bluetooth, etc.
From 2004 to 2005, partnerships between mobile operators were increased. More
standards, marketing, service roll-out, and initial roaming agreements had been made
available. As a result, wider range of location-based services had emerged, including
advertising, personal tracking and basic navigation. From 2006 to 2007, location-based
services will target the mass-market consumers, while still maintain the constant growth
23
in the corporate and vertical market. Researches will be mainly carried out on crossplatform support full-scale service roaming. Featured services of this period are
predicted to be m-commerce (i.e. mobile commerce), billing, breakdown recovery,
mobile office and personal/in-car navigation. (Source: ARC Group Presentation:
Location Based Services 2002- 2007)
In addition, from the previous examples and discussion above, it can be predicted that
the success of future location-based services will also depend on:
1. Increased positioning accessibility and accuracy. And the services are also expected
to be accessible anywhere and anytime. With the help of fast growing technology
support, location-based service consumers are expecting more precise answer of their
location queries.
2. Reduced cost for the mass market. Like currently available “push” services, future
location-based services are likely to be cheap or provided as free services to mobile
users, while fees are charged from companies which want to be listed or advertised.
3. Consistent application design. In order to cope with the broad range of end user
requirements in a context-aware environment, a flexible architecture has to be
designed (Prasad & Ruggieri, 2003). Support is needed for various platforms and over
a variety of network technologies, and full integration with multiple application
platforms is the trend for the future. Mobile API and standards are rapidly growing
and upgrading, service models are also quickly developed and expanded during recent
years. Future location-based services should be standardized and able to run across
platforms with little difference. User friendly interfaces are necessary, since people are
reluctant to read through the long story of instructions.
24
4. PROPOSED SOLUTIONS
As mentioned earlier, Unifind, a location-based application is going to be implemented
for this dissertation. In this chapter, solutions and assumptions are proposed for
problems discussed in section 1.2.
4.1 Positioning
As mentioned in section 1.2, for campus use, the application requires a highly accurate
positioning method, and the application should be able to location the user even when
the satellite signals are lost (e.g. indoor situations).
Based on Table 2.1, satellite positioning methods are preferred over cellular methods
because the accuracy of these methods meets the requirement of this application.
However, the problem with satellites is that the signals cannot propagate through the
walls. The proposed solution is to integrate the GPS Receiver on the handset with an
Inertial Measurement Unit (IMU) using a Kalman Filter. The idea comes from Bjorn
Wells, an honours student from Computer Science Department, University of Otago.
The Inertial Measurement Unit (IMU) comes with the 3-axis gyroscopes,
accelerometers and magnetometers, providing gyro stabilised orientation and
acceleration. The IMU outputs data in several standard sentences. Each sentence
contains a preset type of data, and has an associated rate. For this system, the sentence
required is a sentence providing the acceleration vectors as well as orientation values,
which is used to convert the acceleration vectors from the IMU’s coordinate system
into the Earth’s coordinate system. The sentence providing magnetic field, acceleration
and angular acceleration is at 100Hz. The sentence providing euler and acceleration is at
75Hz. The sentence providing orientation matrix is at 50Hz. IMU can operate either in
polled mode or continuous mode. In poll mode, a command is sent to the IMU and the
corresponding data is returned once. In continuous mode, the IMU sends its data
sentences continuously (B. Wells, personal communication, Nov 1, 2006). Continuous
mode should be applied to this application, because it saves time polling and the data is
sent as soon as it becomes available, which is important for real-time services.
25
A mathematical filter is needed to combine multiple data sources. Bjorn used a Kalman
filter in this system. The Kalman filter is served as a recursive method that combines the
data sources that have noise (measurement errors, multipath fading) and computes a
result that minimises the combined error. The result is achieved by taking the variance
of each source and working out a Kalman gain constant (K), which is the possibility of
getting the least combined error for each measurement. In simple case, Equation 4.1 is
used.
K
P
PR
(4.1)
Where P is the variance in the first source’s measurement and R is the variance in the
second source’s measurement. Figure XX to XX below show how the integrated system
handles the situation when satellite signals are lost. Compare to Figure 4.1, Figure 4.2
(50% GPS data lost) is reasonably accurate at estimating the position over time although
there is a decrease in the smoothness of the graph. When two thirds of the GPS data
points are removed, the smoothness is degraded, as shown in Figure 4.3. (Source: B.
Wells, (2006). Honors Thesis, Intergrating a GPS Receiver With an Inertial Measurement Unit
Using a Kalman Filter)
Figure 4.1 No lost of data
(Source: B. Wells, Intergrating a GPS Receiver With an Inertial Measurement Unit Using a Kalman Filter)
26
Figure 4.2 50% GPS data loss
(Source: B. Wells, Intergrating a GPS Receiver With an Inertial Measurement Unit Using a Kalman Filter)
Figure 4.3 67% GPS data loss
(Source: B. Wells, Intergrating a GPS Receiver With an Inertial Measurement Unit Using a Kalman Filter)
27
Such integrated GPS system gets more data points per time unit than is possible with a
GPS receiver alone, since the Inertial Measurement Unit (IMU) makes predictions and
supplements extra data points, whose errors are minimised by the Kalman filter. The
accuracy can be increased to centimetres (around 30 centimetres in Otago Campus area),
and the combined data performed reasonably well even if 50% of the GPS receiver’s
data was lost (every second data point). It is best-suited for this application (i.e. UniFind)
so far. However, in fact, there is no mobile in current consumer market supports
integrating GPS receiver with user defined components. In order to achieve best
performance of this service, we have to make the assumption made that, the mobile
phones using this application are equipped with such system.
4.2 Symbian and Location API
The recommended mobile handsets are those ones implementing Symbian Operating
System (OS). Symbian phones are chosen for a variety of reasons. It is specially
designed for mobile phones, optimizing battery consumption and data management for
limited memory. An extensive API is available for Object Oriented programming, C++
and Java in particular – C++ is the native language of Symbian, and Symbian support
for Java has been co-developed over ten years in partnership with Sun Microsystems.
The most important point is, Symbian OS is an open OS, which supports the use of
location API. The mobile phones for this application must allow third party developers
to write and install applications, independently from the device manufacturers.
Otherwise the application cannot be used at all. As mentioned in section 2.3.2, location
API can significantly simplify the communication between the application and
positioning system, and provides consistent architecture of the application.
28
5. IMPLEMENTATION - UNIFIND
Although location-based services are no longer alien to the mass market, they are
usually provided as commercial products instead of open sources. The aim of this
UniFind project is to explore the beauty of location API, and to prove that mobile
phones are able to handle conventional location-based tasks.
Black boxes are left in the project for future work. Some icons (e.g. “View Map”)
cannot be selected, otherwise the OS will force the MIDlet (i.e. a Java program for
embedded devices) to enter the “destroy” state.
5.1 Project Description
UniFind is designed as a test application for students in Otago University to find their
current location, plus the location of frequently used places (e.g. Commerce building,
Science library). The original design is to enable users to view the locations on map,
with a red dot represents current location and a green dot represents target location.
Since it is a test application, the requirements for devices are not basic. MIDP2.0
(Mobile Information Device Profile 2.0) needs to be installed for User Interface (UI) to
be correctly displayed, and Java2 Micro Edition (J2ME) is necessary in order to use java
location API. The mobile also has to support third party applications, and connects to
some positioning module (e.g. GPS module).
The application is aimed to provide positions within the range of 2 meters to 20 meters.
There are some limitations of the application. Firstly, if the loss of satellite signals
approaches 67% (two-thirds of data), the ability for application to maintain an accurate
position will be deteriorated. Secondly, the number of landmarks can be stored in the
device is limited to the memory of the specific handset. No limitation on the landmark
storage is set by the application itself, the user has to check the available space and
manage the landmark storage accordingly.
Some assumptions are made for the project:
1. Location providers can supply the positioning data free of charge.
29
2. The Integrated GPS (IGPS) unit is supported by mobiles, as discussed in section
4.3.
5.2 Project Design
Figure 5.1 below illustrates the Use Case Diagram.
Figure 5.1 Unifind: Use Case Diagram
As indicated by the diagram, the mobile user can find locations, including find the user’s
own location and a target location which is installed in the memory. Once the user’s
own location is found, he can not only view the coordinates but also view the map.
Then he may want to save his current location to the target list for future use. On the
other hand, when a target location is found, apart from viewing coordinates and map,
he can choose to go back to the list and choose to view another one.
5.3 Project Architecture
This application is a typical “pull” service. Its architecture falls into the “pull” model:
mobile user initiates the request by start UnifindMIDlet. The MIDlet will ask to confirm
the usage of positioning data and landmark data before execution. After the MIDlet is
30
started, it automatically searches for the location provider. Since location providers are
assumed to be free, no cost confirmation message would appear. Once the provider is
found, listeners are created and registered. Route UI is first called when the first
location update is received. Landmark store is managed by choosing different
commands from the UI.
Figure 5.2 Unifind: Class Diagram
On Figure 5.2, classes in package “location” (down the bottom) are provided by J2ME,
they are from the location API for shadowing the hardware events. Classes on top,
including MIDlet, CommandListener and Canas, are provided by MIDP2.0 for general
MIDlet development. Classes in “unifindUI” are UI classes which manages the screen
display. Classes in package “unifind” are management classes lay between location APIs
and UI classes to manipulate data.
Tasks are handled by Unifind in following way: the UnifindMIDlet listens to events
from UniListener, the interface which tells the MIDlet if a location provider is found
and whether the LocationProvider has successfully started to deliver location updates.
The ProviderConfig class automatically searches for the provider on the start up of the
MIDlet. UniData listens for location updates and proximity monitoring events through
31
LocationListener and ProximityListener, it also refreshes the viewer class UIuni
according to the updates. Finally, all landmaardStore related operations are controlled
via UniLandmarks.
A note on provider selection: providers for the virtual integrated GPS is the first choice,
because of the reasons explained in section 4.1, these providers are best-suited for
campus use. It is followed by the providers of stand-alone GPS. These providers offer
location data with reasonable accuracy, but can only be used in lines of sight to the
satellites. A-GPS is not on the list since users have to subscribe to the mobile network
provider, in order to use A-GPS. And Cellular positioning methods are not accurate
enough for campus use (see Table 2.1).
32
6. RESULTS
To test the performance of the application, several simulations were done in Nokia S60
3rd edition emulator. Section 6.1 describes the test environment and the simulation,
with the calculation of positioning errors. Section 6.2 analysis what happens at each step
of the setup process (i.e. before the user can navigate freely through the menus). Section
6.3 comments on the performance and possible future work of the application.
6.1 Testing
Before the simulation, one thing should be mentioned is that, the map view of the
application has not accomplished, due to the complexity of implementing the mapping
mechanism. The test will focus on the accuracy of the location data, the manipulation of
landmark storage, and the flow of the user interfaces.
6.1.1 Simulation Environment
Figure 6.1 S60 3rd Edition Emulator
33
The application is tested in the emulator of Nokia S60 3rd edition (S60 3rd Edition
Software Development Kit for Symbian OS for MIDP). Figure 6.1 shows how the
emulator appears to be. This SDK is chosen for the following reasons:
1. MIDP2.0 and J2ME are installed in S60 phones. Therefore the Location API can
be used, and User Interface (UI) can be properly displayed. Most importantly,
this series of phones have open OS, hence UniFind can be installed as a third
party application.
2. S60 series UI design is the leading smart phone design in the market. They are
designed for one-hand operation of advanced and consumer-friendly data
services. The enhanced user interface gives a clear view of the application. If the
map UI is finished, it is important for the navigation to be properly displayed. In
addition, the screen of the emulator can be configured to different resolutions. It
is helpful for designing consistent user interface for a variety of phones.
3. The tools collections for location-based application development are provided,
therefore Location API-based applications can be tested for predefined virtual
cases. The tool collections are detailed later in this section. Other tool sets (e.g.
debugging and diagnostics) are also included in the SDK to provide easy
management of application development.
4. Positioning module is supported in this emulator – this SDK implements GPS
module, but parameters (e.g. accuracy and delay) can be modified so that the
module can act like other positioning methods.
5. The emulator is able to be configured to notify the user of low battery events.
Since navigation application can be used frequently, it is useful to test the power
usage of these applications.
6. The SDK is powerful and rich in features (e.g. advanced Game API for map,
multiple emulator support), therefore future work, such as the development of
mapping mechanisms, is made possible.
7. S60 phones are popular in the market. As the leading smartphone built on the
Symbian OS, it is originally development by Nokia, and now is licensed by
34
world’s foremost mobile manufacturers including Nokia, LG, Lenovo, Samsung,
Siemens and Panasonic.
The most important reason is the tools contained by this SDK, they are used to fully
test location-based applications in the emulator. The figure below illustrates the relation
of different tools and the location framework that are available for application
developers.
.
Figure 6.2 tool colletions available for application developers (Sourc: S60 3rd Edition SDK Help)
As illustrated above, Simulation PSY (Simulation Positioning Subsystem), which is valid
from S60 release 3.0 and onwards, can be used by developers, enabling simulation of
different positions without actually needing to go to these different locations. With this
tool set, the retrieval of positioning data is independent of any hardware.
The Route Dialog of Simulation PSY, as shown in Figure 6.3, defines the simulated
route of the mobile handset. It outputs in NMEA or SPS file format. NMEA specifies
single coordinates from a GPS device, while SPS is an artificial format that specifies data,
such as speed and direction.
35
The Configurator plug-in of Simulation PSY, as shown in Figure 6.4, has been
implemented for configuring Simulation PSY. It allows for the selection of the data file
for Simulation PSY.
Figure 6.3 Simulation PSY Route Dialog
Figure 6.4 Simulation PSY Configurator
36
6.1.2 Procedure and Errors
Before install Unifind to the emulator, we need to define the environment. Open the
Simulation PSY Route Dialog, define the movements of the user, as shown in Figure 6.
5.
Figure 6.5 Define the Route
37
Save the movement to file nmea2.nme. Then enable the emulator to use nmea2 as the
route of the handset, by change the settings in Simulation PSY Configurator, as shown
in Figure 6.6.
Figure 6.6 Use the Defined Route in the Emulator
Then Unifind can be installed and tested in this defined case. The user is now vitually
moving from the start point X (Latitude: 28.660, Longitude: -36.401), to the end point
Y (Latitude: 4.500, Longitude: -55.440), at a constant speed of 30 meters per second.
Install Unifind to the emulator. For security reasons, the confirmation screens will
always appear before anything else, asking the user’s permission to be tracked and to use
the pre-installed landmark data. The confirmations screens are illustrated in Figure 6.7
below.
Select “Yes” for both screens, otherwise the user will exit from the application and
return to the main menu. As soon as the user grant the permissions to Unifind of using
positioning and landmark data, the application start to contact the available location
providers. This process may take a while, an information screen appears, as shown in
Figure 6.8, to show the user the progress of getting the first location data, during the
waiting time.
38
Figure 6.7 Privacy Confirmations
Figure 6.8 Waiting for the First Location Update
39
When the first update from the location provider is received, the screen is automatically
changed to show the current location of the user. The format of the positioning screen
is shown in Figure 6.9.
Figure 6.9 At the Start Point X
The coordinates is formatted in order to be displayed and on the screen, by using simple
truncation method. Positioning error can be calculated by using the system output pane.
Remember on Figure 6.5, the “real” coordinate of the terminal is (Latitude:
28.6597000000N, Longitude: 36.401420765W). Use the system output pane to show
40
the coordinate provided by Unifind in full scale, the result is in Figure 6.8. The
coordinate
provided
by
Unifind
is
(Latitude:
28.6597000002N,
Longitude:
36.401420765W). Assuming that the earth is a perfect sphere with a radius of 6378.0
kilometres, calculate the error by first convert the earth coordinates to normal
rectangular coordinates (x,y,z) using the formulae below:
x  r  cos( a) cos( b)
y  r  cos( a) sin( b)
(6.1)
z  r  sin( a)
Where a is the latitude (use negative number to represent south latitude), b is the
longitude (use negative number to represent west latitude), and r is the radius of the
earth. The error can then be calculated by using the property of the dot product
(notated [ p,q ]):
[ p, q]  Length[ p]  Length[q]  cos[ angle.btween. p. & .q]
(6.2)
Figure 6.8 The Coordinates in Full Scale (at start point X)
The calculation shows that, the error between the “real” location and the locations
provides by Unifind is less than 1 meter.
Select the “Editor” menu from the screen (Figure 6.9) to edit current location. Note
that the “View Map” menu cannot be selected as explained at the beginning of this
41
chapter. Address information can be entered – as shown in Figure 6.10, the current
location X (28.659N, 36.401W) can be saved as “Info Centre” to the default landmark
store.
Figure 6.10 Save Current Location
From Figure 6.10, we can notice that there are three operations available: List, Map and
Save. The Map command is designed to show the current location on map, this
function is unfinished and cannot be used.
Figure 6.11 List the Landmarks
42
If the List command is chosen, Unifind ignores the information entered and shows the
list of landmarks, as shown in Figure 6.11. I have preinstalled two locations, Castle 1
and Castle 2. If the Save command is selected, Unifind saves the landmark and
automatically lists the updated landmarks, as shown in Figure 6.12 below.
Figure 6.12 Save the New Landmark to the Store
On the Landmark screen (Figure 6.13), three options are available on the selected
landmark: Map, Update and Remove.
Figure 6.13 Landmark Screen
43
Same as in the Route Screen and Editor Screen, the unfinished Map function is
designed to view the selected destination on map. Update function and Remove
function can be tested as following: Select Castle 1 and then choose Update option, the
information of Castle 1 can be modified as shown in Figure 6.14. Select Info Centre and
then choose Remove, the Info Centre landmark is removed from the landmark list as
illustrated in Figure 6.15.
Figure 6.14 Update Landmark
Figure 6.15 Remove Landmark
44
Keep Unifind running until the handset reaches the stop point Y (4.5003999999N,
55.440491803W), which is shown the second picture of Figure 6.5. Unifind provides the
coordinate of (4.5004000003N, 55.440491857W), as shown in Figure 6.16.
Figure 6.16 At End Point Y
The estimated error is less than 10 meters, using the Formulae 6.1 and 6.2. Again, the
earth is assumed to be a perfect sphere with a radius of 6378.0 kilometres. Other
simulations are performed giving the similar results: errors range from centimetres to 10
meters.
Stop Unifind and reload the route file (i.e. file nmea2.nme). Restart the simulation and
let it run for a while. This time the proximity monitoring will be tested. Save a new
landmark as “Quad 1”, as shown in Figure 6.17.
45
Figure 6.17 Proximity Testing
Save Quad1 to the landmark store and return to the Route view immediately. Change
the resolution of the emulator so that longer texts will not be truncated. The result is
shown in Figure 6.18. Note that the “Proximity Monitoring” state is now changed to
“Landmark Found”.
Figure 6.18 Landmark Found
46
6.1.3 User Interface Flow
Figure 6.19 below shows the screen flow of UniFind:
Figure 6.19 UniFind: screen flow
Starting from the top left corner of the graph, the user is asked to confirm if positioning
data and landmark data can be used. Then the MIDlet starts to search for the location
provider. Once a location provider is found, the on the bottom left corner of the graph
appears to tell the user to wait for location updates.
After received the first location update, the screen is changed to view the received
location information. This information refreshes continuously with location updates
afterwards. Then the user can choose to add this location to landmark stores in the
Editor view – bottom right screen on the graph.
From the editor view, the user can select the “List” command to list the preinstalled and
user-defined locations. As shown on the top right corner of Figure 6.19, Castle 1, Castle
2 and the science library are now installed on the list. More locations should be
47
preinstalled in real implementation. Location information of the listed items can be
viewed by selecting “Update” command.
The map view is left as a black box. In the original design, it should be able to select
from current location view and list view.
Power consumption varies little across platforms. On the Nokia S60 3rd edition
emulator, with a GPS provider and power usage is set to “HIGH”, UniFind can run
continuously for around 30 hours, which is quite satisfactory.
6.2 Analysis
The Management and screen navigation can begin only after the location provider is
found, and UnifindMIDlet is capable of receiving a location update event. The section
is to clarify what is happened at each step of the setup process.
Figure 6.20 UniFind: Sequence Diagram (setup)
The Sequence Diagram in Figure 6.20 demonstrates how the MIDlet is setup to receive
location updates.
48
Like any MIDlet, UniFind starts by calling startApp(). It first checks if Location API is
supported by calling isApiSupported() on ProviderConfig Class. Then UniMIDlet gets
an object of ProvidrConfig by calling getInstance(), and use this instance to select a
location provider by calling findProvider() on ProviderConfig.
With findProvider(), ProviderConfig selects a location provider with certain
requirements. This is done by calling getInstance(criteria) on LocationProvider. Because
the UniListener is registered, a providerFound() event will be received by the MIDlet
once the provider is found.
UniMIDlet calls UIgeneral to show waiting message right after receiving
providerFoudn() event, as shown in Figure 6.8. Hence the user will be aware that the
provider is connected and location update is in progress.
At this point, UnifindMIDlet creates an instance of UniData, and registers the instance
with UniListener. LocationListener and ProximityListener are registered to the instance
during the creation.
Now the UniData instance is listening to the locationUpdate() event through Location
Listener. Once the locationUpdate() is received, it checks if this is the first update. If
this is true, UniData instance sends a firstUpdateEvent() to the MIDlet. The MIDlet
then calls UIuni to show current location (Figure 6.9) from previous waiting screen.
Because the locationUpdate() runs on a separate thread so it can continuously refresh
the information shown on the screen. From here, the sequence of the application is
determined by user’s commands; please refer the previous section for the screen flow
associating with commands.
6.3 Comments
UniFind needs future work before use – no one can navigate with only coordinates and
speed. As mentioned at the beginning, it can only be served as the starting ground for
research in location-based applications. The work done in this project is mainly setting
up the system to receive and manage the positioning data, and building up the sequence
of UI flows. Positioning performance is emphasised since the campus is a small area, if
it is applied to a city or a country, the positioning requirements can be lowered
49
accordingly. Security check is performed automatically to verify that the requesting party
has permission to access location information.
Although the estimated accuracy calculated in section 6.1.1 is satisfactory (up to 10
meters), we need to bear in mind the simulation is done an almost perfect environment.
Attenuation factors such as obstacles, ionosphere and troposphere, are presented in the
test environment. These factors can only be tested in a real situation, with real phones
supporting integrated GPS, and real integrated GPS location providers.
A-GPS can be used if there are mobile operators jointly providing the service. Some
notes on the comparison of A-GPS and stand-alone GPS from Nokia (2005): AGPS
offers better performance than stand-alone GPS because of superior accuracy, quicker
time-to-first-fix (warm-up time), and heightened sensitivity, which leads to better
performance in challenging or blocked environments. A-GPS will be available on the
Nokia 6155i, which is a Series 40 CDMA device. CDMA terminals will support cell ID
along with the A-GPS modes. This will let operators to offer location services even if
they have not upgraded their network for A-GPS. Stand-alone move and cell ID
methods do not offer the performance of A-GPS but offer the ability to enable
applications for location services without network upgrade.
Future work on this project can be divided to following categories:
1. The map view, which makes UniFind a navigation application as discribed in the
original design, can be finished. The current application is impossible to be used,
since the earth coordinates mean nothing to human beings.
Several issues are associated with this focus. First of all, the map of the university has
to be segmented, in order to be displayed on the small screen of a mobile. A map
selection method needs to be coded to the program, involving selecting the right
displayable segment according to user’s location. If the target location and current
location are not on the same segment, the user has to be notified to make a choice.
Another method is to use different resolutions of the map. In this way, user can
choose to magnify certain part of the map. However, in this way, the overall map of
the university will be unclear. Because the cell phone screen is not big enough for the
whole map.
50
Secondly, advance UI API or/and game APIs are likely to be used in viewer class
design, therefore UI consistency across platforms need to be considered. For
example, if it is decided to use FullCanvas from Nokia UI API to provide a full
screen painting area, an alternative view should be developed for phones which do
not support Nokia UI API. Finally, advanced UI display consumes much more
power than ordinary screen, energy saving issues might be considered for user
satisfaction.
2. Focus on finding other mobile handset locations. This will make UniFind a
“finder” application. Borrowing the idea of “Find Friends”, classmates and tutors can
register to a list and choose to be “visible”. Once they are found, the user can do
things such as “making an appointment” by phoning or instant messaging.
3. Focus on associating user location with currently happening events, UniFind can
then serve as a “reminder” application. For example, when the user is near Archway
Lecture Theatre at 1:00PM Friday, he will get a message telling that there is a seminar
on Multi-Agent Systems.
51
7. FUNDINGS AND DISCUSSIONS
In this chapter, findings and mistakes from the project will be described, with an
outlook on LBS market, followed by the conclusion at the end.
7.1 Findings
Many mistakes had been made and wrong direction had been taken, before the use of
location APIs were fully understood.
For example, setting up a virtual location server class was designed at the beginning, in
order to provide virtual positioning data. Hence the project was designed in a way that,
the client communicates with the location server using SMS or WAP. But all the
available SDKs can only be used for client side application development. Then the fact
that, shadowing the communication with the location server is one of the main
purposes of location APIs was realised during the implementation. The designed was
then changed so that SMS/WAP was no longer needed, since the application can
receive positioning data from the provider through LocationProvider class.
Another main advantage of using location APIs is that, it enables the program to run on
any platform supports the APIs. Therefore the code does not need to be changed
according to the different ways that each device handles the positioning signals.
There are always trade-offs in cost, performance and complexity. AGPS offers the best
performance but it is expensive and not so simple to be implemented, therefore not
many devices and networks support this method. Although stand-alone GPS provides
positioning data with high accuracy free of charge, it requires extra module to be
connected, and it has some drawbacks which is discussed in Chapter 1. Cell ID and
ToA do not require upgrading, but the accuracy and delay are obviously lower than
AGPS and GPS.
7.2 Market Outlook
Mobile operators and other professional organizations have found growing application
opportunities for LBS. According to Nokia (2005), these opportunities have been
clearly identified into following categories:
52
1. Mapping, navigation, and directions applications are the obvious targets for LBS,
but developers who combine this capability with directory services and other
offerings will be the long-term winners.
2. Workforce-tracking and management applications may end up being the most
lucrative applications because they will help enterprises optimize utilization of their
people, supplies, and capital equipment in the field. Industry segments include
security, delivery, and service businesses.
3. Entertainment and gaming applications can take the baton from the pioneering
geo-cache enthusiasts and create interactive gaming experiences and services that
complement sporting events, concerts, and more.
4. “Finder” applications can apply users’ locations to helping them locate anything
from the closest restroom to friends in a crowd.
5. Location-enhanced imaging applications can label captured multimedia with
information about the location where the user recorded the file.
6. Weather applications can provide local forecasts and warnings about inclement
weather.
7. Location-based reminder applications can prompt users when they reach particular
locations, displaying, for example, a shopping list when a user gets close to a certain
store.
8. Other applications including different billing models are available, depending on
the positioning method and the operator.
In order to capitalize on LBS, pricing factor is important. Therefore it is useful to find
free location providers (such as GPS), or the ones provide high performance with
affordable subscription fees.
7.3 Conclusion
The overall goal of the dissertation is to explore different aspects of location-based
services. The Unifind project is implemented for providing location information to
53
university students. Location-based software models and the location API are
introduced. Positioning methods are reviewed. Satellite positioning methods provide
better accuracy then cellular positioning methods in general. However, cellular
positioning methods are easier to be implemented.
Began as a result of government mandates, location-based services are rapidly growing,
especially these ones available to the mass market. Some successful/failed cases are
described and analysed. The future location-based services are predicted to be accurate,
affordable (to the mass market), and consistent across platforms.
The integrated GPS system, which is developed by Bjorn Wells, is chosen to be the
proposed possible solution for this project. Together with Symbian phones, it may give
the best performance of the application.
The back-up positioning method used in this project is GPS. Although it can only be
used in lines of sight to the satellites and has several drawbacks, including long warm-up
time, it is still a method providing reasonably accurate positioning and not difficult to
implement. Simulations are done with S60 3rd Edition Software Development Kit for
Symbian OS for MIDP. The estimated errors are within 10 meters of range, which is
reasonable for campus use. Other functions, such as landmark management and
proximity monitoring, are tested and working. The map function is left as a black box
for future development.
In conclusion, with the rapidly growing positioning technologies and API support,
mobile phones are now powerful enough to handle common and even complicated
tasks, which previously can only be done on professional devices. The uses of LBS, and
the use of LBS on mobile handsets, are only limited by developers’ imagination.
54
REFERENCE
Cigular. (2006). Retrieved Retrieved 8 OCT 2006 from:
http://www.cingular.com/mmode/mmode_content#instant
Egypt Marine DGPS. (2006). Retrieved 8 OCT 2006 from:
www.beacon-egypt.com/dgps.htm
Federal Communications Commission. (2006). Retrieved 8 OCT 2006 from:
http://www.fcc.gov/911/enhanced/
Grewal, M.., Weill, L. &. Andrews, A. (2001) Global Positioning Systems, Inertial Navigation,
and Integration. John Wiley & Sons, Inc., New York
Haiges, S. (2003, Oct). The Location API. SYS-CON Media. Retrieved 7 NOV from:
http://www.waikato.ac.nz/library/learning/g_apaguide.shtml
Hanrahan, T. (2003, June). AT&T Find Friends location service. The Wall Street Journal
Oonline. Retrieved 8 OCT 2006 from:
http://interactive.usc.edu/archives/000784.html
55
Intel Corporation. (2006, Feb). IT Information. Adding Location-based Services to Existing
Architectures: Building Feature-rich Mobile Telephony Applications Using Intel NetStructure®
Signaling Components. Retrieved 8 OCT 2006 from:
http://www.bitpipe.com/detail/RES/1157635217_277.html
KDDI Corporation (2003). KDDI to launch EZ Navi Walk, a full-scale navigation
service for pedestrians, Retrieved 8 NOV 2006 from:
http://www.kddi.com/english/corporate/news_release/2003/1006/attachment.ht
ml
Mahmoud, Q. (2004, March). Technical Articles and Tips. J2ME and Location-Based
Services. Retrieved 8 OCT 2006 from:
http://developers.sun.com/techtopics/mobility/apis/articles/location/
Nokia Corporation. (2005, March). Document. Capitalizing On The Location-Based Services
Opportunity. Retrieved 8 OCT 2006 from:
http://www.forum.nokia.com/info/sw.nokia.com/id/90db45d4-5f59-44a0-8cd1cebd62f4967e/Capitalizing_On_v1_1.pdf.html
Nokia Corporation. (2006, March). Document. MIDP: Location API Developer's Guide.
Retrieved 8 OCT 2006 from:
http://www.forum.nokia.com/info/sw.nokia.com/id/708ac992-1168-43b2-a46aaa3931e49d48/MIDP_Location_API_Developers_Guide_v1_0_en.pdf.html
56
Prasad, R., Ruggieri, M. (2003) Technology Trends in Wireless Communications. Artech House.
London. UK
Raja, K., Buchanan, W.J. & Munoz. J. (2004, June). We Know Where You Are. IEE
Communications Engineer.
Rao, B., Minakakis, L. (2003) Evolution of mobile location-based services, ACM Press, New
York, NY, USA
Telia. (2006). Retrieved Retrieved 8 OCT 2006 from:
http://trainingcenter.telia.se/articles/00/00/64/80/01/BROWSERV4index.html
Veijalainen, J., & Gross, T. (2002). Mobile Wireless Interfaces; in Search for the Limits. In:
Developing an Infrastructure for Mobile and Wireless Systems. Revised Papers.
Springer Verlag LNCS Vol. 2538, Dec., pp. 153-163.
Virrantaus, K., Veijalainen, J., Markkula, J., Katasonov, A., Garmash, A., Tirri, H. &
Terziyan, V. (2001). Developing GIS-supported Location-based Services. 2nd International
Conference on Web Information Systems Engineering, 3 - 6 December, Kyoto,
Japan, pp. 423-432.
Wikipedia, the Free Encyclopedia. (2006). Retrieved 8 OCT 2006 from:
http://en.wikipedia.org/wiki/GSM_localization
http://en.wikipedia.org/wiki/Differential_GPS
57
Wormley, S. J. (2004) Gps errors & estimating your receiver’s accuracy,. Retrieved 8 OCT 2006
from:
http://www.edu-observatory.org/gps/gps accuracy.html.
58
APPENDIX: Codes of Unifind
package unifind;
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import unifindUI.UIgeneral;
import unifindUI.UIuni;
/**
* UniMap MIDlet class.
*/
public class UnifindMIDlet extends MIDlet implements UniListener {
/* A static reference to the Display object of UnifindMIDlet */
private static Display display = null;
/* Lock object */
private Object lock = new Object();
/* A Reference to uniData */
private UniData uniData = null;
/**
* MIDlet Constructor
*/
public UnifindMIDlet() {
super();
}
/**
* Default method to start a MIDlet. The application automatically searches
* for the location provider after start up.
*/
public void startApp() {
// Set display of the application
display = Display.getDisplay(this);
if (ProviderConfig.isApiSupported()) {
// Try to find a locaiton provider automatically
ProviderConfig.getInstance().findProvider(this);
} else {
// Otherwise show the locaiton API is not supported by the device
UIgeneral.apiNotSupported();
}
}
/**
* Default method to destroy a MIDlet.
*/
protected void destroyApp(boolean b) throws MIDletStateChangeException {
}
/**
59
* Default method to pause a MIDlet.
*/
public void pauseApp() {
}
/**
* Sets up the waiting screen upon the provider found event received through
* UniListener.
*/
public void providerFound() {
// lock update() method
synchronized (lock) {
// Waiting message before location found
UIgeneral.updateWaiting();
// Inform the user that MIDlet is looking for location data.
uniData = new UniData((UniListener) this);
}
}
/**
* Sets up the UIuni upon the first locaiton update received through
* UniListener.
*/
public void firstLocationUpdateEvent() {
synchronized (lock) {
UIuni uiUni = new UIuni(uniData);
uniData.setUIuni(uiUni);
display.setCurrent(uiUni);
}
}
/**
* Getter method for Display.
*
* @return reference to Display object.
*/
public static Display getDisplay() {
return display;
}
}
package unifind;
import javax.microedition.location.*;
import unifindUI.UIsearch;
/**
* Find and configure location provider infomation
*/
public class ProviderConfig {
/* Selected location provider */
private LocationProvider provider = null;
60
/* Selected criteria */
private Criteria criteria = null;
/* Available criterias */
private static Criteria[] criterias = null;
/* Criteria names */
private static String[] criteriaNames = null;
/* Reference to ProviderQueryUI viewer class. */
private UIsearch uiSearch = null;
/* The instance of ProviderConfig */
private static ProviderConfig INSTANCE = null;
/**
* Performed before the constructor to create available criterias
*/
static {
// Create pre-defined criterias
criterias = new Criteria[2];
criteriaNames = new String[2];
// Integrated GPS
Criteria crit1 = new Criteria();
// Maximum accuracy of 5 meters
crit1.setHorizontalAccuracy(5);
crit1.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
// Prefered response time out of 100 milliseconds
crit1.setPreferredResponseTime(100);
// Use high power consumption to ensure the performance
crit1.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
// Find free providers
crit1.setCostAllowed(false);
crit1.setSpeedAndCourseRequired(true);
crit1.setAltitudeRequired(true);
crit1.setAddressInfoRequired(false);
criterias[0] = crit1;
criteriaNames[0] = "Integrated GPS";
// GPS
Criteria crit1 = new Criteria();
crit2.setHorizontalAccuracy(40);
crit2.setVerticalAccuracy(40);
crit2.setPreferredResponseTime(Criteria.NO_REQUIREMENT);
crit2.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
crit2.setCostAllowed(false);
crit2.setSpeedAndCourseRequired(true);
crit2.setAltitudeRequired(true);
crit2.setAddressInfoRequired(true);
criterias[1] = crit2;
61
criteriaNames[1] = "Stand-alone GPS";
}
/* Constructor class */
private ProviderConfig() {
uiSearch = new UIsearch();
}
/**
* Get a ProvidrConfig instance.
*
* @return static instance of ProviderConfig.
*/
public static ProviderConfig getInstance() {
if (INSTANCE == null) {
// Enable use of this class when Location API is supported.
if (isApiSupported()) {
INSTANCE = new ProviderConfig();
} else {
INSTANCE = null;
}
}
return INSTANCE;
}
/**
* Checks whether Location API is supported.
*
* @return a boolean indicating is Location API supported.
*/
public static boolean isApiSupported() {
String version = System.getProperty("microedition.location.version");
return (version != null && !version.equals("")) ? true : false;
}
/**
* Find a suitable location provider.
*
* @return a matching location provider
*/
public LocationProvider getSelectedProvider() {
return provider;
}
/**
* Find a locaiton provider matches the criterias defined previously.
*
* @param listener *
a listener that listens UniListener events.
*/
public void findProvider(UniListener listener) {
try {
// Location provider is selected. Priority of the criterias is the
62
// sequence of the array
for (int i = 0; i < criterias.length; i++) {
criteria = criterias[i];
provider = LocationProvider.getInstance(criteria);
if (provider != null) {
// Notify user that the location provider found
listener.providerFound();
return;
}
}
} catch (LocationException le) {
//Cannot find a matching provider
uiSearch.showOutOfService();
}
}
}
package unifind;
import java.util.Enumeration;
import javax.microedition.location.*;
import unifindUI.UIgeneral;
import unifindUI.UIuni;
public class UniData implements LocationListener, ProximityListener {
/* A Referenc to UniListener */
private UniListener uniListener = null;
/* A reference to uiUni */
private UIuni uiUni = null;
/* Coordinate detection threshold radius in meters */
public static final float PROXIMITY_RADIUS = 50;
/* The first location update done. */
private boolean firstTime = false;
/* UniData Constructor */
public UniData(UniListener listener) {
uniListener = listener;
ProviderConfig pConfig = ProviderConfig.getInstance();
LocationProvider locationProvider = pConfig.getSelectedProvider();
if (locationProvider != null) {
// 20 seconds
int interval = 20;
// no timeout
int timeout = 0;
// default maximum age of the provider
int maxAge = -1;
63
// Register LocationListener
locationProvider.setLocationListener(this, interval, timeout,
maxAge);
}
// Register ProxymityListener to landmarks
UniLandmarks uniLandmark = UniLandmarks.getInstance();
Enumeration enumeration = uniLandmark.getLandMarks();
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
Landmark landmark = (Landmark) enumeration.nextElement();
createProximityListener(landmark.getQualifiedCoordinates());
}
}
}
/**
* Setter method to UIuni.
*
* @param ui *
Reference to UIuni.
*/
public void setUIuni(UIuni ui) {
uiUni = ui;
}
/**
* Adds ProximityListener to the coordinates provided.
*
* @param coordinates
*/
public void createProximityListener(Coordinates coordinates) {
try {
LocationProvider.addProximityListener(this, coordinates,
PROXIMITY_RADIUS);
} catch (LocationException e) {
UIgeneral.cantAddListener();
}
}
/**
* Events received from ProximityListener when the current location is near
* the saved landmarks. It will result the "Location Provider" changing
* state in "curent state view".
*/
public void proximityEvent(Coordinates coordinates, Location location) {
if (uiUni != null) {
uiUni.setLocationProvider("Landmark found");
Landmark lm = UniLandmarks.getInstance().closest(coordinates);
// landmark found from landmark store
if (lm != null) {
uiUni.setInfo(lm.getAddressInfo(),
lm.getQualifiedCoordinates(), location.getSpeed());
64
}
// landmark not found from the landmark store, this should not never
// happen!
else {
uiUni.setInfo(location.getAddressInfo(), location
.getQualifiedCoordinates(), location.getSpeed());
}
uiUni.repaint();
}
}
/**
* Notifies user that the state of the proximity monitoring has changed
*/
public void monitoringStateChanged(boolean active) {
if (uiUni != null) {
if (active) {
// proximity monitoring is active
uiUni.setProximityState("Waiting");
} else {
// proximity monitoring can't be done currently.
uiUni.setProximityState("Inactive");
}
uiUni.repaint();
}
}
/**
* New thread for locationUpdated event to prevent blocking.
*/
public void locationUpdated(LocationProvider lProvider,
final Location location) {
// Screen needs to be changed upon first location update.
if (!firstTime) {
firstTime = true;
uniListener.firstLocationUpdateEvent();
}
if (uiUni != null) {
new Thread() {
public void run() {
if (location != null && location.isValid()) {
AddressInfo address = location.getAddressInfo();
QualifiedCoordinates coord = location
.getQualifiedCoordinates();
float speed = location.getSpeed();
uiUni.setInfo(address, coord, speed);
uiUni.setLocationProvider("Available");
uiUni.repaint();
} else {
uiUni.setLocationProvider("Not valid location data");
uiUni.repaint();
65
}
}
}.start();
}
}
/**
* New thread for providerStateChanged event to prevent blocking.
*/
public void providerStateChanged(LocationProvider arg0, final int newState) {
if (uiUni != null) {
new Thread() {
public void run() {
switch (newState) {
case LocationProvider.AVAILABLE:
uiUni.setLocationProvider("Available");
break;
case LocationProvider.OUT_OF_SERVICE:
uiUni.setLocationProvider("Out of service");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
uiUni.setLocationProvider("Temporarily unavailable");
break;
default:
uiUni.setLocationProvider("Unknown");
break;
}
uiUni.repaint();
}
}.start();
}
}
}
package unifind;
import java.io.IOException;
import java.util.Enumeration;
import javax.microedition.location.AddressInfo;
import javax.microedition.location.Coordinates;
import javax.microedition.location.Landmark;
import javax.microedition.location.LandmarkException;
import javax.microedition.location.LandmarkStore;
import javax.microedition.location.QualifiedCoordinates;
public class UniLandmarks {
/* A static instance of UniLandmarks */
private static UniLandmarks INSTANCE = null;
/* Reference to LandmarStore */
private LandmarkStore landmarkStore = null;
/* Store name */
66
private static final String STORENAME = "Unifind";
/* Default category */
private static final String DEFAULT_CATEGORY = null;
/* An array of landmarks */
private static Landmark[] lmList = null;
/* Frequently used landmarks are saved by default */
static {
lmList = new Landmark[3];
// Castle 1
AddressInfo addCastle = new AddressInfo();
addCastle.setField(AddressInfo.COUNTRY, "NZ");
addCastle.setField(AddressInfo.STATE, "Otago");
addCastle.setField(AddressInfo.CITY, "Dunedin");
addCastle.setField(AddressInfo.STREET, "123 Castle Street");
addCastle.setField(AddressInfo.BUILDING_NAME, "Castle Lecture Theatre");
QualifiedCoordinates coCastle1 = new QualifiedCoordinates(50.32, 60.75,
Float.NaN, 5, 5);
Landmark castle1 = new Landmark("Castle 1", "Lecture Theatre",
coCastle1, addCastle);
lmList[0] = castle1;
// Castle 2
AddressInfo addCastle2 = new AddressInfo();
addCastle2.setField(AddressInfo.COUNTRY, "NZ");
addCastle2.setField(AddressInfo.STATE, "Otago");
addCastle2.setField(AddressInfo.CITY, "Dunedin");
addCastle2.setField(AddressInfo.STREET, "123 Castle Street");
addCastle2
.setField(AddressInfo.BUILDING_NAME, "Castle Lecture Theatre");
QualifiedCoordinates coCastle2 = new QualifiedCoordinates(50.32, 60.75,
Float.NaN, 5, 5);
Landmark castle2 = new Landmark("Castle 1", "Lecture Theatre",
coCastle2, addCastle2);
lmList[1] = castle2;
// Science Library
AddressInfo addSci = new AddressInfo();
addSci.setField(AddressInfo.COUNTRY, "NZ");
addSci.setField(AddressInfo.STATE, "Otago");
addSci.setField(AddressInfo.CITY, "Dunedin");
addSci.setField(AddressInfo.STREET, "123 Union Street");
addSci.setField(AddressInfo.BUILDING_NAME, "St. David Lecture Theatre");
QualifiedCoordinates coSci = new QualifiedCoordinates(20.32, 40.75,
Float.NaN, 5, 5);
Landmark sciLib = new Landmark("Science Library", "Library", coSci,
addSci);
lmList[2] = sciLib;
}
67
private UniLandmarks() {
String name = null;
try {
landmarkStore = LandmarkStore.getInstance(STORENAME);
} catch (NullPointerException npe) {
}
// If the landmarkStore does not exist
if (landmarkStore == null) {
try {
LandmarkStore.createLandmarkStore(STORENAME);
name = STORENAME;
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LandmarkException e) {
e.printStackTrace();
}
landmarkStore = LandmarkStore.getInstance(name);
}
}
/**
* Enforce that only one instance of this class is used
*
* @return instance of UniLandmarks.
*/
public static UniLandmarks getInstance() {
if (INSTANCE == null) {
INSTANCE = new UniLandmarks();
for (int i = 0; i < lmList.length; i++) {
try {
INSTANCE.addNew(lmList[i]);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return INSTANCE;
}
public Enumeration getLandMarks() {
Enumeration enumeration = null;
try {
enumeration = landmarkStore.getLandmarks();
} catch (IOException e) {
e.printStackTrace();
}
68
return enumeration;
}
public void addNew(Landmark lm) throws IOException {
landmarkStore.addLandmark(lm, DEFAULT_CATEGORY);
}
public void update(Landmark lm) throws IOException, LandmarkException {
landmarkStore.updateLandmark(lm);
}
public Landmark findLandmark(int index) {
Landmark lm = null;
Enumeration ulm = UniLandmarks.getInstance().getLandMarks();
int counter = 0;
while (ulm.hasMoreElements()) {
lm = (Landmark) ulm.nextElement();
if (counter == index) {
break;
}
counter++;
}
return lm;
}
public void delLandmark(Landmark landmark) throws IOException,
LandmarkException {
landmarkStore.deleteLandmark(landmark);
}
/**
* Find closest landmark to the given coordinate
*/
public Landmark closest(Coordinates coord) {
Landmark closestLm = null;
double latRadius = 0.1;
double lonRadius = 0.1;
float dist = Float.MAX_VALUE;
try {
// Generate enumeration of Landmarks that are close to coord.
Enumeration enu = landmarkStore.getLandmarks(null, coord
.getLatitude()
- latRadius, coord.getLatitude() + latRadius, coord
.getLongitude()
- lonRadius, coord.getLongitude() + lonRadius);
float tmpDist;
69
Landmark tmpLandmark = null;
while (enu.hasMoreElements()) {
tmpLandmark = (Landmark) enu.nextElement();
tmpDist = tmpLandmark.getQualifiedCoordinates().distance(coord);
if (tmpDist < dist) {
closestLm = tmpLandmark;
}
}
} catch (IOException ioe) {
return null;
}
return closestLm;
}
}
package unifind;
/**
* General purpose utility class
*/
public class Utils {
/**
* Cast a double value to a String presentation, with an option to choose
* how many digits needed. Output value is just truncated.
*
* @param value *
double value to be converted.
* @param decimals *
number of decimals in the String presentation.
* @return a string representation of the argument.
*/
public static String douCstString(double value, int decimals) {
String doubleStr = "" + value;
int index = doubleStr.indexOf(".") != -1 ? doubleStr.indexOf(".")
: doubleStr.indexOf(",");
// Decimal point can not be found...
if (index == -1)
return doubleStr;
// Truncate all decimals
if (decimals == 0) {
return doubleStr.substring(0, index);
}
int len = index + decimals + 1;
if (len >= doubleStr.length())
len = doubleStr.length();
double d = Double.parseDouble(doubleStr.substring(0, len));
return String.valueOf(d);
}
}
package unifind;
70
/**
* Notify customer with infomation of the location provider
*/
public interface UniListener {
/**
* A Notification that location provider has been found
*/
public void providerFound();
/**
* A Notification about the first location update.
*/
public void firstLocationUpdateEvent();
}
package unifindUI;
import java.io.IOException;
import java.util.Enumeration;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.location.AddressInfo;
import javax.microedition.location.Landmark;
import javax.microedition.location.LandmarkException;
import javax.microedition.location.QualifiedCoordinates;
import unifind.UniData;
import unifind.UniLandmarks;
import unifind.UnifindMIDlet;
import unifind.Utils;
public class UIeditor extends Form implements CommandListener {
/** Landmark list */
private List targets = new List("Landmarks:", List.EXCLUSIVE);
/**Coordinate components*/
private StringItem lat = new StringItem("Lat:", "");
private StringItem lon = new StringItem("Lon:", "");
private StringItem alt = new StringItem("Alt:", "");
/** Commands */
private Command cmdState = new Command("Route", Command.BACK, 1);
71
private Command cmdList = new Command("List", Command.OK, 1);
private Command cmdSave = new Command("Save", Command.OK, 1);
private Command cmdUpdateExist = new Command("Save", Command.OK, 1);
private Command cmdUpdate = new Command("Update", Command.OK, 1);
private Command cmdDelet = new Command("Delete", Command.OK, 1);
private Command cmdMap = new Command("Map", Command.OK, 1);
/** Landmark infomation fields, (*) = required field */
private TextField infoName = new TextField("Name (*):", "", 20,
TextField.ANY);
private TextField infoDesc = new TextField("Description (*):", "", 40,
TextField.ANY);
private TextField infoCountry = new TextField("Country:", "", 20,
TextField.ANY);
private TextField infoState = new TextField("State:", "", 20, TextField.ANY);
private TextField infoCity = new TextField("City:", "", 20, TextField.ANY);
private TextField infoStreet = new TextField("Street:", "", 20,
TextField.ANY);
private TextField infoBuilding = new TextField("Building (*):", "", 20,
TextField.ANY);
/** Other data fields */
private UImap uiMap = null;
private QualifiedCoordinates coordinates = null;
private UniData uniData = null;
private Displayable state = null;
public static final int MODE_UPDATE = 0;
public static final int MODE_ADDNEW = 1;
public static final int MODE_MAPVIEW = 2;
public UIeditor(Displayable dis, UniData uniData) {
super("Edit Landmarks");
// state and list commands always available on editor
addCommand(cmdState);
addCommand(cmdList);
setCommandListener(this);
// can always go back to current state view from landmarks list
targets.addCommand(cmdState);
targets.setCommandListener(this);
72
}
/**
* Initialize UI components and show the landmark editor.
*/
public void initialize(QualifiedCoordinates coord, int mode)
{
this.coordinates = coord;
// initialize coordinate
lat.setText(Utils.douCstString(coord.getLatitude(),4));
lon.setText(Utils.douCstString(coord.getLongitude(), 4));
alt.setText(Utils.douCstString(coord.getAltitude(), 1));
// initialize data fields of Address
infoName.setString("");
infoDesc.setString("");
infoCountry.setString("");
infoState.setString("");
infoCity.setString("");
infoStreet.setString("");
infoBuilding.setString("");
deleteAll();
append(infoName);
append(infoDesc);
append(infoCountry);
append(infoState);
append(infoCity);
append(infoStreet);
append(infoBuilding);
append(lat);
append(lon);
append(alt);
// Update existing landmark.
if (mode == MODE_UPDATE)
{
Landmark lm = UniLandmarks.getInstance().closest(
coord);
if (lm != null)
{
infoName.setString(lm.getName());
infoDesc.setString(lm.getDescription());
AddressInfo info = lm.getAddressInfo();
if (info != null)
{
infoCountry.setString(info.getField(AddressInfo.COUNTRY));
infoState.setString(info.getField(AddressInfo.STATE));
infoCity.setString(info.getField(AddressInfo.CITY));
infoStreet.setString(info.getField(AddressInfo.STREET));
infoBuilding.setString(info
.getField(AddressInfo.BUILDING_NAME));
73
}
}
removeCommand(cmdUpdate);
removeCommand(cmdSave);
addCommand(cmdUpdateExist);
addCommand(cmdList);
UnifindMIDlet.getDisplay().setCurrent(this);
}
// Add new landmark to the landmark store.
else if (mode == MODE_ADDNEW)
{
removeCommand(cmdUpdate);
removeCommand(cmdUpdateExist);
addCommand(cmdSave);
addCommand(cmdList);
UnifindMIDlet.getDisplay().setCurrent(this);
}
// Show map view
else if (mode == MODE_MAPVIEW){
uiMap.showCurrent(coord);
}
}
public void commandAction(Command cmd, Displayable dis) {
Landmark landmark = null;
// Add new Landmark to the LandmarkStore
if (cmd == cmdSave) {
landmark = generateLandmark();
if (landmark != null) {
try {
UniLandmarks.getInstance().addNew(landmark);
uniData.createProximityListener(coordinates);
} catch (IOException e) {
Alert alert = new Alert("Error",
"I/O Error during add operation", null,
AlertType.ERROR);
alert.setTimeout(5000); // 5 secs
UnifindMIDlet.getDisplay().setCurrent(alert);
}
// New landmark is available on the list
list();
}
}
// Update existing landmark
else if (cmd == cmdUpdateExist) {
landmark = generateLandmark();
if (landmark != null) {
try {
UniLandmarks.getInstance().update(landmark);
uniData.createProximityListener(coordinates);
} catch (IOException e) {
Alert alert = new Alert("Error",
74
"I/O Error during update operation", null,
AlertType.ERROR);
alert.setTimeout(3000); // 3 secs
UnifindMIDlet.getDisplay().setCurrent(alert);
} catch (LandmarkException e) {
Alert alert = new Alert("Error",
"Unexpected error: can not find landmark from "
+ "the landmark store.", null,
AlertType.ERROR);
alert.setTimeout(3000); // 3 secs
UnifindMIDlet.getDisplay().setCurrent(alert);
}
// Updated landmark is available on the list
list();
}
}
else if(cmd==cmdMap){
int index = targets.getSelectedIndex();
landmark = UniLandmarks.getInstance().findLandmark(index);
uiMap.showTarget(landmark,this.coordinates);
}
// Go back to the previous screen
else if (cmd == cmdState) {
UnifindMIDlet.getDisplay().setCurrent(state);
}
// Editor the selected landmark.
else if (cmd == cmdUpdate) {
int index = targets.getSelectedIndex();
landmark = UniLandmarks.getInstance().findLandmark(index);
initialize(landmark.getQualifiedCoordinates(), MODE_UPDATE);
}
// Delete selected Landmark from LandmarkStore
else if (cmd == cmdDelet) {
try {
int index = targets.getSelectedIndex();
landmark = UniLandmarks.getInstance().findLandmark(index);
UniLandmarks.getInstance().delLandmark(landmark);
Alert alert = new Alert("Information",
"Landmark is successfully deleted.", null, AlertType.INFO);
alert.setTimeout(3000); // 3 secs
UnifindMIDlet.getDisplay().setCurrent(alert);
} catch (IOException e) {
Alert alert = new Alert("Error", "I/O Error during operation",
null, AlertType.ERROR);
alert.setTimeout(3000); // 3 secs
UnifindMIDlet.getDisplay().setCurrent(alert);
} catch (LandmarkException le) {
Alert alert = new Alert("Error",
"landmark can not be deleted.",
null, AlertType.ERROR);
alert.setTimeout(3000); // 3 secs
UnifindMIDlet.getDisplay().setCurrent(alert);
75
}
list();
}
// Show the list of Landmarks
else if (cmd == cmdList) {
list();
}
}
/**
* The taget landmark list is refreshed each time
* when this method is called.
*/
private void list() {
targets.deleteAll();
Landmark lm = null;
Enumeration landmarks = UniLandmarks.getInstance().getLandMarks();
// Check whether landmarks can be founds from the Landmark store.
if (landmarks != null)
{
while (landmarks.hasMoreElements())
{
lm = ((Landmark) landmarks.nextElement());
targets.append(lm.getName(), null);
}
targets.addCommand(cmdUpdate);
targets.addCommand(cmdDelet);
}
// No landmarks found (list is empty)
else
{
targets.removeCommand(cmdUpdate);
targets.removeCommand(cmdDelet);
}
UnifindMIDlet.getDisplay().setCurrent(targets);
}
private Landmark generateLandmark() {
String info = infoCheck();
if (info != null) {
Alert alert = new Alert("Error", info + " is required.", null,
AlertType.ERROR);
alert.setTimeout(3000); // 3 secs
UnifindMIDlet.getDisplay().setCurrent(alert, this);
return null;
}
AddressInfo address = new AddressInfo();
76
address.setField(AddressInfo.COUNTRY, infoCountry.getString());
address.setField(AddressInfo.STATE, infoState.getString());
address.setField(AddressInfo.CITY, infoCity.getString());
address.setField(AddressInfo.STREET, infoStreet.getString());
address.setField(AddressInfo.BUILDING_NAME, infoBuilding.getString());
Landmark lm = new Landmark(infoName.getString(), infoDesc.getString(),
coordinates, address);
return lm;
}
private String infoCheck() {
if (infoName.getString().equals("")) {
return "Name";
} else if (infoDesc.getString().equals("")) {
return "Description";
} else if (infoBuilding.getString().equals("")) {
return "Building name";
}
return null;
}
}
package unifindUI;
import javax.microedition.lcdui.*;
import unifind.UnifindMIDlet;
/**
* General purpose message UI
*/
public class UIgeneral {
/**
* Shows a alert that listener cannot be added.
*/
public static void cantAddListener() {
Alert alert = new Alert("General", "Listener cannot be added", null,
AlertType.INFO);
UnifindMIDlet.getDisplay().setCurrent(alert);
}
/**
* Shows a alert that Location API is not supported.
*/
public static void apiNotSupported() {
Alert alert = new Alert("General",
"Device do not support Location API", null, AlertType.INFO);
UnifindMIDlet.getDisplay().setCurrent(alert);
}
/**
77
* Shows a alert that the device is waiting for the first location update.
*/
public static void updateWaiting() {
Gauge waiting = new Gauge(null, false, 50, 1);
waiting.setValue(Gauge.CONTINUOUS_RUNNING);
Alert alert = new Alert("General", "Updating current location....",
null, AlertType.INFO);
alert.setIndicator(waiting);
UnifindMIDlet.getDisplay().setCurrent(alert);
}
/**
* Shows a alert that Location data is not available.
*/
public static void locationDataNotAvailable() {
Alert alert = new Alert("General",
"Location data is not yet available.", null, AlertType.INFO);
UnifindMIDlet.getDisplay().setCurrent(alert);
}
}
package unifindUI;
import javax.microedition.lcdui.*;
import unifind.UnifindMIDlet;
/**
* UI class that is responsible for all the queries of the location provider
*/
public class UIsearch {
/* Status information Form */
private Form searchForm = new Form("Seaching for location provider...");
/* StringItem showing the current status. */
private StringItem statusItem = new StringItem("Status:", "");
private static final String OUT_OF_SERVICE_MESSAGE = "Sorry, All Location
providers are currently out of service. "
+ "Pleasing check if the location-providing module is properly connected.";
private static final String SEACHING_PROVIDERS = "Now seaching...";
private static final String NOT_FOUND_MESSAGE = "Try again after location-providing
module is properly connected.";
/**
* Construct the UI with default values.
*/
public UIsearch() {
statusItem.setText(SEACHING_PROVIDERS);
searchForm.append(statusItem);
78
}
/**
* Show out of service error message.
*/
public void showOutOfService() {
Alert alert = new Alert("Error", OUT_OF_SERVICE_MESSAGE, null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
UnifindMIDlet.getDisplay().setCurrent(alert, searchForm);
statusItem.setText(NOT_FOUND_MESSAGE);
}
}
package unifindUI;
import javax.microedition.lcdui.*;
import javax.microedition.location.AddressInfo;
import javax.microedition.location.QualifiedCoordinates;
import unifind.UniData;
public class UIuni extends Canvas implements CommandListener {
/* Rerefence to UIeditor */
private UIeditor uiEditor = null;
/* Command that shows Map view */
private Command cmdMap = new Command("View Map", Command.OK, 1);
/* Command that shows Landmark editor UI */
private Command cmdEditor = new Command("Editor", Command.STOP, 1);
/* The current state of the location provider as a String */
private String locationProvider = "Inactive";
/* Proximity monitoring state. */
private String proximityMonitor = "Waiting";
private QualifiedCoordinates coordinates;
private AddressInfo address;
private float speed;
public UIuni(UniData data) {
uiEditor = new UIeditor(this, data);
addCommand(cmdEditor);
addCommand(cmdMap);
setCommandListener(this);
}
public void setLocationProvider(String change) {
locationProvider = change;
}
79
public void setProximityState(String change) {
proximityMonitor = change;
}
public void setInfo(AddressInfo addr, QualifiedCoordinates coord,
float speed) {
this.address = addr;
this.coordinates = coord;
this.speed = speed;
}
protected void paint(Graphics graphic) {
Font f = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN,
Font.SIZE_SMALL);
graphic.setFont(f);
// use font height as a line height
int lineHeight = f.getHeight();
// current line counter
int line = 0;
// clean the backround
graphic.setColor(0xffffff);
graphic.fillRect(0, 0, getWidth(), getHeight());
graphic.setColor(0x0000ff);
graphic.drawString("Location Provider: " + locationProvider, 0,
lineHeight * (line++), Graphics.LEFT | Graphics.TOP);
graphic.drawString("Proximity monitoring: " + proximityMonitor, 0,
lineHeight * (line++), Graphics.LEFT | Graphics.TOP);
if (coordinates != null) {
double lat = coordinates.getLatitude();
double lon = coordinates.getLongitude();
graphic.drawString("Coordinates: " + lat + "(lat)" + ", " + lon
+ "(lon)", 0, lineHeight * (line++), Graphics.TOP
| Graphics.LEFT);
graphic.drawString("Speed: " + speed + " m/s", 0, lineHeight
* (line++), Graphics.TOP | Graphics.LEFT);
}
// Check if AddressInfo is available
if (address != null) {
String country = address.getField(AddressInfo.COUNTRY);
String state = address.getField(AddressInfo.STATE);
String city = address.getField(AddressInfo.CITY);
String street = address.getField(AddressInfo.STREET);
String buildingName = address.getField(AddressInfo.BUILDING_NAME);
graphic.setColor(0x000000);
if (country != null)
graphic.drawString("Country: " + country, 0, lineHeight
80
* (line++), Graphics.TOP | Graphics.LEFT);
if (state != null)
graphic.drawString("State: " + state, 0, lineHeight * (line++),
Graphics.TOP | Graphics.LEFT);
if (city != null)
graphic.drawString("City: " + city, 0, lineHeight * (line++),
Graphics.TOP | Graphics.LEFT);
if (street != null)
graphic.drawString("Street: " + street, 0, lineHeight
* (line++), Graphics.TOP | Graphics.LEFT);
if (buildingName != null)
graphic.drawString("Building name: " + buildingName, 0,
lineHeight * (line++), Graphics.TOP | Graphics.LEFT);
}
}
public void commandAction(Command cmd, Displayable dis) {
if (cmd == cmdEditor) {
if (coordinates != null) {
// show editor
uiEditor.initialize(coordinates, UIeditor.MODE_ADDNEW);
} else {
UIgeneral.locationDataNotAvailable();
}
} else if (cmd == cmdMap) {
// show map
uiEditor.initialize(coordinates, UIeditor.MODE_MAPVIEW);
}
}
}
package unifindUI;
import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;
import javax.microedition.location.Landmark;
import javax.microedition.location.QualifiedCoordinates;
import unifind.UniData;
/**
* Unfinnish map viewer class
*/
public class UImap extends Canvas implements CommandListener, Runnable {
/* Landmark list */
private List targets = new List("Landmarks:", List.EXCLUSIVE);
81
/* Flag telling is the compass update thread active */
private boolean threadActive = false;
/* Commands */
private Command cmdState = new Command("Current State", Command.BACK, 1);
private Command cmdList = new Command("Target List", Command.OK, 1);
/* Modes */
public static final int MODE_CURRENT = 0;
public static final int MODE_TARGET = 1;
public UImap(Displayable dis, UniData data) {
loadMap();
addCommand(cmdState);
addCommand(cmdList);
setCommandListener(this);
targets.addCommand(cmdState);
targets.setCommandListener(this);
}
private void loadMap() {
String imageName = "/map.gif";
try {
Image mapImage = Image.createImage(getClass().getResourceAsStream(
imageName));
} catch (IOException e) {
e.printStackTrace();
}
}
protected void paint(Graphics g) {
// clean up canvas
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());
// paint the map
}
public void commandAction(Command arg0, Displayable arg1) {
// add commands
}
public void run() {
while (threadActive) {
// updating current position data
}
}
public void showCurrent(QualifiedCoordinates coord) {
82
// show current location on map
}
public void showTarget(Landmark landmark, QualifiedCoordinates coordinates2) {
// show current locacation and target location with different colors
}
}
83
Download