标签:
包含了百度地图的定位,覆盖物,poi搜索,路线搜索,地理编码等功能
<span style="font-family:Microsoft YaHei;"><?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.bmaptest" android:versionCode="1" android:versionName="1.0" > <!-- 百度地图权限 --> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.USE_CREDENTIALS" /> <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" /> <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.BROADCAST_STICKY" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!-- 百度地图定位功能所需权限 --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <permission android:name="android.permission.BAIDU_LOCATION_SERVICE" /> <uses-permission android:name="android.permission.BAIDU_LOCATION_SERVICE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_GPS"/> <uses-permission android:name="android.permission.READ_LOGS" /> <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="15" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name="com.example.bmaptest.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> <service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote" > <intent-filter> <action android:name="com.baidu.location.service_v2.2" > </action> </intent-filter> </service> <!-- meta-data需要写在application中 --> <meta-data android:name="com.baidu.lbsapi.API_KEY" android:value="6Hkv9hnwUfcG8X5LiPW7548z"/> </application> </manifest> </span>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <LinearLayout android:id="@+id/l1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/dingwei" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="定位" android:layout_weight="1" android:textSize="10sp"/> <Button android:id="@+id/poisearch" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="POI搜索" android:layout_weight="1" android:textSize="10sp"/> <Button android:id="@+id/routesearch" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="路线搜索" android:layout_weight="1" android:textSize="10sp"/> <Button android:id="@+id/geocode" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="地理编码" android:layout_weight="1" android:textSize="10sp"/> </LinearLayout> <com.baidu.mapapi.map.MapView android:layout_below="@id/l1" android:id="@+id/bmapView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:clickable="true" /> </RelativeLayout>
<span style="font-family:Microsoft YaHei;">package com.example.bmaptest; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener; import com.baidu.mapapi.map.BaiduMap.OnMarkerDragListener; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.InfoWindow; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.Marker; import com.baidu.mapapi.map.MarkerOptions; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.map.OverlayOptions; import com.baidu.mapapi.map.TextOptions; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.overlayutil.PoiOverlay; import com.baidu.mapapi.overlayutil.TransitRouteOverlay; import com.baidu.mapapi.search.core.CityInfo; import com.baidu.mapapi.search.core.PoiInfo; import com.baidu.mapapi.search.core.SearchResult; import com.baidu.mapapi.search.geocode.GeoCodeOption; import com.baidu.mapapi.search.geocode.GeoCodeResult; import com.baidu.mapapi.search.geocode.GeoCoder; import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener; import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult; import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener; import com.baidu.mapapi.search.poi.PoiCitySearchOption; import com.baidu.mapapi.search.poi.PoiDetailResult; import com.baidu.mapapi.search.poi.PoiDetailSearchOption; import com.baidu.mapapi.search.poi.PoiResult; import com.baidu.mapapi.search.poi.PoiSearch; import com.baidu.mapapi.search.route.DrivingRouteResult; import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener; import com.baidu.mapapi.search.route.PlanNode; import com.baidu.mapapi.search.route.RoutePlanSearch; import com.baidu.mapapi.search.route.TransitRoutePlanOption; import com.baidu.mapapi.search.route.TransitRouteResult; import com.baidu.mapapi.search.route.WalkingRouteResult; import com.example.bmaptest.R; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements BDLocationListener,OnClickListener{ private MapView mMapView; private BaiduMap mBaiduMap; private LatLng point; private OverlayOptions option; private Marker marker; private OverlayOptions textOption; /** * 定位的客户端 */ private LocationClient mLocationClient; /** * 当前定位的模式 */ // private LocationMode mCurrentMode = LocationMode.NORMAL; /*** * 是否是第一次定位 */ private volatile boolean isFristLocation = true; private com.baidu.mapapi.search.poi.PoiSearch mPoiSearch; /** * 初始化定位相关代码 */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //在使用SDK各组件之前初始化context信息,传入ApplicationContext //注意该方法要再setContentView方法之前实现 SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_main); Button dingweiButton = (Button)findViewById(R.id.dingwei); dingweiButton.setOnClickListener(this); Button poisearchButton = (Button)findViewById(R.id.poisearch); poisearchButton.setOnClickListener(this); Button routesearchButton = (Button)findViewById(R.id.routesearch); routesearchButton.setOnClickListener(this); Button geocodeButton = (Button)findViewById(R.id.geocode); geocodeButton.setOnClickListener(this); //获取地图控件引用 mMapView = (MapView) findViewById(R.id.bmapView); mBaiduMap = mMapView.getMap(); //普通地图 mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL); //卫星地图 // mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE); //开启交通图 mBaiduMap.setTrafficEnabled(true); //定义Maker坐标点 point = new LatLng(39.963175, 116.400244); //构建Marker图标 BitmapDescriptor bitmap = BitmapDescriptorFactory .fromResource(R.drawable.ic_launcher); option = new MarkerOptions() .position(point) //设置marker的位置 .icon(bitmap) //设置marker图标 .zIndex(9) //设置marker所在层级 .draggable(true); //设置手势拖拽 //将marker添加到地图上 marker = (Marker)(mBaiduMap.addOverlay(option)); mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker arg0) { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "OnMarkerClick", Toast.LENGTH_SHORT) .show(); //创建InfoWindow展示的view TextView textView = new TextView(getApplicationContext()); textView.setText("marker"); //创建InfoWindow , 传入 view, 地理坐标, y 轴偏移量 InfoWindow mInfoWindow = new InfoWindow(textView, point, 0); //显示InfoWindow mBaiduMap.showInfoWindow(mInfoWindow); return false; } }); //调用BaiduMap对象的setOnMarkerDragListener方法设置marker拖拽的监听 mBaiduMap.setOnMarkerDragListener(new OnMarkerDragListener() { public void onMarkerDrag(Marker marker) { //拖拽中 Toast.makeText(MainActivity.this, "onMarkerDrag", Toast.LENGTH_SHORT) .show(); } public void onMarkerDragEnd(Marker marker) { //拖拽结束 Toast.makeText(MainActivity.this, "onMarkerDragEnd", Toast.LENGTH_SHORT) .show(); } public void onMarkerDragStart(Marker marker) { //开始拖拽 Toast.makeText(MainActivity.this, "onMarkerDragStart", Toast.LENGTH_SHORT) .show(); } }); textOption = new TextOptions() .bgColor(0xAAFFFF00) .fontSize(24) .fontColor(0xFFFF00FF) .text("百度地图SDK") .rotate(-30) .position(point); //在地图上添加该文字对象并显示 mBaiduMap.addOverlay(textOption); // 开启定位图层 mBaiduMap.setMyLocationEnabled(true); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.dingwei: initMyLocation(); break; case R.id.poisearch: poiSearch(); break; case R.id.routesearch: routeSearch(); break; case R.id.geocode: geocodeSearch(); break; default: break; } } private void geocodeSearch() { // TODO Auto-generated method stub GeoCoder mSearch = GeoCoder.newInstance(); mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() { @Override public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) { if (arg0 == null || arg0.error != SearchResult.ERRORNO.NO_ERROR) { //没有找到检索结果 } //获取反向地理编码结果 } @Override public void onGetGeoCodeResult(GeoCodeResult arg0) { if (arg0 == null || arg0.error != SearchResult.ERRORNO.NO_ERROR) { //没有检索到结果 Toast.makeText(MainActivity.this, "没有检索到结果", Toast.LENGTH_SHORT).show(); } //获取地理编码结果 Toast.makeText(MainActivity.this,arg0.getLocation().toString(), Toast.LENGTH_SHORT).show(); } }); mSearch.geocode(new GeoCodeOption() .city("北京") .address("海淀区上地十街10号")); // mSearch.destroy(); } private void routeSearch() { // TODO Auto-generated method stub //第一步,创建检索实例 RoutePlanSearch mSearch = RoutePlanSearch.newInstance(); //设置监听器 mSearch.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() { @Override public void onGetWalkingRouteResult(WalkingRouteResult arg0) { // TODO Auto-generated method stub } @Override public void onGetTransitRouteResult(TransitRouteResult arg0) { if (arg0 == null || arg0.error != SearchResult.ERRORNO.NO_ERROR) { Toast.makeText(MainActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show(); } if (arg0.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) { //起终点或途经点地址有岐义,通过以下接口获取建议查询信息 //result.getSuggestAddrInfo() Toast.makeText(MainActivity.this, "起终点或途经点地址有岐义", Toast.LENGTH_SHORT).show(); return; } if (arg0.error == SearchResult.ERRORNO.NO_ERROR) { Toast.makeText(MainActivity.this, "结果如下", Toast.LENGTH_SHORT).show(); TransitRouteOverlay overlay = new TransitRouteOverlay(mBaiduMap); mBaiduMap.setOnMarkerClickListener(overlay); overlay.setData(arg0.getRouteLines().get(0)); overlay.addToMap(); overlay.zoomToSpan(); } } @Override public void onGetDrivingRouteResult(DrivingRouteResult arg0) { // TODO Auto-generated method stub } }); //准备检索起、终点信息; PlanNode stNode = PlanNode.withCityNameAndPlaceName("北京", "龙泽"); PlanNode enNode = PlanNode.withCityNameAndPlaceName("北京", "西单"); //发起公交线路规划检索; mSearch.transitSearch((new TransitRoutePlanOption()) .from(stNode) .city("北京") .to(enNode)); //释放检索实例; // mSearch.destroy(); } private void poiSearch() { mPoiSearch = PoiSearch.newInstance(); //第二步,设置POI检索监听者 mPoiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() { @Override public void onGetPoiResult(PoiResult arg0) { if (arg0 == null || arg0.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) { Toast.makeText(MainActivity.this, "未找到结果", Toast.LENGTH_LONG) .show(); return; } if (arg0.error == SearchResult.ERRORNO.NO_ERROR) { mBaiduMap.clear(); PoiOverlay overlay = new MyPoiOverlay(mBaiduMap); mBaiduMap.setOnMarkerClickListener(overlay); overlay.setData(arg0); overlay.addToMap(); overlay.zoomToSpan(); return; } if (arg0.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) { // 当输入关键字在本市没有找到,但在其他城市找到时,返回包含该关键字信息的城市列表 String strInfo = "在"; for (CityInfo cityInfo : arg0.getSuggestCityList()) { strInfo += cityInfo.city; strInfo += ","; } strInfo += "找到结果"; Toast.makeText(MainActivity.this, strInfo, Toast.LENGTH_LONG) .show(); } } @Override public void onGetPoiDetailResult(PoiDetailResult arg0) { // TODO Auto-generated method stub if (arg0.error != SearchResult.ERRORNO.NO_ERROR) { Toast.makeText(MainActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT) .show(); } else { Toast.makeText(MainActivity.this, arg0.getName() + ": " + arg0.getAddress(), Toast.LENGTH_SHORT) .show(); } } }); //第三步,发起检索请求; mPoiSearch.searchInCity((new PoiCitySearchOption()) .city("北京") .keyword("美食") .pageNum(10)); //第四步,释放POI检索实例; // mPoiSearch.destroy(); } private class MyPoiOverlay extends PoiOverlay { public MyPoiOverlay(BaiduMap baiduMap) { super(baiduMap); } @Override public boolean onPoiClick(int index) { super.onPoiClick(index); PoiInfo poi = getPoiResult().getAllPoi().get(index); // if (poi.hasCaterDetails) { mPoiSearch.searchPoiDetail((new PoiDetailSearchOption()) .poiUid(poi.uid)); // } return true; } } private void initMyLocation() { // 定位初始化 mLocationClient = new LocationClient(this.getApplicationContext()); mLocationClient.registerLocationListener(this); // 设置定位的相关配置 LocationClientOption option = new LocationClientOption(); option.setOpenGps(true);// 打开gps option.setCoorType("bd09ll"); // 设置坐标类型 option.setScanSpan(1000); mLocationClient.setLocOption(option); mLocationClient.requestLocation(); mLocationClient.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onDestroy() { super.onDestroy(); //在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理 mMapView.onDestroy(); } @Override protected void onResume() { super.onResume(); //在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理 mMapView.onResume(); } @Override protected void onPause() { super.onPause(); //在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理 mMapView.onPause(); } @Override public void onReceiveLocation(BDLocation arg0) { // TODO Auto-generated method stub StringBuffer sb = new StringBuffer(256); sb.append("time : "); sb.append(arg0.getTime()); sb.append("\nerror code : "); sb.append(arg0.getLocType()); sb.append("\nlatitude : "); sb.append(arg0.getLatitude()); sb.append("\nlontitude : "); sb.append(arg0.getLongitude()); sb.append("\nradius : "); sb.append(arg0.getRadius()); System.out.println(sb); // 构造定位数据 MyLocationData locData = new MyLocationData.Builder() .accuracy(arg0.getRadius()) // 此处设置开发者获取到的方向信息,顺时针0-360 .direction(100).latitude(arg0.getLatitude()) .longitude(arg0.getLongitude()).build(); // 设置定位数据 mBaiduMap.setMyLocationData(locData); // 设置定位图层的配置(定位模式,是否允许方向信息,用户自定义定位图标) LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude()); BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory .fromResource(R.drawable.pause); option = new MarkerOptions() .position(latLng) //设置marker的位置 .icon(mCurrentMarker) //设置marker图标 .draggable(false); //设置手势拖拽 //将marker添加到地图上 mBaiduMap.addOverlay(option); // MyLocationConfiguration config = new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker); // mBaiduMap.setMyLocationConfiguration(); // 当不需要定位图层时关闭定位图层 mBaiduMap.setMyLocationEnabled(false); } } </span>
标签:
原文地址:http://blog.csdn.net/u010335298/article/details/43304731