Location服务之Geocoder和LocationManager

提到Android基于位置的服务,就不得不提android.location包,location包提供了很便捷的API来实现基于位置的服务。主要包括Geocoder和LocationManager。今天就先来介绍一下Geocoder。

Geocoder可以在街道地址和经纬度地图坐标之间进行转换。它提供了对两种地理编码功能的访问:

Forward Geocoding(前向地理编码):查找某个地址的经纬度

Reverse Geocoding(反向地理编码):查找一个给定的经纬度所对应的街道地址。

分别对应以下方法:

  1. List<Address>  getFromLocationName(String locationName, int maxResults)  
  2. List<Address>  getFromLocation(double latitude,double longitude,int maxResults);  

我们新建一个location的项目。因为示例要使用到地图服务,所以创建时Build Target要选择Google APIs这一项。

然后修改/res/layout/main.xml,代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent">  
  6.     <com.google.android.maps.MapView  
  7.         android:id="@+id/mapView"  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="fill_parent"  
  10.         android:clickable="true"  
  11.         android:apiKey="your apiKey goes here"/>  
  12.     <LinearLayout  
  13.         android:layout_width="fill_parent"  
  14.         android:layout_height="wrap_content">  
  15.         <EditText  
  16.             android:id="@+id/name"  
  17.             android:layout_width="wrap_content"  
  18.             android:layout_height="wrap_content"  
  19.             android:layout_weight="1"/>  
  20.         <Button  
  21.             android:id="@+id/find"  
  22.             android:layout_width="wrap_content"  
  23.             android:layout_height="wrap_content"  
  24.             android:text="Find"/>  
  25.     </LinearLayout>  
  26. </FrameLayout>  

然后我们来看一下MainActivity.java文件,代码如下:

  1. package com.scott.location;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.List;  
  5.   
  6. import android.location.Address;  
  7. import android.location.Geocoder;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.widget.Button;  
  11. import android.widget.EditText;  
  12. import android.widget.ImageView;  
  13. import android.widget.Toast;  
  14.   
  15. import com.google.android.maps.GeoPoint;  
  16. import com.google.android.maps.MapActivity;  
  17. import com.google.android.maps.MapView;  
  18. import com.google.android.maps.MapView.LayoutParams;  
  19.   
  20. public class MainActivity extends MapActivity {  
  21.       
  22.     private MapView mapView;  
  23.     private EditText name;  
  24.     private Button find;  
  25.       
  26.     private Geocoder geocoder;  
  27.       
  28.     private static final double lat = 39.908716;    
  29.     private static final double lng = 116.397529;    
  30.       
  31.     @Override  
  32.     public void onCreate(Bundle savedInstanceState) {  
  33.         super.onCreate(savedInstanceState);  
  34.         setContentView(R.layout.main);  
  35.           
  36.         mapView = (MapView) findViewById(R.id.mapView);  
  37.         mapView.getController().setZoom(17);  
  38.         mapView.getController().animateTo(new GeoPoint((int)(lat * 1E6),(int)(lng * 1E6)));  
  39.           
  40.         geocoder = new Geocoder(this);  
  41.           
  42.         name = (EditText) findViewById(R.id.name);  
  43.         find = (Button) findViewById(R.id.find);  
  44.           
  45.         find.setOnClickListener(new View.OnClickListener() {  
  46.             @Override  
  47.             public void onClick(View v) {  
  48.                 String keyword = name.getText().toString();  
  49.                 try {  
  50.                     List<Address> addrs = geocoder.getFromLocationName(keyword, 3);  
  51.                     if (addrs != null && addrs.size() > 0) {  
  52.                         int latE6 = (int) (addrs.get(0).getLatitude() * 1E6);  
  53.                         int lngE6 = (int) (addrs.get(0).getLongitude() * 1E6);  
  54.                         GeoPoint point = new GeoPoint(latE6, lngE6);  
  55.                         mapView.getController().animateTo(point);  
  56.                           
  57.                         final MapView.LayoutParams params = new MapView.LayoutParams(LayoutParams.WRAP_CONTENT,  
  58.                                 LayoutParams.WRAP_CONTENT, point, LayoutParams.BOTTOM_CENTER);  
  59.                         final ImageView marker = new ImageView(MainActivity.this);  
  60.                         marker.setImageResource(R.drawable.marker);  
  61.                         marker.setOnClickListener(new View.OnClickListener() {  
  62.                             @Override  
  63.                             public void onClick(View v) {  
  64.                                 Toast.makeText(getApplicationContext(), "hello geocoder!", Toast.LENGTH_SHORT).show();  
  65.                             }  
  66.                         });  
  67.                         mapView.addView(marker, params);  
  68.                     }  
  69.                 } catch (IOException e) {  
  70.                     e.printStackTrace();  
  71.                 }  
  72.             }  
  73.         });  
  74.     }  
  75.   
  76.     @Override  
  77.     protected boolean isRouteDisplayed() {  
  78.         return false;  
  79.     }  
  80. }  

