JavaME JSR-179 Example Code : Detect Location via TinyGeocoder
February 22nd, 2009 Posted in J2ME / JavaME, Location API, Open Source, Smartphone, Tips, Tricks, Guide
I've completed the JSR-179 Location API code for reverse geocoding in JavaME. This code essentially is an expansion of the previous JSR-179 example that i've posted in the blog before, plus the Reverse-Geocoding feature, thanks to TinyGeocoder service.

What this sample MIDlet does?
It obtain coordinates via the mobile phone JSR-179 Location API and subsequently display the name of the location using TinyGeocoder reverse geocoding service.
JAVA:
-
import javax.microedition.midlet.*;
-
import javax.microedition.lcdui.*;
-
import javax.microedition.location.*;
-
import javax.microedition.io.*;
-
import javax.microedition.location.*;
-
import java.io.*;
-
-
public class Geocoder extends MIDlet implements CommandListener
-
{
-
public Display display;
-
public Form form;
-
private Command cmdExit,cmdOK;
-
public StringItem si, sili;
-
-
public Geocoder()
-
{
-
-
display =Display.getDisplay(this);
-
form = new Form("Location Api test");
-
cmdExit = new Command("Exit",Command.EXIT,5);
-
cmdOK = new Command("OK",Command.OK,1);
-
si = new StringItem("Coordinates", "Press OK");
-
sili = new StringItem("Location", "");
-
form.append(si);
-
form.append(sili);
-
form.addCommand(cmdOK);
-
form.addCommand(cmdExit);
-
form.setCommandListener(this);
-
}
-
-
public void startApp()
-
{
-
display.setCurrent(form);
-
}
-
-
-
public void pauseApp()
-
{}
-
-
public void destroyApp(boolean flag) {
-
notifyDestroyed();
-
}
-
-
public void commandAction(Command c, Displayable d)
-
{
-
if (c == cmdOK){
-
Retriever ret = new Retriever(this);
-
ret.start();
-
-
} else if (c == cmdExit) {
-
destroyApp(false);
-
}
-
}
-
-
{
-
si.setText(string);
-
}
-
-
Alert alert = new Alert("Alert",message,null,AlertType.WARNING);
-
display.setCurrent(alert,form);
-
}
-
-
-
-
-
}
-
-
-
private Geocoder midlet;
-
Form formRunning;
-
Gauge gauge;
-
-
-
-
public Retriever(Geocoder midlet)
-
{
-
/**
-
* Constructor
-
*
-
* EFFECTS: Initialise the server and store midlet information
-
*
-
* @param midlet The main application midlet
-
* @param server Forecast Server URL
-
*
-
*/
-
this.midlet = midlet;
-
formRunning = new Form("Retrieving Info");
-
formRunning.append(new Gauge("Processing",false,Gauge.INDEFINITE,Gauge.CONTINUOUS_RUNNING));
-
midlet.display.setCurrent(formRunning);
-
-
}
-
-
public void run()
-
{
-
/**
-
* Entry point of the thread
-
*
-
* EFFECTS: call to connect() method
-
*/
-
try {
-
checkLocation();
-
{
-
ex.printStackTrace();
-
midlet.displayString(ex.toString());
-
} finally {
-
-
}
-
-
-
}
-
-
{
-
String string;
-
Location l;
-
LocationProvider lp;
-
Coordinates c;
-
// Set criteria for selecting a location provider:
-
// accurate to 500 meters horizontally
-
Criteria cr= new Criteria();
-
cr.setHorizontalAccuracy(5000);
-
cr.setVerticalAccuracy(5000);
-
-
// Get an instance of the provider
-
lp= LocationProvider.getInstance(cr);
-
-
// Request the location, setting a one-minute timeout
-
l = lp.getLocation(120);
-
c = l.getQualifiedCoordinates();
-
-
if(c != null ) {
-
// Use coordinate information
-
double lat = c.getLatitude();
-
double lon = c.getLongitude();
-
string = "\nLatitude : " + lat + "\nLongitude : " + lon;
-
new GetData(midlet,lat,lon).start();
-
-
} else {
-
string ="Location API failed";
-
}
-
-
formRunning.append("Obtained coordinates...");
-
midlet.displayString(string);
-
}
-
}
-
-
-
Geocoder midlet;
-
double lat, lon;
-
-
public GetData (Geocoder midlet, double lat, double lon) {
-
-
this.lat = lat;
-
this.lon = lon;
-
this.midlet = midlet;
-
-
-
}
-
-
public void commandAction (Command cmd,Displayable disp)
-
{
-
-
}
-
-
public void start() {
-
t.start();
-
}
-
-
-
public void run() {
-
HttpConnection conn=null;
-
InputStream is=null;
-
String sb;
-
-
try {
-
conn = (HttpConnection) Connector.open(sUrl,Connector.READ);
-
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
-
is = conn.openInputStream();
-
byte buf[] = new byte[128];
-
int total =0;
-
while (total <128) {
-
int count = is.read(buf,total,128-total);
-
if (count<0) {
-
break;
-
}
-
total += count;
-
}
-
-
-
if (sb.length() <10) {
-
midlet.showAlert("Connection error, please try again");
-
is.close();
-
conn.close();
-
-
return;
-
}
-
-
midlet.sili.setText(sb);
-
//midlet.form.append(sb);
-
//vectorized();
-
//midlet.saveCurrency(false,midlet.vector);
-
//midlet.display.setCurrent(midlet.form);
-
} else if (conn.getResponseCode() == HttpConnection.HTTP_NOT_FOUND) {
-
midlet.showAlert("URL not found");
-
-
} else {
-
midlet.showAlert("Server busy or unavailable. Please try again later");
-
}
-
-
midlet.showAlert("Connection failed. You need to authorize this application to access network");
-
midlet.showAlert("Connection failed. Please try again later.");
-
midlet.showAlert(e.toString());
-
e.printStackTrace();
-
//midlet.display.setCurrent(midlet.form);
-
} finally {
-
try {
-
if (is != null) {
-
is.close();
-
}
-
-
if (conn != null) {
-
conn.close();
-
}
-
is =null;
-
conn =null;
-
midlet.display.setCurrent(midlet.form);
-
-
-
}
-
}
-
-
-
{
-
if (s!=null) {
-
int i=0;
-
try {
-
while (true) {
-
int b = (int)s.charAt(i++);
-
if ((b>=0x30 && b<=0x39) || (b>=0x41 && b<=0x5A) || (b>=0x61 && b<=0x7A)) {
-
tmp.append((char)b);
-
}
-
else {
-
tmp.append("%");
-
if (b <= 0xf) tmp.append("0");
-
}
-
}
-
}
-
return tmp.toString();
-
}
-
return null;
-
}
-
}
The code requires mobile device which implements JSR-179 Location API and has been tested on Nokia E71 and 6210 Navigator.
Possibly Related Posts...
Tags: coordinates, e71, example, geocoder, geocoding, gps, j2me, javame, jsr-179, jsr179, lbs, location-api, locationapi, midlet, midlets, mobile, Nokia, source code, tinygeocoder
August 2nd, 2009 at 3:16 am
Hi there.
Is it possible to also display the location with maps (Google Maps, etc) on a J2ME application? If so, how?
September 1st, 2009 at 5:49 pm
Hai,
I tried this code in Nokia E 71 mobile, it’s working fine for showing the coordinates, but it could not represent the location info.
Could you please provide informatiom.
Thanks,
Regards,
Santhosh.
December 2nd, 2009 at 4:13 pm
Hi, there.
I tried some of the method from your project in my own Midlet. But I encountered a problem. The “Location” StringItem won’t return me the coordinate’s place name. Instead it gives me an error that reads “602: Address cannot be found”. Please help….
here’s the full code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.location.*;
import java.io.*;
import javax.microedition.io.*;
/**
* @author Onime no Nero
*/
public class LocationMidletPhase1 extends MIDlet implements CommandListener{
private Command exit=new Command(”Exit”, Command.EXIT,1);
private Command location=new Command(”Location”, Command.ITEM,1);
private Command minimize=new Command(”Minimize”, Command.ITEM,1);
private String sUrl;
private StringItem locationName = new StringItem(”Location”, “”);
private Display display;
private Form mainForm=new Form(”NeroNull: Location Midlet”);
private StringItem lat=new StringItem(”Latitude: “, “”, Item.PLAIN);
private StringItem lon=new StringItem(”Longitude: “,”",Item.PLAIN);
private StringItem alt=new StringItem(”Altitude: “,”",Item.PLAIN);
private StringItem speed=new StringItem(”Speed: “,”",Item.PLAIN);
private StringItem stat=new StringItem(”Status: “,”",Item.PLAIN);
private StringItem version=new StringItem(”Version: “,”Unknown”, Item.PLAIN);
private LocationProvider provider;
private Timer timer;
private ScheduledTransmission task;
private long startTime;
public LocationMidletPhase1(){
mainForm.addCommand(exit);
mainForm.addCommand(location);
mainForm.setCommandListener(this);
version.setText(System.getProperty(”microedition.location.version”));
startTime=System.currentTimeMillis();
mainForm.append(version);
mainForm.append(lat);
mainForm.append(lon);
mainForm.append(alt);
mainForm.append(speed);
mainForm.append(stat);
mainForm.append(locationName);
}
public void startApp() {
display=Display.getDisplay(this);
display.setCurrent(mainForm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d){
if(c==location){
new Thread();
timer = new Timer();
task = new ScheduledTransmission();
timer.schedule(task,10,10000);
}
if(c==exit){
destroyApp(true);
notifyDestroyed();
return;
}
if(c==minimize){
display.setCurrent(null);
}
}
private class ScheduledTransmission extends TimerTask{
public final void run(){
try{
Criteria cr=new Criteria();
cr.setHorizontalAccuracy(0);
cr.setVerticalAccuracy(0);
provider=LocationProvider.getInstance(cr);
long time=System.currentTimeMillis();
Location loc=provider.getLocation(30);
Coordinates coord=loc.getQualifiedCoordinates();
if(coord!=null){
if(loc.isValid()){
try {
testGET(sUrl);
} catch (IOException e) {
System.out.println(”IOException ” + e);
e.printStackTrace();
}
lat.setText(Double.toString(coord.getLatitude()));
lon.setText(Double.toString(coord.getLongitude()));
alt.setText(Float.toString(coord.getAltitude()));
speed.setText(Float.toString(loc.getSpeed()));
stat.setText(”Valid Location Information”);
mainForm.append(locationName);
}
else{
stat.setText(”Invalid Location Information”);
}
}
}
catch(LocationException e){
stat.setText(”Exception: “+e.getMessage());
}
catch(InterruptedException e){
stat.setText(”Timeout: “+e.getMessage());
}
}
}
void testGET(String sUrl) throws IOException {
sUrl =”http://tinygeocoder.com/create-api.php?g=”+lat+”,”+lon;
HttpConnection connection = null;
InputStream is = null;
String sb = null;
try {
connection = (HttpConnection)Connector.open(sUrl);
connection.setRequestMethod(HttpConnection.GET);
is = connection.openInputStream();
byte buf[] = new byte[128];
int total =0;
while (total <128) {
int count = is.read(buf,total,128-total);
if (count<0) {
break;
}
total += count;
}
sb=new String(buf,0,total);
if (sb.length() =0×30 && b=0×41 && b=0×61 && b<=0×7A)) {
tmp.append((char)b);
}
else {
tmp.append("%");
if (b <= 0xf) tmp.append("0");
tmp.append(Integer.toHexString(b));
}
}
}
catch (Exception e) {}
return tmp.toString();
}
return null;
}
}