Google地图(Map)API在J2ME中使用方法

最近在Android的学习中,感觉到Android中使用Google Map Api很强大,于是乎想在J2me上来使用Google Map Api,搜索了一下,果然已经有很多人实现过了。
当然,要使用Google Map Api首先就得申请“Google Maps API Key”。这里就不多说了,不会的点击这里。
同样,早有人实现了,大家也可以查看效果:Java ME Google Maps API sample MIDlet。
截图如下:

Google地图(Map)API在J2ME中使用方法

下面是J2me中的GoogleMaps类:

 


  1. import java.io.ByteArrayOutputStream;     
  2. import java.io.DataOutputStream;     
  3. import java.io.IOException;     
  4. import java.io.InputStream;     
  5. import java.util.Vector;     
  6. import javax.microedition.io.Connector;     
  7. import javax.microedition.io.HttpConnection;     
  8. import javax.microedition.lcdui.Image;     
  9.     
  10. public class GoogleMaps     
  11. {     
  12.     private static final String URL_UNRESERVED = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789-_.~";     
  13.     private static final char[] HEX = "0123456789ABCDEF".toCharArray();     
  14.     
  15.     public static final int offset = 268435456;     
  16.     public static final double radius = offset / Math.PI;     
  17.     
  18.     private String apiKey = null;     
  19.     
  20.     
  21.     public GoogleMaps(String key)     
  22.     {     
  23.         apiKey = key;     
  24.     }     
  25.     
  26.     
  27.     public double[] geocodeAddress(String address) throws Exception     
  28.     {     
  29.         byte[] res = loadHttpFile(getGeocodeUrl(address));     
  30.         String[] data = split(new String(res, 0, res.length), ',');     
  31.     
  32.         if (data[0].compareTo("200") != 0)     
  33.         {     
  34.             int errorCode = Integer.parseInt(data[0]);     
  35.             throw new Exception("Google Maps Exception: "    
  36.                     + getGeocodeError(errorCode));     
  37.         }     
  38.     
  39.         return new double[] { Double.parseDouble(data[2]),     
  40.                 Double.parseDouble(data[3]) };     
  41.     }     
  42.     
  43.     
  44.     public Image retrieveStaticImage(int width, int height, double lat,     
  45.         double lng, int zoom, String format) throws IOException     
  46.     {     
  47.         byte[] imageData = loadHttpFile(getMapUrl(width, height, lng, lat,zoom, format));     
  48.     
  49.         return Image.createImage(imageData, 0, imageData.length);     
  50.     }     
  51.     
  52.     
  53.     private static String getGeocodeError(int errorCode)     
  54.     {     
  55.         switch (errorCode)     
  56.         {     
  57.             case 400:     
  58.                 return "Bad request";     
  59.             case 500:     
  60.                 return "Server error";     
  61.             case 601:     
  62.                 return "Missing query";     
  63.             case 602:     
  64.                 return "Unknown address";     
  65.             case 603:     
  66.                 return "Unavailable address";     
  67.             case 604:     
  68.                 return "Unknown directions";     
  69.             case 610:     
  70.                 return "Bad API key";     
  71.             case 620:     
  72.                 return "Too many queries";     
  73.             default:     
  74.                 return "Generic error";     
  75.         }     
  76.     }     
  77.     
  78.     
  79.     private String getGeocodeUrl(String address)     
  80.     {     
  81.         return "http://maps.google.com/maps/geo?q=" + urlEncode(address)     
  82.                 + "&output=csv&key=" + apiKey;     
  83.     }     
  84.     
  85.     
  86.     private String getMapUrl(int width, int height, double lng, double lat,     
  87.         int zoom, String format)     
  88.     {     
  89.         return "http://maps.google.com/staticmap?center=" + lat + "," + lng     
  90.                 + "&format=" + format + "&zoom=" + zoom + "&size=" + width     
  91.                 + "x" + height + "&key=" + apiKey;     
  92.     }     
  93.     
  94.     
  95.     private static String urlEncode(String str)     
  96.     {     
  97.         StringBuffer buf = new StringBuffer();     
  98.         byte[] bytes = null;     
  99.         try    
  100.         {     
  101.             ByteArrayOutputStream bos = new ByteArrayOutputStream();     
  102.             DataOutputStream dos = new DataOutputStream(bos);     
  103.             dos.writeUTF(str);     
  104.             bytes = bos.toByteArray();     
  105.         }     
  106.         catch (IOException e)     
  107.         {     
  108.         }     
  109.         for (int i = 2; i < bytes.length; i++)     
  110.         {     
  111.             byte b = bytes[i];     
  112.             if (URL_UNRESERVED.indexOf(b) >= 0)     
  113.             {     
  114.                 buf.append((char) b);     
  115.             }     
  116.             else    
  117.             {     
  118.                 buf.append('%').append(HEX[(b >> 4) & 0x0f]).append(     
  119.                     HEX[b & 0x0f]);     
  120.             }     
  121.         }     
  122.         return buf.toString();     
  123.     }     
  124.     
  125.     
  126.     private static byte[] loadHttpFile(String url) throws IOException     
  127.     {     
  128.         byte[] byteBuffer;     
  129.     
  130.         HttpConnection hc = (HttpConnection) Connector.open(url);     
  131.         System.out.println("loadHttpFile:" + url);     
  132.         try    
  133.         {     
  134.             hc.setRequestMethod(HttpConnection.GET);     
  135.             InputStream is = hc.openInputStream();     
  136.             try    
  137.             {     
  138.                 int len = (int) hc.getLength();     
  139.                 if (len > 0)     
  140.                 {     
  141.                     byteBuffer = new byte[len];     
  142.                     int done = 0;     
  143.                     while (done < len)     
  144.                     {     
  145.                         done += is.read(byteBuffer, done, len - done);     
  146.                     }     
  147.                 }     
  148.                 else    
  149.                 {     
  150.                     ByteArrayOutputStream bos = new ByteArrayOutputStream();     
  151.                     byte[] buffer = new byte[512];     
  152.                     int count;     
  153.                     while ((count = is.read(buffer)) >= 0)     
  154.                     {     
  155.                         bos.write(buffer, 0, count);     
  156.                     }     
  157.                     byteBuffer = bos.toByteArray();     
  158.                 }     
  159.             }     
  160.             finally    
  161.             {     
  162.                 is.close();     
  163.             }     
  164.         }     
  165.         finally    
  166.         {     
  167.             hc.close();     
  168.         }     
  169.     
  170.         return byteBuffer;     
  171.     }     
  172.     
  173.     
  174.     private static String[] split(String s, int chr)     
  175.     {     
  176.         Vector res = new Vector();     
  177.     
  178.         int curr;     
  179.         int prev = 0;     
  180.     
  181.         while ((curr = s.indexOf(chr, prev)) >= 0)     
  182.         {     
  183.             res.addElement(s.substring(prev, curr));     
  184.             prev = curr + 1;     
  185.         }     
  186.         res.addElement(s.substring(prev));     
  187.     
  188.         String[] splitted = new String[res.size()];     
  189.         res.copyInto(splitted);     
  190.     
  191.         return splitted;     
  192.     }     
  193. }  

注意:在使用时,可能需要对一些数据进行转换,可以参考:MicroFloat website。
通过这个类,大家都应该明白如何使用了吧。
首先实例化对象:


  1. GoogleMaps gMap = new GoogleMaps("API_KEY");  

通过地址查找坐标:


  1. double[] lanLng = gMap.geocodeAddress("chengdu");  

取得指定大小的图片:


  1. Image map = gMap.retrieveStaticImage(24032051.510605, -0.1307288"png32"); 

最后将取得的图片绘制出来即可:


  1. g.drawImage(map,(getWidth()-240)/2,(getHeight()-320)/2,0);   

就写到这里了,ok!谢谢大家支持! 





本文转自 yarin 51CTO博客,原文链接:http://blog.51cto.com/yarin/381930,如需转载请自行联系原作者

上一篇:入驻“云栖社区”


下一篇:软件测试方法和技术