我有这个倾向:
list.add(new LatLng(51.410831451416016,16.195022583007812));
list.add(new LatLng(51.40906524658203,16.19700813293457));
list.add(new LatLng(51.406280517578125,16.200498580932617));
list.add(new LatLng(51.40361022949219,16.20193862915039));
list.add(new LatLng(51.400203704833984,16.20381736755371));
list.add(new LatLng(51.400081634521484,16.213804244995117));
list.add(new LatLng(51.40199661254883,16.216102600097656));
list.add(new LatLng(51.40852355957031,16.219417572021484));
list.add(new LatLng(51.43153762817383,16.23755645751953));
list.add(new LatLng(51.447242736816406,16.245569229125977));
list.add(new LatLng(51.45175552368164,16.234098434448242));
list.add(new LatLng(51.45286178588867,16.24496841430664));
list.add(new LatLng(51.46625900268555,16.2692928314209));
list.add(new LatLng(51.47911071777344,16.266849517822266));
list.add(new LatLng(51.50560760498047,16.268840789794922));
list.add(new LatLng(51.510677337646484,16.259723663330078));
list.add(new LatLng(51.510677337646484,16.259723663330078));
list.add(new LatLng(51.50559997558594,16.2688045501709));
list.add(new LatLng(51.476688385009766,16.267772674560547));
list.add(new LatLng(51.46686935424805,16.270612716674805));
list.add(new LatLng(51.451759338378906,16.234111785888672));
list.add(new LatLng(51.45033264160156,16.244768142700195));
list.add(new LatLng(51.44853591918945,16.24496841430664));
list.add(new LatLng(51.43154525756836,16.237483978271484));
list.add(new LatLng(51.40877151489258,16.21938133239746));
我想获取路线并将其绘制在地图上。
我创建了一种方法来生成路线beetwen两个poit。
private class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
@Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
for (int i = 0; i < result.size(); i++) {
points = new ArrayList();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);
}
mMap.addPolyline(lineOptions);
}
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
String mode = "mode=driving";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
有时候我有300磅点,并下载了点1到2,然后是2到3等的路由。这样做是更好的主意吗?我所做的事情持续了很长时间,我掌握了很多信息。
答案 0 :(得分:4)
我已经在您的指南的代码中进行了注释,您可以使用此代码从航点获取路线。
public class DirectionFinder {
// this is directio api URL
private static final String DIRECTION_URL_API = "https://maps.googleapis.com/maps/api/directions/json?";
// your api key
private static final String GOOGLE_API_KEY = "YOUR_API_KEY";
// your origin point latlong
LatLng originlatlong;
// your destinatio point latlong
LatLng destinationlatlong;
// your array list of waypoints
ArrayList<LatLng> waypoints;
// adding way points to arraylist
void addwaypoints(){
waypoints = new ArrayList<>()
waypoints.add(new LatLng(51.410831451416016,16.195022583007812));
waypoints.add(new LatLng(51.40906524658203,16.19700813293457));
waypoints.add(new LatLng(51.406280517578125,16.200498580932617));
waypoints.add(new LatLng(51.40361022949219,16.20193862915039));
waypoints.add(new LatLng(51.400203704833984,16.20381736755371));
waypoints.add(new LatLng(51.400081634521484,16.213804244995117));
waypoints.add(new LatLng(51.40199661254883,16.216102600097656));
waypoints.add(new LatLng(51.40852355957031,16.219417572021484));
waypoints.add(new LatLng(51.43153762817383,16.23755645751953));
waypoints.add(new LatLng(51.447242736816406,16.245569229125977));
waypoints.add(new LatLng(51.45175552368164,16.234098434448242));
waypoints.add(new LatLng(51.45286178588867,16.24496841430664));
waypoints.add(new LatLng(51.46625900268555,16.2692928314209));
waypoints.add(new LatLng(51.47911071777344,16.266849517822266));
waypoints.add(new LatLng(51.50560760498047,16.268840789794922));
waypoints.add(new LatLng(51.510677337646484,16.259723663330078));
waypoints.add(new LatLng(51.510677337646484,16.259723663330078));
waypoints.add(new LatLng(51.50559997558594,16.2688045501709));
waypoints.add(new LatLng(51.476688385009766,16.267772674560547));
waypoints.add(new LatLng(51.46686935424805,16.270612716674805));
waypoints.add(new LatLng(51.451759338378906,16.234111785888672));
waypoints.add(new LatLng(51.45033264160156,16.244768142700195));
waypoints.add(new LatLng(51.44853591918945,16.24496841430664));
waypoints.add(new LatLng(51.43154525756836,16.237483978271484));
waypoints.add(new LatLng(51.40877151489258,16.21938133239746));
}
// your async task execute
//new DirectionFinder().execute(); like this
public void execute() throws UnsupportedEncodingException {
new DownloadRawData().execute(createUrlwaypoints());
}
// url create with waypoints
private String createUrlwaypoints() throws UnsupportedEncodingException {
String wayPointss = "";
for (int i = 0;i<waypoints.size();i++){
if (i==(waypoints.size()-1)){
wayPointss += ""+waypoints.get(i).latitude+","+waypoints.get(i).longitude+"";
}else {
wayPointss += "" + waypoints.get(i).latitude + "," + waypoints.get(i).longitude + "|";
}
}
return DIRECTION_URL_API + "origin=" + originlatlong.latitude+","+originlatlong.longitude + "&destination=" + destinationlatlong.latitude+","+destinationlatlong.longitude + "&waypoints=optimize:true|"+wayPointss+"|&key=" + GOOGLE_API_KEY;
}
// async task to download routes
private class DownloadRawData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String link = params[0];
try {
URL url = new URL(link);
InputStream is = url.openConnection().getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String res) {
try {
parseJSon(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void parseJSon(String data) throws JSONException {
if (data == null)
return;
// here Route is my getter setter model class that have some parametes like distance,duration,etc..
List<Route> routes = new ArrayList<Route>();
JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
JSONArray jsonArray = jsonRoute.getJSONArray("waypoint_order");
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
int[] indexes = new int[jsonArray.length()];
for (int index = 0;index<jsonArray.length();index++){
indexes[index] = (int) jsonArray.get(index);
}
route.indexes = indexes;
routes.add(route);
}
// read all data and you can here put code to plot route on map
drawOnMap(routes);
}
private List<LatLng> decodePolyLine(final String poly) {
int len = poly.length();
int index = 0;
List<LatLng> decoded = new ArrayList<LatLng>();
int lat = 0;
int lng = 0;
while (index < len) {
int b;
int shift = 0;
int result = 0;
do {
b = poly.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 = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
decoded.add(new LatLng(
lat / 100000d, lng / 100000d
));
}
return decoded;
}
void drawOnMap(ArrayList<Route> routes){
polyLinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarker = new ArrayList<>();
for (Route route : routes) {
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.startflags))
.title(route.startAddress)
.position(originPoints));
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.endflags))
.title(route.endAddress)
.position(destinationPoints));
PolylineOptions polylineOptions = new PolylineOptions()
.geodesic(true)
.color(getResources().getColor(R.color.colorPrimary))
.width(5);
if (wayPoints!=null){
for (int i = 0;i<wayPoints.size();i++){
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.busstopp))
.title(wayPoints.get(i).getStopName())
.position(wayPoints.get(i).getLatLng()));
}
}
for (int i = 0; i < route.points.size(); i++) {
polylineOptions.add(route.points.get(i));
}
polyLinePaths.add(mMap.addPolyline(polylineOptions));
}
}
//路线等级
public class Route {
public Distance distance;
public Duration duration;
public String endAddress;
public LatLng endLocation;
public String startAddress;
public LatLng startLocation;
public List<LatLng> points;
public int[] indexes;
}
答案 1 :(得分:0)
您正在寻找的是 Waypoints 。请参阅可选参数部分here。
指定沿中间位置包括的一系列中间位置 通过或在起点和终点之间的路线 中途停留地点。航点通过引导路线改变路线 指定的位置。
我建议您建立从第一个点到最后一个的路径,并以中间点作为航路点。
包含经纬度航路点的URL示例:
https://maps.googleapis.com/maps/api/directions/json?
origin=sydney,au&destination=perth,au
&waypoints=via:-37.81223%2C144.96254%7Cvia:-34.92788%2C138.60008
&key=YOUR_API_KEY