MapView的使用

在论坛里看到一篇 "MapView和其它控件一起显示 " 的帖子, 那是很老的一篇帖子了, 很多朋友都说无法在android SDK 1.0上运行。既然那么多人关心,我在这里就把它重写一遍,顺便加入了一些新的功能 ,感兴趣的朋友可以看看。 第一步,当然是增加map的支持了。在Android Manifest.xml中增加以下语句: <uses-library android:name="com.google.android.maps" /> 第二步, 传说中的Layout: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <com.google.android.maps.MapView android:id="@+id/map" android:layout_width="fill_parent" android:layout_height="fill_parent" android:apiKey="Map_Demo" android:clickable="true" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="输入查询地址" android:selectAll/> </RelativeLayout> 然后, 创建一个MapViewActivity: public class MapViewActivity extends MapActivity { MapView mapView; MapController mapController; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mapView = (MapView) findViewById(R.id.map); mapController = mapView.getController(); mapController.setZoom(15); updateView(); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } private void updateView(){ Double lat = 31.23717*1E6; Double lng = 121.50811*1E6; GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue()); mapController.setCenter(point); } } 好了,你的MapView上面就多了一个EditText了。 接着,我希望在MapView中增加ZoomIn和ZoomOut的功能(鄙视一下Google ,缺省的MapView居然连这个功能都没有) 1. 在我们的Layout中增加一段: <LinearLayout android:id="@+id/zoom" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" /> 2. 在onCreate函数中增加: ViewGroup zoom=(ViewGroup)findViewById(R.id.zoom); zoom.addView(mapView.getZoomControls()); 现在在你的地图中点一下,屏幕左下角,是不是出现了一个Zoom Table? 这才是一个最基本的地图功能嘛。 以下技巧是基于SDK 1.0的) 一、申请Apikey,并放在正确的位置http://iceskysl.1sters.com/?action=show&id=441 这个应该都知道,但是是申请得到的key放哪里很多人不知道,可以放在 1、XML布局文件中 <view android:id="@+id/mv" class="com.google.android.maps.MapView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:apiKey="01Yu9W3X3vbpYT3x33chPXXX7U1Z6jy8WYZXNFA" /> 申请APIkey的时候,类似命令如下: C:\Documents and Settings\Administrator\Local Settings\Application Data\Android> "C:\Program Files\Java\jdk1.6.0_10\bin\keytool.exe" -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android androiddebugkey, 2008-9-23, PrivateKeyEntry, 认证指纹 (MD5): 1D:68:43:7C:14:2E:CC:CA:35:8B:1F:93:A7:91:AD:45 2、java中 mMapView = new MapView(this, "01Yu9W3X3vbpYT3x33chPxxx7U1Z6jy8WYZXNFA"); 二、记得导入uses-library 由于1.0版本的修改,使得map包不再是默认的了,使用的时候需要在manifest中的application节点下加入 <uses-library android:name="com.google.android.maps" /> 否则,你将遇到可恶的“java.lang.NoClassDefFoundError: ”,切记! 三、需要给予一定的权限 因为要使用GoogleMAP的service,所以需要 <uses-permission android:name="android.permission.INTERNET"></uses-permission> 如果需要GPS等应用,还需要 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> 四、Activity需要继承自MapActivity 类似如下代码; package com.iceskysl.showmap; import com.google.android.maps.MapActivity; import android.os.Bundle; public class ShowMap extends MapActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } } 在Android中使用其提供的Sensor非常方便,如下是强制Landscape时候的情况: values[0]:方位角(水平旋转角),简单的说就是手机的头现在朝向哪个方位,0=北、90=东、180=南、270=西(可是好像不太准) values[1]:纵向旋转角,0=面朝上平置、-90=垂直向上、-180/180=面朝下平置、90=垂直向下 values[2]:橫向旋转角,0=朝前、90=往右倒、-90=往左倒 在Android中计算GPS两点间的距离/速度 Q:how to get distance between two GeoPoints in sdk 1.0 ? MapPoint.distanceSquared(MapPoint) is gone thaks!! A:you'll need to brush up on your trigonometry, and first compute the Haversine function (this is the standard way of doing it). In order to use the Java trig functions, you'll have to first convert all your angles from degrees to radians. Given two longitude/latitude pairs, and the earth's average radius (assume 6356.78km for your calculations), you can calculate the distance between the 2 points via this Java code: double EarthRad = 6356.78; // in km ! // first convert to radians... double geo1_lat = geo1.getLatitude()*java.lang.Math.PI/360; double geo1_lng = geo1.getLongitude()*java.lang.Math.PI/360; double geo2_lat = geo2.getLatitude()*java.lang.Math.PI/360; double geo2_lng = geo2.getLongitude()*java.lang.Math.PI/360; double deltaLat = java.lang.Math.abs(java.lang.Math.abs(geo2_lat) - java.lang.Math.abs(geo1_lat)); double deltaLng = java.lang.Math.abs(java.lang.Math.abs(geo2_lng) - java.lang.Math.abs(geo1_lng)); double dist = 2*EarthRad*java.lang.Math.asin(java.lang.Math.sqrt(haversine(deltaLat) + java.lang.Math.cos(pair1_lat) *java.lang.Math.cos(pair1_lng)*haversine(deltaLng))); Where "dist" now contains the distance between along the earth's surface. You can find the Haversine function trig equation by Googling it, then construct a method that returns the appropriate value. Computing the speed is straightforward: you know your sampling frequency, and you now know the distance between the most recent two points, so, employee speed = distance / sampling interval 参考:http://www.anddev.org/distance_between_two_geopoints_in_sdk10-t4195.html http://www.anddev.org/calculating_distance_between_two_gps_points-t3708.html 获得maps api的方法:本人的 打开Eclipse--->Windows--->Preferences--->Android--->Build 查看默认的debug keystore位置,我的是C:\Documents and Settings\Administrator\Local Settings\Application Data\Android\debug.keystore 启动命令行 直接 输入如下内容: keytool -list -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator\Local Settings\Application Data\Android\debug.keystore" -storepass android -keypass android 结果如下:Microsoft Windows XP [版本 5.1.2600] (C) 版权所有 1985-2001 Microsoft Corp. C:\Documents and Settings\Administrator>keytool -list -alias androiddebugkey -ke ystore "C:\Documents and Settings\Administrator\Local Settings\Application Data\ Android\debug.keystore" -storepass android -keypass android androiddebugkey, 2009-3-12, keyEntry, 认证指纹 (MD5): 0F:C3:F0:C6:32:49:CE:C6:0E:18:57:CA:48:D7:CD:12 C:\Documents and Settings\Administrator> 屏幕图如下: 打开http://code.google.com/intl/zh-CN/android/maps-api-signup.html 填入你的认证指纹(MD5)即可获得apiKey了 0Ua9BENcUvNLXp8wn_vXXvVf70rLTYixrNxbHNQ http://www.androidcompetencycenter.com/category/android-api/ http://duzike.blogbus.com/logs/35386568.html http://www.helloandroid.com/node/206 http://www.diybl.com/course/6_system/linux/Linuxjs/2008819/136351.html 根据输入城市名动态加载google地图 文章出处:http://www.diybl.com/course/6_system/linux/Linuxjs/2008819/136351.html 1)SendCityName.java: package com.google.android.citygmapview; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class SendCityName extends Activity { protected static final int REQUEST_SEND_DATA = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); getAndSendCityName(); } public void getAndSendCityName() { Button btn = (Button)findViewById(R.id.confirm); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { EditText edt=(EditText)SendCityName.this.findViewById(R.id.edt); Intent intent = new Intent(); intent.setClass(SendCityName.this, ShowGmapView.class); if(edt.getText().length()!= 0) { String data = edt.getText().toString(); String name="data"; intent.putExtra(name, data); startSubActivity(intent,REQUEST_SEND_DATA); } } }); } } 说明: if(edt.getText().length()!= 0)用来处理用户输入为空的情况,为空时数据不会传递到另外一个activity中去,节省资源。 (2)ShowGmapView.java: package com.google.android.citygmapview; import java.io.IOException; import java.util.Locale; import com.google.android.location.GmmGeocoder; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.Point; import android.location.Address; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.Menu.Item; public class ShowGmapView extends MapActivity { private static final int EXIT_ID = 0; private MapView myMapView; private Address[] maddrs; protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.gmap_view); Bundle extras = getIntent().getExtras(); String name="data"; if(extras != null) { String data1 = extras.getString(name); GmmGeocoder mgc = new GmmGeocoder(Locale.getDefault()); try { maddrs = mgc.query(data1, GmmGeocoder.QUERY_TYPE_LOCATION, 0, 0, 180.0, 360.0); if (null!=maddrs && maddrs.length > 0) { Log.d("CountryName: ", maddrs[0].getCountryName()); maddrs[0].getLatitude(); } else { setResult(RESULT_OK, null, extras); finish(); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } myMapView = new MapView(this); if(null!=maddrs && maddrs.length > 0) { Point p = new Point((int) (maddrs[0].getLatitude() * 1000000), (int) (maddrs[0].getLongitude() * 1000000)); /** 地图控制器 */ MapController mc = myMapView.getController(); mc.animateTo(p); /** 21是最zoom in的一级,一共是1-21级 */ mc.zoomTo(21); setContentView(myMapView); /** 切换到卫星地图 */ myMapView.toggleSatellite(); } setResult(RESULT_OK, null, extras); } } 文章出处:http://www.diybl.com/course/6_system/linux/Linuxjs/2008819/136351.html public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_I) { /** zoom in */ myMapView.getController().zoomTo(myMapView.getZoomLevel() + 1); return true; } else if (keyCode == KeyEvent.KEYCODE_O) { /** zoom out */ myMapView.getController().zoomTo(myMapView.getZoomLevel() - 1); return true; } else if (keyCode == KeyEvent.KEYCODE_S) { /** 卫星地图 */ myMapView.toggleSatellite(); return true; } else if (keyCode == KeyEvent.KEYCODE_T) { /** traffic,路况 */ myMapView.toggleTraffic(); return true; } return false; } 文章出处:http://www.diybl.com/course/6_system/linux/Linuxjs/2008819/136351_2.html @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, EXIT_ID, R.string.exit_gmap); return true; } @Override public boolean onMenuItemSelected(int featureId, Item item) { super.onMenuItemSelected(featureId, item); switch(item.getId()) { case EXIT_ID: finish(); break; } return true; } } 说明: 在开始设计时采用了Geocoder这个类,但似乎通过它获取的经纬度为空值,所以最后采取了GmmGeocoder,并能达到目的。 图示: (3)main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/txt" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> <EditText android:id="@+id/edt" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> <Button android:id="@+id/confirm" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/confirm"> </Button> </LinearLayout> (4)gmap_view.xml: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/txt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" /> (5)strings.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">city gmap view</string> <string name="confirm">confirm</string> <string name="exit_gmap">Exit google map</string> </resources> (6)AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.google.android.citygmapview"> <application android:icon="@drawable/icon"> <activity android:name=".SendCityName" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ShowGmapView" android:label="@string/app_name"></activity> </application> </manifest> 文章出处:http://www.diybl.com/course/6_system/linux/Linuxjs/2008819/136351_3.html ### MapView的使用详解 MapView是在Android开发中用于展示地图的一种控件,它可以与其它UI控件结合使用,实现丰富的地图交互功能。本文将详细介绍如何在Android应用中使用MapView,并结合具体的实例进行说明。 #### 一、MapView的基本使用 1. **添加Map支持** 在Android应用中使用MapView之前,需要在`AndroidManifest.xml`文件中添加对地图库的支持声明: ```xml <uses-library android:name="com.google.android.maps" /> ``` 2. **定义布局文件** 定义包含MapView的布局文件,如下所示: ```xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.maps.MapView android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" android:apiKey="Map_Demo" android:clickable="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:text="输入查询地址" android:selectAll="true" /> </RelativeLayout> ``` 其中,MapView的`android:apiKey`属性需要填写有效的API密钥。 3. **创建MapViewActivity** 创建一个继承自`MapActivity`的类,并在其中初始化MapView: ```java public class MapViewActivity extends MapActivity { MapView mapView; MapController mapController; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (MapView) findViewById(R.id.map); mapController = mapView.getController(); mapController.setZoom(15); updateView(); } @Override protected boolean isRouteDisplayed() { return false; } private void updateView() { Double lat = 31.23717 * 1E6; Double lng = 121.50811 * 1E6; GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue()); mapController.setCenter(point); } } ``` #### 二、增加ZoomIn和ZoomOut功能 1. **修改布局文件** 为了实现地图的缩放功能,需要在布局文件中添加一个LinearLayout来放置缩放按钮: ```xml <LinearLayout android:id="@+id/zoom" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" /> ``` 2. **在Activity中添加缩放按钮** 在`onCreate`方法中添加如下代码: ```java ViewGroup zoom = (ViewGroup) findViewById(R.id.zoom); zoom.addView(mapView.getZoomControls()); ``` #### 三、申请ApiKey并正确放置 1. **获取ApiKey** 获取ApiKey通常需要使用命令行工具获取设备的认证指纹,例如: ```bash keytool -list -alias androiddebugkey -keystore "路径/debug.keystore" -storepass android -keypass android ``` 2. **放置ApiKey** 可以将ApiKey放置在XML布局文件或Java代码中: - XML布局文件: ```xml <MapView android:id="@+id/mv" android:apiKey="01Yu9W3X3vbpYT3x33chPXXX7U1Z6jy8WYZXNFA" /> ``` - Java代码: ```java MapView mapView = new MapView(this, "01Yu9W3X3vbpYT3x33chPxxx7U1Z6jy8WYZXNFA"); ``` #### 四、其他注意事项 1. **导入uses-library** 为确保MapView正常工作,需要在`AndroidManifest.xml`文件中声明对地图库的支持: ```xml <uses-library android:name="com.google.android.maps" /> ``` 2. **给予必要的权限** 应用程序可能需要访问网络或GPS定位服务,因此需要在`AndroidManifest.xml`中声明相应的权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> ``` 3. **继承MapActivity** 使用MapView的Activity需要继承自`MapActivity`: ```java public class ShowMap extends MapActivity { // ... } ``` #### 五、计算地图上的距离和速度 1. **计算两点之间的距离** 计算两个GeoPoint之间的距离可以通过Haversine公式实现,具体代码如下: ```java double EarthRad = 6356.78; // 地球平均半径 double geo1_lat = geo1.getLatitude() * Math.PI / 180; double geo1_lng = geo1.getLongitude() * Math.PI / 180; double geo2_lat = geo2.getLatitude() * Math.PI / 180; double geo2_lng = geo2.getLongitude() * Math.PI / 180; double deltaLat = Math.abs(Math.abs(geo2_lat) - Math.abs(geo1_lat)); double deltaLng = Math.abs(Math.abs(geo2_lng) - Math.abs(geo1_lng)); double dist = 2 * EarthRad * Math.asin(Math.sqrt(haversine(deltaLat) + Math.cos(geo1_lat) * Math.cos(geo1_lng) * haversine(deltaLng))); ``` 2. **计算速度** 计算速度的公式为:速度 = 距离 / 采样间隔时间 #### 六、根据输入城市名动态加载地图 1. **实现流程** 实现根据输入的城市名动态加载地图的过程分为以下几个步骤: - 获取用户输入的城市名。 - 使用Geocoder或GmmGeocoder获取该城市的经纬度坐标。 - 使用获取到的坐标设置MapView的中心位置。 - 显示地图。 2. **示例代码** 以下是一个简单的示例,展示了如何通过用户输入的城市名加载对应的地图: ```java public class ShowGmapView extends MapActivity { private MapView myMapView; private Address[] maddrs; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gmap_view); Bundle extras = getIntent().getExtras(); String data1 = extras.getString("data"); try { maddrs = mgc.query(data1, GmmGeocoder.QUERY_TYPE_LOCATION, 0, 0, 180.0, 360.0); if (null != maddrs && maddrs.length > 0) { Point p = new Point((int) (maddrs[0].getLatitude() * 1000000), (int) (maddrs[0].getLongitude() * 1000000)); MapController mc = myMapView.getController(); mc.animateTo(p); mc.zoomTo(21); setContentView(myMapView); myMapView.toggleSatellite(); } } catch (IOException e) { e.printStackTrace(); } } } ``` 通过以上步骤和代码示例,我们可以较为全面地了解如何在Android应用中使用MapView,包括基本的初始化、添加缩放功能、获取和设置ApiKey以及计算地图上的距离和速度等功能。


















