Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在google map v2 android中绘制两个位置之间的道路_Android_Google Maps - Fatal编程技术网

在google map v2 android中绘制两个位置之间的道路

在google map v2 android中绘制两个位置之间的道路,android,google-maps,Android,Google Maps,我正在尝试在我提供的两个位置之间绘制一条道路/路径,我的代码目前如下所示: map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); LatLng lt = new LatLng(35.7687310, -5.8280540); map.addMarker(new MarkerOptions().position(lt).title("Home")); LatLng lt2 = new Lat

我正在尝试在我提供的两个位置之间绘制一条道路/路径,我的代码目前如下所示:

map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

LatLng lt = new LatLng(35.7687310, -5.8280540);
map.addMarker(new MarkerOptions().position(lt).title("Home"));
LatLng lt2 = new LatLng(35.7462510, -5.8481330);
map.addMarker(new MarkerOptions().position(lt2).title("School"));
我需要在两个标记之间画一个道路方向,谢谢 我一直在寻找解决方案,但大多数都是旧的&在崩溃时无法运行它们。。。 我希望你能帮忙,谢谢

编辑: 我的主要问题是,我试图在另一个不包含相同包名的项目上使用我的api,谢谢大家的帮助;)

试试这个:
if(googleMap==null){
googleMap=((MapFragment)getFragmentManager().findFragmentById(
R.id.map_)).getMap();
googleMap.clear();
googleMap.setMapType(googleMap.MAP\u TYPE\u NORMAL);
V2GetroutedDirection=新的GMAPv2etroutedDirection();
字符串url=getDirectionsUrl(新LatLng(源纬度,源纬度),新LatLng(目的纬度,目的纬度));
DownloadTask DownloadTask=新的DownloadTask();
//开始从Google Directions API下载json数据
downloadTask.execute(url);
//检查是否成功创建映射
if(googleMap==null){
Toast.makeText(Ride_Share.this,
“抱歉!无法创建地图”,Toast.LENGTH\u SHORT)
.show();
}
}
私有字符串getDirectionsUrl(LatLng来源,LatLng目的地){
//路线起点
字符串str_origin=“origin=“+origin.latitude+”,“+origin.longitude;
//路线目的地
字符串str_dest=“destination=”+dest.latitude+”,“+dest.longitude;
//传感器启用
字符串sensor=“sensor=false”;
//为web服务构建参数
字符串参数=str_origin+“&”+str_dest+“&”+传感器;
//输出格式
字符串输出=“json”;
//构建web服务的url
字符串url=”https://maps.googleapis.com/maps/api/directions/“+输出+”?“+参数;
返回url;
}
/**从url下载json数据的方法*/
私有字符串下载URL(字符串strUrl)引发IOException{
字符串数据=”;
InputStream iStream=null;
HttpURLConnection-urlConnection=null;
试一试{
URL=新URL(strUrl);
//创建http连接以与url通信
urlConnection=(HttpURLConnection)url.openConnection();
//连接到url
urlConnection.connect();
//从url读取数据
iStream=urlConnection.getInputStream();
BufferedReader br=新的BufferedReader(新的InputStreamReader(iStream));
StringBuffer sb=新的StringBuffer();
字符串行=”;
而((line=br.readLine())!=null){
某人附加(行);
}
data=sb.toString();
br.close();
}捕获(例外e){
Log.d(“下载url时出现异常”,例如toString());
}最后{
iStream.close();
urlConnection.disconnect();
}
返回数据;
}
//从传递的url获取数据
私有类DownloadTask扩展了AsyncTask{
//在非ui线程中下载数据
@凌驾
受保护的字符串doInBackground(字符串…url){
//用于存储来自web服务的数据
字符串数据=”;
试一试{
//从web服务获取数据
数据=下载url(url[0]);
}捕获(例外e){
Log.d(“后台任务”,例如toString());
}
返回数据;
}
//在UI线程中执行,在
//doInBackground()
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
ParserTask ParserTask=新的ParserTask();
//调用线程以解析JSON数据
执行(结果);
}
}
/**以JSON格式解析GooglePlaces的类*/
私有类ParserTask扩展了AsyncTask{
//解析非ui线程中的数据
@凌驾
受保护列表doInBackground(字符串…jsonData){
JSONObject jObject;
列表路由=空;
试一试{
jObject=新的JSONObject(jsonData[0]);
DirectionsJSONParser=新的DirectionsJSONParser();
//开始解析数据
routes=parser.parse(jObject);
}捕获(例外e){
e、 printStackTrace();
}
返回路线;
}
//解析过程后,在UI线程中执行
@凌驾
受保护的void onPostExecute(列表结果){
ArrayList points=null;
PolylineOptions lineOptions=null;
MarkerOptions MarkerOptions=新MarkerOptions();
字符串距离=”;
字符串持续时间=”;
if(result.size()1):(result>>1));
lat+=dlat;
移位=0;
结果=0;
做{
b=编码的.charAt(索引++)-63;
结果|=(b&0x1f)=0x20);
int-dlng=((结果&1)!=0?~(结果>>1):(结果>>1));
液化天然气+=液化天然气;
车床位置=新车床((双)车床/1E5,(双)车床/1E5);
poly.add(位置);
}
返回多边形;
}
}

