如何在android的谷歌地图中选择不同的路线?
我正在开发一个应用程序,它使用大量的谷歌地图交互。在一个活动中,我展示了两点之间的路线。我希望这些路线是可选的,根据用户的选择显示,请帮助我。 这里我附上活动的图片: 下面是上述活动的代码:如何在android的谷歌地图中选择不同的路线?,android,google-maps-android-api-2,google-directions-api,Android,Google Maps Android Api 2,Google Directions Api,我正在开发一个应用程序,它使用大量的谷歌地图交互。在一个活动中,我展示了两点之间的路线。我希望这些路线是可选的,根据用户的选择显示,请帮助我。 这里我附上活动的图片: 下面是上述活动的代码: public class RouteActivity extends FragmentActivity { private GoogleMap mMap; // Might be null if Google Play services APK is not available. double sl1,sl
public class RouteActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
double sl1,sl2,el1,el2;
FrameLayout fl;
TextView distTextView,timeTextView;
String routeArray[];
List<LatLng> list;
List<Polyline> polylineList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route);
setUpMapIfNeeded();
mMap.getUiSettings().setZoomControlsEnabled(true);
polylineList=new ArrayList<Polyline>();
fl=(FrameLayout)findViewById(R.id.frame_layout);
distTextView=(TextView)findViewById(R.id.distance_textView);
timeTextView=(TextView)findViewById(R.id.time_textView);
String start = getIntent().getStringExtra("start");
String end = getIntent().getStringExtra("end");
Geocoder coder = new Geocoder(this);
List<Address> address;
try {
address = coder.getFromLocationName(start, 5);
if (address == null) {
}
Address location = address.get(0);
sl1=location.getLatitude();
sl2=location.getLongitude();
} catch (IOException e) {
e.printStackTrace();
}
try {
address = coder.getFromLocationName(end, 5);
if (address == null) {
}
Address location = address.get(0);
el1=location.getLatitude();
el2=location.getLongitude();
} catch (IOException e) {
e.printStackTrace();
}
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.from);
markers[0]=mMap.addMarker(new MarkerOptions().position(new LatLng(sl1, sl2)).title(start).icon(icon));
markers[1]=mMap.addMarker(new MarkerOptions().position(new LatLng(el1, el2)).title(end).icon(icon));
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();
CameraUpdate cu=CameraUpdateFactory.newLatLngBounds(bounds,500,500,0);
mMap.moveCamera(cu);
mMap.animateCamera(cu);
String url=makeURL(sl1,sl2,el1,el2);
Log.e("Generated URL ",url);
new MyAsyncTask().execute(url);
fl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
int x=0;
for (Polyline polyline : polylineList)
{
for (LatLng polyCoords : polyline.getPoints()) {
float[] results = new float[1];
Location.distanceBetween(latLng.latitude, latLng.longitude,
polyCoords.latitude, polyCoords.longitude, results);
if (results[0] < 100) {
mMap.clear();
for(Polyline pl:polylineList)
{
if(pl!=polyline) {
mMap.addPolyline(new PolylineOptions().color(Color.GRAY).addAll(pl.getPoints()));
}
else if(pl==polyline)
{
mMap.addPolyline(new PolylineOptions()
.color(Color.BLUE)
.addAll(pl.getPoints()));
}
}
}
}
}
Log.e("PolyLine ",polylineList.toString());
}
});
}
@Override
protected void onResume() {
super.onResume();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
public class MyAsyncTask extends AsyncTask<String,Void,String> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
progressDialog=new ProgressDialog(RouteActivity.this);
progressDialog.setMessage("Finding Route ...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.show();
}
@Override
protected String doInBackground(String... str) {
ParserClass parser = new ParserClass();
String json_str = parser.getJSON(str[0], 2000);
Log.e("JSON Data", json_str);
return json_str;
}
@Override
protected void onPostExecute(String s) {
try {
progressDialog.dismiss();
JSONObject jsonRootObject = new JSONObject(s);
JSONArray routeArray=jsonRootObject.getJSONArray("routes");
Log.e("ROUTES ",routeArray.toString());
for(int i=routeArray.length()-1;i>=0;i--) {
JSONObject routes = routeArray.getJSONObject(i);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
JSONArray legs=routes.getJSONArray("legs");
for(int j=0;j<legs.length();j++)
{
JSONObject distObj=legs.getJSONObject(j);
JSONObject distance =distObj.getJSONObject("distance");
String dist=distance.getString("text");
JSONObject duration=distObj.getJSONObject("duration");
String time=duration.getString("text");
Log.e("Route"+i+" DISTANCE ",dist);
Log.e("Route"+i+" TIME ",time);
distTextView.setText("Distance "+dist);
timeTextView.setText("Time "+time);
}
String encodedString = overviewPolylines.getString("points");
Log.e("Waypoint "+i,encodedString);
list = decodePoly(encodedString);
Log.e("List "+i,list.toString());
if(i==0) {
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.BLUE)
.geodesic(true)
);
Log.e("PolyLine ",line.toString());
polylineList.add(line);
}
else{
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.DKGRAY)
.geodesic(true)
);
polylineList.add(line);
Log.e("PolyLine ",line.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
private void setUpMap() {
mMap.clear();
}
public void showMap(Double l1,Double l2,String str)
{
LatLng position=new LatLng(l1,l2);
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap googleMap = fm.getMap();
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.from);
mMap.addMarker(new MarkerOptions().position(new LatLng(l1, l2)).title(str).icon(icon));
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);
CameraUpdate updateZoom=CameraUpdateFactory.zoomTo(15);
googleMap.moveCamera(updatePosition);
googleMap.animateCamera(updateZoom);
}
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
StringBuilder urlString = new StringBuilder();
urlString.append("https://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode=driving&alternatives=true&units=imperial");
urlString.append("&key=AIzaSyD5NOOpYKObjlZbt_-4CUOMi14mObzbGNo");
return urlString.toString();
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
公共类RouteActivity扩展了FragmentActivity{
私有GoogleMap mMap;//如果Google Play services APK不可用,则可能为空。
双sl1,sl2,el1,el2;
框架布局fl;
TextView distTextView、timeTextView;
字符串routerray[];
名单;
列表列表;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route);
setupmapifneed();
mMap.getUiSettings().setZoomControlsEnabled(true);
polylineList=新的ArrayList();
fl=(框架布局)findViewById(R.id.frame\U布局);
distTextView=(TextView)findViewById(R.id.distance\u TextView);
timeTextView=(TextView)findViewById(R.id.time\u TextView);
字符串start=getIntent().getStringExtra(“start”);
字符串结束=getIntent().getStringExtra(“结束”);
地理编码器=新地理编码器(本);
名单地址;
试一试{
地址=编码器.getFromLocationName(开始,5);
如果(地址==null){
}
地址位置=地址。获取(0);
sl1=location.getLatitude();
sl2=location.getLongitude();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
地址=编码器.getFromLocationName(结束,5);
如果(地址==null){
}
地址位置=地址。获取(0);
el1=location.getLatitude();
el2=location.getLongitude();
}捕获(IOE异常){
e、 printStackTrace();
}
BitmapDescriptor图标=BitmapDescriptorFactory.fromResource(R.drawable.from);
markers[0]=mMap.addMarker(newmarkeroptions().position(new-LatLng(sl1,sl2)).title(start).icon(icon));
markers[1]=mMap.addMarker(新MarkerOptions().position(新LatLng(el1,el2)).title(end).icon(icon));
LatLngBounds.Builder=新的LatLngBounds.Builder();
用于(标记:标记){
include(marker.getPosition());
}
LatLngBounds bounds=builder.build();
CameraUpdate cu=CameraUpdateFactory.newLatLngBounds(边界,500500,0);
移动摄像机(cu);
mMap.animateCamera(cu);
字符串url=makeURL(sl1、sl2、el1、el2);
Log.e(“生成的URL”,URL);
新建MyAsyncTask().execute(url);
fl.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
完成();
}
});
mMap.setOnMapClickListener(新的GoogleMap.OnMapClickListener(){
@凌驾
公共无效的点击(LatLng LatLng){
int x=0;
用于(多段线多段线:多段线列表)
{
对于(LatLng polyCoords:polyline.getPoints()){
浮动[]结果=新浮动[1];
位置。距离(纬度、经度、,
polyCoords.纬度,polyCoords.经度,结果);
如果(结果[0]<100){
mMap.clear();
用于(多段线pl:polylineList)
{
如果(pl!=多段线){
addPolyline(新的PolylineOptions().color(color.GRAY).addAll(pl.getPoints());
}
else if(pl==多段线)
{
mMap.addPolyline(新的PolylineOptions()
.颜色(颜色.蓝色)
.addAll(pl.getPoints());
}
}
}
}
}
Log.e(“PolyLine”,polylineList.toString());
}
});
}
@凌驾
受保护的void onResume(){
super.onResume();
}
私有void setUpMapIfNeeded(){
//执行空检查以确认尚未实例化映射。
如果(mMap==null){
//尝试从SupportMapFragment获取映射。
mMap=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
//检查我们是否成功获得地图。
如果(mMap!=null){
setUpMap();
}
}
}
公共类MyAsyncTask扩展了AsyncTask{
进行对话进行对话;
@凌驾
受保护的void onPreExecute(){
progressDialog=新建progressDialog(RouteActivity.this);
progressDialog.setMessage(“查找路由…”);
progressDialog.setCancelable(假);
progressDialog.setUndeterminate(false);
progressDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…str){
ParserClass parser=新的ParserClass();
字符串json_str=parser.getJSON(str[0],2000);
Log.e(“JSON数据”,JSON_str);
返回json_str;
}
@凌驾
受保护的void onPostExecute(字符串s){
试一试{
progressDialog.disclose();
JSONObject jsonRootObject=新的JSONObject;
JSONArray routarray=jsonRootObject.getJSONArray(“路由”);
Log.e(“ROUTES”,routeArray.toString());
对于(int i=routarray.length()-1;i>=0;i--){
JSONObject routes=routeArray.getJSONObject(i);
JSONObject overviewPolylines=routes.getJSONObject(“overview_Polylines”);
JSONArray legs=routes.getJSONArray(“legs”);
对于(intj=0;j>1):(结果>>1));
lat+=dlat;
移位=0;
结果=0;
做{
b=编码的.charAt(索引++)-63;
结果|=(b&0x1f)=0x20);
int dlng=((结果和1)!=0?~(结果)