剩余10页未读,继续阅读

- 键盘指板2014-12-04有一定的帮助,值得一看

- 粉丝: 0
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助


最新资源
- update9-20250731.5.209.slice.img.7z.001.pd
- 基于COMSOL仿真的光学波导传输技术研究:光纤波导三维弯曲、模场分布及损耗分析
- 基于距离和方位的多智能体编队分布式控制:原理、仿真与稳定性分析 - 多智能体系统
- 基于MATLAB Simulink的高频隔离DAB-双有源全桥DC-DC变换器仿真模型,实现电压电流双闭环与ZVS软开关,功率双向流动的学习交流使用 MATLAB
- 基于S7-200 PLC和MCGS组态的灌装贴标生产线系统解析 梯形图程序、接线图原理图和组态画面
- CarSim与Simulink联合仿真实现基于MPC的超车换道路径动态规划及实时检测
- Django框架多模态知识图谱智能旅游推荐系统Python源码SQL数据库详细注释毕设新项目
- 崔帕斯T1080电脑调音软件下载
- AI辅导员问答信息word文档
- 番茄钟html版的源码
- update9-20250731.5.209.slice.img.7z.002
- 基于 OpenMV 和 STM32 的循迹小车
- 崔帕斯T1980电脑调音软件下载
- 基于COMSOL仿真的光学手性BIC在光子晶体板中的连续域束缚态及琼斯矩阵透射谱分析
- 电力电子领域LLC谐振变换器Simulink仿真的电压电流双环竞争控制策略及其实现 LLC谐振变换器 说明


