概述,為了滿足項目的需求,在項目當中集成了百度map,除了簡單的定位,還包含了poi搜索,地理編碼、周邊搜索等功能;
1.集成,首先要去百度地圖開發(fā)者平臺成為開發(fā)者,并申請appkey,規(guī)則是sha1 + packageName;
如果不知道怎么申請key,可以看說明,例如
http://lbsyun.baidu.com/index.php?title=androidsdk/guide/key 如果覺得太長不看也沒關系,可以直接將baiduMap demo運行一遍,當然項目能運行,但并不能跑通,可以觀察到在android monitor當中會告訴你的sha1以及包名,那么就直接用這個去申請創(chuàng)建自己項目即可;說點題外話,將其他的項目移植到自己的Android studio當中,那么需要改動的地方有幾個,如圖 :
將項目build.gradle的compile 改成自己項目中的compile版本,我這邊是2.3.1那么直接改,其次就是在gredle文件下有個gradle-wrapper.properties文件,也改成自己的,我這邊是3.3;好了轉(zhuǎn)回正文,開始我們項目集成;
(1).下載demo,將libs庫當中jar包以及.so文件移植到項目中jniLibs目錄下;
(2).androidManifest.xml文件當中將必須的permission service copy;
(3).開始項目代碼的編寫;
private void initMap() {
// 地圖初始化
mMapView = (MapView) findViewById(R.id.bmapView);
mBaiduMap = mMapView.getMap();
// 開啟定位圖層
mBaiduMap.setMyLocationEnabled(true);
// 定位初始化
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 打開gps
option.setCoorType("bd09ll"); // 設置坐標類型
option.setScanSpan(1000);//設置掃描頻率,值<1000ms將不執(zhí)行
option.setIsNeedLocationPoiList(true); //獲取定位周邊poi信息
mLocClient.setLocOption(option);
mLocClient.start();
}
這里的myListener需要去implement BDLocationListener并重寫onReceiveLocation,重點是可以獲取poi列表,我們一般定位是基于手機,不單單是wifi、gps、基站等;那么怎么能比較準確呢?
/**
* 定位SDK監(jiān)聽函數(shù)
*/
public class LocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
// map view 銷毀后不在處理新接收的位置
if (location == null || mMapView == null) {
return;
}
MyLocationData locData = new MyLocationData.Builder()
/**周邊范圍*/
.accuracy(location.getRadius())
// 此處設置開發(fā)者獲取到的方向信息,順時針0-360
.direction(100).
latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
mBaiduMap.setMyLocationData(locData);
if (isFirstLoc) {
isFirstLoc = false;
/**latlng是經(jīng)緯度坐標的類*/
LatLng ll = new LatLng(location.getLatitude(),
location.getLongitude());
MapStatus.Builder builder = new MapStatus.Builder();
builder.target(ll).zoom(18.0f);
mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
List poiList = location.getPoiList();
if(poiList != null && poiList.size() > 0) {
for (int i = 0; i< poiList.size();i ++) {
Log.e(Tag,poiList.get(i).address);
Log.e(Tag,poiList.get(i).name);
//可以將address和name信息拼接成adapter的bean,并增加到列表供用戶選擇
}
}
}
}
}
我這邊提供一個簡單的layout,如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.baidu.mapapi.map.MapView
android:layout_width="match_parent"
android:layout_height="260dp"
android:id="@+id/map_view"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view"/>
</LinearLayout>
當然我不是這么做的,因為還有一種更好的方法,可以提供更加準確的poi列表,這邊是使用定位后的經(jīng)緯度反地理編碼后的poi列表,而且用戶在移動mapView的同時,隨時獲取map中點附件poi列表