Android學習筆記 地圖定位

一、系統設置
和定位代碼一樣,我們要設置系統的permission,在 AndroidManifest.xml的application之前,添加:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_GPS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_LOCATION"></uses-permission>


二、界面設置
我們要做地圖的view上添加兩個按鈕,一個是標記爲+的放大按鈕,一個是標記爲-的縮小按鈕。將view部分改成下文:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<view class="com.google.android.maps.MapView"
android:id="@+id/myMap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled = "true"
android:apiKey="……………………"></view>
<Button android:id="@+id/buttonZoomIn"
style="?android:attr/buttonStyleSmall"
android:text="+"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button android:id="@+id/buttonZoomOut"
style="?android:attr/buttonStyleSmall"
android:text="-"
android:layout_alignBottom="@+id/myMap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>

另外再定義一個按鈕,用於獲取用戶的GPS地址。
顯示結果如圖:
[img]http://labs.chinamobile.com/upload/my_blog/4d/1e/fa/int_3783425034a979d25d0a23.GIF[/img]

三、關鍵代碼編寫
在原來的地圖程序中,添加一個新的定位按鈕,代碼如下:

final Button where = (Button) findViewById(R.id.whereami);
where.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
mService = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
geoLatitude = mService.getCurrentLocation("gps").getLatitude();
geoLongitude = mService.getCurrentLocation("gps").getLongitude();
latText.setText(Double.toString(geoLatitude));
lngText.setText(Double.toString(geoLongitude));
}});

即把獲取的地理座標顯示到兩個EditText中。

在放大和縮小的按鈕中,添加如下代碼,並且在每次縮放後再放大倍數的edittext中顯示當前倍數:


四、結果顯示
[img]http://labs.chinamobile.com/upload/my_blog/96/60/2a/re.JPG[/img]
運行程序後,先點擊i按鈕,再點擊locate按鈕,顯示出當前所在的地圖和座標。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章