1. 程式人生 > >基於百度地圖SDK整合的一些功能

基於百度地圖SDK整合的一些功能

    最近開發的專案用到了地圖,並在地圖上顯示某些座標位置的標記圖示,點選圖示來顯示此座標處的一些資訊,之後我從百度地圖卡房平臺下載了百度地圖的SDK和Demo,並結合API總結了一下幾點內容,實現了下面的幾個功能:

(1)最基本功能,定位到當前位置 並獲取當前的位置資訊
(2)實現了開啟地圖顯示自定義座標點位置
(3)實現了為地圖上的某個座標點新增一個Marker圖示
(4)在地圖上標註多個覆蓋點 並且有點選事件,點選每個點顯示某點的自定義資訊
(5)實現了在地圖上畫幾何圖形覆蓋在一定的座標區域內
下面我們來看下具體怎麼整合實現的:
一 、首先在百度開放平臺下載jar包和.so檔案放到工程專案裡面
二 、在AndroidManifest.xml裡新增許可權

    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />

    <!-- 這個許可權用於進行網路定位 -->

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <!-- 這個許可權用於訪問GPS定位 -->

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<!-- 用於訪問wifi網路資訊,wifi資訊會用於進行網路定位 --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- 獲取運營商資訊,用於支援提供運營商資訊相關的介面 --> <uses-permission android:name="android.permission.ACCESS_NETWORK_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.INTERNE" /> //設定KEY <meta-data android:name="com.baidu.lbsapi.API_KEY" android:value="yplInAzbWE0uOBMxfSenlA9YXsjBZdfM" />

三 、定義一個Application類

public class TestApplication extends Application {



    @Override

    public void onCreate() {

        super.onCreate();

        // 在使用 SDK 各組間之前初始化 context 資訊,傳入 ApplicationContext

        SDKInitializer.initialize(this);

        //自4.3.0起,百度地圖SDK所有介面均支援百度座標和國測局座標,用此方法設定您使用的座標型別.

        //包括BD09LL和GCJ02兩種座標,預設是BD09LL座標。

        SDKInitializer.setCoordType(CoordType.GCJ02);

   }
}

四 、MainActivit類實現具體功能

package com.junto.baidumaptest;



import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;



import com.baidu.location.BDLocation;

import com.baidu.location.BDLocationListener;

import com.baidu.location.LocationClient;

import com.baidu.location.LocationClientOption;

import com.baidu.mapapi.CoordType;

import com.baidu.mapapi.map.BaiduMap;

import com.baidu.mapapi.map.BitmapDescriptor;

import com.baidu.mapapi.map.BitmapDescriptorFactory;

import com.baidu.mapapi.map.MapStatus;

import com.baidu.mapapi.map.MapStatusUpdate;

import com.baidu.mapapi.map.MapStatusUpdateFactory;

import com.baidu.mapapi.map.MapView;

import com.baidu.mapapi.map.Marker;

import com.baidu.mapapi.map.MarkerOptions;

import com.baidu.mapapi.map.MyLocationConfiguration;

import com.baidu.mapapi.map.MyLocationData;

import com.baidu.mapapi.map.OverlayOptions;

import com.baidu.mapapi.map.PolygonOptions;

import com.baidu.mapapi.map.Stroke;

import com.baidu.mapapi.model.LatLng;



import java.util.ArrayList;

import java.util.List;



public class MainActivity extends Activity {



    private MapView mapView;

    private BaiduMap mBaiduMap;

    // 定位相關

    LocationClient mlocationClient;

    private BitmapDescriptor geo;



    private Button btn_click;

    private List<MarkerInfoUtil> infos;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        initView();

