Android基于Google map V2地图开发基础

参考资料

google map v2 api网址:

https://developers.google.com/maps/documentation/android/map

google map v2 官方用例网址:

https://developers.google.com/maps/documentation/android/utility/

基础开发环境配置网址:

http://www.cnblogs.com/linzhichao86/p/Android_GoogleMap.html

http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/

其他的参考资料网址:

http://blog.csdn.net/mad1989/article/category/1121318

http://tech.it168.com/a2012/0309/1322/000001322925.shtml

 

 

知识整理

1.安装google setting 和 google play store 

   请确保你的手机上安装这2个软件(google settings 就是google play store服务)

2.下载 Google play services

   打开Eclipse ⇒ Windows ⇒ Android SDK Manager,选择Extra选项下的Google play services,下载该选项。

  下载完成后该lib位置在

  android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib

  为项目引用该lib,Eclipse ⇒ Android ⇒ Library ,选择add

3.SHA获取

   SHA网络上获取有几种方式,这边列出2种。

(1)Keytool

     Keytool这个文件一般位于%JAVA_HOME%/bin目录下,如果是Linux系统,则位于 

$JAVA_HOME/bin下的,比如windows下在C:\programs\Java\jdk1.6.0_18\bin下。

输入命令:

Window系统:

    Keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" 

    -alias androiddebugkey -storepass android -keypass android

linux or Mac OS系统:

    keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey 

    -storepass android -keypass android

(2)较为快捷的方式

Eclipse ⇒ Android⇒ Build,SHA1 fingerprint的值

4.注册Google mail账号

   需要google mail的账号,当然如果你有,就可以直接跳过这步骤了。

5.Google map v2 key值获取

  终于快结束了环境配置了,Key值获取的网址如下:

https://code.google.com/apis/console/

打开google map android api v2服务,接着选择API access,点击选择Create new Android key.....,在弹出框内,输入获取SHA,输入格式为SHA;你的项目包名(如果你换掉IDE(eclipse)或者换掉包名都需要重新申请——我没试过换掉eclipse是否要重新申请的情况)

代码片段:

1.AndroidMainfest.xml配置文件配置

  

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.googlemap"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="9" />

    <!--begin-->
    <permission
        android:name="com.googlemap.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />
  <uses-permission android:name="com.map.permission.MAPS_RECEIVE" />
   <!--end api可下载地图,注意com.googlemap替换为项目包名----------------------->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>  
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!--允许API可存取Google web-based 服务-->
  <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <!--允许网络定位-->
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!--允许GPS定位-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <!--Google Maps Android API 2会使用到OpenGL ES version 2,所以添加此特性,以免Google Play Store 认为APP不支持OpenGL ES version 2-->
    <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" >
    
    
      <!--注意com.googlemap替换为项目包名,android:value值更改为申请的KEY-->  
      <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your key" />
        
        <activity
            android:name="com.googlemap.MainActivity2"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

 

 

 

2.Xml布局文件

 

 <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:map="http://schemas.android.com/apk/res-auto" 
     android:layout_width="match_parent"
     android:layout_height="match_parent"
>
    <!--sdk 3.1即(API12)之前的版本为com.google.android.gms.maps.SupportMapFragment,其他版本则为com.google.android.gms.maps.MapFragment-->
    <fragment
        android:id="@+id/googlemap"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />
   </RelativeLayout>

 

 

 

 

 

3.地图初始显示

  

 /**sdk 3.1即(API12)之前的版本需要继承FragmentActivity,其他版本则无需*/
  public class MainActivity extends FragmentActivity {
     @Override
     protected void onCreate(Bundle arg0) {
         super.onCreate(arg0);
         setContentView(R.layout.main);
     }
}

 

 

 

4.定位

     定位自己当前的位置,使用到LocationManager类,代码如下:

 

    

 /**初始化GoogleMap*/
if (null == mGoogleMap) {//此处初始化方法为sdk3.1(API12)之前的版本
    mGoogleMap = ((SupportMapFragment)   getSupportFragmentManager()
.findFragmentById(R.id.nav_testmap)).getMap();
}
 /**if (null == mGoogleMap) {
    mGoogleMap = 
            ((MapFragment) this.findFragmentById(R.id.nav_testmap)).getMap();
}*/
    
 /**定位自己当前位置*/
void getPointLocation() {
      Criteria criteria = new Criteria();
     // ACCURACY_FINE 较高精确度
     criteria.setAccuracy(Criteria.ACCURACY_FINE);
     criteria.setAltitudeRequired(false);
     criteria.setBearingRequired(false);
     criteria.setCostAllowed(true);
     criteria.setPowerRequirement(Criteria.POWER_LOW);
     //获取LocationManager对象
     locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
     //provider的Criteria.ACCURACY_FINE精确度不是最精确的
     //若正式环境改为精确度最高的
     //LocationManager.GPS_PROVIDER
     provider = locationManager.getBestProvider(criteria, true);
 
    locationListener = new LocationListener() {
 
      @Override
      public void onStatusChanged(String provider, int status,
         Bundle extras) {
      }
 
      @Override
      public void onProviderEnabled(String provider) {
        }
 
     @Override
    public void onProviderDisabled(String provider) {
       }
 
     @Override
     public void onLocationChanged(Location location) {
   	 //获取当前位置
        lat = location.getLatitude();
        lng = location.getLongitude();
      }
     };
         //返回缓存中的位置信息(上次获取的位置信息)
 location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
 location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
 //注册周期性位置更新,第二个参数为最短更新时间,第三个参数为最短更新距离
 locationManager.requestLocationUpdates(provider, 0, 0,locationListener);
}
 
