Wednesday, January 20, 2010

Archive for the ‘Location API’ Category:

JavaME JSR-179 Example Code : Detect Location via TinyGeocoder

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.

J2ME GPS Reverse Geocoding mypapit

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:
  1. import javax.microedition.midlet.*;
  2. import javax.microedition.lcdui.*;
  3. import javax.microedition.location.*;
  4. import javax.microedition.io.*;
  5. import javax.microedition.location.*;
  6. import java.io.*;
  7. public class Geocoder extends MIDlet implements CommandListener
  8. {
  9. public Display display;
  10. public Form form;
  11. private Command cmdExit,cmdOK;
  12. public StringItem si, sili;
  13. public Geocoder()
  14. {
  15. display =Display.getDisplay(this);
  16. form = new Form("Location Api test");
  17. cmdExit = new Command("Exit",Command.EXIT,5);
  18. cmdOK = new Command("OK",Command.OK,1);
  19. si = new StringItem("Coordinates", "Press OK");
  20. sili = new StringItem("Location", "");
  21. form.append(si);
  22. form.append(sili);
  23. form.addCommand(cmdOK);
  24. form.addCommand(cmdExit);
  25. form.setCommandListener(this);
  26. }
  27. public void startApp()
  28. {
  29. display.setCurrent(form);
  30. }
  31. public void pauseApp()
  32. {}
  33. public void destroyApp(boolean flag) {
  34. notifyDestroyed();
  35. }
  36. public void commandAction(Command c, Displayable d)
  37. {
  38. if (c == cmdOK){
  39. Retriever ret = new Retriever(this);
  40. ret.start();
  41. } else if (c == cmdExit) {
  42. destroyApp(false);
  43. }
  44. }
  45. public void displayString(String string)
  46. {
  47. si.setText(string);
  48. }
  49. public void showAlert(String message) {
  50. Alert alert = new Alert("Alert",message,null,AlertType.WARNING);
  51. display.setCurrent(alert,form);
  52. }
  53. }
  54. class Retriever extends Thread {
  55. private Geocoder midlet;
  56. Form formRunning;
  57. Gauge gauge;
  58. public Retriever(Geocoder midlet)
  59. {
  60. /**
  61. * Constructor
  62. *
  63. * EFFECTS: Initialise the server and store midlet information
  64. *
  65. * @param midlet The main application midlet
  66. * @param server Forecast Server URL
  67. *
  68. */
  69. this.midlet = midlet;
  70. formRunning = new Form("Retrieving Info");
  71. formRunning.append(new Gauge("Processing",false,Gauge.INDEFINITE,Gauge.CONTINUOUS_RUNNING));
  72. midlet.display.setCurrent(formRunning);
  73. }
  74. public void run()
  75. {
  76. /**
  77. * Entry point of the thread
  78. *
  79. * EFFECTS: call to connect() method
  80. */
  81. try {
  82. checkLocation();
  83. } catch (Exception ex)
  84. {
  85. ex.printStackTrace();
  86. midlet.displayString(ex.toString());
  87. } finally {
  88. }
  89. }
  90. public void checkLocation() throws Exception
  91. {
  92. String string;
  93. Location l;
  94. LocationProvider lp;
  95. Coordinates c;
  96. // Set criteria for selecting a location provider:
  97. // accurate to 500 meters horizontally
  98. Criteria cr= new Criteria();
  99. cr.setHorizontalAccuracy(5000);
  100. cr.setVerticalAccuracy(5000);
  101. // Get an instance of the provider
  102. lp= LocationProvider.getInstance(cr);
  103. // Request the location, setting a one-minute timeout
  104. l = lp.getLocation(120);
  105. c = l.getQualifiedCoordinates();
  106. if(c != null ) {
  107. // Use coordinate information
  108. double lat = c.getLatitude();
  109. double lon = c.getLongitude();
  110. string = "\nLatitude : " + lat + "\nLongitude : " + lon;
  111. new GetData(midlet,lat,lon).start();
  112. } else {
  113. string ="Location API failed";
  114. }
  115. formRunning.append("Obtained coordinates...");
  116. midlet.displayString(string);
  117. }
  118. }
  119. class GetData implements Runnable,CommandListener {
  120. Geocoder midlet;
  121. double lat, lon;
  122. public GetData (Geocoder midlet, double lat, double lon) {
  123. this.lat = lat;
  124. this.lon = lon;
  125. this.midlet = midlet;
  126. }
  127. public void commandAction (Command cmd,Displayable disp)
  128. {
  129. }
  130. public void start() {
  131. Thread t = new Thread(this);
  132. t.start();
  133. }
  134. public void run() {
  135. HttpConnection conn=null;
  136. InputStream is=null;
  137. String sb;
  138. try {
  139. String sUrl = "http://tinygeocoder.com/create-api.php?g="+""+lat+","+""+lon;
  140. conn = (HttpConnection) Connector.open(sUrl,Connector.READ);
  141. if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
  142. is = conn.openInputStream();
  143. byte buf[] = new byte[128];
  144. int total =0;
  145. while (total <128) {
  146. int count = is.read(buf,total,128-total);
  147. if (count<0) {
  148. break;
  149. }
  150. total += count;
  151. }
  152. sb = new String(buf,0,total);
  153. if (sb.length() <10) {
  154. midlet.showAlert("Connection error, please try again");
  155. is.close();
  156. conn.close();
  157. return;
  158. }
  159. midlet.sili.setText(sb);
  160. //midlet.form.append(sb);
  161. //vectorized();
  162. //midlet.saveCurrency(false,midlet.vector);
  163. //midlet.display.setCurrent(midlet.form);
  164. } else if (conn.getResponseCode() == HttpConnection.HTTP_NOT_FOUND) {
  165. midlet.showAlert("URL not found");
  166. } else {
  167. midlet.showAlert("Server busy or unavailable. Please try again later");
  168. }
  169. } catch (SecurityException sex) {
  170. midlet.showAlert("Connection failed. You need to authorize this application to access network");
  171. } catch (IOException ioex) {
  172. midlet.showAlert("Connection failed. Please try again later.");
  173. } catch (Exception e){
  174. midlet.showAlert(e.toString());
  175. e.printStackTrace();
  176. //midlet.display.setCurrent(midlet.form);
  177. } finally {
  178. try {
  179. if (is != null) {
  180. is.close();
  181. }
  182. if (conn != null) {
  183. conn.close();
  184. }
  185. } catch (IOException ioexception) {}
  186. is =null;
  187. conn =null;
  188. midlet.display.setCurrent(midlet.form);
  189. }
  190. }
  191. public String URLEncode(String s)
  192. {
  193. if (s!=null) {
  194. int i=0;
  195. try {
  196. while (true) {
  197. int b = (int)s.charAt(i++);
  198. if ((b>=0x30 && b<=0x39) || (b>=0x41 && b<=0x5A) || (b>=0x61 && b<=0x7A)) {
  199. tmp.append((char)b);
  200. }
  201. else {
  202. tmp.append("%");
  203. if (b <= 0xf) tmp.append("0");
  204. tmp.append(Integer.toHexString(b));
  205. }
  206. }
  207. }
  208. catch (Exception e) {}
  209. return tmp.toString();
  210. }
  211. return null;
  212. }
  213. }

The code requires mobile device which implements JSR-179 Location API and has been tested on Nokia E71 and 6210 Navigator.




Post a Comment

Template by : kendhin x-template.blogspot.com by :