Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Revision as of 14:42, 17 November 2013 by kiran10182 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Mapping points of interest using Java ME

From Wiki
Jump to: navigation, search
Featured Article
17 Nov

This article explains how to use Nokia SDK 2.0 to create application for mapping points of interest for a Series 40 full touch device. The app also gets weather and news information from web services.

Note.pngNote: This is an entry in the Asha Touch Competition 2012Q3

Article Metadata
Code ExampleTested with
Devices(s): X3-02, Asha 311, Asha 501
Platform(s): Asha, Series 40, Symbian^1, Symbian^3
Nokia Asha
Nokia Asha Platform 1.0
Series 40
Series 40 DP 2.0
Series 40 DP 1.1
Created: adarsha_saraff (08 Jul 2012)
Last edited: kiran10182 (17 Nov 2013)



Quick Walk through

The code example uses the content of a Refreshment app. The app provides information about current weather, contains news, and includes mapping features to help you locate refreshment.

In future the app may be extended to include navigation information with transits, walk and drive, or to additionally help users locate ATM's, bus stops, metro stations, nearby taxi stand and many more.

Quick intro to Location API

We need the current location to request Weather data to the server. I will explain how to request to the server to obtain weather data later in the coming topics. Current location is also used with maps to find out the nearest chat center and hangouts.

Creating object of location

LocationProvider myloc;

Current location through Cellular ID

Series 40 supports cellular ID and WLAN positioning. Series 40 extends the Location API with the class. Therefore, I have used LocationUtil.getLocationProvider(type, null). However, support for this in specific devices vary. So, I will be using MTE_CELLID, MTY_NETWORKBASED and MTA_ASSISTED.

Use the following statements in startApp() method.