如果您遇到任何问题,请告诉我。请添加您自己实现的代码。不要只是复制粘贴代码@PiyushGupta..这些代码有什么问题…上面的代码在我的应用程序中运行良好..如果是,那么你只需要共享链接,不要复制粘贴代码。这是什么意思。只是为了赢得名声?@PiyushGupta我只是想
Try this one:


        if (googleMap == null) {
            googleMap = ((MapFragment)getFragmentManager().findFragmentById(
                    R.id.map_rideshare)).getMap();

            googleMap.clear();
            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);


            v2GetRouteDirection = new GMapV2GetRouteDirection();


            String url = getDirectionsUrl(new LatLng(source_lat,source_long), new LatLng(destination_lat,destination_long));
            DownloadTask downloadTask = new DownloadTask();

            // Start downloading json data from Google Directions API
            downloadTask.execute(url);

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(Ride_Share.this,
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }



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

        // Building the parameters to the web service
        String parameters = str_origin+"&"+str_dest+"&"+sensor;

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


    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            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 while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    // Fetches data from url passed
    private class DownloadTask extends AsyncTask<String, Void, String>{

        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {

            // For storing data from web service
            String data = "";

            try{
                // Fetching the data from web service
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }

        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            ParserTask parserTask = new ParserTask();

            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
        }
    }

    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{

        // Parsing the data in non-ui thread
        @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();

                // Starts parsing data
                routes = parser.parse(jObject);
            }catch(Exception e){
                e.printStackTrace();
            }
            return routes;
        }

        // Executes in UI thread, after the parsing process
        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result) {
            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();
            String distance = "";
            String duration = "";

            if(result.size()<1){
                //Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
                return;
            }

            // Traversing through all the routes
            for(int i=0;i<result.size();i++){
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();

                // Fetching i-th route
                List<HashMap<String, String>> path = result.get(i);

                // Fetching all the points in i-th route
                for(int j=0;j<path.size();j++){
                    HashMap<String,String> point = path.get(j);

                    if(j==0){    // Get distance from the list
                        distance = (String)point.get("distance");
                        continue;
                    }else if(j==1){ // Get duration from the list
                        duration = (String)point.get("duration");
                        continue;
                    }

                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);

                    points.add(position);
                }

                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points);
                lineOptions.width(4);
                lineOptions.color(Color.GRAY);
            }

            //tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);

            // Drawing polyline in the Google Map for the i-th route
            googleMap.addPolyline(lineOptions);
        }
    }
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.util.Log;

import com.google.android.gms.maps.model.LatLng;

public class GMapV2GetRouteDirection {

    public final static String MODE_DRIVING = "driving";
    public final static String MODE_WALKING = "walking";

    public GMapV2GetRouteDirection() { }

    public Document getDocument(LatLng start, LatLng end, String mode) {
        Log.i("GMAP", "step2");
        String url = "http://maps.googleapis.com/maps/api/directions/xml?"
                + "origin=" + start.latitude + "," + start.longitude 
                + "&destination=" + end.latitude + "," + end.longitude
                + "&sensor=false&units=metric&mode=driving";

        Log.i("url", url);
        Log.i("GMAP", "step3");
        try {
            Log.i("GMAP", "step4");
            HttpClient httpClient = new DefaultHttpClient();
            Log.i("GMAP", "step5");
            HttpContext localContext = new BasicHttpContext();
            Log.i("GMAP", "step6");
            HttpPost httpPost = new HttpPost(url);
            Log.i("GMAP", "step7");
            HttpResponse response = httpClient.execute(httpPost, localContext);
            Log.i("GMAP", "step8");
            InputStream in = response.getEntity().getContent();
            Log.i("GMAP", "step9");
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Log.i("GMAP", "step10");
            Document doc = builder.parse(in);
            Log.i("GMAP", "step11");

            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getDurationText (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        Log.i("DurationText", node2.getTextContent());
        return node2.getTextContent();
    }

    public int getDurationValue (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        Log.i("DurationValue", node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String getDistanceText (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        Log.i("DistanceText", node2.getTextContent());
        return node2.getTextContent();
    }

    public int getDistanceValue (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        Log.i("DistanceValue", node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String getStartAddress (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("start_address");
        Node node1 = nl1.item(0);
        Log.i("StartAddress", node1.getTextContent());
        return node1.getTextContent();
    }

    public String getEndAddress (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("end_address");
        Node node1 = nl1.item(0);
        Log.i("StartAddress", node1.getTextContent());
        return node1.getTextContent();
    }

    public String getCopyRights (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("copyrights");
        Node node1 = nl1.item(0);
        Log.i("CopyRights", node1.getTextContent());
        return node1.getTextContent();
    }

    public ArrayList<LatLng> getDirection (Document doc) {
        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));

                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));
                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
                for(int j = 0 ; j < arr.size() ; j++) {
                    listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
                }

                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "lat"));
                lat = Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    private int getNodeIndex(NodeList nl, String nodename) {
        for(int i = 0 ; i < nl.getLength() ; i++) {
            if(nl.item(i).getNodeName().equals(nodename))
                return i;
        }
        return -1;
    }

    private ArrayList<LatLng> decodePoly(String encoded) {
        ArrayList<LatLng> poly = new ArrayList<LatLng>();
        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 position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
            poly.add(position);
        }
        return poly;
    }
}