你的位置:首页 > 操作系统

[操作系统]百度地图简单的使用


最近写了百度地图的Demo,所以总结下遇到的问题;

1.使用百度地图,先看下官方的例子。要再清单文件中配置KEY,如果用到定位要注册serviece:android:name="com.baidu.location.f"

2.要创建application类并在清单文件中配置;不然一直报 java.lang.IllegalStateException: you have not supplyed the global app context info from SDKInitializer.initialize(Context) function. SDKInitializer.initialize(this)即可;
3.还有注意MapView的生命周期,记得及时创建和销毁。

4.在定位当前时,获取当前的地名使用option.setIsNeedAddress(true);//设置地址信息;原先的option.setAddrType("all")过期不过也能获得信息。

5.在使用Marker时,marker.getExtraInfo()一直报空指针的问题;报空是因为在加入Marker是没有将bundle赋予到每个Marker,当然会得null了;

需要在OverlayOptions中添加extraInfo(bundle)字段。

6.

如下是我demo的截图 

                       

先定位自己,再在地图上展示6个Marker,点击每个Marker时展示出当前Marker的信息

如下是主要代码

package com.it.hello.activity.baidu;import java.util.ArrayList;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.mapapi.map.BaiduMap;import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;import com.baidu.mapapi.map.BaiduMap.OnMyLocationClickListener;import com.baidu.mapapi.map.BitmapDescriptor;import com.baidu.mapapi.map.BitmapDescriptorFactory;import com.baidu.mapapi.map.InfoWindow;import com.baidu.mapapi.map.MapStatus;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.MyLocationData;import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;import com.baidu.mapapi.map.MarkerOptions.MarkerAnimateType;import com.baidu.mapapi.map.OverlayOptions;import com.baidu.mapapi.model.LatLng;import com.it.hello.R;import com.it.hello.activity.entity.CarInfo;import com.it.hello.activity.util.DensityUtils;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;/** * 百度Marker的问题 * @author zh * */public class MyBaidu extends Activity{  private MapView mMapView;  private BaiduMap mBaiduMap;  /**清除Marker*/  private Button btn_clean;  /**地图上Marker的信息*/  private List<CarInfo> carInfos = new ArrayList<CarInfo>();  /**定位相关*/  private LocationClient mLocClient;  /**定位当前的位置名称*/  private String nowPosition = "";  @Override  protected void onCreate(Bundle savedInstanceState) {    // TODO Auto-generated method stub    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_baidu);    mMapView = (MapView)findViewById(R.id.baidu_mapView);    btn_clean =(Button)findViewById(R.id.baidu_clean);    mBaiduMap = mMapView.getMap();//    MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(12.0f);//    mBaiduMap.setMapStatus(msu);        // 开启定位图层    mBaiduMap.setMyLocationEnabled(true);    // 定位初始化    mLocClient = new LocationClient(this);    mLocClient.registerLocationListener(new MyLocationListenner());    LocationClientOption option = new LocationClientOption();    option.setOpenGps(true);// 打开GPS    option.setCoorType("bd09ll");//设置坐标类型        option.setScanSpan(1000);//设置扫描间隔,单位是毫秒 当<1000(1s)时,定时定位无效        //option.setAddrType("all");    option.setIsNeedAddress(true);//设置地址信息,默认无地址信息    mLocClient.setLocOption(option);    mLocClient.start();    /**     * 地图定位图标点击事件监听接口     */    mBaiduMap.setOnMyLocationClickListener(new OnMyLocationClickListener() {            @Override      public boolean onMyLocationClick() {        // TODO Auto-generated method stub        //吐司当前位置信息        DensityUtils.showToast(MyBaidu.this, nowPosition) ;        return false;      }    });        initOverlay();    /**     * Marker点击事件的监听接口     */    mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {            @Override      public boolean onMarkerClick(Marker marker) {        // TODO Auto-generated method stub        TextView textView = new TextView(getApplicationContext());        textView.setPadding(15, 10, 15, 30);        textView.setBackgroundResource(R.drawable.popup);        OnInfoWindowClickListener listener = null;        System.out.println(marker.getExtraInfo() + " d " + marker);        final CarInfo carInfo = (CarInfo)marker.getExtraInfo().get("STATION");        textView.setText("车牌号:" +carInfo.getLicenseNumber());        textView.setTextColor(getResources().getColor(R.color.action_bar_bg_select));        listener = new OnInfoWindowClickListener() {                    @Override          public void onInfoWindowClick() {            // TODO Auto-generated method stub            System.out.println(carInfo + carInfo.getLatitude() + " " + carInfo.getLongitude());            mBaiduMap.hideInfoWindow();          }        };        LatLng ll = marker.getPosition();        InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(textView), ll, -47, listener);        mBaiduMap.showInfoWindow(mInfoWindow);        return true;      }    });    /**     * 清除Marker,单击事件的接口     */    btn_clean.setOnClickListener(new View.OnClickListener() {            @Override      public void onClick(View arg0) {        // TODO Auto-generated method stub        mBaiduMap.clear();        carInfos.clear();      }    });  }    /**   * 定位SDK监听函数   *   */  boolean isFirstLoc = true; // 是否首次定位  private class MyLocationListenner implements BDLocationListener {    @Override    public void onReceiveLocation(BDLocation location) {      // TODO Auto-generated method stub      if (location == null || mMapView == null) {        return;      }      MyLocationData locData = new MyLocationData.Builder()          .accuracy(location.getRadius())          // 此处设置开发者获取到的方向信息,顺时针0-360          .direction(100).latitude(location.getLatitude())          .longitude(location.getLongitude()).build();      mBaiduMap.setMyLocationData(locData);      if (isFirstLoc) {        isFirstLoc = false;        LatLng ll = new LatLng(location.getLatitude(),            location.getLongitude());        Log.d("jiejie", "Latitude" + location.getLatitude()            + "  Longitude" + location.getLongitude() + " location"            + location.getCity() + location.getAddrStr() );        //tv_location.setText(ll + "详细地点:" +location.getAddrStr() + "  城市:"+location.getCity());        nowPosition = location.getAddrStr();        MapStatus.Builder builder = new MapStatus.Builder();        builder.target(ll).zoom(12.0f);        mBaiduMap.animateMapStatus(MapStatusUpdateFactory            .newMapStatus(builder.build()));      }    }  }  /**   * 添加mark   */  private BitmapDescriptor bdA = BitmapDescriptorFactory      .fromResource(R.drawable.icon_marka);  private Bundle bundle;  private void initOverlay() {    // TODO Auto-generated method stub    //加载的数据    carInfos.add(new CarInfo("无报警", "1", "39.939723", "116.425541", "皖A111", "9208000", "11", "Acc关闭空车"));    carInfos.add(new CarInfo("无报警", "2", "39.942821", "116.369199", "皖A222", "9208000", "12", "Acc关闭空车"));    carInfos.add(new CarInfo("无报警", "3", "31.843025", "117.275366", "皖N333", "9208000", "13", "ACC关闭空车"));    carInfos.add(new CarInfo("无报警", "4", "31.803025", "117.255366", "皖N444", "9208000", "14", "ACC关闭空车"));    carInfos.add(new CarInfo("有报警", "5", "30.82943", "116.89586", "皖WA555", "9208000", "15", "Acc不关闭"));    carInfos.add(new CarInfo("有报警", "6", "31.81943", "117.134623", "皖WA666", "9208000", "16", "Acc不关闭"));    for(CarInfo info : carInfos){      LatLng llLng = new LatLng(Float.parseFloat(info.getLatitude()),Float.parseFloat(info.getLongitude()));      bundle = new Bundle();      bundle.putSerializable("STATION", info);//      MarkerOptions ooA = new MarkerOptions().position(llLng).icon(bdA).extraInfo(bundle)//          .zIndex(9).draggable(true);//      ooA.animateType(MarkerAnimateType.grow);      OverlayOptions options = new MarkerOptions().position(llLng).icon(bdA).extraInfo(bundle)          .zIndex(9).title(info.getLicenseNumber()).draggable(true).animateType(MarkerAnimateType.grow);            mBaiduMap.addOverlay(options);    }  }  @Override  protected void onPause() {    // MapView的生命周期与Activity同步,当activity挂起时需调用MapView.onPause()    mMapView.onPause();    super.onPause();  }  @Override  protected void onResume() {    // MapView的生命周期与Activity同步,当activity恢复时需调用MapView.onResume()    mMapView.onResume();    super.onResume();  }  @Override  protected void onDestroy() {    // 退出时销毁定位    mLocClient.stop();    // 关闭定位图层    mBaiduMap.setMyLocationEnabled(false);    // MapView的生命周期与Activity同步,当activity销毁时需调用MapView.destroy()    mMapView.onDestroy();    mMapView = null;    super.onDestroy();    // 回收 bitmap 资源    bdA.recycle();  }}