int[] type = {Location.MTE_CELLID|Location.MTY_NETWORKBASED|Location.MTA_ASSISTED};
try {
myloc = LocationUtil.getLocationProvider(type, null);
javax.microedition.location.Location Loc = myloc.getLocation(300);
if(Loc != null){
QualifiedCoordinates cor = Loc.getQualifiedCoordinates();
lat = cor.getLatitude();
lon = cor.getLongitude();
} catch (Exception ex) {}

Quick intro to Nokia Map API

Creating object of MapCanvas and setting up the things

MapCanvas mapCanvas = new MapCanvas(Display.getDisplay(this)) {
public void onMapUpdateError(String arg0, Throwable arg1, boolean arg2) {
// TODO Auto-generated method stub
public void onMapContentComplete() {
// TODO Auto-generated method stub

In startApp() method add the following lines to setup initial things.


Positioning the map to current location and zooming

We will start with positioning to current location on map and extend this location to find out refreshment places near.

mapCanvas.getMapDisplay().zoomTo(new GeoBoundingBox(new GeoCoordinate(lat, lon, 0)), false);
mapCanvas.getMapDisplay().addMapObject(mapCanvas.getMapFactory().createStandardMarker(new GeoCoordinate(lat, lon, 0), 1, "It's You", 2));

Tip.pngTip: It is good practice to create a marker to indicate current position. Use createStandardMarker() method of MapFactory class as shown above.

Refreshment map find nearby.png

Nokia UI Components used in here

Apart from using pure LCDUI components, I will make use of two new components provided and supported on Series 40 full touch devices. These are Category Bar and Icon Command.

Tip.pngTip: If you are interested in designing an app UI with Category Bar see this article.


Creating Category Bar and making it visible.

CategoryBar cbar;
try {
Image[] unsel = { Image.createImage("/home.png"),
Image.createImage("/refreshment.png") };
Image[] sel = { Image.createImage("/home.png"),
Image.createImage("/refreshment.png") };
String[] lab = { "Home", "News", "Refreshments" };
cbar = new CategoryBar(unsel, sel, lab);
} catch (Exception ex) {}

Note.pngNote: App can have only one Category Bar set visible at a time. However You can create multiple Category Bars but only one can be made visible. If the app requires multiple Category Bars, create as many as needed and change visibility as required. Ex: Form f1 has CategoryBar cbar1 with some items and Form f2 has CategoryBar cbar2 with some items. For Form f1 as current display, use: cbar1.setVisibility(true); cbar2.setVisibility(false); and so on.


Creating and using Icon Command is like normal command. More on Icon Command

try {
refeshCommand = new IconCommand("Refresh",Image.createImage("/refresh.png"),Image.createImage("/refresh.png"), Command.OK, 0);
currentposCommand = new IconCommand("Current pos",Image.createImage("/curloc.png"), Image.createImage("/curloc.png"), Command.OK, 0);
} catch (Exception ex) {

Weather feed

Weather feed and rss feed data will be in XML format and we need to parse these xml to extract required information. There are number of XML parsers available: About XML Parser. kXML is one of such parser I would like to use. kXML 1.2 have been included in source program.

public void run() {
try {
//Url format for http request is:<latitude>,<longitude>&format=xml&num_of_days=1&key=XXXXXXXXXXXXXXXXXXXXXX
// or<City>,<Country>&format=xml&num_of_days=1&key=XXXXXXXXXXXXXXXXXXXXXX
String reqUrl = url + lat + "," + lon + keys;
con = (HttpConnection), Connector.READ_WRITE,true);
} catch (Exception e) {

Note.pngNote: Weather API returns data in XML, CSV, json format. XML is easy to parse, so I will use xml in &format field.

<query>Lat 28.64 and Lon 77.24</query>
<observation_time>11:10 AM</observation_time>
<![CDATA[ Light rain shower ]]>
<![CDATA[ Partly Cloudy ]]>

Above is sample XML data response. We need to parse the xml data to obtain required information. Important information required observation_time, temp_C, weatherIconUrl and weatherDesc. We need to design the XML parser to parse the weather feed. XML parser for this will be one below:

public void weatherxmlparser(InputStream xmldata) {
Reader r = new InputStreamReader(xmldata);
try {
XmlParser parser = new XmlParser(r);
traverse( parser, "" );
} catch (Exception e) {
public void traverse(XmlParser parser, String indent) {
try {
boolean leave = false;
do {
ParseEvent event =;
ParseEvent pe;
switch (event.getType()) {
// For example, <title>
case Xml.START_TAG:
// see API doc of StartTag for more access methods
// Pick up Time for display
if ("observation_time".equals(event.getName())) {
pe =;
this.r.wtr.time = pe.getText();
// Pick up temperature for display and so on
if ("temp_C".equals(event.getName())) {
pe =;
this.r.wtr.tempINDegC = pe.getText();
if ("weatherIconUrl".equals(event.getName())) {
pe =;
//download image for the corresponding URL
this.r.wtr.wicon = loadImage(pe.getText());
if ("weatherDesc".equals(event.getName())) {
pe =;
this.r.wtr.climate = pe.getText();
traverse( parser, "" ) ; // recursion call for each <tag></tag>
// For example </title>
case Xml.END_TAG:
leave = true;
// For example </data>
leave = true;
// For example, the text between tags
case Xml.TEXT:
} while (!leave);
} catch (Exception e) {

Refreshment home.png
Weather data obtained from server is parsed and painted on Canvas of a CustomItem.

News Feed

To get latest new, we will be using Yahoo News RSS feed.

Category Feed URL
Top Stories
World News

In news form, user selects an choice from choice group. Through itemState listener we are able to identify the change in the selection. Depending upon the selection, request to server is sent through HTTP request. Which is done using Thread. Using Thread because server may busy at the time of request and may not respond to our request. Therefore we make repeated request until server responds to our request. Then by opening I/O streams we can read the data. The thread t handles the task of requesting and opening I/O connection.

public void getFeeds(String url) {
yahooNewURL = url;
t = new Thread(this);
public void run() {
try {
con = (HttpConnection),Connector.READ_WRITE, true);
} catch (Exception e) {
// TODO: handle exception
<rss xmlns:media="" version="2.0">
<title>Movies News Headlines - Yahoo! News</title>
Get the latest Movies news headlines from Yahoo! News. Find breaking Movies news, including analysis and opinion on top Movies stories, photos and more.
<copyright>Copyright (c) 2012 Yahoo! Inc. All rights reserved</copyright>
<pubDate>Mon, 23 Jul 2012 20:19:11 -0400</pubDate>
<title>Movies News Headlines - Yahoo! News</title>
<title>"Dark Knight Rises" earns $160.8 million in debut</title>
<p><a href=""><img src="" width="130" height="86" alt="A poster for &quot;The Dark Knight Rises&quot; is displayed in Burbank" align="left" title="A poster for &quot;The Dark Knight Rises&quot; is displayed in Burbank" border="0" /></a>LOS ANGELES (Reuters) - Warner Bros said on Monday &quot;The Dark Knight Rises&quot; took in $160.8 million at U.S. and Canadian box offices over the weekend, which is lower than industry estimates for the debut that felt the impact of last week&#039;s movie theater massacre in Colorado. &quot;Dark Knight Rises&quot; also opened in 17 international markets with $88 million in ticket sales to put its global total at just under $250 million for its debut. Warner Bros, a unit of Time Warner Inc, made no initial comment beyond simply releasing the figures. ...</p><br clear="all"/>
<pubDate>Mon, 23 Jul 2012 20:19:11 -0400</pubDate>
<source url="">Reuters</source>
<guid isPermaLink="false">
<media:content url="" type="image/jpeg" width="130" height="86"/>
<media:text type="html">
<p><a href=""><img src="" width="130" height="86" alt="A poster for &quot;The Dark Knight Rises&quot; is displayed in Burbank" align="left" title="A poster for &quot;The Dark Knight Rises&quot; is displayed in Burbank" border="0" /></a>LOS ANGELES (Reuters) - Warner Bros said on Monday &quot;The Dark Knight Rises&quot; took in $160.8 million at U.S. and Canadian box offices over the weekend, which is lower than industry estimates for the debut that felt the impact of last week&#039;s movie theater massacre in Colorado. &quot;Dark Knight Rises&quot; also opened in 17 international markets with $88 million in ticket sales to put its global total at just under $250 million for its debut. Warner Bros, a unit of Time Warner Inc, made no initial comment beyond simply releasing the figures. ...</p><br clear="all"/>
<media:credit role="publishing company"/>

Above shows the sample RSS feed in XML format received from server. We need to parse this XML to retrieve the required information. We are interested in reading title, link and published date. Therefore our parser should be designed to read only these fields located between <item> and </item> tag. So we do recursive parsing between each <item>and </item> tags until the end of document is reached.
Code for the same will be:

public void getData(InputStream xmldata) {
Reader r = new InputStreamReader(xmldata);
try {
XmlParser parser = new XmlParser(r);
ParseEvent pe = null;
parser.skip();, null, "rss");
parser.skip();, null, "channel");
boolean trucking = true;
while (trucking) {
pe =;
if (pe.getType() == Xml.START_TAG) {
String name = pe.getName();
if (name.equals("item")) {
String title, link, description;
title = link = description = null;
while ((pe.getType() != Xml.END_TAG)
|| (pe.getName().equals(name) == false)) {
pe =;
if (pe.getType() == Xml.START_TAG
&& pe.getName().equals("title")) {
pe =;
title = pe.getText();
} else if (pe.getType() == Xml.START_TAG
&& pe.getName().equals("link")) {
pe =;
link = pe.getText();
} else if (pe.getType() == Xml.START_TAG
&& pe.getName().equals("pubDate")) {
pe =;
description = pe.getText();
this.r.newsf.append(new customlist(title, link,
description, this.r));
} else {
while ((pe.getType() != Xml.END_TAG)
|| (pe.getName().equals(name) == false))
pe =;
if (pe.getType() == Xml.END_TAG && pe.getName().equals("rss")){
trucking = false;
t = null;
} catch (Exception e) {

Once we get these required information, we need to append this to our form. Which is done using this.r.newsf.append(new customlist(title,link,description, this.r)); . Where r - instance of Refreshment MIDlet, newsf is the form where we need to append.

Refreshment news.png

Finally after parsing and appending the whole XML document. News Form looks like as above.

Working with MapCanvas

Bookmarking the location

Bookmarking feature enables to save the favorite locations on mobile. You visit some place or hotels, you may forget the address or name of the hotel. So using bookmark feature you can tag and save the current location in mobile phone.

if(c == bookmarkCommand){
else if(c == okCommand){
writeSavedData(bookmark.getString(), lat, lon);
else if(c == deleteCommand){

Locating bookmarked location on map

public void updateMap(double lat, double lon, String name){
new GeoBoundingBox(new GeoCoordinate(lat, lon, 0)), false);
new GeoCoordinate(lat, lon, 0), 1, name, 2));

Saving, Loading and Clearing bookmarks

We will be using record store to save the bookmark location, including name and date of bookmark using RMS.

We need a some structured way to store - latitude, longitude, date of bookmark and bookmark name. So that we can retrieve and use the same point to locate on map. Fist let us construct a schema to store in our database (record store).

Type Column 1 Column 2 Column 3 Column 4
Field name Latitude Bookmark name Longitude Bookmark date
Datatype double String double String

Saving Bookmark name in between Latitude and Longitude is that we can differentiate two double value, i.e String between them acts as a delimiter.

public void readSavedData() {
homef.append("Recient Visit");
try {
if(refreshmentRecordStore.getNumRecords() == 0){ /*Checking the record store for records. if total no. of record is zero*/
homef.append("\nYou have not visited any place."); /* append some string like, you have not bookmarked any places */
byte[] byt = new byte[1000]; /* read the records from record store and add them to home screen */
ByteArrayInputStream Istream = new ByteArrayInputStream(byt);
DataInputStream dinp = new DataInputStream(Istream);
for (int i = 1; i <= refreshmentRecordStore.getNumRecords(); i++) {
double lat = dinp.readDouble(); /* latitude is a double value, that is stored at first column */
String place = dinp.readUTF(); /* Favorite name a string value, that is stored at second column */
double lon = dinp.readDouble(); /* longitude is double value, that is stored at third column */
String date = dinp.readUTF(); /* date is string value, that is stored at fourth column */
homef.append(new recentvisitlist(place, lat, lon,date,this)); /*create a list item with these value and append to home form*/
} catch (Exception e) {
public void writeSavedData(String title, double lat, double lon) {
DateField now = new DateField("",DateField.DATE_TIME); /* get current system date and time */
now.setDate(new Date());
String date = now.getDate().toString(); /* convert the date to string, so that we can store it in record store */
openRefreshmentRecordStore(); /* open record store and save */
ByteArrayOutputStream Ostream = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(Ostream);
byte[] byt = Ostream.toByteArray();
refreshmentRecordStore.addRecord(byt, 0, byt.length);
}catch (Exception e) {
// TODO: handle exception
public void clearbookmark(){
RecordStore.deleteRecordStore("refreshmentDataBase"); /* to clear all bookmark, delete the record store */
}catch (Exception e) {
// TODO: handle exception

More with maps

You can add functions like finding route between two locations, searching an address and locating them on map. Since there are wiki articles on working on map, I am not covering them here in this article or example.

Source Files


Category Bar
Icon Command
Custom Item

This page was last modified on 17 November 2013, at 14:42.
950 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.


Thank you!

We appreciate your feedback.