簡體   English   中英

Android:在Google Map Java中繪制方向

[英]Android: Draw direction in google map java

如何在Android的Google Maps API中找到多個位置的最佳路線? 我有一些位置作為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);

試試這個,在latLongList中傳遞您的latlong列表

  1. 如何獲得路線

您可能需要查看距離矩陣服務: 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.要用您的經緯線繪制折線

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

使用Google Maps Direction 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 =將優化通過給定航點的路線(即跟隨Traveling Salesman問題),而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 map對象。

*******更新api呼叫********

為了調用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);

您可以相應地更改坐標

現在調用下面的方法來調用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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM