1. 程式人生 > >百度地圖定位API,locationClient的使用

百度地圖定位API,locationClient的使用

使用百度地圖的API進行定位,因為V3.0版本之後很多類如MapController等不再使用,因此百度將定位API分離使用,下面是定位的Demo。使用的是百度最新的定位API。

1.首先呼叫SDKInitializer對API進行初始化,一定在setContentView之前完成。

//在使用SDK各元件之前初始化context資訊,傳入ApplicationContext  
        //注意該方法要再setContentView方法之前實現  
SDKInitializer.initialize(getApplicationContext());     setContentView(R.layout.activity_main)
;

2.初始化地圖例項並進行定位器的判斷和設定。

//得到地圖例項
 mMapView = (MapView) findViewById(R.id.bmapView);
 baiduMap = mMapView.getMap();

//將BaiduMap的setMyLocationEnabled設定為True
baiduMap.setMyLocationEnabled(true);


// 設定地圖放大縮小引數
 MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);        
 baiduMap.setMapStatus(msu);
//使用LocationManager判斷可以使用的定位方式 locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> providerList= locationManager.getProviders(true); if(providerList.contains(LocationManager.GPS_PROVIDER)){ provider=LocationManager.GPS_PROVIDER; }else if(providerList.contains
(LocationManager.NETWORK_PROVIDER)){ provider=LocationManager.NETWORK_PROVIDER; } else{ Toast.makeText(this, "No location Provider to use", Toast.LENGTH_SHORT).show(); return; }

3.建立LocationClient例項並進行註冊監聽器,設定LocationClientOption

//建立LocationClient例項
locationClient= new LocationClient(this);
mbdLocationListener= new MbdLocationListener();
//註冊監聽器,定位成功後回撥     locationClient.registerLocationListener(mbdLocationListener);
//初始化
setLocationOption();
//啟動LocationClient開始定位,定位結果返回在監聽器的onReceiveLocation中
locationClient.start();


public void setLocationOption(){        
LocationClientOption option = new LocationClientOption();
option.setCoorType("gcj02");// 返回的定位結果是百度經緯度,預設值gcj02
option.setIsNeedAddress(true);// 位置,一定要設定,否則後面得不到地址
option.setOpenGps(true);// 開啟GPS
option.setScanSpan(5000);// 多長時間進行一次請求       option.setLocationMode(LocationMode.Hight_Accuracy);// 高精度
locationClient.setLocOption(option);// 使用設定     
    }

4.實現介面類BDLocationListener,location為定位返回的結果,將結果進行顯示。

private class MbdLocationListener implements BDLocationListener{

@Override
public void  onReceiveLocation(BDLocation location){            

//建立MyLocationData類 
MyLocationData locationdata= new MyLocationData.Builder()
            .accuracy(location.getRadius())
            .latitude(location.getLatitude())
            .longitude(location.getLongitude())
            .build();
//在BaiduMap中設定
baiduMap.setMyLocationData(locationdata);

mLatitude=location.getLatitude();
mLongitude=location.getLongitude();

//判斷是否第一次定位,如果是執行如下程式碼

if(isFirstIn){
LatLng  latLng =new LatLng(mLatitude,mLongitude);               
MapStatusUpdate msu= MapStatusUpdateFactory.newLatLng(latLng);
baiduMap.animateMapStatus(msu);
isFirstIn=false;                
Toast.makeText(
                 context,
                 "地址是:"+ location.getAddrStr()+"\n"                       
                  +"定位精度是:"+location.getRadius()+"\n"
                  ,Toast.LENGTH_LONG).show();           
    Log.e("Address", String.valueOf(location.getCity()));
    Log.e("District", String.valueOf(location.getAddrStr()));
    Log.e("Location", String.valueOf(location));                    

    }
}

以下是layout檔案:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"

