好炫的高德:
Mainfest清单:需要key
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.xmb.test_1" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <meta-data android:name="com.amap.api.v2.apikey" android:value="d707ab913a39a7801a58807f022e6439" /> <activity android:name=".Main2" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".TakePictures" android:screenOrientation="landscape"> </activity> </application> <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"></uses-permission> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.CAMERA"/> <!-- 在SDCard中创建与删除文件权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- 往SDCard写入数据权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> </manifest>
main2.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <fragment android:id="@+id/map1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginRight="5dp" android:layout_weight="1" class="com.amap.api.maps.SupportMapFragment" />" </LinearLayout>
Main2.java
1 package com.xmb.test_1; 2 3 4 import com.amap.api.location.AMapLocation; 5 import com.amap.api.location.AMapLocationListener; 6 import com.amap.api.location.LocationManagerProxy; 7 import com.amap.api.location.LocationProviderProxy; 8 import com.amap.api.maps.AMap; 9 import com.amap.api.maps.AMap.OnMapClickListener; 10 import com.amap.api.maps.LocationSource.OnLocationChangedListener; 11 import com.amap.api.maps.SupportMapFragment; 12 import com.amap.api.maps.model.BitmapDescriptorFactory; 13 import com.amap.api.maps.model.LatLng; 14 import com.amap.api.maps.model.MarkerOptions; 15 import com.amap.api.search.core.AMapException; 16 import com.amap.api.search.core.LatLonPoint; 17 import com.amap.api.search.route.Route; 18 import com.amap.api.search.route.Route.FromAndTo; 19 20 import android.annotation.SuppressLint; 21 import android.app.Activity; 22 import android.location.Criteria; 23 import android.location.Location; 24 import android.os.Bundle; 25 import android.support.v4.app.FragmentActivity; 26 import android.util.Log; 27 import android.view.View; 28 29 public class Main2 extends FragmentActivity implements AMapLocationListener{ 30 private AMap mMapView; 31 private OnLocationChangedListener mListener; 32 private LocationManagerProxy locationManager = null; //声明LocationManagerProxy 33 protected void onCreate(Bundle savedInstanceState) { 34 super.onCreate(savedInstanceState); 35 setContentView(R.layout.main2); 36 locationManager = LocationManagerProxy.getInstance(this); //初始化LocationManagerProxy 37 mMapView= ((SupportMapFragment) getSupportFragmentManager() 38 .findFragmentById(R.id.map1)).getMap(); 39 //mMapView.setMapType(AMap. MAP_TYPE_SATELLITE); //卫星界面 40 //标记Marker 41 /*LatLng marker1 = new LatLng(23.173218,113.413142); 42 mMapView.addMarker(new MarkerOptions().position(marker1).title("Marker1 ") 43 .icon(BitmapDescriptorFactory 44 .fromResource(R.drawable.car_green)).snippet("Marker2") 45 .draggable(true));*/ 46 //监听动作 47 /*mMapView.setOnMapClickListener(new OnMapClickListener(){ 48 49 @Override 50 public void onMapClick(LatLng arg0) { 51 // TODO Auto-generated method stub 52 mMapView.addMarker(new MarkerOptions().position(arg0).title("Marker1 ") 53 .icon(BitmapDescriptorFactory 54 .fromResource(R.drawable.car_green)).snippet("Marker2") 55 .draggable(true)); 56 } 57 58 });*/ 59 //enableMyLocation(); 60 //路线规划(驾车) 61 LatLonPoint startpoint=new LatLonPoint(23.173218,113.413142); 62 LatLonPoint endtpoint=new LatLonPoint(23.072222,113.402222); 63 FromAndTo fromAndTo = new FromAndTo(startpoint, endtpoint); 64 //routeResult = Route.calculateRoute(Main2.this, fromAndTo,Route.WalkDefault); 65 Route route = null; 66 try { 67 route = Route.calculateRoute(Main2.this, fromAndTo,Route.DrivingDefault).get(0); 68 } catch (AMapException e) { 69 // TODO Auto-generated catch block 70 e.printStackTrace(); 71 } //这里只取出查询路径的第一条 72 if (route != null) { 73 RouteOverlay routeOverlay = new RouteOverlay (Main2.this,mMapView, route); 74 routeOverlay.removeFormMap(); 75 routeOverlay.addMarkerLine(); 76 } 77 78 79 } 80 81 //初始化一个Criteria 对象,设置相关参数,此对象自动匹配最适合的定位类型。调用enableMyLocation函数启动定位模块,disableMyLocation 函数关闭定位模块。 82 83 //根据Criteria 对象获取提供位置信息的provider,并启动定位模块 84 85 @SuppressLint("ParserError") 86 public boolean enableMyLocation() { 87 88 89 90 boolean result = true; 91 92 Criteria cri = new Criteria(); 93 94 cri.setAccuracy(Criteria.ACCURACY_COARSE); 95 96 cri.setAltitudeRequired(false); 97 98 cri.setBearingRequired(false); 99 100 cri.setCostAllowed(false); 101 102 String bestProvider = locationManager.getBestProvider(cri, true); 103 104 locationManager.requestLocationUpdates(bestProvider, 10000, 10, 105 106 this); 107 Log.i("out", "1"); 108 return result; 109 110 } 111 112 // 关闭定位模块 113 114 public void disableMyLocation() { 115 116 locationManager.removeUpdates(this); 117 locationManager =null; 118 119 } 120 121 //LocationListener 的监听接口 122 123 @Override 124 125 public void onLocationChanged(Location location) { 126 127 // TODO Auto-generated method stub 128 129 if (location != null) { 130 131 Double geoLat = location.getLatitude(); 132 133 Double geoLng = location.getLongitude(); 134 135 String str =("定位成功1:(" + geoLng + "," + geoLat + ")"); 136 137 Log.i("out","str1="+str); 138 139 }else{ 140 Log.i("out", "null"); 141 } 142 143 } 144 @Override 145 public void onProviderDisabled(String provider) { 146 // TODO Auto-generated method stub 147 148 } 149 150 @Override 151 public void onProviderEnabled(String provider) { 152 // TODO Auto-generated method stub 153 enableMyLocation(); 154 } 155 156 @Override 157 public void onStatusChanged(String provider, int status, Bundle extras) { 158 // TODO Auto-generated method stub 159 160 } 161 162 @Override 163 public void onLocationChanged(AMapLocation arg0) { 164 // TODO Auto-generated method stub 165 if (arg0 != null) { 166 167 Double geoLat = arg0.getLatitude(); 168 169 Double geoLng = arg0.getLongitude(); 170 Bundle locBundle = arg0.getExtras(); 171 if (locBundle != null) { 172 // 城市编码及位置描述 173 String cityCode = locBundle.getString("citycode"); 174 String desc = locBundle.getString("desc"); 175 } 176 177 String str =("定位成功2:(" + geoLng + "," + geoLat + ")"); 178 179 Log.i("out","str2="+str+"citycode="+locBundle.getString("citycode")+",addr="+locBundle.getString("desc")); 180 181 }else{ 182 Log.i("out", "null"); 183 } 184 } 185 186 }
工具类,画图:
RouteOverlay.java
package com.xmb.test_1; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import android.content.Context; import android.graphics.Color; import android.text.Spanned; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.amap.api.maps.AMap; import com.amap.api.maps.AMap.InfoWindowAdapter; import com.amap.api.maps.AMap.OnMarkerClickListener; import com.amap.api.maps.CameraUpdateFactory; import com.amap.api.maps.model.BitmapDescriptor; import com.amap.api.maps.model.BitmapDescriptorFactory; import com.amap.api.maps.model.LatLng; import com.amap.api.maps.model.Marker; import com.amap.api.maps.model.MarkerOptions; import com.amap.api.maps.model.PolylineOptions; import com.amap.api.search.core.LatLonPoint; import com.amap.api.search.route.BusSegment; import com.amap.api.search.route.DriveSegment; import com.amap.api.search.route.WalkSegment; import com.amap.api.search.route.Route; import com.amap.api.search.route.Segment; public class RouteOverlay implements OnMarkerClickListener, InfoWindowAdapter { private AMap mMap; private Route mRoute; private LatLng startPoint; private LatLng endPoint; private Context mContext; private Map<Integer, Marker> markerMap; private int currentIndex = 0; private static int zoomLevel = 15; public RouteOverlay(Context context, AMap map, Route route) { mContext = context; mMap = map; mRoute = route; mMap.setOnMarkerClickListener(this); mMap.setInfoWindowAdapter(this); startPoint = SearchPointConvert(route.getStartPos()); endPoint = SearchPointConvert(route.getTargetPos()); markerMap = new HashMap<Integer, Marker>(); } /** * 绘制节点和线路 */ public void addMarkerLine() { Marker startMarker = mMap.addMarker((new MarkerOptions()) .position(startPoint) .icon(BitmapDescriptorFactory.fromResource(R.drawable.start)) .title("0")); startMarker.showInfoWindow(); mMap.moveCamera(CameraUpdateFactory .newLatLngZoom(startPoint, zoomLevel)); markerMap.put(0, startMarker); for (int i = 0; i < mRoute.getStepCount(); i++) { if (i != 0) { Segment segment = mRoute.getStep(i); BitmapDescriptor icon = null; if (segment instanceof BusSegment) { icon = BitmapDescriptorFactory.fromResource(R.drawable.little); } else if (segment instanceof WalkSegment) { icon = BitmapDescriptorFactory.fromResource(R.drawable.little); } else if (segment instanceof DriveSegment) { icon = BitmapDescriptorFactory.fromResource(R.drawable.little); } Marker tempMarker = mMap.addMarker((new MarkerOptions()) .position( SearchPointConvert(mRoute.getStep(i) .getFirstPoint())).icon(icon) .anchor(0.5f, 0.5f).title("" + i)); markerMap.put(i, tempMarker); } mMap.addPolyline((new PolylineOptions()) .addAll(convertArrList(mRoute.getStep(i).getShapes())) .color(Color.argb(180, 54, 114, 227)).width(20.9F)); } Marker targerMarker = mMap.addMarker((new MarkerOptions()) .position(endPoint) .icon(BitmapDescriptorFactory.fromResource(R.drawable.end)) .title("" + (mRoute.getStepCount()))); markerMap.put(mRoute.getStepCount(), targerMarker); } /** * 清除绘制 */ public void removeFormMap() { currentIndex = 0; mMap.clear(); } public boolean showPrePopInfo() { if (currentIndex > 0) { currentIndex--; Marker merker = markerMap.get(currentIndex); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom( merker.getPosition(), zoomLevel)); merker.showInfoWindow(); } if (currentIndex == 0) { return false; } else { return true; } } public boolean showNextPopInfo() { if (currentIndex < mRoute.getStepCount()) { currentIndex++; Marker merker = markerMap.get(currentIndex); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom( merker.getPosition(), zoomLevel)); merker.showInfoWindow(); } if(currentIndex == mRoute.getStepCount()){ return false; }else{ return true; } } @Override public boolean onMarkerClick(Marker marker) { marker.showInfoWindow(); currentIndex = Integer.parseInt(marker.getTitle()); return false; } @Override public View getInfoContents(Marker arg0) { int index = Integer.parseInt(arg0.getTitle()); return getInfoView(mContext, index); } @Override public View getInfoWindow(Marker arg0) { return null; } /** * 根据Segment index 生成popInfo view * * @param index * @return */ public View getInfoView(Context cnt, int index) { if (index < 0 || index > mRoute.getStepCount()) { return null; } LinearLayout ll_parents = new LinearLayout(cnt); ll_parents.setOrientation(LinearLayout.VERTICAL); ll_parents.setBackgroundResource(R.drawable.custom_info_bubble); LinearLayout ll_child1 = new LinearLayout(cnt); ll_child1.setOrientation(LinearLayout.HORIZONTAL); ll_child1.setGravity(Gravity.AXIS_PULL_BEFORE); TextView titleVw = new TextView(cnt); String spannedInfos[] = getSpannedInfo(index).toString() .split("\\n", 2); titleVw.setTextColor(Color.BLACK); titleVw.setText(AMapUtil.stringToSpan(spannedInfos[0])); titleVw.setPadding(3, 0, 0, 3); ll_child1.addView(titleVw, new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); TextView backgroud = new TextView(cnt); backgroud.setBackgroundColor(Color.rgb(165, 166, 165)); backgroud.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 1)); LinearLayout ll_child3 = new LinearLayout(cnt); ll_child3.setOrientation(LinearLayout.VERTICAL); TextView titleVwdown = new TextView(cnt); if (spannedInfos.length == 2) { ll_child3.addView(backgroud, new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 1)); titleVwdown.setText(AMapUtil.stringToSpan(spannedInfos[1])); titleVwdown.setTextColor(Color.rgb(82, 85, 82)); ll_child3.addView(titleVwdown, new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); } LinearLayout ll_child2 = new LinearLayout(cnt); ll_child2.setOrientation(LinearLayout.HORIZONTAL); ll_child2.setGravity(Gravity.CENTER_HORIZONTAL); ll_parents.addView(ll_child1, new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); ll_parents.addView(ll_child3, new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 1)); ll_parents.addView(ll_child2, new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); return ll_parents; } /** * 获取popInfo描述 * * @param index * @return */ public Spanned getSpannedInfo(int index) { if (index == mRoute.getStepCount()) { StringBuffer buf = new StringBuffer(); buf.append(ChString.Arrive); buf.append(mRoute.getTargetPlace()); return AMapUtil.stringToSpan(buf.toString()); } if (mRoute.getStep(index) instanceof BusSegment) { return getBusSpan(index); } else if (mRoute.getStep(index) instanceof DriveSegment) { return getCarInfo(index); } return getFootSpan(index); } /** * 获取公交popInfo描述 * * @param index * @return */ private Spanned getBusSpan(int index) { BusSegment seg = (BusSegment) mRoute.getStep(index); StringBuffer buf = new StringBuffer(); buf.append(AMapUtil.colorFont(seg.getLineName(), AMapUtil.HtmlBlack)); buf.append(AMapUtil.makeHtmlSpace(3)); buf.append(AMapUtil.colorFont(seg.getLastStationName(), AMapUtil.HtmlBlack)); buf.append(ChString.Direction); buf.append(AMapUtil.makeHtmlNewLine()); buf.append(ChString.GetOn + " : "); buf.append(AMapUtil.colorFont(seg.getOnStationName(), AMapUtil.HtmlBlack)); buf.append(AMapUtil.makeHtmlSpace(3)); buf.append(AMapUtil.makeHtmlNewLine()); buf.append(ChString.GetOff + " : "); buf.append(AMapUtil.colorFont(seg.getOffStationName(), AMapUtil.HtmlBlack)); buf.append(AMapUtil.makeHtmlNewLine()); buf.append(String.format("%s%d%s , ", ChString.Gong, seg.getStopNumber() - 1, ChString.Zhan)); buf.append(ChString.About + AMapUtil.getFriendlyLength(seg.getLength())); return AMapUtil.stringToSpan(buf.toString()); } /** * 获取驾车popInfo描述 * * @param index * @return */ public Spanned getCarInfo(int index) { String content = ""; DriveSegment seg = (DriveSegment) mRoute.getStep(index); if (!AMapUtil.IsEmptyOrNullString(seg.getRoadName()) && !AMapUtil.IsEmptyOrNullString(seg.getActionDescription())) { content = seg.getActionDescription() + " --> " + seg.getRoadName(); } else { content = seg.getActionDescription() + seg.getRoadName(); } content = AMapUtil.colorFont(content, AMapUtil.HtmlGray); content += AMapUtil.makeHtmlNewLine(); content += String.format("%s%s", ChString.About, AMapUtil.getFriendlyLength(seg.getLength())); return AMapUtil.stringToSpan(content); } /** * 获取步行popInfo描述 * * @param index * @return */ private Spanned getFootSpan(int index) { if (mRoute.getMode() == Route.WalkDefault) { String content = ""; WalkSegment seg = (WalkSegment) mRoute.getStep(index); if (!AMapUtil.IsEmptyOrNullString(seg.getRoadName()) && !AMapUtil .IsEmptyOrNullString(seg.getActionDescription())) { content = seg.getActionDescription() + " --> " + seg.getRoadName(); } else { content = seg.getActionDescription() + seg.getRoadName(); } content = AMapUtil.colorFont(content, AMapUtil.HtmlGray); content += AMapUtil.makeHtmlNewLine(); content += String.format("%s%s", ChString.About, AMapUtil.getFriendlyLength(seg.getLength())); return AMapUtil.stringToSpan(content); } else { StringBuilder result = new StringBuilder(); result.append(ChString.ByFoot).append(ChString.To); if (index == mRoute.getStepCount() - 1) { result.append(AMapUtil.colorFont(ChString.TargetPlace, AMapUtil.HtmlGray)); } else { result.append(AMapUtil.colorFont( ((BusSegment) mRoute.getStep(index + 1)).getLineName() + ChString.Station, AMapUtil.HtmlGray)); } result.append(AMapUtil.makeHtmlNewLine()); result.append(ChString.About + AMapUtil.getFriendlyLength(mRoute.getStep(index) .getLength())); return AMapUtil.stringToSpan(result.toString()); } } /** * 工具方法, 将一个segment shaps 转化成map的LatLng list 方便添加到地图 * * @param shapes * @return */ private ArrayList<LatLng> convertArrList(LatLonPoint[] shapes) { ArrayList<LatLng> lineShapes = new ArrayList<LatLng>(); for (LatLonPoint point : shapes) { LatLng latLngTemp = SearchPointConvert(point); lineShapes.add(latLngTemp); } return lineShapes; } /** * 工具方法,将搜索得到的LatLonPoint转成latLng 才能添加到地图上 * * @param latLonPoint * @return */ private LatLng SearchPointConvert(LatLonPoint latLonPoint) { return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()); } }
ChString.java
package com.xmb.test_1; public class ChString { public static final String Kilometer = "\u516c\u91cc";// "公里"; public static final String Meter = "\u7c73";// "米"; public static final String ByFoot = "\u6b65\u884c";// "步行"; public static final String To = "\u53bb\u5f80";// "去往"; public static final String Station = "\u8f66\u7ad9";// "车站"; public static final String TargetPlace = "\u76ee\u7684\u5730";// "目的地"; public static final String StartPlace = "\u51fa\u53d1\u5730";// "出发地"; public static final String About = "\u5927\u7ea6";// "大约"; public static final String Direction = "\u65b9\u5411";// "方向"; public static final String GetOn = "\u4e0a\u8f66";// "上车"; public static final String GetOff = "\u4e0b\u8f66";// "下车"; public static final String Zhan = "\u7ad9";// "站"; public static final String cross = "\u4ea4\u53c9\u8def\u53e3"; // 交叉路口 public static final String type = "\u7c7b\u522b"; // 类别 public static final String address = "\u5730\u5740"; // 地址 public static final String PrevStep = "\u4e0a\u4e00\u6b65"; public static final String NextStep = "\u4e0b\u4e00\u6b65"; public static final String Gong = "\u516c\u4ea4"; public static final String ByBus = "\u4e58\u8f66"; public static final String Arrive = "\u5230\u8FBE";// 到达 }