Android Map Api 使用和开发(3)浮动搜索框 ,通过地址名称获取经纬度和详细地址并定位

这篇把  浮动搜索框 ,通过地址名称获取经纬度和详细地址并定位 这些功能加上,算是一个比较完整的地图了。 

 

 

前辈们都说不要重复的造相同的轮子, 希望这整个例子对正在研究或做地图的同学有帮助。 

 

 

先上图,看看效果

 

搜索框: 

用的icon是愤怒的小鸟,尼玛默认的icon太难看了,换个好看的。哈哈

 

 

 

 

 

 

点击搜索后的效果:

 

 

 

 

 

 

那就开始吧!

 

 

一、配置搜索框

 

searchable.xml

 

 

 

搜索框其实是系统提供的, 可以设置很多属性,想要通过语音搜索也可以配置上去,这个这里就不介绍了

 

 

 

二 、AndroidManifest.xml 文件如何写?

 

 

我上源码一般都是全部的,不是一截一截的,方便那些想省事的人。 

 

 

 

<activity android:name="FzMapActivity"  android:screenOrientation="portrait" 

                  android:label="@string/app_name"  android:launchMode="singleTop">

            <intent-filter>

                <action android:name="android.intent.action.SEARCH"></action>

            </intent-filter>

            <meta-data android:name="android.app.default_searchable"

                       android:value="FzMapActivity" />

            <meta-data android:resource="@xml/searchable" android:name="android.app.searchable"></meta-data>

        </activity>

 

 

这里重点介绍下段 , <action android:name="android.intent.action.SEARCH"></action>   加上action

 

配置搜索配置文件 <meta-data android:resource="@xml/searchable" android:name="android.app.searchable"></meta-data>

 

搜索属于那个Activity   <meta-data android:name="android.app.default_searchable"

                       android:value="FzMapActivity" />

 

模式要设置成 android:launchMode="singleTop".

 

 

三、 保存历史搜索记录   SearchSuggestionProvider

 

 

 

 

android:launchMode="singleTop"

 

 

四、 重点来了,  在FzMapActivity里加上这段代码 ,用来调起搜索框和得到搜索框内容的

 

 

 

搜索需要联网,所以起了个线程,去处理。

 

 

 

 

在点搜索的button时调用  onSearchRequested方法就可以搜索了

 

 

 

 

五、通过地址搜索的方法 searchLocationByName

 

private Address searchLocationByName(String addressName){

Geocoder geoCoder = new Geocoder(getBaseContext(),

Locale.CHINA);

try {

List<Address> addresses = geoCoder.getFromLocationName(addressName, 1);

Address address_send = null;

for(Address address : addresses){

locPoint = new GeoPoint((int)(address.getLatitude() * 1E6), (int)(address.getLongitude() * 1E6));

address.getAddressLine(1);

address_send = address;

}

return address_send;

} catch (IOException e) {

e.printStackTrace();

return null;

}

}

 

 

 

geoCoder.getFromLocationName(addressName, 1);  第二个参数是返回结果的数量,

 

这个接口有时候返回null,那可能是因为google当时的服务不好。 多试几次就好了。

 

我在代码里写的试重试五次,如果获取不到就返回错误。

 

 

好吧,解释就这么多,直接去下全部源码看效果吧 。有收获的就顶顶哈

 

源码下载地址 http://www.eoeandroid.com/thread-82185-1-1.html

 

 

 

posted @ 2011-06-30 17:10  移动应用开发  阅读(281)  评论(0编辑  收藏  举报