    tools:context="com.example.baidumapdemo.MainActivity"
    tools:ignore="MergeRootFrame" >

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

</LinearLayout>

下面是MainActivity

package com.example.baidumapdemo;

import java.util.List;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends ActionBarActivity {
    private MapView mMapView;
    private LocationManager locationManager;
    private String provider;
    private LocationClient locationClient;
    private BDLocation bdLocation;
    private MbdLocationListener mbdLocationListener;
    private boolean isFirstIn = true;
    private double mLatitude;//緯度
    private double mLongitude;//經度
    private BaiduMap baiduMap;
    private Context context;
    private LocationManager locationManger;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);

          //在使用SDK各元件之前初始化context資訊,傳入ApplicationContext  
        //注意該方法要再setContentView方法之前實現  
        SDKInitializer.initialize(getApplicationContext());  


        setContentView(R.layout.activity_main);

        this.context = this;
        initMapView();  

        initLocation();        



}

    public void initMapView(){

        //得到地圖例項
        mMapView = (MapView) findViewById(R.id.bmapView);
        baiduMap = mMapView.getMap();

        //將BaiduMap的setMyLocationEnabled設定為True
        baiduMap.setMyLocationEnabled(true);


        // 設定地圖放大縮小引數
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);        
        baiduMap.setMapStatus(msu);

        //使用LocationManager判斷可以使用的定位方式

        locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
        List<String> providerList= locationManager.getProviders(true);

        if(providerList.contains(LocationManager.GPS_PROVIDER)){
            provider=LocationManager.GPS_PROVIDER;

        }else if(providerList.contains(LocationManager.NETWORK_PROVIDER)){
            provider=LocationManager.NETWORK_PROVIDER;
        } else{
            Toast.makeText(this, "No location Provider to use", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    public void initLocation(){

        //建立LocationClient例項
        locationClient= new LocationClient(this);
        mbdLocationListener= new MbdLocationListener();
        //註冊監聽器,定位成功後回撥
        locationClient.registerLocationListener(mbdLocationListener);
        //初始化
        setLocationOption();
        //啟動LocationClient開始定位,定位結果返回在監聽器的onReceiveLocation中
        locationClient.start();


}


public void setLocationOption(){


       LocationClientOption option = new LocationClientOption();
       option.setCoorType("gcj02");// 返回的定位結果是百度經緯度,預設值gcj02
       option.setIsNeedAddress(true);// 位置,一定要設定,否則後面得不到地址
       option.setOpenGps(true);// 開啟GPS
       option.setScanSpan(5000);// 多長時間進行一次請求
       option.setLocationMode(LocationMode.Hight_Accuracy);// 高精度
        locationClient.setLocOption(option);// 使用設定

    }



private class MbdLocationListener implements BDLocationListener{

        @Override
        public void  onReceiveLocation(BDLocation location){            

        //建立MyLocationData類 
            MyLocationData locationdata= new MyLocationData.Builder()
            .accuracy(location.getRadius())
            .latitude(location.getLatitude())
            .longitude(location.getLongitude())
            .build();
        //在BaiduMap中設定
            baiduMap.setMyLocationData(locationdata);

            mLatitude=location.getLatitude();
            mLongitude=location.getLongitude();

        //判斷是否第一次定位,如果是執行如下程式碼

        if(isFirstIn){
                LatLng  latLng =new LatLng(mLatitude,mLongitude);               
                MapStatusUpdate msu= MapStatusUpdateFactory.newLatLng(latLng);
                baiduMap.animateMapStatus(msu);
                isFirstIn=false;                
                Toast.makeText(
                        context,
                         "地址是:"+ location.getAddrStr()+"\n"                       
                          +"定位精度是:"+location.getRadius()+"\n"
                          ,Toast.LENGTH_LONG).show();           
                Log.e("Address", String.valueOf(location.getCity()));
                Log.e("District", String.valueOf(location.getAddrStr()));
                Log.e("Location", String.valueOf(location));                    

            }
        }           



    }



        @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  
            protected void onDestroy() {  
                super.onDestroy();  
                //在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命週期管理  
                mMapView.onDestroy(); 
                //反註冊監聽器
                locationClient.unRegisterLocationListener(mbdLocationListener);
            } 



    @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
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}