简体   繁体   English

Android:在Google Map Java中绘制方向

[英]Android: Draw direction in google map java

how to find the best route for multiple locations in google maps api in android? 如何在Android的Google Maps API中找到多个位置的最佳路线? I have some locations as LatLng but I dont know how specify a optimal route 我有一些位置作为LatLng,但我不知道如何指定最佳路线

ArrayList<LatLng> directionPoint = latLongList;
            PolylineOptions rectLine = new PolylineOptions().width(8).color(
                    Color.RED);

            for (int i = 0; i < directionPoint.size(); i++) {
                rectLine.add(directionPoint.get(i));
            }

            // Adding route on the map
            map.addPolyline(rectLine);

Try this , pass your list of latlongs in latLongList 试试这个,在latLongList中传递您的latlong列表

  1. How to get the route 如何获得路线

You might want to look at the Distance Matrix service: https://developers.google.com/maps/documentation/javascript/distancematrix 您可能需要查看距离矩阵服务: https : //developers.google.com/maps/documentation/javascript/distancematrix

It gives you distances between a set of origins and destinations, and might help you with narrowing down options. 它为您提供了一组起点和终点之间的距离,并可能有助于您缩小选择范围。

2. To Find the best route : 2.寻找最佳路线:

If using the web service, ensure you set optimize:true before listing your waypoints, and check the waypoint_order array. 如果使用Web服务,请确保在列出航点之前先设置optimize:true,然后检查waypoint_order数组。

http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale, SA&sensor = false

If use the JS API, set optimizeWaypoints:true in your request. 如果使用JS API,请在您的请求中设置optimizeWaypoints:true。

3. To draw polyline with the latlongs you have 3.要用您的经纬线绘制折线

PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);

for (int z = 0; z < list.size(); z++) {

    LatLng point = list.get(z);
    options.add(point);

}

line = myMap.addPolyline(options);

Using Google maps direction api you can acheive it, follow the documentation about using waypoints - https://developers.google.com/maps/documentation/directions/intro#Waypoints 使用Google Maps Direction API,您可以实现它,并遵循有关使用航点的文档-https: //developers.google.com/maps/documentation/directions/intro#Waypoints

Now a fully functional api looks like this - 现在,功能齐全的api看起来像这样-

https://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&key=YOUR_API_KEY https://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale, SA&key = YOUR_API_KEY

Here origin = starting point, destination = Ending point, waypoints = points that you want to cover, optimize :true = the route through the given waypoints will be optimized(ie following Traveling Salesman Problem) and key = your map api key. 在这里, 起点 =起点, 终点 =终点, 航点 =您要覆盖的点, 优化 :true =将优化通过给定航点的路线(即跟随Traveling Salesman问题),而key =您的地图api键。

Now in order to save the api response here is the model class - 现在,为了保存api响应,这里是模型类-

public class DirectionApiResponse {
private ArrayList<Geocoded_waypoints> geocoded_waypoints;

private String status;

private ArrayList<Routes> routes;

public ArrayList<Geocoded_waypoints> getGeocoded_waypoints ()
{
    return geocoded_waypoints;
}

public void setGeocoded_waypoints (ArrayList<Geocoded_waypoints> geocoded_waypoints)
{
    this.geocoded_waypoints = geocoded_waypoints;
}

public String getStatus ()
{
    return status;
}

public void setStatus (String status)
{
    this.status = status;
}

public ArrayList<Routes> getRoutes ()
{
    return routes;
}

public void setRoutes (ArrayList<Routes> routes)
{
    this.routes = routes;
}

@Override
public String toString()
{
    return "ClassPojo [geocoded_waypoints = "+geocoded_waypoints+", status = "+status+", routes = "+routes+"]";
}


public class Geocoded_waypoints
{
    private String place_id;

    private String geocoder_status;

    private ArrayList<String> types;

    public String getPlace_id ()
    {
        return place_id;
    }

    public void setPlace_id (String place_id)
    {
        this.place_id = place_id;
    }

    public String getGeocoder_status ()
    {
        return geocoder_status;
    }

    public void setGeocoder_status (String geocoder_status)
    {
        this.geocoder_status = geocoder_status;
    }

