第二部分:使用MapABC地图服务,实现定位,实现导航功能 使用MapABC开发Android 地图可参考的资料比较多,毕竟高德拿了几千万美金的风险投资,在国内,其地图开发是钢钢的而且在官网上还提供了在Android 开发平台的样例包可供参考,本日志所使用的代码大部分来自样例的代码 ,只是做了一些小修改,增加了定位功能,其定位的代码其实与Google map里面写的代码差不多,不知道为什么,这部分程序在虚拟机上运行良好,在真机上却多多少少出现了一些小问题。
一、下载MapABC提供的API 开发包 MapABC官网上提供android 地图 API开发包,需要注册,才能下载,其次需要获得密钥,MapABC地图开发的密钥要求不是很严格,不象Google Map 那样每个不同的设备都需要不同的密钥,否则就会满屏幕出现小方格。
二、其开发的过程与Google map 差不多,代码奉上:
import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import akson.epms.Epms.Crop; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.location.Address; import android.location.Criteria; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.autonavi.mapapi.GeoPoint; import com.autonavi.mapapi.ItemizedOverlay; import com.autonavi.mapapi.MapActivity; import com.autonavi.mapapi.MapController; import com.autonavi.mapapi.MapView; import com.autonavi.mapapi.Overlay; import com.autonavi.mapapi.OverlayItem; import com.autonavi.mapapi.PoiPagedResult; import com.autonavi.mapapi.PoiSearch; import com.autonavi.mapapi.PoiTypeDef; import com.autonavi.mapapi.Projection; import com.autonavi.mapapi.Route; import com.autonavi.mapapi.RouteMessageHandler; import com.autonavi.mapapi.RouteOverlay; import com.autonavi.mapapi.MapView.LayoutParams; import com.autonavi.mapapi.Route.FromAndTo;
/** * @author by qiannuo * Create time: 2011-09-16 * E_mail:qiannuo0317@163.com * QQ:405923111 * eoeandroid.: http://www.eoeandroid.com/space-uid-511333.html * CSDN: http://blog.csdn.net/qiannuo * * Title:MyMapActivity 高德地图 * 功能:定位 、导航、显示地图 */ /** * 高德地图提供的android maps 的API非常全,如果熟读他的参考文档,可以开发出一个灰常优秀的地图软件出来,本程序不需要的很强的功能,实现其 * 基本功能即可,如要好的设计,需要详读他的Api */
public class GdMapActivity extends MapActivity implements OnGestureListener, RouteMessageHandler {
public static final String TAG = "GdMapActivity"; private GestureDetector mGestureDetector = new GestureDetector(this); private PoiSearch poiSearchStart, poiSearchEnd; private String startStr, endStr; private PoiPagedResult resultStart, resultEnd; private PoiOverlaySelectPoint selectPointStart, selectPointEnd; private GeoPoint startPoint, endPoint; private List<Route> route; private RouteOverlay routeOverlay, oldRouteOverlay; private ImageButton popupDipStart, popupDipEnd; private int mode = Route.DrivingDefault; private int oldMode = Route.DrivingDefault; private FromAndTo fromAndTo; private Button calculateRoute; private ImageButton navigation_gd; private GeoPoint tempPoint; public MyLocationOverlay myPosition; MapView mMapView; MapController mMapController; MapController mc; LocationManager m_LocationManager; LocationListener m_LocationListener; GeoPoint point; public View popView; Cursor mCursor; private String dip; private final int REQUESTCODE = 1; private Drawable draw; private String POINT_IN_MAP = "地图上的点";
@Override /** *显示地图,启用内置缩放控件,并用MapController控制地图的中心点及Zoom级别 */ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map_gd);
// 标题 TextView title = (TextView) findViewById(R.id.myTitle); title.setText(R.string.dzdt_name);
// 返回 ImageButton backButton = (ImageButton) findViewById(R.id.back_button); backButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } });
mMapView = (MapView) findViewById(R.id.mapview); mMapView.setBuiltInZoomControls(true); // 设置启用内置的缩放控件 mMapController = mMapView.getController(); // 得到mMapView的控制权,可以用它控制和驱动平移和缩放 point = new GeoPoint((int) (34.301822 * 1E6), (int) (117.239085 * 1E6)); // 用给定的经纬度构造一个GeoPoint,单位是微度 // (度 // * // 1E6) mMapController.setCenter(point); // 设置地图中心点 mMapController.setZoom(15); // 设置地图zoom级别 //定位按钮 ImageButton getlocation_gd = (ImageButton) findViewById(R.id.getlocation); getlocation_gd.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) { //点击这里进行定位 Log.i(TAG, "点击了定位按钮"); //首先判断GPS模块是否存在或开启 openGPSSettings(); // 在这里获取定位信息 m_LocationManager = (LocationManager) GdMapActivity.this .getSystemService(Context.LOCATION_SERVICE); mMapController =mMapView.getController(); // 在这里 需要重写LocationListener()方法 myPosition = new MyLocationOverlay(); List<Overlay> overlays = mMapView.getOverlays(); overlays.add(myPosition); //设置Criteria(服务商)的信息 Criteria criteria = new Criteria(); //经度要求 criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(false); criteria.setPowerRequirement(Criteria.POWER_LOW); // 较少的电量消耗 //取得效果最好的criteria 在google map 提供的定位中有 GPS定位 WIFI定位 基站定位等,各种定位的方式效果是不一样的 String provider = m_LocationManager.getBestProvider(criteria, true); //取得坐标的相关信息 Location location = m_LocationManager.getLastKnownLocation(provider); updataWithNewLocation(location); m_LocationManager.requestLocationUpdates( provider, 3000, 0, MyLocationListener); }
});

