技术开发 频道

OPhone学习笔记 - 地图(4)

  【IT168 技术文章】在这个例子里面,我们把定位和地图结合起来,通过地图来找到自己,并且为了观察地图方便,我们增加两个缩放功能的按钮。所有代码基于前文的地图代码。

  一、系统设置

  和定位代码一样,我们要设置系统的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地址。

  显示结果如图:

三、关键代码编写

  在原来的地图程序中,添加一个新的定位按钮,代码如下:

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中显示当前倍数:

  四、结果显示

  运行程序后,先点击i按钮,再点击locate按钮,显示出当前所在的地图和坐标。

0
相关文章