最后需要在AndroidManifest.xml中的application标签之间加入google map library:

  1. <uses-library android:name="com.google.android.maps" />  

然后就是一些位置服务所需的权限:

  1. <uses-permission android:name="android.permission.INTERNET" />  
  2. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />    
  3. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  

有一点需要跟朋友们提一下,Geocoder查找是同步地进行的,因此,它们将会阻塞调用它们的线程。对于低速的数据连接来说,这可能会导致出现ANR(Application Not Respond)的问题。在大部分情况下,更好的做法是把这些查找移动到服务或者后台线程中,前面几篇文章中也涉及到了一些异步任务的相关知识,不熟悉的朋友们可以参看以下HandlerAsyncTask的使用。为了清晰和简洁起见,上面代码中的查找操作直接放在了UI线程中,应用时最好不要这样写。

做完上面的操作,基本上就算是完成了该示例。不过如果使用模拟器时用的是Google API v8时会出现一个异常,将无法完成查找功能:

这是什么原因呢?在网上搜寻了一通,发现讨论区,真的很给力:http://code.google.com/p/android/issues/detail?id=8816

看看个别的评论:

看来真机和v7都没问题,v8会出问题。

也有高人给出解决方案,另辟蹊径,使用访问url的方式,获取json数据,然后解析获取经度和纬度,最后再组装成一个GeoPoint对象即可。我们新建一个LocationUtil.java文件,代码如下:

  1. package com.scott.location;  
  2.   
  3. import java.io.InputStream;  
  4.   
  5. import org.apache.http.HttpEntity;  
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.client.HttpClient;  
  8. import org.apache.http.client.methods.HttpGet;  
  9. import org.apache.http.impl.client.DefaultHttpClient;  
  10. import org.json.JSONArray;  
  11. import org.json.JSONException;  
  12. import org.json.JSONObject;  
  13.   
  14. import com.google.android.maps.GeoPoint;  
  15.   
  16. public class LocationUtil {  
  17.       
  18.     public static GeoPoint getFromLocationName(String address) {  
  19.         String url = "http://maps.google.com/maps/api/geocode/json";  
  20.         HttpGet httpGet = new HttpGet(url + "?sensor=false&address=" + address);  
  21.         HttpClient client = new DefaultHttpClient();  
  22.         HttpResponse response;  
  23.         StringBuilder stringBuilder = new StringBuilder();  
  24.         try {  
  25.             response = client.execute(httpGet);  
  26.             HttpEntity entity = response.getEntity();  
  27.             InputStream stream = entity.getContent();  
  28.             int b;  
  29.             while ((b = stream.read()) != -1) {  
  30.                 stringBuilder.append((char) b);  
  31.             }  
  32.         } catch (Exception e) {  
  33.             e.printStackTrace();  
  34.         }  
  35.   
  36.         JSONObject jsonObject = new JSONObject();  
  37.         try {  
  38.             jsonObject = new JSONObject(stringBuilder.toString());  
  39.         } catch (JSONException e) {  
  40.             e.printStackTrace();  
  41.         }  
  42.         return getGeoPoint(jsonObject);  
  43.     }  
  44.   
  45.     private static GeoPoint getGeoPoint(JSONObject jsonObject) {  
  46.         try {  
  47.             JSONArray array = (JSONArray) jsonObject.get("results");  
  48.             JSONObject first = array.getJSONObject(0);  
  49.             JSONObject geometry = first.getJSONObject("geometry");  
  50.             JSONObject location = geometry.getJSONObject("location");  
  51.               
  52.             double lat = location.getDouble("lat");  
  53.             double lng = location.getDouble("lng");  
  54.               
  55.             return new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));  
  56.         } catch (JSONException e) {  
  57.             e.printStackTrace();  
  58.         }  
  59.         return null;  
  60.     }  
  61.   
  62. }  

然后对MainActivity.java关键地方进行改写:

  1. GeoPoint point = LocationUtil.getFromLocationName(keyword);  

大功告成,当我们搜索后把结果中的第一个显示到地图中,然后点击图标时,弹出提示。我们来看一下效果:

以上是关于android.location包基于位置服务中Geocoder的基本介绍,更多的内容会在以后找机会和大家再分享。

————————————————————————————————————————————————————————————————————

上次介绍了位置服务中的Geocoder,这次就来介绍一下LocationManager。LocationManager系统服务是位置服务的核心组件,它提供了一系列方法来处理与位置相关的问题,包括查询上一个已知位置、注册和注销来自某个LocationProvider的周期性的位置更新、注册和注销接近某个坐标时对一个已定义的Intent的触发等。今天我们就一起探讨一下LocationManager的简单应用。

在进入正题之前,朋友们需要了解与LocationManager相关的两个知识点:

provider:LocationManager获取位置信息的途径,常用的有两种:GPS和NETWORK。GPS定位更精确,缺点是只能在户外使用,耗电严重,并且返回用户位置信息的速度远不能满足用户需求。NETWORK通过基站和Wi-Fi信号来获取位置信息,室内室外均可用,速度更快,耗电更少。为了获取用户位置信息,我们可以使用其中一个,也可以同时使用两个。

LocationListener:位置监听器接口,定义了常见的provider状态变化和位置的变化的方法,我们需要实现此接口,完成自己的处理逻辑,然后让LocationManager注册此监听器,完成对各种状态的监听。

既然上面讲到位置服务的核心是LocationManager,那么我们如何取得一个LocationManager呢?像其他系统服务一样,通过以下方式即可得到一个LocationManager实例:

  1. LocationManager locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  

对象实例是获取到了,可是怎么应用呢?下面就通过一个示例具体演示一下。

我们新建一个location项目。因为示例是基于地图服务的,所以创建时别忘了Build Target要选中Google APIs这一项。

然后修改/res/layout/main.xml,代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent">  
  6.     <com.google.android.maps.MapView  
  7.         android:id="@+id/mapView"  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="fill_parent"  
  10.         android:clickable="true"  
  11.         android:apiKey="your apiKey goes here"/>  
  12.     <Button  
  13.         android:id="@+id/removeUpdates"  
  14.         android:layout_width="fill_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="removeUpdates"/>  
  17. </FrameLayout>  