    public ArrayList<String> getTypes ()
    {
        return types;
    }

    public void setTypes (ArrayList<String> types)
    {
        this.types = types;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [place_id = "+place_id+", geocoder_status = "+geocoder_status+", types = "+types+"]";
    }
}
public class Routes {
    private String summary;

    private Bounds bounds;

    private String copyrights;

    private ArrayList<String> waypoint_order;

    private ArrayList<Legs> legs;

    private ArrayList<String> warnings;

    private Overview_polyline overview_polyline;

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public Bounds getBounds() {
        return bounds;
    }

    public void setBounds(Bounds bounds) {
        this.bounds = bounds;
    }

    public String getCopyrights() {
        return copyrights;
    }

    public void setCopyrights(String copyrights) {
        this.copyrights = copyrights;
    }

    public ArrayList<String> getWaypoint_order() {
        return waypoint_order;
    }

    public void setWaypoint_order(ArrayList<String> waypoint_order) {
        this.waypoint_order = waypoint_order;
    }

    public ArrayList<Legs> getLegs() {
        return legs;
    }

    public void setLegs(ArrayList<Legs> legs) {
        this.legs = legs;
    }

    public ArrayList<String> getWarnings() {
        return warnings;
    }

    public void setWarnings(ArrayList<String> warnings) {
        this.warnings = warnings;
    }

    public Overview_polyline getOverview_polyline() {
        return overview_polyline;
    }

    public void setOverview_polyline(Overview_polyline overview_polyline) {
        this.overview_polyline = overview_polyline;
    }

    @Override
    public String toString() {
        return "ClassPojo [summary = " + summary + ", bounds = " + bounds + ", copyrights = " + copyrights + ", waypoint_order = " + waypoint_order + ", legs = " + legs + ", warnings = " + warnings + ", overview_polyline = " + overview_polyline + "]";
    }

    public class Bounds
    {
        private Southwest southwest;

        private Northeast northeast;

        public Southwest getSouthwest ()
        {
            return southwest;
        }

        public void setSouthwest (Southwest southwest)
        {
            this.southwest = southwest;
        }

        public Northeast getNortheast ()
        {
            return northeast;
        }

        public void setNortheast (Northeast northeast)
        {
            this.northeast = northeast;
        }

        @Override
        public String toString()
        {
            return "ClassPojo [southwest = "+southwest+", northeast = "+northeast+"]";
        }

        public class Southwest
        {
            private String lng;

            private String lat;

            public String getLng ()
            {
                return lng;
            }

            public void setLng (String lng)
            {
                this.lng = lng;
            }

            public String getLat ()
            {
                return lat;
            }

            public void setLat (String lat)
            {
                this.lat = lat;
            }

            @Override
            public String toString()
            {
                return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
            }
        }

        public class Northeast
        {
            private String lng;

            private String lat;

            public String getLng ()
            {
                return lng;
            }

            public void setLng (String lng)
            {
                this.lng = lng;
            }

            public String getLat ()
            {
                return lat;
            }

            public void setLat (String lat)
            {
                this.lat = lat;
            }

            @Override
            public String toString()
            {
                return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
            }
        }
    }

    public class Overview_polyline {
        private String points;

        public String getPoints() {
            return points;
        }

        public void setPoints(String points) {
            this.points = points;
        }

        @Override
        public String toString() {
            return "ClassPojo [points = " + points + "]";
        }

    }

    public class Legs {
        private Duration duration;

        private Distance distance;

        private End_location end_location;

        private String start_address;

        private String end_address;

        private Start_location start_location;

        private ArrayList<String> traffic_speed_entry;

        private ArrayList<String> via_waypoint;

        private ArrayList<Steps> steps;

        public Duration getDuration() {
            return duration;
        }

        public void setDuration(Duration duration) {
            this.duration = duration;
        }

        public Distance getDistance() {
            return distance;
        }

        public void setDistance(Distance distance) {
            this.distance = distance;
        }

        public End_location getEnd_location() {
            return end_location;
        }

        public void setEnd_location(End_location end_location) {
            this.end_location = end_location;
        }

        public String getStart_address() {
            return start_address;
        }

        public void setStart_address(String start_address) {
            this.start_address = start_address;
        }

