码迷,mamicode.com
首页 > 其他好文 > 详细

在Fragment中实现百度地图,定位到当前位置(基于SDKv2.1.0)

时间:2015-06-05 12:10:17      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:

使用最新版本的百度地图需要注意的几个地方:
1、libs文件夹下要有android-support-v4.jar、baidumapapi_v2_1_0.jar、locSDK_3.1.jar三个jar包和armeabi文件夹。
2、布局文件要写成<com.baidu.mapapi.map.MapView />,旧版本是写作<com.baidu.mapapi.MapView />的。
3、AndroidMainfest这个配置文件要把该添加的东西都加上。比如各种权限、比如屏幕支持、比如百度地图服务

<service     
android:name="com.baidu.location.f" android:enabled="true" android:process=":remote"> </service>

4、不要忘了申请自己的密钥。
……时间有限,就写这么多吧,遇到问题就百度一下,基本上也就解决了。
噢,附上自己的demo和各个链接。
百度地图API>Android SDK>相关下载  sdk下载  (http://developer.baidu.com/map/sdkandev-download.htm )
百度地图API>Android SDK>申请Key  申请key的链接  (http://developer.baidu.com/map/android-mobile-apply-key.htm)
百度地图API>定位 SDK>Android 定位SDK> 定位sdk的链接 (http://developer.baidu.com/map/geosdk-android-download.htm)

1、代码结构:
2、各个类的大致作用:
    (1) Cheeses.java  填充没有用到的Fragment的内容
    (2) DemoApplication.java  从百度地图sdk demo中直接拿来的;主要用来处理与key相关的操作
    (3) MainActivity.java  实现适配器,完成不同Fragment之间的切换
    (4) MapFragment.java  定位相关的操作
3、附上主要类的源码:
    (1) MainActivity.java

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {
    static final int NUM_ITEMS = 10;

    MyAdapter mAdapter;

    ViewPager mPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAdapter = new MyAdapter(getSupportFragmentManager());

        mPager = (ViewPager)findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);

    }

    public static class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return NUM_ITEMS;
        }

        @Override
        public Fragment getItem(int position) {
                if (position == 0) {
                                return MapFragment.newInstance();
                        }else{
                    return ArrayListFragment.newInstance(position);
                        }
        }
    }

    public static class ArrayListFragment extends ListFragment {
        int mNum;

        /**
         * Create a new instance of CountingFragment, providing "num"
         * as an argument.
         */
        static ArrayListFragment newInstance(int num) {
            ArrayListFragment f = new ArrayListFragment();

            // Supply num input as an argument.
            Bundle args = new Bundle();
            args.putInt("num", num);
            f.setArguments(args);

            return f;
        }

        /**
         * When creating, retrieve this instance‘s number from its arguments.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mNum = getArguments() != null ? getArguments().getInt("num") : 1;
        }

        /**
         * The Fragment‘s UI is just a simple text view showing its
         * instance number.
         */
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
            View tv = v.findViewById(R.id.text);
            ((TextView)tv).setText("Fragment #" + mNum);
            return v;
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            setListAdapter(new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_1, Cheeses.sCheeseStrings));
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            Log.i("FragmentList", "Item clicked: " + id);
        }
    }
}

  (2)  MapFragment.java

import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MapFragment extends Fragment {

    static MapView mMapView = null;
    private MapController mMapController = null;

    // 定位相关
        LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    MyLocationOverlay myLocationOverlay = null;
    LocationData locData = null;

    static MapFragment newInstance() {
        MapFragment f = new MapFragment();
        return f;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DemoApplication app = (DemoApplication) getActivity().getApplication();
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(getActivity());
            app.mBMapManager.init(DemoApplication.strKey, new DemoApplication.MyGeneralListener());
        }

        // LocationClient just init once;
        // start() is moved
        mLocClient = new LocationClient(getActivity());

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型      
//        option.setScanSpan(5000);        //设置发起定位请求的间隔时间,单位毫秒

        mLocClient.setLocOption(option);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_locationoverlay, container, false);

        mMapView = (MapView) v.findViewById(R.id.bmapView);
        mMapController = mMapView.getController();
        mMapView.getController().setZoom(14);
        mMapView.getController().enableClick(true);
        mMapView.setBuiltInZoomControls(true);

        myLocationOverlay = new MyLocationOverlay(mMapView);
        locData = new LocationData();
        myLocationOverlay.setData(locData);
        mMapView.getOverlays().add(myLocationOverlay);
        myLocationOverlay.enableCompass();
        mMapView.refresh();
        return v;
    }

    /**
     * 监听函数,有新位置的时候,格式化成字符串,输出到屏幕中
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            costTime = System.currentTimeMillis() - startTime;
            Log.d("MapFragment", "" + costTime);
            locData.latitude = location.getLatitude();
            locData.longitude = location.getLongitude();
            locData.accuracy = location.getRadius();
            locData.direction = location.getDerect();
            myLocationOverlay.setData(locData);
            mMapView.refresh();
            mMapController.animateTo(new GeoPoint((int) (locData.latitude * 1e6), (int) (locData.longitude * 1e6)));
            // if request location success , stop it
            stopRequestLocation();
        }

        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null) {
                return;
            }
        }
    }

    /**
     * warning: this method is callback by activity manager; Be careful it‘s
     * lifecycle : It is called after oncreate , before oncreateview; see
     * detail:
     * http://developer.android.com/reference/android/support/v4/app/Fragment
     * .html#setUserVisibleHint(boolean)
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {        //核心方法,避免因Fragment跳转导致地图崩溃
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser == true) {
            // if this view is visible to user, start to request user location
            startRequestLocation();
        } else if (isVisibleToUser == false) {
            // if this view is not visible to user, stop to request user
            // location
            stopRequestLocation();
        }
    }

    private void stopRequestLocation() {
        if (mLocClient != null) {
            mLocClient.unRegisterLocationListener(myListener);
            mLocClient.stop();
        }
    }

    long startTime;
    long costTime;

    private void startRequestLocation() {
        // this nullpoint check is necessary
        if (mLocClient != null) {
            mLocClient.registerLocationListener(myListener);
            mLocClient.start();
            mLocClient.requestLocation();
            startTime = System.currentTimeMillis();
        }
    }

    @Override
    public void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        if (mLocClient != null)
            mLocClient.stop();
        mMapView.destroy();
        super.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);

    }

}

 

MapFragment.java

在Fragment中实现百度地图,定位到当前位置(基于SDKv2.1.0)

标签:

原文地址:http://www.cnblogs.com/zhujiabin/p/4553962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!