百度地图v3.5最新版本使用覆盖物,通用版。

好久没用百度地图了。以前用的是2.4.0,现在更新到3.5了,发现很多接口用不了,或者重构了。为此写了一份比较通用的项目。

项目资源地址:http://download.csdn.net/detail/u010090644/8956223 

如需转载,请注明出处。http://blog.csdn.net/u010090644/article/details/47257651

如果下载后项目运行有误,可以评论私聊。

1.单个添加覆盖物 MapActivity主要代码

public class MapAvtivity extends FragmentActivity{
	
	private MyMapFragment map;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.my_map);
		FragmentManager fm = getSupportFragmentManager();
		PUser user = new PUser();
		user.setLatitude(25.856013);
		user.setLongitude(114.958339);
		map = MyMapFragment.newInstance(user);
        if (fm.findFragmentById(R.id.fragment) == null) {
            fm.beginTransaction().add(R.id.fragment, map).commit();
        }
	}
	
	public static class MyMapFragment extends MFragment<PUser> implements OnMarkerClickListener{
		
		public static MyMapFragment newInstance(PUser user) {
            MyMapFragment f = new MyMapFragment();
            Bundle args = new Bundle();
            args.putParcelable("user", user);
            f.setArguments(args);
            return f;
        }


		private PUser user;
		private Marker mMarkerA;
		private InfoWindow mInfoWindow;
		
		@Override
		public void onCreate(Bundle arg0) {
			super.onCreate(arg0);
			
		}
		
		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			
			
			user = getArguments().getParcelable("user");
			
			LatLng llA = new LatLng(user.getLatitude(), user.getLongitude());
			BitmapDescriptor bdA = BitmapDescriptorFactory
					.fromResource(R.drawable.ic_launcher);
			OverlayOptions over = new MarkerOptions().position(llA).icon(bdA)
					.zIndex(9).draggable(true);

			
			mBaiduMap.addOverlay(over);
			mBaiduMap.setOnMarkerClickListener(this);
			mMarkerA = (Marker) mBaiduMap.addOverlay(over);
			
		}
		

		@Override
		public Loader<PUser> onCreateLoader(int id, Bundle args) {
			return null;
		}

		@Override
		public boolean onMarkerClick(final Marker marker) {
			Button button = new Button(getActivity());
			button.setBackgroundResource(R.drawable.popup);
			OnInfoWindowClickListener listener = null;
			if (marker == mMarkerA) {
				button.setText("更改位置");
				listener = new OnInfoWindowClickListener() {
					public void onInfoWindowClick() {
						LatLng ll = marker.getPosition();
						LatLng llNew = new LatLng(ll.latitude + 0.005,
								ll.longitude + 0.005);
						marker.setPosition(llNew);
						mBaiduMap.hideInfoWindow();
					}
				};
				LatLng ll = marker.getPosition();
				mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(button), ll, -47, listener);
				mBaiduMap.showInfoWindow(mInfoWindow);
			}
			return true;
		}
	}
	
	
	
}

2.基类MFragment是继承Fragment的,至于为什么不继承SupportMapFragment是为了更好的在一般项目中通用。

有了以下个类就可以实现定位自己的位置,并添加单个覆盖物。上代码在说:

public abstract class MFragment<T> extends Fragment implements LoaderCallbacks<T>, OnMapClickListener{
	
	
	protected BaiduMap mBaiduMap;
	protected MapView mapView;
	public MyLocationListenner myListener = new MyLocationListenner();
	private LocationClient mLocClient;
	
	private boolean isFirstLoc = true;
	