// 在这里设置一个导航系统 setInitView();
// 浮动气泡 popView = super.getLayoutInflater().inflate(R.layout.overlay_pop, null); mMapView.addView(popView, new MapView.LayoutParams(230, 140, null, MapView.LayoutParams.BOTTOM_CENTER)); popView.setVisibility(View.GONE);
/* * Perform a managed query. The Activity will handle closing and * requerying the cursor when needed. */ mCursor = managedQuery(Crop.CONTENT_URI, null, null, null, Crop.DEFAULT_SORT_ORDER); if (mCursor == null || mCursor.getCount() <= 0) { return; }
// 在地图上标示出企业位置 List<Overlay> mapOverlays = mMapView.getOverlays(); Drawable drawable = this.getResources().getDrawable(R.drawable.crop); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); // 为maker定义位置和边界 OverItemT itemizedoverlay = new OverItemT(drawable, this);
while (mCursor.moveToNext()) { Double longitude = mCursor.getFloat(mCursor .getColumnIndex(Crop.LONGITUDE)) * 1E6; Double latitude = mCursor.getFloat(mCursor .getColumnIndex(Crop.LATITUDE)) * 1E6;
String cropName = mCursor.getString(mCursor .getColumnIndex(Crop.CORPNAME)); String cropId = mCursor.getString(mCursor .getColumnIndex(Crop.CORPID));
OverlayItem overlayitem = new OverlayItem(new GeoPoint( latitude.intValue(), longitude.intValue()), cropName, cropId + ":" + mCursor.getPosition()); itemizedoverlay.addOverlay(overlayitem); }
mapOverlays.add(itemizedoverlay); } //////////////////////////////////////////////////////////////////////////// //这一段是定位时的代码 //2011-09-23 对定位程序写个异步处理方法 //首先判断GPS模块是否存在或开启 private void openGPSSettings(){ m_LocationManager = (LocationManager) GdMapActivity.this .getSystemService(Context.LOCATION_SERVICE); if (m_LocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) { Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT).show(); Log.i(TAG, "GPS模块正常"); //模块开启正常的话直接返回,否则执行下面的代码 return; } Toast.makeText(this, "GPS模块异常", Toast.LENGTH_LONG).show(); //跳入到GPS设置界面 Intent gps_intent = new Intent(Settings.ACTION_SECURITY_SETTINGS); startActivityForResult(gps_intent, 0); }
private void updataWithNewLocation(Location location){ String LnglatString; //把找到的地址显现在顶部 LinearLayout my_gdloc = (LinearLayout) GdMapActivity.this.findViewById(R.id.my_gdloc); TextView get_mygdloction = (TextView) GdMapActivity.this.findViewById(R.id.get_mygdloction); String addressString = "没有找到地址\n"; if(location != null){ //为绘制标志的设计坐标 myPosition.setLocation(location); //取得纬度和经度 Double geoLat = location.getLatitude() * 1E6; //纬度 Double geoLng = location.getLongitude() * 1E6; //经度 //将其转换为int型 GeoPoint point = new GeoPoint(geoLat.intValue(),geoLng.intValue()); //定位到指定坐标 mMapController.animateTo(point); Double lng = location.getLongitude(); Double lat = location.getLatitude(); LnglatString = "经度:" + lng + "\n纬度:" + lat; //取出地理的经纬度 Double longitude = (int)location.getLongitude()/1E6; Double latitude = (int)location.getLatitude()/1E6; //根据地理环境来确定编码 Geocoder gc = new Geocoder(GdMapActivity.this, Locale.getDefault()); try { //取得地址相关的一些信息、经度和纬度 List<Address> addresses = gc.getFromLocation(latitude, longitude, 1); StringBuilder sBuilder = new StringBuilder(); if (addresses.size() > 0) { Address address = addresses.get(0); for(int i = 0; i< address.getMaxAddressLineIndex(); i++) sBuilder.append(address.getAddressLine(i)).append("\n"); sBuilder.append(address.getLocality()).append("\n"); sBuilder.append(address.getCountryName()); sBuilder.append(address.getPostalCode()); addressString = sBuilder.toString(); } } catch (Exception e) { } }else{ LnglatString = "没有找到坐标"; Toast.makeText(this, "GPS信号很弱,无法获得确切地址", Toast.LENGTH_LONG); } //把相关信息显示在屏幕上 my_gdloc.setVisibility(View.VISIBLE); //将LinearLayout显示出来 get_mygdloction.setText("你当前的位置如下:\n" + LnglatString + "\n" + addressString); my_gdloc.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { //点击确定时,让界面消失 LinearLayout my_gdloc = (LinearLayout) GdMapActivity.this.findViewById(R.id.my_gdloc); my_gdloc.setVisibility(View.GONE); } }); }
LocationListener MyLocationListener = new LocationListener() { public void onStatusChanged(String provider, int status, Bundle extars) {} public void onProviderEnabled(String arg0) {} public void onProviderDisabled(String provider) { updataWithNewLocation(null); } public void onLocationChanged(Location location) { Log.i(TAG, "MyLocationListener::onLocationChanged.."); if (location != null) { Log.i(TAG, "得到地理坐标的经度:" + location.getLongitude()); Log.i(TAG, "得到地理坐标的纬度:" + location.getLatitude()); } updataWithNewLocation(location); } }; //不需要GPS时,就把GPS关掉 protected void onPause() { if (m_LocationManager != null) { m_LocationManager.removeUpdates(MyLocationListener); } super.onPause(); }
class MyLocationOverlay extends Overlay{ Location m_Location; //在更新坐标时,设置该坐标,以便画图 public void setLocation(Location location){ m_Location = location; }
public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, shadow); Paint paint = new Paint(); Point myScreenCoords = new Point(); try { GeoPoint tempGeoPoint = new GeoPoint((int)(m_Location.getLatitude() * 1E6),(int)(m_Location.getLongitude() * 1E6)); Log.i(TAG, "打印======"+(int)(m_Location.getLatitude() * 1E6)+", " + (int)(m_Location.getLongitude() * 1E6)); mapView.getProjection().toPixels(tempGeoPoint, myScreenCoords); paint.setStrokeWidth(1); paint.setARGB(255, 255, 0, 0); paint.setStyle(Paint.Style.STROKE); //定位好位置后,在位置上画图片,已标注出来 Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.marker_gpsvalid); //四个参数的含义是: 1 :图片 2:横坐标 3:纵坐标 4:点 canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint); canvas.drawText("我在这里", myScreenCoords.x, myScreenCoords.y, paint); } catch (Exception e) { Toast.makeText(GdMapActivity.this, "机器定位出现异常,请到室外接收卫星信号", Toast.LENGTH_LONG).show(); }
return ; } } /////////////////////////////////////////////////////////////////////////////// //这一段是导航所使用的方法 private void setInitView() { // 导航方式,默认为自驾使 navigation_gd = (ImageButton) this.findViewById(R.id.navigation_gd); calculateRoute = (Button) this.findViewById(R.id.calculateRoute); navigation_gd.setOnClickListener(clickListener); calculateRoute.setOnClickListener(clickListener); mMapView.setLongClickable(true); mGestureDetector.setIsLongpressEnabled(true); }

