最近在做android地图的应用,之前就做过,可是这次再做,发现google很强大,更新太快了,网上流传的那些都落伍了,google map都更新到V2这个版本了,
这是我自己花费无数心血的成果,参考了国内外好多人写的东西,
1.首先安装Google Play services SDK
Google Maps Android API是作为这个SDK的一部分发行的。
这个安装是通过Android SDK Manager进行,配置好之后的Eclipse上面应该有Android SDK Manager的图标,一般的SDK版本安装和更新都在这里进行。
安装和更新Extras下的Google Play services即可。
Google Maps Android API是作为这个SDK的一部分发行的。
[attach]/data/attachment/forum/201303/eyeandroid.com62910122141101.png[/attach]
2.获取API key
获取Maps API key需要两样东西:应用的signing certificate和它的package name。
获取这个key之后,把它加在应用程序的AndroidManifest.xml文件里即可。
为应用获取一个key还是需要好几个步骤的,下面详细说明:
获取数字证书(digital certificate)信息
数字证书有Debug和Release两种,下面主要说Debug的。
要获取一个叫做SHA-1 fingerprint的东西,作为数字证书的一个简短代表。
这个指纹(fingerprint)是通过一个哈希算法得到的字符串,为了得到你的证书的SHA-1 fingerprint,首先要找到你的debug keystore 文件,文件名叫debug.keystore。
默认情况下它和虚拟机AVD存放在一起,win7下的路径是:C:\Users\your_user_name\.android\,也可以通过Eclipse中的Windows > Prefs > Android > Build来查看这个路径。
然后,在cmd命令行里运行下列命令:
keytool -list -v -keystore "C:\Users\your_user_name\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
就显示一大堆东西,其中就有证书指纹:
[attach]/data/attachment/forum/201303/eyeandroid.com62910122141102.png[/attach]
SHA1那一行就包含了证书的SHA-1 fingerprint,是二十段用冒号割开的数字段,每段是两个十六进制的数。
在Google APIs Console上创建API Project
在Google APIs Console上创建项目,并且注册Maps API。
首先,去这个网址:https://code.google.com/apis/console/
用Gmail的账户登录,如果是第一次的话,需要创建项目,默认情况会创建一个叫做API Project的项目。
点击左边的Services,会在中间看到很多的APIs和Services,找到Google Maps Android API v2,然后把它设置成on,需要接受一些服务条款。
获得API Key
在左边的导航条中选择API Access。
在出来的页面中选择Create New Android Key...就可以生成key了:
[attach]/data/attachment/forum/201303/eyeandroid.com62910122141103.png[/attach]
然后在对话框中填入:SHA-1 指纹, 分号隔开,然后是应用的 package name.然后就会生成一个Key。
一定记得要用分号隔开。
比如:
[attach]/data/attachment/forum/201303/eyeandroid.com62910122141104.png[/attach]
3.把API Key加入应用程序
首先,建立虚拟设备AVD和应用程序。
关于AVD,官方文档并没详细介绍,我后面会有说明。
建立好应用程序,注意包名应该和申请key时候的包名一致。
之后修改AndroidManifest.xml文件:
3.1.在<application>元素中加入子标签
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your_api_key"/>
其中your_api_key置换成自己申请的API Key。
3.2.加入一些许可信息
<permission android:name="com.example.mapdemo.permission.MAPS_RECEIVE" android:protectionLevel="signature"/> <uses-permission android:name="com.example.mapdemo.permission.MAPS_RECEIVE"/>
其中com.example.mapdemo换成自己的包名。
4. AndroidManifest.xml中的其他具体设置
许可设置
<uses-permission> 作为<manifest> 的子元素,需要加入下列一些:
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
OpenGL ES V2特性支持
同样也是作为<manifest> 的子元素。
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
5.加上地图
首先布局文件:
<?xml version="1.0" encoding="utf-8"?> <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.MapFragment"/>
这是代码
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.model.LatLng;
import android.app.Dialog;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap mMap;
private String TAG = "MainActivity";
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// mLocationSource = new LongPressLocationSource();
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else {
setUpMapIfNeeded();
testLocation();
}
// locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// locationManager.requestLocationUpdates(
// LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); // You
// can
// also
// use
// LocationManager.GPS_PROVIDER
// and
// LocationManager.PASSIVE_PROVIDER
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
// mLocationSource.onResume();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
// setUpMap();
}
}
}
public void testLocation()
{
// Enabling MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
private void setUpMap() {
mMap.setLocationSource(mLocationSource);
mMap.setOnMapLongClickListener(mLocationSource);
mMap.setMyLocationEnabled(true);
}
/**
* A {@link LocationSource} which reports a new location whenever a user
* long presses the map at the point at which a user long pressed the map.
*/
private static class LongPressLocationSource implements LocationSource,
OnMapLongClickListener {
private OnLocationChangedListener mListener;
/**
* Flag to keep track of the activity's lifecycle. This is not strictly
* necessary in this case because onMapLongPress events don't occur
* while the activity containing the map is paused but is included to
* demonstrate best practices (e.g., if a background service were to be
* used).
*/
private boolean mPaused;
@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
}
@Override
public void deactivate() {
mListener = null;
}
@Override
public void onMapLongClick(LatLng point) {
if (mListener != null && !mPaused) {
Location location = new Location("LongPressLocationProvider");
location.setLatitude(point.latitude);
location.setLongitude(point.longitude);
location.setAccuracy(100);
mListener.onLocationChanged(location);
}
}
public void onPause() {
mPaused = true;
}
public void onResume() {
mPaused = false;
}
}
private LongPressLocationSource mLocationSource;
@Override
protected void onPause() {
super.onPause();
// mLocationSource.onPause();
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// LatLng latLng = new LatLng(location.getLatitude(),
// location.getLongitude());
// CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng,
// 10);
// Log.i(TAG, "onLocationChanged");
//
// mMap.animateCamera(cameraUpdate);
// locationManager.removeUpdates(this);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
这是布局
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
这是配置文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hao.map.test4"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The following two permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<permission
android:name="com.hao.map.test4.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.hao.map.test4.permission.MAPS_RECEIVE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-library android:name="com.google.android.maps" />
<activity
android:name="com.hao.map.test4.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value=http://blog.csdn.net/haojunming/article/details/"AIzaSyCbXfAnx4TBbhZxPiA_u-nXxQF_hWeSX-4" />
</application>
</manifest>
目前国内这一块对google map V2版本介绍的不多,问题不少,大家可以相互讨论