	@Override
	public void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		
		getLoaderManager().initLoader(1, null, this);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle arg2) {
		View v = inflater.inflate(R.layout.map, container, false);
		mapView = (MapView) v.findViewById(R.id.map);
		mBaiduMap = mapView.getMap();
		mBaiduMap.setMyLocationEnabled(true);
		MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(16.0f);
		mBaiduMap.setMapStatus(msu);
		mBaiduMap.setOnMapClickListener(this);
		mBaiduMap.setMaxAndMinZoomLevel(3, 20);
		mLocClient = new LocationClient(getActivity());
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setCoorType("bd09ll"); 
		option.setScanSpan(1000);
		mLocClient.setLocOption(option);
		mLocClient.start();
		
		return v;
	}
	
	
	public void forceLoad() {
		getLoaderManager().restartLoader(1, null, this);
	}
	
	public class MyLocationListenner implements BDLocationListener {


		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null || mapView == null)
				return;
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);
			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}
	
	
	@Override
	public void onStart() {
		super.onStart();
		
	}

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

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

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

	@Override
	public void onStop() {
		super.onStop();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
//		mBaiduMap.setMyLocationEnabled(false);
//		mapView.onDestroy();
//		mapView = null;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	@Override
	abstract public Loader<T> onCreateLoader(int id, Bundle args);

	@Override
	public void onLoadFinished(Loader<T> loader, T data) {
	}

	@Override
	public void onLoaderReset(Loader<T> loader) {
		
	}
	
	@Override
	public void onMapClick(LatLng arg0) {
		
	}
	
	@Override
	public boolean onMapPoiClick(MapPoi arg0) {
		String title = "";
		if (arg0 != null){
			title = arg0.getName();
			Toast.makeText(getActivity(), title, Toast.LENGTH_SHORT).show();
		}
		return false;
	}

}


3.很多情况下不需要添加覆盖物,只需要定位。这里写了一个定位的Service.

public class BaiduLocationService extends Service {
	
    public static final String ACTION_LOCATION_CHANGED = "com.yundi.wlqc.service.action.location_changed";
    private static final String TAG = "BaiduLocationService";
    public boolean isAutoStopSelf;
    public LocationClient mLocationClient;
    public MyocationListenner myListener = new MyocationListenner();
    private SDKReceiver mReceiver;
    
    public void onCreate() {
        super.onCreate();
        SDKInitializer.initialize(getApplicationContext());
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        IntentFilter iFilter = new IntentFilter();
		iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
		iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
		mReceiver = new SDKReceiver();
		registerReceiver(mReceiver, iFilter);
    }
    
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(!mLocationClient.isStarted()) {
            Log.d("BaiduLocationService", "Start locate");
            LocationClientOption option = getLocationOption();
            mLocationClient.setLocOption(option);
            mLocationClient.requestLocation();
            mLocationClient.start();
        } else {
            Log.d("BaiduLocationService", "Request locate");
            mLocationClient.requestLocation();
        }
        if(intent != null) {
            isAutoStopSelf = intent.getBooleanExtra("extra_stop", true);
        }
        return 0x1;
    }
    
    private LocationClientOption getLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setAddrType("all");
        option.setScanSpan(1000);
        option.setIsNeedAddress(true);
        return option;
    }
    
    public void onDestroy() {
        super.onDestroy();
        Log.d("BaiduLocationService", "Stop locate");
        mLocationClient.stop();
    }
    
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    public class MyocationListenner implements BDLocationListener {

		public void onReceivePoi(BDLocation poiLocation) {
		}
		
		@Override
		public void onReceiveLocation(BDLocation location) {
			StringBuffer sb = new StringBuffer(256);
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				sb.append("GPS");
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("Network");
			}

			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\naddr : ");
			sb.append(location.getAddrStr());

			Log.i(TAG, sb.toString());
			System.out.println(sb.toString());
            Toast.makeText(getApplicationContext(), sb.toString(), Toast.LENGTH_SHORT).show();

			writeLocationAndSendBroadcast(location);

			if (isAutoStopSelf) {
				stopSelf();
			}
		}


	}
    
    private void writeLocationAndSendBroadcast(BDLocation bdlocation) {
        Location location = new Location("local");
        location.setLatitude(bdlocation.getLatitude());
        location.setLongitude(bdlocation.getLongitude());
        LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
        Intent intent = new Intent("com.yundi.wlqc.service.action.location_changed");
        intent.putExtra("extra_location", location);
        intent.putExtra("exra_radius", bdlocation.getRadius());
//        intent.putExtra("extra_derect", bdlocation.getDerect());
        lbm.sendBroadcast(intent);
    }
    
    
    private Context getService() {
        return this;
    }
    
    public class SDKReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
				Toast.makeText(getService(), "key error", Toast.LENGTH_SHORT)
						.show();
			}
			if (action.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
				Toast.makeText(getService(), "network...", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}
}

4.重点来了,需要添加一个列表呢?多个覆盖物呢?以下代码来:

public class MapListAvtivity extends FragmentActivity{
	
