---
title: "android google地图定位开发，且可以自由移动位置重新获取定位，地址信息"
author: "hack_zhang"
date: "2013-05-20T15:00:06Z"
tags: []
categories: ["移动开发"]
slug: "android-google"
draft: false
lastmod: "2013-05-20T15:05:36Z"
id: 1872136
url: "https://hack-zhang.iteye.com/blog/1872136"
---

一：申请key:

1.首先找到debug keystore位置：

　　打开Eclipse---&gt;Windows---&gt;Preferences---&gt;Android---&gt;Build

一般是这样的路径 C:\\Documents and Settings\\Administrator\\.android\\debug.keystore

2.在cmd中执行

keytool -list -alias androiddebugkey -keystore "C:\\Documents and Settings\\Administrator\\.android\\debug.keystore" -storepass android -keypass android

得到认证指纹 (MD5)如：6F:C9:41:48:A5:F3:36:A5:D3:DD:B5:D1:CB:AC:47:88

3.打开申请key页面 [http://code.google.com/android/maps-api-signup.html](https://developers.google.com/android/maps-api-signup)

复制 认证指纹 (MD5)：到下面的 My certificate's MD5 fingerprint

4.然后点击 Generate Api key

5.等到apikey:0Mg\_koWoyZUhlluO4-i6-bq9WYMFbxKodZZMz2Q

 

二：设计main.xml如下：（将申请到得key设置在com.google.android.maps.MapView 中如下所示）

 

 

Xml代码  [![收藏代码](http://104zz.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="utf-8"?&gt;
02. &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03. android:layout\_width="fill\_parent"
04. android:layout\_height="fill\_parent"
05. android:orientation="vertical" &gt;
06. &lt;FrameLayout
07. android:id="@+id/map\_layout"
08. android:layout\_width="fill\_parent"
09. android:layout\_height="fill\_parent"
10. android:orientation="vertical" &gt;
11. &lt;com.google.android.maps.MapView
12. android:id="@+id/map\_view"
13. android:layout\_width="fill\_parent"
14. android:layout\_height="fill\_parent"
15. android:apiKey="0Mg\_koWoyZUhlluO4-i6-bq9WYMFbxKodZZMz2Q"
16. android:clickable="true"
17. android:enabled="true" /&gt;
18. &lt;LinearLayout
19. android:layout\_width="wrap\_content"
20. android:layout\_height="wrap\_content"
21. android:layout\_gravity="center"
22. android:orientation="vertical"
23. android:paddingBottom="105dip" &gt;
24. &lt;TextView
25. android:id="@+id/map\_bubbleText"
26. android:layout\_width="wrap\_content"
27. android:layout\_height="wrap\_content"
28. android:background="@drawable/location\_tips"
29. android:gravity="left|center"
30. android:maxEms="12"
31. android:paddingLeft="12dip"
32. android:paddingRight="10dip"
33. android:text="@string/load\_tips"
34. android:textColor="#cfcfcf"
35. android:textSize="14sp" /&gt;
36. &lt;/LinearLayout&gt;
37. &lt;LinearLayout
38. android:layout\_width="wrap\_content"
39. android:layout\_height="wrap\_content"
40. android:layout\_gravity="center"
41. android:orientation="vertical" &gt;
42. &lt;ImageView
43. android:id="@+id/point\_image"
44. android:layout\_width="wrap\_content"
45. android:layout\_height="wrap\_content"
46. android:layout\_gravity="center"
47. android:layout\_marginBottom="30dip"
48. android:src="@drawable/point\_start" /&gt;
49. &lt;/LinearLayout&gt;
50. &lt;/FrameLayout&gt;
51. &lt;/LinearLayout&gt;

 

 

三：创建MyLocationManager类主要用于管理经纬度获取方法实现

 

Java代码  [![收藏代码](http://104zz.iteye.com/images/icon_star.png)]()

01. package com.android.map;
02. import android.content.Context;
03. import android.location.Location;
04. import android.location.LocationListener;
05. import android.location.LocationManager;
06. import android.os.Bundle;
07. import android.util.Log;
08. public class MyLocationManager {
09. private final String TAG = "FzLocationManager";
10. private static Context mContext;
11. private LocationManager gpsLocationManager;
12. private LocationManager networkLocationManager;
13. private static final int MINTIME = 2000;
14. private static final int MININSTANCE = 2;
15. private static MyLocationManager instance;
16. private Location lastLocation = null;
17. private static LocationCallBack mCallback;
18. public static void init(Context c , LocationCallBack callback) {
19. mContext = c;
20. mCallback = callback;
21. }
22. private MyLocationManager() {
23. // Gps 定位
24. gpsLocationManager = (LocationManager) mContext
25. .getSystemService(Context.LOCATION\_SERVICE);
26. Location gpsLocation = gpsLocationManager
27. .getLastKnownLocation(LocationManager.GPS\_PROVIDER);
28. gpsLocationManager.requestLocationUpdates(LocationManager.GPS\_PROVIDER,
29. MINTIME, MININSTANCE, locationListener);
30. // 基站定位
31. networkLocationManager = (LocationManager) mContext
32. .getSystemService(Context.LOCATION\_SERVICE);
33. Location networkLocation = gpsLocationManager
34. .getLastKnownLocation(LocationManager.GPS\_PROVIDER);
35. networkLocationManager.requestLocationUpdates(
36. LocationManager.NETWORK\_PROVIDER, MINTIME, MININSTANCE,
37. locationListener);
38. }
39. public static MyLocationManager getInstance() {
40. if (null == instance) {
41. instance = new MyLocationManager();
42. }
43. return instance;
44. }
45. private void updateLocation(Location location) {
46. lastLocation = location;
47. mCallback.onCurrentLocation(location);
48. }
49. private final LocationListener locationListener = new LocationListener() {
50. public void onStatusChanged(String provider, int status, Bundle extras) {
51. }
52. public void onProviderEnabled(String provider) {
53. }
54. public void onProviderDisabled(String provider) {
55. }
56. public void onLocationChanged(Location location) {
57. Log.d(TAG, "onLocationChanged");
58. updateLocation(location);
59. }
60. };
61. public Location getMyLocation() {
62. return lastLocation;
63. }
64. private static int ENOUGH\_LONG = 1000 * 60;
65. public interface LocationCallBack{
66. /\**
67. * 当前位置
68. * @param location
69. \*/
70. void onCurrentLocation(Location location);
71. }
72. public void destoryLocationManager(){
73. Log.d(TAG, "destoryLocationManager");
74. gpsLocationManager.removeUpdates(locationListener);
75. networkLocationManager.removeUpdates(locationListener);
76. }
77. }

   

 

四：创建MyMapOverlay抽象类，并继承Overlay，创建抽象方法 

changePoint(GeoPoint newPoint,int type)用于回调重新获取到的GeoPoint 重新定位地图，并获取地址信息

 

 

Java代码  [![收藏代码](http://104zz.iteye.com/images/icon_star.png)]()

01. import android.view.MotionEvent;
02. import com.google.android.maps.GeoPoint;
03. import com.google.android.maps.MapView;
04. import com.google.android.maps.Overlay;
05. //覆盖整个地图捕捉触控事件的OverLay
06. public abstract class MyMapOverlay extends Overlay{
07. private int point\_X;
08. private int point\_Y;
09. private GeoPoint newPoint;
10. public MyMapOverlay(int x,int y){
11. point\_X = x;
12. point\_Y = y;
13. }
14. boolean flagMove=false;
15. //触控屏幕移动地图，重新根据屏幕中心点获取该点经纬度
16. @Override
17. public boolean onTouchEvent(MotionEvent event, MapView mapView) {
18. System.out.println("X-&gt;"+event.getX()+":"+point\_X);
19. System.out.println("Y-&gt;"+event.getY()+":"+point\_Y);
20. if(event.getAction() == MotionEvent.ACTION\_DOWN){
21. changePoint(newPoint,1);
22. }else if(event.getAction() == MotionEvent.ACTION\_UP){
23. newPoint = mapView.getProjection().fromPixels(point\_X,point\_Y);
24. changePoint(newPoint,2);
25. }
26. return false;
27. }
28. public abstract void changePoint(GeoPoint newPoint,int type);
29. }

 

 

五：MyMapActivity 继承MapActivity类并实现经纬度获取回调接口LocationCallBack 。项目实现如下：

 

Java代码  [![收藏代码](http://104zz.iteye.com/images/icon_star.png)]()

001. package com.android.googlemap;
002. import java.io.IOException;
003. import java.util.List;
004. import java.util.Locale;
005. import android.graphics.Rect;
006. import android.location.Address;
007. import android.location.Geocoder;
008. import android.location.Location;
009. import android.os.Bundle;
010. import android.os.Handler;
011. import android.os.Message;
012. import android.view.View;
013. import android.view.Window;
014. import android.widget.TextView;
015. import com.android.map.MyLocationManager;
016. import com.android.map.MyLocationManager.LocationCallBack;
017. import com.android.map.MyMapOverlay;
018. import com.google.android.maps.GeoPoint;
019. import com.google.android.maps.MapActivity;
020. import com.google.android.maps.MapController;
021. import com.google.android.maps.MapView;
022. import com.google.android.maps.Overlay;
023. public class MyMapActivity extends MapActivity implements LocationCallBack {
024. private MapView mapView;
025. private MapController mMapCtrl;
026. private MyLocationManager myLocation;
027. private List&lt;Overlay&gt; mapOverlays;
028. public GeoPoint locPoint;
029. private MyMapOverlay mOverlay;
030. private TextView desText;
031. private String lost\_tips;
032. private int point\_X;
033. private int point\_Y;
034. private int statusBarHeight;
035. public final int MSG\_VIEW\_LONGPRESS = 10001;
036. public final int MSG\_VIEW\_ADDRESSNAME = 10002;
037. public final int MSG\_GONE\_ADDRESSNAME = 10003;
038. @Override
039. public void onCreate(Bundle savedInstanceState) {
040. super.onCreate(savedInstanceState);
041. requestWindowFeature(Window.FEATURE\_NO\_TITLE);
042. setContentView(R.layout.main);
043. mapView = (MapView) findViewById(R.id.map\_view);
044. desText = (TextView) this.findViewById(R.id.map\_bubbleText);
045. lost\_tips = getResources().getString(R.string.load\_tips);
046. mapView.setBuiltInZoomControls(true);
047. mapView.setClickable(true);
048. mMapCtrl = mapView.getController();
049. point\_X = this.getWindowManager().getDefaultDisplay().getWidth() / 2;
050. point\_Y = this.getWindowManager().getDefaultDisplay().getHeight() / 2;
051. mOverlay = new MyMapOverlay(point\_X, point\_Y) {
052. @Override
053. public void changePoint(GeoPoint newPoint, int type) {
054. if (type == 1) {
055. mHandler.sendEmptyMessage(MSG\_GONE\_ADDRESSNAME);
056. } else {
057. locPoint = newPoint;
058. mHandler.sendEmptyMessage(MSG\_VIEW\_LONGPRESS);
059. }
060. }
061. };
062. mapOverlays = mapView.getOverlays();
063. if (mapOverlays.size() &gt; 0) {
064. mapOverlays.clear();
065. }
066. mapOverlays.add(mOverlay);
067. mMapCtrl.setZoom(12);
068. MyLocationManager.init(MyMapActivity.this.getApplicationContext(),
069. MyMapActivity.this);
070. myLocation = MyLocationManager.getInstance();
071. }
072. @Override
073. protected void onResume() {
074. super.onResume();
075. }
076. @Override
077. protected void onPause() {
078. super.onPause();
079. }
080. @Override
081. protected boolean isRouteDisplayed() {
082. // TODO Auto-generated method stub
083. return false;
084. }
085. public void onCurrentLocation(Location location) {
086. if (locPoint == null) {
087. locPoint = new GeoPoint((int) (location.getLatitude() * 1E6),
088. (int) (location.getLongitude() * 1E6));
089. mHandler.sendEmptyMessage(MSG\_VIEW\_LONGPRESS);
090. }
091. }
092. public void changePoint(GeoPoint locPoint) {
093. }
094. /\**
095. * 通过经纬度获取地址
096. \*
097. * @param point
098. * @return
099. \*/
100. private String getLocationAddress(GeoPoint point) {
101. String add = "";
102. Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
103. try {
104. List&lt;Address&gt; addresses = geoCoder.getFromLocation(
105. point.getLatitudeE6() / 1E6, point.getLongitudeE6() / 1E6,
106. 1);
107. Address address = addresses.get(0);
108. int maxLine = address.getMaxAddressLineIndex();
109. if (maxLine &gt;= 2) {
110. add = address.getAddressLine(1) + address.getAddressLine(2);
111. } else {
112. add = address.getAddressLine(1);
113. }
114. } catch (IOException e) {
115. add = "";
116. e.printStackTrace();
117. }
118. return add;
119. }
120. /\**
121. \*
122. * 用线程异步获取
123. \*/
124. Runnable getAddressName = new Runnable() {
125. public void run() {
126. String addressName = "";
127. while (true) {
128. addressName = getLocationAddress(locPoint);
129. if (!"".equals(addressName)) {
130. break;
131. }
132. }
133. Message msg = new Message();
134. msg.what = MSG\_VIEW\_ADDRESSNAME;
135. msg.obj = addressName;
136. mHandler.sendMessage(msg);
137. }
138. };
139. private Handler mHandler = new Handler() {
140. @Override
141. public void handleMessage(Message msg) {
142. switch (msg.what) {
143. case MSG\_VIEW\_LONGPRESS:// 处理长按时间返回位置信息
144. {
145. if (null == locPoint)
146. return;
147. new Thread(getAddressName).start();
148. desText.setVisibility(View.VISIBLE);
149. desText.setText(lost\_tips);
150. mMapCtrl.animateTo(locPoint);
151. mapView.invalidate();
152. }
153. break;
154. case MSG\_VIEW\_ADDRESSNAME:
155. desText.setText((String) msg.obj);
156. desText.setVisibility(View.VISIBLE);
157. if (statusBarHeight == 0) {
158. Rect frame = new Rect();
159. getWindow().getDecorView().getWindowVisibleDisplayFrame(
160. frame);
161. statusBarHeight = frame.top;
162. point\_Y -= statusBarHeight / 2;
163. }
164. break;
165. case MSG\_GONE\_ADDRESSNAME:
166. desText.setVisibility(View.GONE);
167. break;
168. }
169. }
170. };
171. // 关闭程序也关闭定位
172. @Override
173. protected void onDestroy() {
174. // TODO Auto-generated method stub
175. super.onDestroy();
176. myLocation.destoryLocationManager();
177. }
178. }

   

六：在AndroidManifest.xml中不要忘了要添加访问网络和启动定位等的几个权限已经google地图库

 

Xml代码  [![收藏代码](http://104zz.iteye.com/images/icon_star.png)]()

01. &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
02. &lt;uses-permission android:name="android.permission.ACCESS\_NETWORK\_STATE"/&gt;
03. &lt;uses-permission android:name="android.permission.ACCESS\_COARSE\_LOCATION"/&gt;
04. &lt;uses-permission android:name="android.permission.ACCESS\_FINE\_LOCATION"/&gt;
05. &lt;!--在application里面添加google地图库如下（一定要记得添加）：--&gt;
06. &lt;application android:icon="@drawable/icon" android:label="@string/app\_name"&gt;
07. &lt;uses-library android:name="com.google.android.maps" /&gt;
08. &lt;activity android:name="com.android.googlemap.MyMapActivity"  android:screenOrientation="portrait"
09. android:label="@string/app\_name"&gt;
10. &lt;intent-filter&gt;
11. &lt;action android:name="android.intent.action.MAIN" /&gt;
12. &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
13. &lt;/intent-filter&gt;
14. &lt;/activity&gt;
15. &lt;/application&gt;

 

 

七：运行效果：

1

![](http://dl.iteye.com/upload/attachment/0074/0176/fc4f77f2-c90e-3bac-b8ff-d05a34bc3ed4.png)

2以后后重新获取如下：  
 

 

![](http://dl.iteye.com/upload/attachment/0074/0178/5c472c06-ce5e-3883-9725-a12e30190dd6.png)

提示：如果没有出现地图只出现地址信息背景是网格的，那就是key的问题，根据开始的方法找到自己开发的eclipse中sdk的debug keystore位置重新申请key即可