        public String getEnd_address() {
            return end_address;
        }

        public void setEnd_address(String end_address) {
            this.end_address = end_address;
        }

        public Start_location getStart_location() {
            return start_location;
        }

        public void setStart_location(Start_location start_location) {
            this.start_location = start_location;
        }

        public ArrayList<String> getTraffic_speed_entry() {
            return traffic_speed_entry;
        }

        public void setTraffic_speed_entry(ArrayList<String> traffic_speed_entry) {
            this.traffic_speed_entry = traffic_speed_entry;
        }

        public ArrayList<String> getVia_waypoint() {
            return via_waypoint;
        }

        public void setVia_waypoint(ArrayList<String> via_waypoint) {
            this.via_waypoint = via_waypoint;
        }

        public ArrayList<Steps> getSteps() {
            return steps;
        }

        public void setSteps(ArrayList<Steps> steps) {
            this.steps = steps;
        }

        @Override
        public String toString() {
            return "ClassPojo [duration = " + duration + ", distance = " + distance + ", end_location = " + end_location + ", start_address = " + start_address + ", end_address = " + end_address + ", start_location = " + start_location + ", traffic_speed_entry = " + traffic_speed_entry + ", via_waypoint = " + via_waypoint + ", steps = " + steps + "]";
        }


        public class Duration {
            private String text;

            private String value;

            public String getText() {
                return text;
            }

            public void setText(String text) {
                this.text = text;
            }

            public String getValue() {
                return value;
            }

            public void setValue(String value) {
                this.value = value;
            }

            @Override
            public String toString() {
                return "ClassPojo [text = " + text + ", value = " + value + "]";
            }
        }
        public class Start_location
        {
            private String lng;

            private String lat;

            public String getLng ()
            {
                return lng;
            }

            public void setLng (String lng)
            {
                this.lng = lng;
            }

            public String getLat ()
            {
                return lat;
            }

            public void setLat (String lat)
            {
                this.lat = lat;
            }

            @Override
            public String toString()
            {
                return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
            }
        }

        public class End_location {
            private String lng;

            private String lat;

            public String getLng() {
                return lng;
            }

            public void setLng(String lng) {
                this.lng = lng;
            }

            public String getLat() {
                return lat;
            }

            public void setLat(String lat) {
                this.lat = lat;
            }

            @Override
            public String toString() {
                return "ClassPojo [lng = " + lng + ", lat = " + lat + "]";
            }
        }

        public class Distance {
            private String text;

            private String value;

            public String getText() {
                return text;
            }

            public void setText(String text) {
                this.text = text;
            }

            public String getValue() {
                return value;
            }

            public void setValue(String value) {
                this.value = value;
            }

            @Override
            public String toString() {
                return "ClassPojo [text = " + text + ", value = " + value + "]";

            }
        }

        public class Steps
        {
            private String html_instructions;

            private Duration duration;

            private Distance distance;

            private End_location end_location;

            private Polyline polyline;

            private Start_location start_location;

            private String travel_mode;

            public String getHtml_instructions ()
            {
                return html_instructions;
            }

            public void setHtml_instructions (String html_instructions)
            {
                this.html_instructions = html_instructions;
            }

            public Duration getDuration ()
            {
                return duration;
            }

            public void setDuration (Duration duration)
            {
                this.duration = duration;
            }

            public Distance getDistance ()
            {
                return distance;
            }

            public void setDistance (Distance distance)
            {
                this.distance = distance;
            }

            public End_location getEnd_location ()
            {
                return end_location;
            }

            public void setEnd_location (End_location end_location)
            {
                this.end_location = end_location;
            }

            public Polyline getPolyline ()
            {
                return polyline;
            }

            public void setPolyline (Polyline polyline)
            {
                this.polyline = polyline;
            }

            public Start_location getStart_location ()
            {
                return start_location;
            }

            public void setStart_location (Start_location start_location)
            {
                this.start_location = start_location;
            }

            public String getTravel_mode ()
            {
                return travel_mode;
            }

            public void setTravel_mode (String travel_mode)
            {
                this.travel_mode = travel_mode;
            }