	private MyMapFragment map;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.my_map);
		FragmentManager fm = getSupportFragmentManager();
		map = MyMapFragment.newInstance();
        if (fm.findFragmentById(R.id.fragment) == null) {
            fm.beginTransaction().add(R.id.fragment, map).commit();
        }
	}
	
	public static class MyMapFragment extends MListFragment<PUser> implements OnMarkerClickListener{
		
		public static MyMapFragment newInstance() {
            MyMapFragment f = new MyMapFragment();
            return f;
        }

		@Override
		protected List<PUser> loadData(Context context) throws Exception {
			List<PUser> list = new ArrayList<PUser>();
			PUser user = new PUser();
			user.setId("1");
			user.setLatitude(25.856013);
			user.setLongitude(114.958339);
			list.add(user);
			PUser user1 = new PUser();
			user1.setId("2");
			user1.setLatitude(25.8444676614);
			user1.setLongitude(114.908875473);
			list.add(user1);
			PUser user2 = new PUser();
			user2.setId("3");
			user2.setLatitude(25.830770050254);
			user2.setLongitude(114.9804583851);
			list.add(user2);
			return list;
		}

		@Override
		protected OverlayOptions getOverlayItem(PUser item) {
			View v = View.inflate(getActivity(), R.layout.mdwd_map_item, null);
            TextView t_name = (TextView) v.findViewById(R.id.t_name);
            t_name.setText(item.getLatitude()+ "");
//            BitmapDrawable b = new BitmapDrawable(getResources(),
//                    ViewUtils.getBitmapFromView(v));
            LatLng l = new LatLng(item.getLatitude(), item.getLongitude());
            BitmapDescriptor bdA = BitmapDescriptorFactory.fromView(v);
            Bundle b = new Bundle();
            b.putParcelable("user", item);
            OverlayOptions o = new MarkerOptions().position(l).
            		icon(bdA).zIndex(9).draggable(true).extraInfo(b);
            mBaiduMap.setOnMarkerClickListener(this);
			return o;
		}
		

		@Override
		public boolean onMarkerClick(Marker arg0) {
			for(Marker m : markers){
				if(arg0 == m){
					PUser user = arg0.getExtraInfo().getParcelable("user");
					Toast.makeText(getActivity(), user.getId(), Toast.LENGTH_SHORT).show();
				}
			}
			return true;
		}
		
	}
	
}


和MListFragment

public abstract class MListFragment<T> extends MFragment<List<T>> {
	
	private Exception ex;
	private OverlayManager overlayManager;
	protected List<OverlayOptions> overlayOptions;
	protected List<Marker> markers;
	

	@Override
	public Loader<List<T>> onCreateLoader(int id, Bundle args) {
		return new ListAsyncTaskLoader<T>(getActivity()) {

			@Override
			protected List<T> loadInBackground(Context context) {
				try {
					return loadData(context);
				} catch (Exception e) {
					e.printStackTrace();
					ex = e;
				}
				return null;
			}

		};
	}
	
	@Override
	public void onLoadFinished(Loader<List<T>> loader, List<T> data) {
		super.onLoadFinished(loader, data);
		if (ex != null) {
			ex = null;
			return;
		}
		
		overlayOptions = new ArrayList<OverlayOptions>();
		markers = new ArrayList<Marker>();
		for (int i = 0; i < data.size(); i++) {
			OverlayOptions item = getOverlayItem(data.get(i));
			overlayOptions.add(item);
			Marker m = (Marker) mBaiduMap.addOverlay(item);
			markers.add(m);
		}
		
	}
	
	
	abstract protected List<T> loadData(Context context) throws Exception;

	abstract protected OverlayOptions getOverlayItem(T item);

	public List<OverlayOptions> getOverlayOptions() {
		return overlayOptions;
	}

	public void setOverlayOptions(List<OverlayOptions> overlayOptions) {
		this.overlayOptions = overlayOptions;
	}
	
	
	
	
}

5.此小demo里的MFragment, MListFragment在一般项目中很通用,需要的XML和LoaderCallbacks,有需要的话可以下载项目。

项目资源地址:http://download.csdn.net/detail/u010090644/8956223

如需转载,请注明出处。http://blog.csdn.net/u010090644/article/details/47257651

猜你喜欢

转载自blog.csdn.net/u010090644/article/details/47257651
今日推荐