        center();

//        setMarker1();

//        setPolyline();

//        locate();

    }



    private void initView() {

        mapView = (MapView) findViewById(R.id.mapView);

        mBaiduMap = mapView.getMap();

        //普通地圖

        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);

        // 開啟定點陣圖層

        mBaiduMap.setMyLocationEnabled(true);



        btn_click = (Button) findViewById(R.id.btn_click);

        btn_click.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                locate();

            }

        });

    }



    @Override

    protected void onPause() {

        mapView.onPause();

        super.onPause();

    }



    @Override

    protected void onResume() {

        mapView.onResume();

        super.onResume();

    }



    @Override

    protected void onDestroy() {

        mapView.onDestroy();

        super.onDestroy();

        // 關閉定點陣圖層

        mBaiduMap.setMyLocationEnabled(false);

    }



    //開啟地圖顯示自定義座標點位置

    private void center() {

        Marker marker;

        //設定中心點座標 

        LatLng cenpt = new LatLng(39.142693, 117.216624);

        //構建Marker圖示

        BitmapDescriptor bitmap = BitmapDescriptorFactory

                .fromResource(R.mipmap.icon_gcoding);

        //定義地圖狀態

        MapStatus mMapStatus = new MapStatus.Builder()

                .target(cenpt)

                .zoom(18)

                .build();

        //定義MapStatusUpdate物件,以便描述地圖狀態將要發生的變化

        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);



        //構建MarkerOption,用於在地圖上新增Marker

        OverlayOptions option = new MarkerOptions()

                .position(cenpt)

                .icon(bitmap);

        //在地圖上新增Marker,並顯示

        mBaiduMap.addOverlay(option);

        //改變地圖狀態

        mBaiduMap.setMapStatus(mMapStatusUpdate);

    }



    //為地圖上的某個座標點新增一個Marker圖示

    private void setMarker1() {

        //定義Maker座標點

        LatLng point = new LatLng(39.142693, 117.216624);

        //構建Marker圖示

        BitmapDescriptor bitmap = BitmapDescriptorFactory

                .fromResource(R.mipmap.icon_gcoding);

        Marker marker;

        //構建MarkerOption,用於在地圖上新增Marker

        OverlayOptions option = new MarkerOptions()

                .position(point)

                .icon(bitmap);

        //在地圖上新增Marker,並顯示

        mBaiduMap.addOverlay(option);

    }



    //地圖上標註多個覆蓋點 並且有點選事件,點選每個點顯示某點的自定義資訊

    private void setMarker() {

        infos = new ArrayList<>();

        MarkerInfoUtil markerInfoUtil1 = new MarkerInfoUtil();

        markerInfoUtil1.setLatitude(39.93923);

        markerInfoUtil1.setLongitude(116.357428);

        markerInfoUtil1.setDescription("標誌點1");

        MarkerInfoUtil markerInfoUtil2 = new MarkerInfoUtil();

        markerInfoUtil2.setLatitude(39.91923);

        markerInfoUtil2.setLongitude(116.327428);

        markerInfoUtil2.setDescription("標誌點2");

        MarkerInfoUtil markerInfoUtil3 = new MarkerInfoUtil();

        markerInfoUtil3.setLatitude(39.89923);

        markerInfoUtil3.setLongitude(116.347428);

        markerInfoUtil3.setDescription("標誌點3");

        MarkerInfoUtil markerInfoUtil4 = new MarkerInfoUtil();

        markerInfoUtil4.setLatitude(39.89923);

        markerInfoUtil4.setLongitude(116.367428);

        markerInfoUtil4.setDescription("標誌點4");

        MarkerInfoUtil markerInfoUtil5 = new MarkerInfoUtil();

        markerInfoUtil5.setLatitude(39.91923);

        markerInfoUtil5.setLongitude(116.387428);

        markerInfoUtil5.setDescription("標誌點5");

        infos.add(markerInfoUtil1);

        infos.add(markerInfoUtil2);

        infos.add(markerInfoUtil3);

        infos.add(markerInfoUtil4);

        infos.add(markerInfoUtil5);

        for (int i = 0; i < infos.size(); i++) {

            LatLng point = new LatLng(infos.get(i).getLatitude(), infos.get(i).getLongitude());

//        }

            //定義Maker座標點

//        LatLng point = new LatLng(39.963175, 116.400244);

            //構建Marker圖示

            BitmapDescriptor bitmap = BitmapDescriptorFactory

                    .fromResource(R.mipmap.icon_gcoding);

            Marker marker;

            //構建MarkerOption,用於在地圖上新增Marker

            OverlayOptions option = new MarkerOptions()

                    .position(point)

                    .icon(bitmap);

            //在地圖上新增Marker,並顯示

            mBaiduMap.addOverlay(option);

            //新增marker

            marker = (Marker) mBaiduMap.addOverlay(option);

            //使用marker攜帶info資訊,當點選事件的時候可以通過marker獲得info資訊

            Bundle bundle = new Bundle();

            //info必須實現序列化介面

            bundle.putSerializable("info", infos.get(i));

            marker.setExtraInfo(bundle);

        }

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override

            public boolean onMarkerClick(Marker marker) {

                //從marker中獲取info資訊

                Bundle bundle = marker.getExtraInfo();

                MarkerInfoUtil infoUtil = (MarkerInfoUtil) bundle.getSerializable("info");

                Toast.makeText(MainActivity.this, infoUtil.getDescription(), Toast.LENGTH_SHORT).show();

                Log.e("tag", "Description=" + infoUtil.getDescription());

                return false;

            }

        });

    }



    //地圖上幾何覆蓋物

    private void setPolyline() {

        //定義多邊形的五個頂點

        LatLng pt1 = new LatLng(39.93923, 116.357428);

        LatLng pt2 = new LatLng(39.91923, 116.327428);

        LatLng pt3 = new LatLng(39.89923, 116.347428);

        LatLng pt4 = new LatLng(39.89923, 116.367428);

        LatLng pt5 = new LatLng(39.91923, 116.387428);

        List<LatLng> pts = new ArrayList<LatLng>();

        pts.add(pt1);

        pts.add(pt2);

        pts.add(pt3);

        pts.add(pt4);

        pts.add(pt5);

        //構建使用者繪製多邊形的Option物件

        OverlayOptions polygonOption = new PolygonOptions()

                .points(pts)

                .stroke(new Stroke(5, 0xAA00FF00))

                .fillColor(0xAAFFFF00);

        //在地圖上新增多邊形Option,用於顯示

        mBaiduMap.addOverlay(polygonOption);

    }



    //定位到當前位置 並獲取當前的位置資訊

    private void locate() {

        // 定位初始化

        mlocationClient = new LocationClient(getApplicationContext());

        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 設定定位模式  高精度

        option.setOpenGps(true); // 開啟GPRS

        option.setCoorType(String.valueOf(CoordType.GCJ02));// 返回的定位結果是百度經緯度,預設值gcj02

        option.setScanSpan(5000);// 設定發起定位請求的間隔時間為5000ms

        option.disableCache(false);// 禁止啟用快取定位

        option.setIsNeedAddress(true);// 返回的定位結果包含地址資訊

        option.setNeedDeviceDirect(true);// 返回的定位結果包含手機機頭的方向

        mlocationClient.setLocOption(option);

        mlocationClient.registerLocationListener(new BDLocationListener() {

            @Override

            public void onReceiveLocation(BDLocation result) {

                Log.e("tag", "BuildingName=" + result.getBuildingName());

                Log.e("tag", "Country=" + result.getCountry());

                Log.e("tag", "City=" + result.getCity());

                Log.e("tag", "AddrStr=" + result.getAddrStr());

                Log.e("tag", "Street=" + result.getStreet());

                Log.e("tag", "Latitude=" + result.getLatitude());//緯度

                Log.e("tag", "Longitude=" + result.getLongitude());//經度

                Log.e("tag", "Radius=" + result.getRadius());//獲取定位精度

                Log.e("tag", "Direction=" + result.getDirection());//獲取手機當前方向

                Log.e("tag", "District=" + result.getDistrict());//獲取區/縣資訊

                Log.e("tag", "Floor=" + result.getFloor());//獲取樓層資訊,僅室內定位有效

                if (result != null) {

                    MyLocationData data = new MyLocationData.Builder()

                            .accuracy(100)

//                            .accuracy(result.getRadius())

                            .latitude(result.getLatitude())

                            .longitude(result.getLongitude()).build();

                    // 設定定位資料

                    mBaiduMap.setMyLocationData(data);

                    LatLng ll = new LatLng(result.getLatitude(),

                            result.getLongitude());

                    MapStatus.Builder builder = new MapStatus.Builder();

                    //地圖縮放比設定為18

                    builder.target(ll).zoom(18.0f);

                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                }

  nnrride

            public void onConnectHotSpotMessage(String s, int i) {

                Log.e("tag", "s=" + s + "i=" + i);

            }

        });

        geo = BitmapDescriptorFactory.fromResource(R.mipmap.location_marker);

        MyLocationConfiguration configu
ration = new MyLocationConfiguration(

                MyLocationConfiguration.LocationMode.FOLLOWING, true, geo);

        mBaiduMap.setMyLocationConfigeration(configuration);// 設定定位模式

        mBaiduMap.setMyLocationEnabled(true);// 開啟定點陣圖層

        mlocationClient.start();// 呼叫此方法開始定位

    }

}