            @Override
            public String toString()
            {
                return "ClassPojo [html_instructions = "+html_instructions+", duration = "+duration+", distance = "+distance+", end_location = "+end_location+", polyline = "+polyline+", start_location = "+start_location+", travel_mode = "+travel_mode+"]";
            }


            public class Polyline
            {
                private String points;

                public String getPoints ()
                {
                    return points;
                }

                public void setPoints (String points)
                {
                    this.points = points;
                }

                @Override
                public String toString()
                {
                    return "ClassPojo [points = "+points+"]";
                }
            }
        }
    }
}
}

Now to draw the route in between way-points you can use the below method - 现在要在航点之间绘制路线,可以使用以下方法-

private void setRoutePath(DirectionApiResponse directionObj){
    gMap.clear();
    addMarkers(localLeedsArrayList);
    int count = 0;
    ArrayList<LatLng> points = null;
    DirectionApiResponse.Routes route = directionObj.getRoutes().get(0);
    // Traversing through all the routes
    for(DirectionApiResponse.Routes.Legs leg : route.getLegs()){
        PolylineOptions lineOptions = new PolylineOptions();
        points = new ArrayList<LatLng>();
        Log.e("Route", leg.getStart_address()+" "+leg.getEnd_address());

        // Fetching all the points in i-th route
        //for(DirectionApiResponse.Routes.Legs.Steps step : leg.getSteps()){
        for(int j=0;j<leg.getSteps().size();j++){
            DirectionApiResponse.Routes.Legs.Steps step = leg.getSteps().get(j);
            points.addAll(PolyUtil.decode(step.getPolyline().getPoints()));
        }

        // Adding all the points in the route to LineOptions
        lineOptions.addAll(points);
        lineOptions.width(20);
        lineOptions.color(colors[count]);
        Polyline polylineFinal = gMap.addPolyline(lineOptions);
        count++;
    }
    Log.e("SouthWest",directionObj.getRoutes().get(0).getBounds().getSouthwest().getLat()+"  "+directionObj.getRoutes().get(0).getBounds().getSouthwest().getLng());
    Log.e("northeast",directionObj.getRoutes().get(0).getBounds().getNortheast().getLat()+"  "+directionObj.getRoutes().get(0).getBounds().getNortheast().getLng());

    /*LatLng lSouth = new LatLng(Double.valueOf(directionObj.getRoutes().get(0).getBounds().getSouthwest().getLat()),
            Double.valueOf(directionObj.getRoutes().get(0).getBounds().getSouthwest().getLng()));
    LatLng lNorth = new LatLng(Double.valueOf(directionObj.getRoutes().get(0).getBounds().getNortheast().getLat()),
            Double.valueOf(directionObj.getRoutes().get(0).getBounds().getNortheast().getLng()));
    LatLngBounds latLngBounds = new LatLngBounds(lNorth,lSouth);
    gMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds,14));*/

    gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude()),15));
}

Here gMap is the google map object.. 这里的gMap是google map对象。

******* UPDATE Api Calling******** *******更新api呼叫********

In order to call the api Create interface IApiMethods and put the code below - 为了调用api Create接口IApiMethods并将代码放在下面-

@GET("json?origin=35.693391,51.424261&destination=35.692032,51.432715&waypoints=35.691997,51.432758")
Call<DirectionApiResponse> getDirectionWalking(@Query("key")String key);

you can change the co-ordinates accordingly 您可以相应地更改坐标

Now call the method below to call the api and get the DirectionApiResponse object 现在调用下面的方法来调用api并获取DirectionApiResponse对象

 private void getDirection(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://maps.googleapis.com/maps/api/directions/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    IApiMethods service = retrofit.create(IApiMethods.class);
    Call<DirectionApiResponse> directionApiResponseCall = service.getDirectionWalking("YOUR API KEY");
    directionApiResponseCall.enqueue(new Callback<DirectionApiResponse>() {
        @Override
        public void onResponse(Call<DirectionApiResponse> call, Response<DirectionApiResponse> response) {
            setRoutePath(response.body());
        }

        @Override
        public void onFailure(Call<DirectionApiResponse> call, Throwable t) {

        }
    });
}

Finally add the following dependencies to the app's build.gradle file - 最后,将以下依赖项添加到应用程序的build.gradle文件中-

compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM