Android 地理编码

来源:互联网 发布:gradle mac 环境变量 编辑:程序博客网 时间:2024/05/02 01:51

地理编码可以在街道地址和经纬度地图坐标之间进行转换。这样就可以为基于位置的服务和基于地图的Activity中所用的位置或者坐标提供一个可识别的上下文。

Geocoder类包含在Google Maps库中,所以要使用Geocoder类,就必须把该库导入到应用程序中:

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

地理编码查找是在服务器上进行的:

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

Geocoder类提供了两种地理编码函数:

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

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

这些调用返回的结果将会放到一个区域(用来定义你常驻位置和所用语言)中。如果没有指定区域设置,那么它将会被假定为设备默认的区域设置。

    Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());

这两种地理编码函数返回的都是Address对象列表,每一个列表都可以包含多个可能的结果,在调用函数时可以指定结果的最大数量。

Geocoder使用一个Web服务来实现有些Android设备可能不支持的查找。Android 2.3(API Level 9)引入了isPresent方法来确定指定的设备上是否存在Ceocoder实现:

    boolean geocoderExists = Geocoder.isPresent();

一.反向地理编码

反向地理编码可以返回由经度和纬度指定的物理位置的街道地址。

要执行反向查找,需要向地理编码器对象的getFromLocation方法传入目标纬度和经度。它会返回一个可能匹配的地址的列表。如果对于指定的坐标,地理编码器不能解析出任何地址,那么它将会返回null。

  private void reverseGeocode(Location location) {    double latitude = location.getLatitude();    double longitude = location.getLongitude();    List<Address> addresses = null;    Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());    try {      addresses = gc.getFromLocation(latitude, longitude, 10);    } catch (IOException e) {      Log.e(TAG, "IO Exception", e);    }  }

二.前向地理编码

前向地理编码可以确定一个给定位置的地图坐标。

对一个地址进行地理编码:

    List<Address> results = gc.getFromLocationName(streetAddress, maxResults);

在进行前向查找的过程中,实例化Geocoder对象时所指定的Locale对象尤其重要。Locale提供了解释搜索请求的地理上下文,因为多个区域可能存在相同的位置名称。

对一个地址进行地理编码:

    Geocoder fwdGeocoder = new Geocoder(this, Locale.US);    String streetAddress = "160 Riverside Drive, New York, New York";    List<Address> locations = null;    try {      locations = fwdGeocoder.getFromLocationName(streetAddress, 5);    } catch (IOException e) {      Log.e(TAG, "IO Exception", e);    }

为了得到更具体的结果,可以指定左下方和右上方的纬度和经度值,从而把搜索限制在一个地理边界范围内:

    List<Address> locations = null;    try {      locations = fwdGeocoder.getFromLocationName(streetAddress, 10, llLat, llLong, urLat, urLong);    } catch (IOException e) {      Log.e(TAG, "IO Exception", e);    }


0 0