Android:在Google地图java中绘制方向

时间:2016-07-14 06:08:16

标签: java android api google-maps location

如何在Android中的google maps api中找到多个位置的最佳路径?我有一些位置作为LatLng但我不知道如何指定最佳路线

3 个答案:

答案 0 :(得分:0)

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);
  

试试这个,在latLongList中传递你的latlongs列表

答案 1 :(得分:0)

  1. 如何获取路线
  2. 您可能需要查看距离矩阵服务:https://developers.google.com/maps/documentation/javascript/distancematrix

    它为您提供了一组来源和目的地之间的距离,可能会帮助您缩小选项范围。

    <强> 2。找到最佳路线:

    如果使用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

    如果使用JS API,请在请求中设置optimizeWaypoints:true。

    第3。要使用您拥有的latlong绘制折线

    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);
    

答案 2 :(得分:0)

使用Google地图方向api,您可以实现它,请按照有关使用航点的文档进行操作 - https://developers.google.com/maps/documentation/directions/intro#Waypoints

现在一个功能齐全的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

此处原点 =起点,目的地 =结束点,航路点 =您想要涵盖的点,优化:true =通过给定航点的路线将被优化(即遵循旅行商问题)和key =你的地图api密钥。

现在为了保存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+"]";
                }
            }
        }
    }
}
}

现在要在路点之间绘制路线,您可以使用以下方法 -

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));
}

此处 gMap 是Google地图对象..

*******更新Api致电********

为了调用api创建界面 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);

你可以相应改变坐标

现在调用下面的方法来调用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) {

        }
    });
}

最后将以下依赖项添加到应用程序的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'