Android中通过当前经纬度获得城市

 

  1. package com.yy;  
  2.   
  3. import java.io.InputStreamReader;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.URL;  
  6.   
  7. import javax.xml.parsers.SAXParser;  
  8. import javax.xml.parsers.SAXParserFactory;  
  9.   
  10. import org.xml.sax.Attributes;  
  11. import org.xml.sax.InputSource;  
  12. import org.xml.sax.SAXException;  
  13. import org.xml.sax.XMLReader;  
  14. import org.xml.sax.helpers.DefaultHandler;  
  15.   
  16. import android.content.Context;  
  17. import android.location.Location;  
  18. import android.location.LocationManager;  
  19.   
  20. public class GetCity {  
  21.     /** 
  22.      * 借助Google MAP 通过用户当前经纬度 获得用户当前城市 
  23.      */  
  24.     static final String GOOGLE_MAPS_API_KEY = "abcdefg";  
  25.   
  26.     private LocationManager locationManager;  
  27.     private Location currentLocation;  
  28.     private String city="全国";  
  29.     public GetCity(Context context) {  
  30.         this.locationManager = (LocationManager) context  
  31.                 .getSystemService(Context.LOCATION_SERVICE);  
  32.         //只是简单的获取城市 不需要实时更新 所以这里先注释   
  33. //      this.locationManager.requestLocationUpdates(   
  34. //              LocationManager.GPS_PROVIDER,  1000, 0,   
  35. //              new LocationListener() {   
  36. //                  public void onLocationChanged(Location loc) {   
  37. //                      //当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发    
  38. //                      // Save the latest location   
  39. //                      currentLocation = loc;   
  40. //                      // Update the latitude & longitude TextViews   
  41. //                      System.out   
  42. //                              .println("getCity()"   
  43. //                                      + (loc.getLatitude() + " " + loc   
  44. //                                              .getLongitude()));   
  45. //                  }   
  46. //   
  47. //                  public void onProviderDisabled(String arg0) {   
  48. //                      System.out.println(".onProviderDisabled(关闭)"+arg0);   
  49. //                  }   
  50. //   
  51. //                  public void onProviderEnabled(String arg0) {   
  52. //                      System.out.println(".onProviderEnabled(开启)"+arg0);   
  53. //                  }   
  54. //   
  55. //                  public void onStatusChanged(String arg0, int arg1,   
  56. //                          Bundle arg2) {   
  57. //                      System.out.println(".onStatusChanged(Provider的转态在可用、" +   
  58. //                              "暂时不可用和无服务三个状态直接切换时触发此函数)"+   
  59. //                              arg0+" "+arg1+" "+arg2);   
  60. //                  }   
  61. //              });   
  62.         currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);  
  63.   
  64.         if (currentLocation == null)  
  65.             currentLocation = locationManager  
  66.                     .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);  
  67.     }  
  68.     /** 
  69.      * 开始解析 
  70.      */  
  71.     public void start() {  
  72.         if(currentLocation!=null){  
  73.             new Thread(){  
  74.                 public void run(){  
  75.                     String temp=reverseGeocode(currentLocation);  
  76.                     if(temp!=null&&temp.length()>=2)  
  77.                         city=temp;  
  78.                 }  
  79.             }.start();  
  80.         }else{  
  81.             System.out.println("GetCity.start()未获得location");  
  82.         }  
  83.     }  
  84.       
  85.     /** 
  86.      * 获得城市  
  87.      * @return 
  88.      */  
  89.     public String getCity(){  
  90.         return city;  
  91.     }  
  92.       
  93.     /** 
  94.      * 通过Google  map api 解析出城市 
  95.      * @param loc 
  96.      * @return 
  97.      */  
  98.     public String reverseGeocode(Location loc) {  
  99.         // http://maps.google.com/maps/geo?q=40.714224,-73.961452&output=json&oe=utf8&sensor=true_or_false&key=your_api_key   
  100.         String localityName = "";  
  101.         HttpURLConnection connection = null;  
  102.         URL serverAddress = null;  
  103.   
  104.         try {  
  105.             // build the URL using the latitude & longitude you want to lookup   
  106.             // NOTE: I chose XML return format here but you can choose something   
  107.             // else   
  108.             serverAddress = new URL("http://maps.google.com/maps/geo?q="  
  109.                     + Double.toString(loc.getLatitude()) + ","  
  110.                     + Double.toString(loc.getLongitude())  
  111.                     + "&output=xml&oe=utf8&sensor=true&key="  
  112.                     + GOOGLE_MAPS_API_KEY);  
  113.             // set up out communications stuff   
  114.             connection = null;  
  115.   
  116.             // Set up the initial connection   
  117.             connection = (HttpURLConnection) serverAddress.openConnection();  
  118.             connection.setRequestMethod("GET");  
  119.             connection.setDoOutput(true);  
  120.             connection.setReadTimeout(10000);  
  121.   
  122.             connection.connect();  
  123.   
  124.             try {  
  125.                 InputStreamReader isr = new InputStreamReader(connection  
  126.                         .getInputStream());  
  127.                 InputSource source = new InputSource(isr);  
  128.                 SAXParserFactory factory = SAXParserFactory.newInstance();  
  129.                 SAXParser parser = factory.newSAXParser();  
  130.                 XMLReader xr = parser.getXMLReader();  
  131.                 GoogleReverseGeocodeXmlHandler handler = new GoogleReverseGeocodeXmlHandler();  
  132.   
  133.                 xr.setContentHandler(handler);  
  134.                 xr.parse(source);  
  135.   
  136.                 localityName = handler.getLocalityName();  
  137.                 System.out.println("GetCity.reverseGeocode()"+localityName);  
  138.             } catch (Exception ex) {  
  139.                 ex.printStackTrace();  
  140.             }  
  141.         } catch (Exception ex) {  
  142.             ex.printStackTrace();  
  143.             System.out.println("GetCity.reverseGeocode()"+ex);  
  144.         }  
  145.   
  146.         return localityName;  
  147.     }  
  148.   
  149.     /** 
  150.      * The final piece of this puzzle is parsing the xml that is returned from 
  151.      * google’s service. For this example I am using the java SAX (simple api 
  152.      * for xml) parser. The final class to show here is 
  153.      * GoogleReverseGeocodeXmlHandler. In my example, I only want the name of 
  154.      * the city the user is in, so my XmlHandler class I’m about to show only 
  155.      * parses that piece of information. If you want to grab more complete 
  156.      * information (I’ll also give an example file that contains the XML 
  157.      * returned by Google), you’ll have to add more to this class 
  158.      *  
  159.      * @author Administrator 
  160.      *  
  161.      */  
  162.     public class GoogleReverseGeocodeXmlHandler extends DefaultHandler {  
  163.         private boolean inLocalityName = false;  
  164.         private boolean finished = false;  
  165.         private StringBuilder builder;  
  166.         private String localityName;  
  167.   
  168.         public String getLocalityName() {  
  169.             return this.localityName;  
  170.         }  
  171.   
  172.         @Override  
  173.         public void characters(char[] ch, int start, int length)  
  174.                 throws SAXException {  
  175.             super.characters(ch, start, length);  
  176.             if (this.inLocalityName && !this.finished) {  
  177.                 if ((ch[start] != '\n') && (ch[start] != ' ')) {  
  178.                     builder.append(ch, start, length);  
  179.                 }  
  180.             }  
  181.         }  
  182.   
  183.         @Override  
  184.         public void endElement(String uri, String localName, String name)  
  185.                 throws SAXException {  
  186.             super.endElement(uri, localName, name);  
  187.   
  188.             if (!this.finished) {  
  189.                 if (localName.equalsIgnoreCase("LocalityName")) {  
  190.                     this.localityName = builder.toString();  
  191.                     this.finished = true;  
  192.                 }  
  193.   
  194.                 if (builder != null) {  
  195.                     builder.setLength(0);  
  196.                 }  
  197.             }  
  198.         }  
  199.   
  200.         @Override  
  201.         public void startDocument() throws SAXException {  
  202.             super.startDocument();  
  203.             builder = new StringBuilder();  
  204.         }  
  205.   
  206.         @Override  
  207.         public void startElement(String uri, String localName, String name,  
  208.                 Attributes attributes) throws SAXException {  
  209.             super.startElement(uri, localName, name, attributes);  
  210.   
  211.             if (localName.equalsIgnoreCase("LocalityName")) {  
  212.                 this.inLocalityName = true;  
  213.             }  
  214.         }  
  215.     }  
  216. }  


参考:

http://kryptonum.iteye.com/blog/363950

http://www.cnblogs.com/transmuse/archive/2010/12/31/1923358.html

http://blog.csdn.net/dadoneo/archive/2011/03/18/6259781.aspx

http://www.ispiders.net/?p=325

 http://www.smnirven.com/?p=39#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android Studio,我们可以使用LocationManager和LocationListener来获取当前经纬度。 首先,我们需要在AndroidManifest.xml文件添加相应的权限: <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 然后,在你的Activity,在onCreate方法获取LocationManager的实例,并检查是否获得了权限: LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); boolean isCoarseLocationEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); boolean isFineLocationEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 然后,我们需要创建一个LocationListener来监听位置变化事件: LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // 当位置变化时触发该方法 double latitude = location.getLatitude(); //获取纬度 double longitude = location.getLongitude(); //获取经度 // 将经纬度保存到变量,或者进行其他需要的处理 } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) {} }; 接下来,我们需要请求位置更新: if (isCoarseLocationEnabled) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } else if (isFineLocationEnabled) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } 最后,当不再需要获取位置信息时,要记得取消位置更新: locationManager.removeUpdates(locationListener); 这样,当我们点击按钮时,就能实时获得当前经纬度了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值