然后我们来看以下MainActivity.java文件,代码如下:

  1. package com.scott.location;  
  2.   
  3. import android.content.Context;  
  4. import android.location.Location;  
  5. import android.location.LocationListener;  
  6. import android.location.LocationManager;  
  7. import android.os.Bundle;  
  8. import android.view.View;  
  9. import android.widget.Button;  
  10. import android.widget.ImageView;  
  11. import android.widget.Toast;  
  12.   
  13. import com.google.android.maps.GeoPoint;  
  14. import com.google.android.maps.MapActivity;  
  15. import com.google.android.maps.MapView;  
  16. import com.google.android.maps.MapView.LayoutParams;  
  17.   
  18. public class MainActivity extends MapActivity {  
  19.       
  20.     private MapView mapView;  
  21.       
  22.     @Override  
  23.     public void onCreate(Bundle savedInstanceState) {  
  24.         super.onCreate(savedInstanceState);  
  25.         setContentView(R.layout.main);  
  26.           
  27.         mapView = (MapView) findViewById(R.id.mapView);  
  28.         mapView.getController().setZoom(17);  
  29.           
  30.         final LocationManager locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
  31.           
  32.         //获取缓存中的位置信息  
  33.         Location location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);  
  34.         if (location != null) {  
  35.             markCurrLocation(location);  
  36.         }  
  37.           
  38.         final MyLocationListener listener = new MyLocationListener();  
  39.         //注册位置更新监听(最小时间间隔为5秒,最小距离间隔为5米)  
  40.         locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 50005, listener);  
  41.           
  42.         Button removeUpdates = (Button) findViewById(R.id.removeUpdates);  
  43.         removeUpdates.setOnClickListener(new View.OnClickListener() {  
  44.             @Override  
  45.             public void onClick(View v) {  
  46.                 //停止监听  
  47.                 locMgr.removeUpdates(listener);  
  48.             }  
  49.         });  
  50.     }  
  51.       
  52.     /** 
  53.      * 标记当前位置 
  54.      * @param location 
  55.      */  
  56.     private void markCurrLocation(Location location) {  
  57.         mapView.removeAllViews();   //清除地图上所有标记视图  
  58.         GeoPoint point = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));  
  59.         mapView.getController().animateTo(point);  
  60.         final MapView.LayoutParams params = new MapView.LayoutParams(LayoutParams.WRAP_CONTENT,  
  61.                 LayoutParams.WRAP_CONTENT, point, LayoutParams.BOTTOM_CENTER);  
  62.         final ImageView marker = new ImageView(MainActivity.this);  
  63.         marker.setImageResource(R.drawable.marker);  
  64.         marker.setOnClickListener(new View.OnClickListener() {  
  65.             @Override  
  66.             public void onClick(View v) {  
  67.                 Toast.makeText(getApplicationContext(), "hello, location manager!", Toast.LENGTH_SHORT).show();  
  68.             }  
  69.         });  
  70.         mapView.addView(marker, params);  
  71.     }  
  72.   
  73.     @Override  
  74.     protected boolean isRouteDisplayed() {  
  75.         return false;  
  76.     }  
  77.       
  78.     private final class MyLocationListener implements LocationListener {  
  79.   
  80.         @Override  
  81.         public void onLocationChanged(Location location) {  
  82.             markCurrLocation(location);  
  83.         }  
  84.   
  85.         @Override  
  86.         public void onStatusChanged(String provider, int status, Bundle extras) {  
  87.             //Provider状态在可用、暂不可用、无服务三个状态之间直接切换时触发此函数  
  88.         }  
  89.   
  90.         @Override  
  91.         public void onProviderEnabled(String provider) {  
  92.             //Provider被enable时触发此函数,比如GPS被打开  
  93.         }  
  94.   
  95.         @Override  
  96.         public void onProviderDisabled(String provider) {  
  97.             //Provider被disable时触发此函数,比如GPS被关闭  
  98.         }  
  99.           
  100.     }  
  101. }  

因为用到了地图服务,所以需要在AndroidManifest.xml中的application标签之间加入google map library声明:

  1. <uses-library android:name="com.google.android.maps" />  

然后加入位置服务所需的权限:

  1. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  

这里朋友们需要注意:如果使用GPS_PROVIDER或者同时使用GPS_PROVIDER和NETWORK_PROVIDER,则只需声明ACCESS_FINE_LOCATION权限,它对于上述两个provider都是有效的;而ACCESS_COARSE_LOCATION权限只针对NETWORK_PROVIDER。

如果是在模拟器里调试的话,我们可以用以下两种方法设置一个模拟的坐标值:geo命令和DDMS。

先来说一下geo命令,它需要telnet到本机的5554端口,然后在命令行下输入geo fix命令,参数可附带经度、纬度和海拔(可选)。

具体操作如图:

如果朋友用的系统是windows7的话,会遇到一些小小的麻烦,因为windows7默认是没有装Telnet服务,所以我们需要手动安装一下,点击“开始->控制面板->程序->程序和功能”,然后再弹出的窗口左侧点击“打开或关闭Windows功能”,会弹出一下界面,选中“Telnet客户端”和“Telnet服务端”即可。如图:

不过,使用geo命令还是挺麻烦的,ADT提供了一个设置模拟坐标的界面,打开“Emulator Control”视图,即可看到一下界面:

如果设置了模拟坐标后,在模拟器的状态栏就会出现一个雷达图形的标志,如图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值