五 、xml佈局檔案

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.junto.baidumaptest.MainActivity">

    <com.baidu.mapapi.map.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true"/>

    <Button
        android:id="@+id/btn_click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="40dp"
        android:text="獲取當前位置"/>

</RelativeLayout>

此例子還用到了一個地圖標註資訊的實體類,程式碼如下:

package com.junto.baidumaptest;

import java.io.Serializable;

/**
 * Created by wangjinyong on 2017/8/11.
 * 地圖標註資訊實體類
 */

public class MarkerInfoUtil implements Serializable {

    private double latitude;//緯度
    private double longitude;//經度
    private String name;//名字
    private int imgId;//圖片
    private String description;//描述
    //構造方法
    public MarkerInfoUtil() {}
    public MarkerInfoUtil(double latitude, double longitude, String name, int imgId, String description) {
        super();
        this.latitude = latitude;
        this.longitude = longitude;
        this.name = name;
        this.imgId = imgId;
        this.description = description;
    }
    //toString方法
    @Override
    public String toString() {
        return "MarkerInfoUtil [latitude=" + latitude + ", longitude=" + longitude + ", name=" + name + ", imgId="
                + imgId + ", description=" + description + "]";
    }
    //getter setter
    public double getLatitude() {
        return latitude;
    }
    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }
    public double getLongitude() {
        return longitude;
    }
    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getImgId() {
        return imgId;
    }
    public void setImgId(int imgId) {
        this.imgId = imgId;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

到這裡基本功能就已經實現了,有不足之處歡迎大家提出意見
下面附上本例子原始碼下載地址供參考
Demo原始碼