谷歌地图Android V2和方向API

谷歌地图Android V2和方向API,android,google-maps-mobile,google-maps-android-api-2,Android,Google Maps Mobile,Google Maps Android Api 2,我正在开发一个应用程序,我需要知道当前用户位置和兴趣点之间的路径 我使用的是安卓2.3.3、谷歌地图安卓v2和direction api。 我的问题是,我找到的所有代码都是针对旧版本的地图的,我也试图修改代码,但失败了。我尝试在LatLng中更改地质点(新版本不支持)。 问题是我无法显示路径,为此,我创建了一条新的多段线,并将其添加到地图中 我发布我的代码: 解析器: public interface Parser { public Route parse(); } XML解析器 pu

我正在开发一个应用程序,我需要知道当前用户位置和兴趣点之间的路径

我使用的是安卓2.3.3、谷歌地图安卓v2和direction api。 我的问题是,我找到的所有代码都是针对旧版本的地图的,我也试图修改代码,但失败了。我尝试在LatLng中更改地质点(新版本不支持)。 问题是我无法显示路径,为此,我创建了一条新的多段线,并将其添加到地图中

我发布我的代码:

解析器:

public interface Parser {
    public Route parse();
}
XML解析器

public class XMLParser {
    // names of the XML tags
    protected static final String MARKERS = "markers";
    protected static final String MARKER = "marker";

    protected URL feedUrl;

    protected XMLParser(final String feedUrl) {
            try {
                    this.feedUrl = new URL(feedUrl);
            } catch (MalformedURLException e) {
                    Log.e(e.getMessage(), "XML parser - " + feedUrl);
            }
    }

    protected InputStream getInputStream() {
            try {
                    return feedUrl.openConnection().getInputStream();
            } catch (IOException e) {
                    Log.e(e.getMessage(), "XML parser - " + feedUrl);
                    return null;
            }
    }
}
JsonParser(解析google方向json)

我的主要活动(由于用户本地化,有326个代码行,你可以在google开发者网站上找到它,所以我们可以假设有两个静态点A和B,我想从A到B):

public类MainActivity扩展了FragmentActivity{
私人谷歌地图;
私有标记位置;
专用多段线选项路径线;
私人车床imhere=新车床(41.8549038,12.4618208);
私人LatLng poi=新LatLng(41.89000,12.49324);
私人场所经理;
私人经理人;
两者兼而有之;
私人语境;
//用于在旋转后维护UI状态的键。
私有静态最终字符串键\u BOTH=“使用\u BOTH”;
//UI处理程序代码。
私有静态最终整数更新\u LATLNG=2;
专用静态最终整数五秒=5000;
专用静态最终int三米=3;
私人静态最终整数两分钟=1000*60*2;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
Marker-colorseomarker=map.addMarker(新的MarkerOptions()
.职位(首席执行官)
.标题(“开始”)
.片段(“poi”)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_启动器));
标记当前位置=map.addMarker(新标记选项()
.位置(此处)
.title(“我在这里”)
.snippet(“在这里!”)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_启动器));
上下文=这个;
setOnMarkerClickListener(新的OnMarkerClickListener(){
@凌驾
公共布尔onMarkerClick(标记){
最终字符串[]选项={“Calcola il Percorso”};
AlertDialog.Builder=新建AlertDialog.Builder(MainActivity.this);
建筑商名称(“Ottieni Informazioni aggiuntive”);
setPositiveButton(“Calcola Percorso”,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface对话框,int-id){
LatLng start=新LatLng(imhere.纬度,imhere.经度);
LatLng dest=新LatLng(点纬度、点经度);
路线=绘图路径(起点、终点);
List=route.getPoints();
如果(pathLine!=null)pathLine=null;
路径线=新的多段线选项();
pathLine.addAll(列表);
pathLine.color(color.rgb(0191255));
map.addPolyline(路径线);
}
});
AlertDialog alert=builder.create();
alert.show();
Toast.makeText(MainActivity.this,marker.getSnippet(),Toast.LENGTH_SHORT.show();
返回true;
}
});
map.animateCamera(CameraUpdateFactory.newLatLngZoom(此处,12));
}
}
};
//获取对LocationManager对象的引用。
mLocationManager=(LocationManager)getSystemService(Context.LOCATION\u服务);
}
专用路线绘制路径(LatLng start,LatLng dest){
解析器;
字符串jsonURL=”http://maps.google.com/maps/api/directions/json?";
最终StringBuffer sBuf=新StringBuffer(jsonURL);
sBuf.append(“origin=”);
sBuf.append(起始纬度);
sBuf.append(',');
追加(起始经度);
sBuf.append(“&destination=”);
sBuf.append(目的地纬度);
sBuf.append(',');
sBuf.append(目的地经度);
追加(“&sensor=true&mode=walking”);
parser=newJSONParser(sBuf.toString());
路由r=parser.parse();
返回r;
}
}