private void showPoiOverlay(String poiType, String cityStr, boolean start) {
try { if (start) { // PoiSearch.Query 设置POI 查询条件 // startStr为查询字符串,poiType为类型,cityStr是城市代码 poiSearchStart = new PoiSearch(this, new PoiSearch.Query( startStr, poiType, cityStr)); // 返回 PoiPagedResult resultStart = poiSearchStart.searchPOI(); // PoiOverlaySelectPoint继承自PoiOverlay,resultStart.getPage(1),取结果第一页 selectPointStart = new PoiOverlaySelectPoint(null, resultStart.getPage(1), startPoint, endPoint, true, this); selectPointStart.addToMap(mMapView); } else { poiSearchEnd = new PoiSearch(this, new PoiSearch.Query(endStr, poiType, cityStr)); // 返回 PoiPagedResult resultEnd = poiSearchEnd.searchPOI(); // PoiOverlaySelectPoint继承自PoiOverlay,resultStart.getPage(1),取结果第一页 selectPointEnd = new PoiOverlaySelectPoint(null, resultEnd.getPage(1), startPoint, endPoint, false, this); selectPointEnd.addToMap(mMapView); } } catch (IOException e) { this.showToast("网络连接异常"); e.printStackTrace(); } }
// 选择出行方式,默认为自驾驶 private void setModeBackResource(int mode) { mode = Route.DrivingDefault; }
// 点击方式 OnClickListener clickListener = new OnClickListener() {
public void reCalculate(int mode, GeoPoint start, GeoPoint end) { setModeBackResource(mode); if ((startPoint != null) && (endPoint != null)) { if (oldMode != mode) { try { displayRoute(startPoint, endPoint, mode); } catch (IllegalArgumentException e) {
} catch (Exception e1) {
} } }
}
public void onClick(View v) { // 计算路径 if (calculateRoute.equals(v)) { if (selectPointStart != null && selectPointEnd != null) { startPoint = selectPointStart.getStartPoint(); endPoint = selectPointEnd.getEndPoint(); } else if (selectPointStart == null && selectPointEnd != null) { endPoint = selectPointEnd.getEndPoint(); } else if (selectPointStart != null && selectPointEnd == null) { startPoint = selectPointStart.getStartPoint(); } try { mMapView.getOverlays().clear(); displayRoute(startPoint, endPoint, mode); } catch (IllegalArgumentException e) {
} catch (Exception e1) {
} setModeBackResource(mode); }
// navigation_gd 高德导航 if (navigation_gd.equals(v)) { //计算路径 calculateRoute.setClickable(true); Intent intent = new Intent(GdMapActivity.this, SearchInput.class); Bundle dle = new Bundle(); dle.putString("start", startStr); dle.putString("end", endStr); dle.putString("mode", String.valueOf(mode)); intent.putExtras(dle); if (routeOverlay != null) { routeOverlay.removeFromMap(mMapView); } GdMapActivity.this.startActivityForResult(intent, REQUESTCODE); }
// 设置默认模式为自驾模式
mode = Route.DrivingDefault; reCalculate(mode, startPoint, endPoint);
// MapView 点击选择起点 if (popupDipStart != null && popupDipStart.equals(v)) { startPoint = tempPoint; Intent intent = new Intent(GdMapActivity.this, SearchInput.class); Bundle dle = new Bundle(); dle.putString("start", POINT_IN_MAP); dle.putString("end", endStr); dle.putString("mode", String.valueOf(mode)); intent.putExtras(dle); mMapView.removeView(popupDipStart); GdMapActivity.this.startActivityForResult(intent, REQUESTCODE);
// MapView 点击选择终点 } else if (popupDipEnd != null && popupDipEnd.equals(v)) { endPoint = tempPoint;
Intent intent = new Intent(GdMapActivity.this, SearchInput.class); Bundle dle = new Bundle(); dle.putString("start", startStr); dle.putString("end", POINT_IN_MAP); dle.putString("mode", String.valueOf(mode)); intent.putExtras(dle); mMapView.removeView(popupDipEnd); GdMapActivity.this.startActivityForResult(intent, REQUESTCODE); }
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (intent != null) { Bundle bundle = intent.getExtras(); if (bundle != null) { startStr = bundle.getString("start"); endStr = bundle.getString("end"); dip = bundle.getString("dip"); // 判断点击按钮 String modeTemp = bundle.getString("mode"); if (modeTemp != null && (!modeTemp.equals(""))) { mode = Integer.parseInt(modeTemp); setModeBackResource(mode); } if (dip.equals("startDip")) {// 点击起点点选跳转到此 showToast("在地图上点击您的起点"); mMapView.setOnTouchListener(touchListener); } else if (dip.equals("endDip")) {// 点击终点点选跳转到此 showToast("在地图上点击您的终点"); mMapView.setOnTouchListener(touchListener); } else if (dip.equals("okDip")) {// 点击确定按钮跳转到此 if (startStr.equals(POINT_IN_MAP) && endStr.equals(POINT_IN_MAP)) {// 起终点都点选 calculateRoute.setClickable(false); try {
displayRoute(startPoint, endPoint, mode); } catch (IllegalArgumentException e) {
} catch (Exception e1) {
} } else if ((startStr.equals(POINT_IN_MAP))// 起点点选 && (!endStr.equals(POINT_IN_MAP))) { mMapView.getOverlays().clear(); removeMyView(mMapView); showPoiOverlay(PoiTypeDef.PlaceAndAddress, "110000", false); } else if ((!startStr.equals(POINT_IN_MAP))// 终点点选 && (endStr.equals(POINT_IN_MAP))) { mMapView.getOverlays().clear(); removeMyView(mMapView); showPoiOverlay(PoiTypeDef.PlaceAndAddress, "110000", true);
} else if ((!startStr.equals(POINT_IN_MAP))// 起终点都非点选 && (!endStr.equals(POINT_IN_MAP))) { mMapView.getOverlays().clear(); showPoiOverlay(PoiTypeDef.PlaceAndAddress, "110000", true); showPoiOverlay(PoiTypeDef.PlaceAndAddress, "110000", false); } } } } }
private void removeMyView(MapView mMapView2) { if (popupDipStart != null) { mMapView2.removeView(popupDipStart); } if (popupDipEnd != null) { mMapView2.removeView(popupDipEnd); }
}
private void displayRoute(GeoPoint startPoint, GeoPoint endPoint, int mode) throws IllegalArgumentException, Exception { if (startPoint != null && (!startPoint.equals("")) && endPoint != null && (!endPoint.equals(""))) { // FromAndTo 传入参数分别为 GeoPoint from, GeoPoint to, int trans // trans设置是否偏转 fromAndTo = new FromAndTo(startPoint, endPoint); try { if (routeOverlay != null) { routeOverlay.removeFromMap(mMapView); mMapView.getOverlays().clear(); } // 计算路径,传入参数分别为 MapActivity act, FromAndTo ft, int mode,mode // 为路径模式,返回路径规划的List route = Route.calculateRoute(GdMapActivity.this, fromAndTo, mode);
// 构造RouteOverlay 参数为 MapActivity cnt, Route rt。这里只取了查到路径的第一条。 if (route.size() > 0) { routeOverlay = new RouteOverlay(GdMapActivity.this, route.get(0)); routeOverlay.registerRouteMessage(GdMapActivity.this); routeOverlay.addToMap(mMapView); setOldRouteOverlay(routeOverlay); oldMode = mode; mMapView.setOnTouchListener(null); }
} catch (IOException e) { showToast("网络异常"); Log.v("SPAN", "not found load"); e.printStackTrace(); } catch (IllegalArgumentException e1) { e1.printStackTrace(); showToast("参数不正确"); throw new IllegalArgumentException(); } catch (Exception e2) { e2.printStackTrace(); showToast("路径查询异常"); throw new Exception(); } finally { mMapView.setOnTouchListener(null); calculateRoute.setClickable(false); }
} }
OnTouchListener touchListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return mGestureDetector.onTouchEvent(event); }
};
public boolean onDown(MotionEvent arg0) { // TODO Auto-generated method stub return false; }
public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { // TODO Auto-generated method stub return false; }
public void onLongPress(MotionEvent arg0) { // TODO Auto-generated method stub
}
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { // TODO Auto-generated method stub return false; }
public void onShowPress(MotionEvent arg0) { // TODO Auto-generated method stub
}
public boolean onSingleTapUp(MotionEvent e) { // mv.removeAllViews(); //会隐掉API的上一步下一步按钮 removeMyView(mMapView); float x = e.getX(); float y = e.getY(); tempPoint = mMapView.getProjection().fromPixels((int) x, (int) y); Resources res = GdMapActivity.this.getResources(); if (dip.equals("startDip")) { popupDipStart = new ImageButton(GdMapActivity.this); if (draw == null) { draw = res.getDrawable(R.drawable.popup); } popupDipStart.setBackgroundDrawable(draw); mMapView.addView( popupDipStart, new MapView.LayoutParams(draw.getIntrinsicWidth(), draw .getIntrinsicHeight(), tempPoint, LayoutParams.BOTTOM_CENTER)); popupDipStart.setOnClickListener(clickListener); } else if (dip.equals("endDip")) { popupDipEnd = new ImageButton(GdMapActivity.this); if (draw == null) { draw = res.getDrawable(R.drawable.popup); } popupDipEnd.setBackgroundDrawable(draw); mMapView.addView( popupDipEnd, new MapView.LayoutParams(draw.getIntrinsicWidth(), draw .getIntrinsicHeight(), tempPoint, LayoutParams.BOTTOM_CENTER)); popupDipEnd.setOnClickListener(clickListener); } mMapView.invalidate(); return false; }
// 在屏幕上显示Toast public void showToast(String showString) { Toast.makeText(getApplicationContext(), showString, Toast.LENGTH_SHORT) .show(); }
// RouteOverlay拖动过程中触发
public void onDrag(MapView mapView, RouteOverlay overlay, int index, GeoPoint newPos) { Log.v("SPAN", "on drag"); // TODO Auto-generated method stub }
// RouteOverlay拖动开始时触发 public void onDragBegin(MapView mapView, RouteOverlay overlay, int index, GeoPoint pos) { Log.v("SPAN", "on drag Begin"); calculateRoute.setClickable(false); // TODO Auto-generated method stub
}
// RouteOverlay拖动完成触发 public void onDragEnd(MapView mapView, RouteOverlay overlay, int index, GeoPoint pos) { Log.v("SPAN", "on drag end"); routeOverlay.removeFromMap(mMapView); try { startPoint = overlay.getStartPos(); endPoint = overlay.getEndPos(); overlay.renewOverlay(mapView); // displayRoute(overlay.getStartPos(), overlay.getEndPos(), mode); } catch (IllegalArgumentException e) { overlay.restoreOverlay(mMapView); overlayToBack(routeOverlay, mMapView); } catch (Exception e1) { overlay.restoreOverlay(mMapView); overlayToBack(routeOverlay, mMapView); } }
private void overlayToBack(RouteOverlay overlay, MapView mapView) { startPoint = overlay.getStartPos(); endPoint = overlay.getEndPos(); }
public boolean onRouteEvent(MapView arg0, RouteOverlay arg1, int arg2, int arg3) { // TODO Auto-generated method stub return false; }
public void setOldRouteOverlay(RouteOverlay oldRouteOverlay) { this.oldRouteOverlay = oldRouteOverlay; }
public RouteOverlay getOldRouteOverlay() { return oldRouteOverlay; } }
//导航代码结束 //////////////////////////////////////////////////////////////////////////

class OverItemT extends ItemizedOverlay<OverlayItem> { private List<OverlayItem> GeoList = new ArrayList<OverlayItem>(); private Drawable marker; private GdMapActivity mContext;
public OverItemT(Drawable marker, Context context) { super(boundCenterBottom(marker));
this.marker = marker; this.mContext = (GdMapActivity) context;
populate(); // createItem(int)方法构造item。一旦有了数据,在调用其它方法前,首先调用这个方法 }
@Override public void draw(Canvas canvas, MapView mapView, boolean shadow) {
// Projection接口用于屏幕像素点坐标系统和地球表面经纬度点坐标系统之间的变换 Projection projection = mapView.getProjection(); for (int index = size() - 1; index >= 0; index--) { // 遍历GeoList OverlayItem overLayItem = getItem(index); // 得到给定索引的item
String title = overLayItem.getTitle(); // 把经纬度变换到相对于MapView左上角的屏幕像素坐标 Point point = projection.toPixels(overLayItem.getPoint(), null);
/* 文字设置 */ Paint paintText = new Paint(); paintText.setColor(Color.RED); paintText.setAntiAlias(true); paintText.setFakeBoldText(true);
// 绘制文字 canvas.drawText(title, point.x - 50, point.y + 10, paintText); }
super.draw(canvas, mapView, shadow); // 调整一个drawable边界,使得(0,0)是这个drawable底部最后一行中心的一个像素 boundCenterBottom(marker); }
@Override protected OverlayItem createItem(int i) { // TODO Auto-generated method stub return GeoList.get(i); }
@Override public int size() { // TODO Auto-generated method stub return GeoList.size(); }
public void addOverlay(OverlayItem overlay) { GeoList.add(overlay); populate(); }
// 处理当点击事件 protected boolean onTap(int i) { setFocus(GeoList.get(i));
OverlayItem item = GeoList.get(i);
MapView.LayoutParams geoLP = (MapView.LayoutParams) mContext.popView .getLayoutParams(); String cropName = item.getTitle(); String snippet = item.getSnippet(); final String cropId = snippet.split(":")[0]; final int index = Integer.valueOf(snippet.split(":")[1]);
// 修改浮动气泡位置 geoLP.point = item.getPoint(); mContext.mMapView.updateViewLayout(mContext.popView, geoLP); mContext.popView.setVisibility(View.VISIBLE);
// 企业名称 TextView textView1 = (TextView) mContext .findViewById(R.id.map_bubbleTitle); textView1.setText(cropName);
// 按钮 Button button1 = (Button) mContext.findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mContext, CompanyDetailActivity.class); intent.putExtra("corpId", cropId); mContext.startActivity(intent); } });
Button button2 = (Button) mContext.findViewById(R.id.button2); button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mContext, DataMonitorActivity.class); intent.putExtra("index", index); mContext.startActivity(intent); } });
Button button3 = (Button) mContext.findViewById(R.id.button3); button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mContext, OperationMonitorActivity.class); intent.putExtra("index", index); mContext.startActivity(intent); } });
Button button4 = (Button) mContext.findViewById(R.id.button4); button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mContext, VideoActivity.class); intent.putExtra("index", index); mContext.startActivity(intent); } });
// 关闭浮动气泡 ImageView imageView = (ImageView) mContext .findViewById(R.id.map_bubbleImage); imageView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) {
mContext.popView.setVisibility(View.GONE); } }); return true; } }
/////////////////////////////////////////////////////////////////////////////////////////// PoiOverlaySelectPoint方法
package akson.epms;
import java.util.List;
import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.text.Html; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.TextView; import com.autonavi.mapapi.GeoPoint; import com.autonavi.mapapi.PoiItem; import com.autonavi.mapapi.PoiOverlay; /* * 继承PoiOverlay ,重写getPopupView 方法,实现在弹出窗口中添加设置起点/终点功能 */ public class PoiOverlaySelectPoint extends PoiOverlay {
private boolean start = true; private TextView startView, endView; private GeoPoint startPoint, endPoint, point; private Context context;
public PoiOverlaySelectPoint(Drawable pic, List<PoiItem> items, String catagory, GeoPoint startPoint, GeoPoint endPoint, boolean start,Context context) { super(pic, items, catagory); this.start = start; this.startPoint = startPoint; this.endPoint = endPoint; this.setContext(context); }
public PoiOverlaySelectPoint(Drawable pic, List<PoiItem> items, GeoPoint startPoint, GeoPoint endPoint, boolean start,Context context) { super(pic, items); this.start = start; this.startPoint = startPoint; this.endPoint = endPoint; this.setContext(context); } //重写PoiOverlay方法,在弹出窗口添加设置起点、终点功能 protected View getPopupView(PoiItem item) { View view = super.getPopupView(item); LinearLayout fill = new LinearLayout(view.getContext()); fill.setOrientation(LinearLayout.VERTICAL); fill.setGravity(Gravity.CENTER); fill.addView(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); startView = new TextView(view.getContext()); startView.setClickable(true); startView.setTextColor(Color.BLUE); startView.setTextSize(16); endView = new TextView(view.getContext()); endView.setClickable(true); endView.setTextColor(Color.BLUE); endView.setTextSize(16); if (start) { startView.setText(Html.fromHtml("<u>设为起点</u>")); startView.setOnClickListener(listener); fill.addView(startView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); } else { endView.setText(Html.fromHtml("<u>设为终点</u>")); endView.setOnClickListener(listener); fill.addView(endView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); } return fill; }
protected boolean onTap(int index) { super.onTap(index); point = super.getItem(index).getPoint(); return true; }
OnClickListener listener = new OnClickListener() {
public void onClick(View v) { if (startView.equals(v)) { startPoint = point; PoiOverlaySelectPoint.this.closePopupWindow(); } else if (endView.equals(v)) { endPoint = point; PoiOverlaySelectPoint.this.closePopupWindow(); }
} };
public GeoPoint getStartPoint() { return startPoint; }
public void setStartPoint(GeoPoint startPoint) { this.startPoint = startPoint; }
public GeoPoint getEndPoint() { return endPoint; }
public void setEndPoint(GeoPoint endPoint) { this.endPoint = endPoint; }
public void setContext(Context context) { this.context = context; }
public Context getContext() { return context; }
}

更多相关文章

  1. android 百度地图系列之地图初始化及定位
  2. Android Studio:10分钟教会你做百度地图定位!并解决SDK22中方法报
  3. Android 应用集成百度地图开发和注意事项
  4. Android Intent跳转第三方地图导航大全
  5. 百度地图自定义公交路线源码
  6. 地图相关
  7. 关于百度地图Android
  8. android 获取本地图片或音乐
  9. Flutter 混合开发 - 02 百度地图定位功能 android 篇

随机推荐

  1. android postInvalidateDelayed 方法
  2. Android(java)学习笔记88:TextView属性大全
  3. Android(安卓)ColorStateList使用方法
  4. 更新UI时遇到:Only the original thread t
  5. Android okhttp3 底层网络实现解析
  6. android 第一行代码(第二版)Litepal遇到的
  7. android 设置dialog的黑暗度
  8. 收藏的Android很好用的组件或者框架。
  9. Android 4.0 事件输入(Event Input)系统
  10. QT 环境的 Android(安卓)配置和编译