如何在 google 中的地图中选择不同的路线 android?
How to make different routes selectable in google Maps in android?
我正在开发一个使用大量 google 地图交互的应用程序。在 activity 中,我显示了两点之间的路线。我希望这些路线可以选择,根据用户的选择显示请帮助我。
我在这里附上 activity 的图片:
这里是上面显示的 activity 的代码:
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;
}
}
在 abouce 代码中,我使用 google 方向创建这些路径 api
请帮忙选择不同的路线。谢谢
伙计们,我已经实现了所需的功能,只是对现有代码进行了一些更改,现在可以使用了。感谢您的指导:)
我正在开发一个使用大量 google 地图交互的应用程序。在 activity 中,我显示了两点之间的路线。我希望这些路线可以选择,根据用户的选择显示请帮助我。
我在这里附上 activity 的图片:
这里是上面显示的 activity 的代码:
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;
}
}
在 abouce 代码中,我使用 google 方向创建这些路径 api
请帮忙选择不同的路线。谢谢
伙计们,我已经实现了所需的功能,只是对现有代码进行了一些更改,现在可以使用了。感谢您的指导:)