//移除位置监听
locationManager.removeUpdates(locationListener);
 

 

 

 

5.标识

   标识位置,使用到的类Marker,代码如下:

   

 marker = mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("lat:" + lat + " lng:" + lng).snippet("我的位置"));

 

 

   你可以设置markericon图标

 

// GREEN color icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// Changing your own marker icon
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_marker_icon)));

 

 

6.镜头定位移动

 

cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(17).bearing(0).tilt(20).build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

 

 

 

7.路线绘制

  start = new LatLng(22.43040815, 114.20932812);
  			   end = new LatLng(22.410410, 114.247622);
    //移除地图上的覆盖物
  mGoogleMap.clear();
  wayLine(start, end);

    /**路线绘制*/
    private void wayLine(LatLng start, LatLng end) {
  	  String url = navUtil.getDirectionsUrl(start, end);
  	  NavUtil.googleMapRouteTask gRouteTask = navUtil.new googleMapRouteTask(
  				url);
  	  gRouteTask.execute(url);
  }
  
    /**组合成googlemap direction所需要的url*/
	public String getDirectionsUrl(LatLng origin, LatLng dest) {
		// Origin of route
		String str_origin = "origin=" + origin.latitude + ","
				+ origin.longitude;

		// Destination of route
		String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

		// Sensor enabled
		String sensor = "sensor=false";

		// Travelling Mode
		String mode = "mode=driving";

		// String waypointLatLng = "waypoints="+"40.036675"+","+"116.32885";

		// 如果使用途径点,需要添加此字段
		// String waypoints = "waypoints=";

		String parameters = null;
		// Building the parameters to the web service

		parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
		// parameters = str_origin + "&" + str_dest + "&" + sensor + "&"
		// + mode+"&"+waypoints;

		// Output format
		// String output = "json";
		String output = "xml";

		// Building the url to the web service
		String url = "https://maps.googleapis.com/maps/api/directions/"
				+ output + "?" + parameters;
		System.out.println("getDerectionsURL--->: " + url);
		return url;
	}
  	
     /**异步请求获取导航数据*/
	public class googleMapRouteTask extends
			AsyncTask<String, Void, List<LatLng>> {
		HttpClient client;
		String url;
		List<LatLng> routes = null;

		public googleMapRouteTask(String url) {
			this.url = url;
		}

		@Override
		protected List<LatLng> doInBackground(String... params) {
			HttpGet get = new HttpGet(url);
			try {
				HttpResponse response = client.execute(get);
				int statusecode = response.getStatusLine().getStatusCode();
				System.out.println("response:" + response + "      statuscode:"
						+ statusecode);
				if (statusecode == 200) {

					String responseString = EntityUtils.toString(response
							.getEntity());

					int status = responseString.indexOf("<status>OK</status>");
					System.out.println("status:" + status);
					if (-1 != status) {
						int pos = responseString.indexOf("<overview_polyline>");
						pos = responseString.indexOf("<points>", pos + 1);
						int pos2 = responseString.indexOf("</points>", pos);
						responseString = responseString
								.substring(pos + 8, pos2);
						routes = decodePoly(responseString);
					} else {
						// 错误代码,
						return null;
					}
				} else {
					// 请求失败
					return null;
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("doInBackground:"+routes);
			return routes;
		}

		@Override
		protected void onPreExecute() {
			client = new DefaultHttpClient();
			client.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
					15000);
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(List<LatLng> routes) {
			super.onPostExecute(routes);
			if (routes == null) {
				// 导航失败
				Toast.makeText(context, "没有搜索到线路", Toast.LENGTH_LONG).show();
			}
			else{
				//地图描点
				PolylineOptions lineOptions = new PolylineOptions();
				lineOptions.addAll(routes);
				lineOptions.width(3);
				lineOptions.color(Color.BLUE);
				mGoogleMap.addPolyline(lineOptions);
				//定位到第0点经纬度
			mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(routes.get(0)));
			}
		}
	}

  
    /**解析返回xml中overview_polyline的路线编码*/
	private List<LatLng> decodePoly(String encoded) {
		List<LatLng> poly = new ArrayList<LatLng>();
		int index = 0, len = encoded.length();
		int lat = 0, lng = 0;
		while (index < len) {
			int b, shift = 0, result = 0;
			do {
				b = encoded.charAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);
			int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
			lat += dlat;
			shift = 0;
			result = 0;
			do {
				b = encoded.charAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);
			int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
			lng += dlng;
			LatLng p = new LatLng((((double) lat / 1E5)),
					(((double) lng / 1E5)));
			poly.add(p);
		}
		return poly;
	}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值