每个建议都被广泛接受

如果您不需要自定义代码,请尝试此库,只需几行代码即可完成您需要的操作

我的做法如下。我想这对你有帮助

 Marker interestedMarker;
    private void plot_direction(){
        if (currentSelectedPin !=null) {
            LatLng origin = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
            new GoogleMapDirection(getActivity(), origin, interestedMarker.getPosition(), new DirectionListener() {
                @Override
                public void onDirectionPointsReceived(ArrayList<RouteModel> routeList, String distance, String duration) {
                    PolylineOptions lineOptions = null;
                    for (RouteModel route : routeList) {
                        lineOptions = new PolylineOptions();
                        lineOptions.addAll(route.getSteps());
                        lineOptions.width(20);
                        lineOptions.color(ContextCompat.getColor(getContext(), R.color.map_route));
                    }

                    //For removing existing line
                    if (routeMap!=null){
                        routeMap.remove();
                    }
                    if(lineOptions != null) {
                        routeMap = mMap.addPolyline(lineOptions);
                    }
                }
            });
        }
    }
标记感兴趣的标记;
私有void plot_direction(){
如果(currentSelectedPin!=null){
LatLng origin=新LatLng(currentLocation.getLatitude(),currentLocation.getLength());
新建GoogleMapDirection(getActivity(),origin,interestedMarker.getPosition(),new DirectionListener()){
@凌驾
接收到的方向点上的公共void(ArrayList路由列表、字符串距离、字符串持续时间){
PolylineOptions lineOptions=null;
对于(RouteModel路线:routeList){
lineOptions=新的多段线选项();
lineOptions.addAll(route.getSteps());
线条选项。宽度(20);
lineOptions.color(ContextCompat.getColor(getContext(),R.color.map_route));
}
//用于移除现有线路
if(routeMap!=null){
routeMap.remove();
}
if(lineOptions!=null){
public class Route {
    private String name;
    private final List<LatLng> points;
    private List<Segment> segments;
    private String copyright;
    private String warning;
    private String country;
    private int length;
    private String polyline;

    public Route() {
        points = new LinkedList<LatLng>();
        segments = new LinkedList<Segment>();
    }

    public void addPoint(final LatLng p) {
        points.add(p);
    }

    public void addPoints(final List<LatLng> points) {
        this.points.addAll(points);
    }

    public List<LatLng> getPoints() {
        return points;
    }

    public void addSegment(final Segment s) {
        segments.add(s);
    }

    public List<Segment> getSegments() {
        return segments;
    }

    /**
     * @param name the name to set
     */
     public void setName(final String name) {
        this.name = name;
    }

    /**
     * @return the name
     */
     public String getName() {
         return name;
     }

     /**
      * @param copyright the copyright to set
      */
     public void setCopyright(String copyright) {
         this.copyright = copyright;
     }

     /**
      * @return the copyright
      */
     public String getCopyright() {
         return copyright;
     }

     /**
      * @param warning the warning to set
      */
     public void setWarning(String warning) {
         this.warning = warning;
     }

     /**
      * @return the warning
      */
     public String getWarning() {
         return warning;
     }

     /**
      * @param country the country to set
      */
     public void setCountry(String country) {
         this.country = country;
     }

     /**
      * @return the country
      */
     public String getCountry() {
         return country;
     }

     /**
      * @param length the length to set
      */
     public void setLength(int length) {
         this.length = length;
     }

     /**
      * @return the length
      */
     public int getLength() {
         return length;
     }


     /**
      * @param polyline the polyline to set
      */
     public void setPolyline(String polyline) {
         this.polyline = polyline;
     }

     /**
      * @return the polyline
      */
     public String getPolyline() {
         return polyline;
     }

}
public class Segment {
    /** Points in this segment. **/
    private LatLng start;
    /** Turn instruction to reach next segment. **/
    private String instruction;
    /** Length of segment. **/
    private int length;
    /** Distance covered. **/
    private double distance;

    /**
     * Create an empty segment.
     */

    public Segment() {
    }


    /**
     * Set the turn instruction.
     * @param turn Turn instruction string.
     */

    public void setInstruction(final String turn) {
            this.instruction = turn;
    }

    /**
     * Get the turn instruction to reach next segment.
     * @return a String of the turn instruction.
     */

    public String getInstruction() {
            return instruction;
    }

    /**
     * Add a point to this segment.
     * @param point LatLng to add.
     */

    public void setPoint(LatLng point) {
            start = point;
    }

    /** Get the starting point of this 
     * segment.
     * @return a LatLng
     */

    public LatLng startPoint() {
            return start;
    }

    /** Creates a segment which is a copy of this one.
     * @return a Segment that is a copy of this one.
     */

    public Segment copy() {
            final Segment copy = new Segment();
            copy.start = start;
            copy.instruction = instruction;
            copy.length = length;
            copy.distance = distance;
            return copy;
    }

    /**
     * @param length the length to set
     */
    public void setLength(final int length) {
            this.length = length;
    }

    /**
     * @return the length
     */
    public int getLength() {
            return length;
    }

    /**
     * @param distance the distance to set
     */
    public void setDistance(double distance) {
            this.distance = distance;
    }

    /**
     * @return the distance
     */
    public double getDistance() {
            return distance;
    }

}
public class MainActivity extends FragmentActivity{
    private GoogleMap map;
    private Marker currentLocation;
    private PolylineOptions pathLine;
    private LatLng imhere = new LatLng(41.8549038,12.4618208);
        private LatLng poi = new LatLng(41.89000,12.49324);


    private LocationManager mLocationManager;
    private Handler mHandler;
    private boolean mUseBoth;
    private Context context;
    // Keys for maintaining UI states after rotation.
    private static final String KEY_BOTH = "use_both";
    // UI handler codes.
    private static final int UPDATE_LATLNG = 2;

    private static final int FIVE_SECONDS = 5000;
    private static final int THREE_METERS = 3;
    private static final int TWO_MINUTES = 1000 * 60 * 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        Marker colosseoMarker  = map.addMarker(new MarkerOptions()
        .position(colosseo)
        .title("Start")
        .snippet("poi")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));

                Marker current pos = map.addMarker(new MarkerOptions()
        .position(imhere)
        .title("i'm here")
        .snippet("here!")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));

        context =this ;
        map.setOnMarkerClickListener(new OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker) {
                final String[] options = {"Calcola il Percorso"};
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Ottieni Informazioni aggiuntive");
                builder.setPositiveButton("Calcola Percorso",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        LatLng start = new LatLng(imhere.latitude,imhere.longitude);
                        LatLng dest = new LatLng(poi.latitude, poi.longitude);
                        Route route = drawPath(start, dest);

                        List<LatLng> list= route.getPoints();

if(pathLine!= null) pathline =null;                         
pathLine = new PolylineOptions();

                        pathLine.addAll(list);
                        pathLine.color(Color.rgb(0,191,255));

                        map.addPolyline(pathLine);

                    }
                  });

                AlertDialog alert = builder.create();
                alert.show();
                Toast.makeText(MainActivity.this, marker.getSnippet(),Toast.LENGTH_SHORT).show();
                return true;
            }
        });


                    map.animateCamera(CameraUpdateFactory.newLatLngZoom(imhere, 12));
                }
            }
        };
        // Get a reference to the LocationManager object.
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }


     private Route drawPath(LatLng start, LatLng dest) {
            Parser parser;
            String jsonURL = "http://maps.google.com/maps/api/directions/json?";
            final StringBuffer sBuf = new StringBuffer(jsonURL);
            sBuf.append("origin=");
            sBuf.append(start.latitude);
            sBuf.append(',');
            sBuf.append(start.longitude);
            sBuf.append("&destination=");
            sBuf.append(dest.latitude);
            sBuf.append(',');
            sBuf.append(dest.longitude);
            sBuf.append("&sensor=true&mode=walking");
            parser = new JsonParser(sBuf.toString());
            Route r =  parser.parse();
            return r;
        }
}
 Marker interestedMarker;
    private void plot_direction(){
        if (currentSelectedPin !=null) {
            LatLng origin = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
            new GoogleMapDirection(getActivity(), origin, interestedMarker.getPosition(), new DirectionListener() {
                @Override
                public void onDirectionPointsReceived(ArrayList<RouteModel> routeList, String distance, String duration) {
                    PolylineOptions lineOptions = null;
                    for (RouteModel route : routeList) {
                        lineOptions = new PolylineOptions();
                        lineOptions.addAll(route.getSteps());
                        lineOptions.width(20);
                        lineOptions.color(ContextCompat.getColor(getContext(), R.color.map_route));
                    }

                    //For removing existing line
                    if (routeMap!=null){
                        routeMap.remove();
                    }
                    if(lineOptions != null) {
                        routeMap = mMap.addPolyline(lineOptions);
                    }
                }
            });
        }
    }
public class GoogleMapDirection {
    private DirectionListener listener;
    public GoogleMapDirection(final Activity activity, LatLng source, LatLng destination, DirectionListener listener){
        this.listener=listener;
        String url = null;
        try {
            url = "https://maps.googleapis.com/maps/api/directions/json?origin="+ URLEncoder.encode(Double.toString(source.latitude) + "," + Double.toString(source.longitude), "UTF-8") + "&destination=" + URLEncoder.encode(Double.toString(destination.latitude) + "," + Double.toString(destination.longitude), "UTF-8") + "&mode=driving&sensor=false&key=" + Config.GOOGLE_API_BROWSER_KEY;
            Print.d(url);
        } catch (UnsupportedEncodingException e) {
            Print.exception(e);
        }

        JSONObject parameters = new JSONObject();
        VolleyJsonBodyRequest.execute(activity, url, parameters, new VolleyResponseListener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getString("status").equals("OK")) {
                        String distance = "NA";
                        String duration = "NA";
                        if (response.has("routes")){
                            JSONArray routesJArray = response.getJSONArray("routes");
                            if (routesJArray.length()>0){
                                if (routesJArray.getJSONObject(0).has("legs")){
                                    JSONArray legsJArray = routesJArray.getJSONObject(0).getJSONArray("legs");
                                    if (legsJArray.length()>0){
                                        JSONObject firstLegsJObj = legsJArray.getJSONObject(0);
                                        if (firstLegsJObj.has("distance")){
                                            distance = firstLegsJObj.getJSONObject("distance").getString("text");
                                        }
                                        if (firstLegsJObj.has("duration")){
                                            duration = firstLegsJObj.getJSONObject("duration").getString("text");
                                        }


                                    }
                                }
                            }
                        }
                        GoogleResponseParserTask task = new GoogleResponseParserTask(distance,duration);
                        task.execute(response);
                    }
                } catch (JSONException e) {
                    Print.exception(e);
                    DialogWindow.showOK(activity, Config.MESSAGE_INVALID_RESPONSE_FORMAT, new DialogListenerOK() {
                        @Override
                        public void onOK() {

                        }
                    });
                }
            }
            @Override
            public void onErrorResponse(VolleyResponseError error) {
                Print.e(error.getDetails());
                DialogWindow.showOK(activity, error.getMessage(), new DialogListenerOK() {
                    @Override
                    public void onOK() {

                    }
                });
            }
        });
    }


    /**
     * A class to parse the Google Places in JSON format
     */
    private class GoogleResponseParserTask extends AsyncTask<JSONObject, Integer, ArrayList<RouteModel>> {

        String distance;
        String duration;
        private GoogleResponseParserTask(String distance, String duration){
            this.distance=distance;
            this.duration=duration;

        }
        @Override
        protected ArrayList<RouteModel> doInBackground(JSONObject... jsonResponse) {
            ArrayList<RouteModel> routes = null;
            try {
                routes = parse(jsonResponse[0]);
            } catch (Exception e) {
                Print.exception(e);
            }
            return routes;
        }
        @Override
        protected void onPostExecute(ArrayList<RouteModel> result) {
            listener.onDirectionPointsReceived(result,distance,duration);
        }
    }


    /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
    public ArrayList<RouteModel> parse(JSONObject jObject){

        ArrayList<RouteModel> routeList = new ArrayList<>() ;
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for(int i=0;i<jRoutes.length();i++){
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
                ArrayList<LatLng> pointList = new ArrayList<>();

                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){
                    jSteps = ((JSONObject)jLegs.get(j)).getJSONArray("steps");
                    JSONObject jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    JSONObject jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");

                    String distance = jDistance.getString("text");
                    String duration = jDuration.getString("text");

                    /** Traversing all steps */
                    for(int k=0;k<jSteps.length();k++){
                        String polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                        ArrayList<LatLng> stepList = decodePoly(polyline);

                        /** Traversing all points */
                        for(int l=0;l<stepList.size();l++){
                            LatLng point = new LatLng((stepList.get(l)).latitude, (stepList.get(l)).longitude);
                            pointList.add(point);
                        }
                    }
                    RouteModel routeModel = new RouteModel();
                    routeModel.setSteps(pointList);
                    routeModel.setDistance(distance);
                    routeModel.setDuration(duration);
                    routeList.add(routeModel);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }catch (Exception e){
        }


        return routeList;
    }


    /**
     * Method to decode polyline points
     * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
     * */
    private ArrayList<LatLng> decodePoly(String encoded) {

        ArrayList<LatLng> poly = new ArrayList<>();
        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;
    }