Android的谷歌地图V2拿到附近的加油站,并得到经度和站的纬度然后绘制的路线吧 [英] Android Google Maps V2 get nearby gas stations and get longitude and latitude of station then draw route to it

查看:156
本文介绍了Android的谷歌地图V2拿到附近的加油站,并得到经度和站的纬度然后绘制的路线吧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是开发与谷歌地图V2,以获得最近的加油站与他们的地位,如果他们有气体或没有一个Android应用程序,现在我伸手去拿我的当前位置和吸取我的当前位置和给定的经度和纬度之间路由并获得在驱动模式到该位置的距离和持续时间。

我的问题怎么去附近的加油站,有没有办法让他们得到经度和他们的宽容度,因为我想要执行的是让最近的一个与它的最小距离和有身份有在这气然后绘制的路线到该位置。

我正要方案执行的是让所有的经度和纬度,并将它们存储到与他们的身份数据库,当用户去任何地方,它让所有最近的加油站然后去数据库状态进行搜索然后计算距离,然后得出附近的车站的路线最短路径,这是执行合适的方式还是可以用另一种方式做,如果是的话我怎么能做到这一点。

请在以下使用的$ C $词,也是我正在测试上三星Galaxy S二重奏S7562

Map.java

 包com.banzina;

公共类地图扩展活动实现LocationListener的{

    GoogleMap的地图;
    ArrayList的<经纬度> markerPoints;
    经纬度myposition;
    经纬度位置2;
    浮动[]结果=新的浮动[1];
    TextView的tvDistanceDuration;

    @覆盖
    保护无效的onCreate(包savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.show_map);

        tvDistanceDuration =(TextView中)findViewById(R.id.tv_dis);

        MapFragment FM =(MapFragment)getFragmentManager()findFragmentById(R.id.map)。
        地图= fm.getMap();
        map.setMyLocationEnabled(真正的);
        LocationManager locationManager =(LocationManager)getSystemService(LOCATION_SERVICE);
        标准标准=新标准(); //对象来检索提供者
        字符串商= locationManager.getBestProvider(标准,真正的);
        位置位置= locationManager.getLastKnownLocation(供应商);
        如果(位置!= NULL){
        onLocationChanged(位置);

    }
    locationManager.requestLocationUpdates(供应商,20000,0,这一点);
        markerPoints =新的ArrayList<经纬度>();
        地图= fm.getMap();
        map.setMyLocationEnabled(真正的);
        map.setOnMapClickListener(新OnMapClickListener(){
    @覆盖
    公共无效onMapClick(经纬度点){
        如果(markerPoints.size()→1){
            markerPoints.clear();
            map.clear();
        }
        markerPoints.add(点);
        MarkerOptions选项=新MarkerOptions();
        options.position(点);
        如果(markerPoints.size()== 1){options.icon(BitmapDesc​​riptorFactory.defaultMarker(BitmapDesc​​riptorFactory.HUE_GREEN));
        }
        否则如果(markerPoints.size()== 2){options.icon(BitmapDesc​​riptorFactory.defaultMarker(BitmapDesc​​riptorFactory.HUE_RED));
        }
        map.addMarker(选件);
        情况2 =新的经纬度(30.08393,31.24225);
        如果(markerPoints.size()> = 2)
        {
            经纬度原点= markerPoints.get(0);
            经纬度DEST = markerPoints.get(1);
              字符串URL = getDirectionsUrl(myposition,位置2);
              DownloadTask downloadTask =新DownloadTask();
              downloadTask.execute(URL);
              Location.distanceBetween(myposition.latitude,myposition.longitude,position2.latitude,position2.longitude,结果);
              map.addMarker(新MarkerOptions()位置(位置2).title伪(结束));

        }
    }
        });
    }

    公共无效distanceTo(位置DEST){}
    公共静态无效distanceBetween(双startLatitude,双startLongitude,双endLatitude,双endLongitude,浮法[]的结果){

    }

    公共无效onLocationChanged(位置定位){
                双纬度= location.getLatitude();

        双经度= location.getLongitude();
        经纬度经纬度=新的经纬度(纬度,经度);
        myposition =新的经纬度(纬度,经度);

        map.addMarker(新MarkerOptions()位置(myposition).title伪(开始));
        map.moveCamera(CameraUpdateFactory.newLatLng(经纬度));
        map.animateCamera(CameraUpdateFactory.zoomTo(17));
        TextView的T =(TextView中)findViewById(R.id.tv_location);
        t.se​​tText(纬度:+纬度+,经度:+经度);
    }

    私人字符串getDirectionsUrl(经纬度的起源,经纬度DEST){
        字符串str_origin =原产地=+ origin.latitude +,+ origin.longitude;
        字符串str_dest =目标=+ dest.latitude +,+ dest.longitude;
             弦传感器=传感器=假;
        字符串参数= str_origin +&放大器;+ str_dest +&放大器;+传感器;

        // 输出格式
        字符串输出=JSON;

        //构建URL给Web服务
        字符串URL =htt​​ps://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;

        返回URL;
    }

    / **的方法来从URL下载JSON数据* /
    私人字符串downloadUrl(字符串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();

            串线=;
            而((行= br.readLine())!= NULL){
                sb.append(线);
            }

            数据= sb.toString();

            br.close();

        }赶上(例外五){
            Log.d(异常边下载网址,e.toString());
        }最后{
            iStream.close();
            urlConnection.disconnect();
        }
        返回的数据;
    }

    //获取从URL数据传递
    私有类DownloadTask扩展的AsyncTask<字符串,太虚,字符串> {

        //下载在非UI线程的数据
        @覆盖
        保护字符串doInBackground(字符串... URL){

            //从网络服务中存储的数据
            字符串数据=;

            尝试{
                //获取从Web服务中的数据
                数据= downloadUrl(URL [0]);
            }赶上(例外五){
                Log.d(后台任务,e.toString());
            }
            返回的数据;
        }

        //执行的UI线程,执行后
        // doInBackground()
        @覆盖
        保护无效onPostExecute(字符串结果){
            super.onPostExecute(结果);

            ParserTask parserTask =新ParserTask();

            //调用线程解析JSON数据
            parserTask.execute(结果);
        }
    }

    / **一个类来分析谷歌地方JSON格式* /
    私有类ParserTask扩展的AsyncTask<字符串,整数,列表<列表< HashMap的<字符串,字符串>>> > {

        //解析在非UI线程的数据
        @覆盖
        受保护的名单,其中,名单,其中,HashMap的<字符串,字符串>>> doInBackground(字符串... jsonData){

            的JSONObject jObject;
            名单<列表< HashMap的<字符串,字符串>>>路线= NULL;

            尝试{
                jObject =新的JSONObject(jsonData [0]);
                DirectionsJSONParser分析器=新DirectionsJSONParser();

                //开始分析数据
                路线= parser.parse(jObject);
            }赶上(例外五){
                e.printStackTrace();
            }
            返回路线;
        }

        //执行的UI线程,解析过程后,
        @覆盖
        保护无效onPostExecute(名单<列表< HashMap的<字符串,字符串>>>的结果){
            ArrayList的<经纬度>分= NULL;
            PolylineOptions lineOptions = NULL;
            MarkerOptions markerOptions =新MarkerOptions();
            字符串距离=;
            串持续时间=;

            //通过遍历所有路线
            的for(int i = 0; I< result.size();我++){
                分=新的ArrayList<经纬度>();
                lineOptions =新PolylineOptions();

                //撷取第i路线
                名单< HashMap的<字符串,字符串>>路径= result.get(ⅰ);

                //取回所有的点在第i个路线
                对于(INT J = 0; J< path.size(); J ++){
                    HashMap的<字符串,字符串>点= path.get(J);
                    如果(j == 0){//从列表中距离
                        距离=(字符串)point.get(距离);
                        继续;
                    }否则,如果(j == 1){//获取时间从名单
                        持续时间=(字符串)point.get(期限);
                        继续;
                    }

                    双纬度= Double.parseDouble(point.get(土地增值税));
                    双LNG = Double.parseDouble(point.get(LNG));
                    经纬度位置=新的经纬度(纬度,经度);

                    points.add(位置);
                }

                //添加所有点的路线LineOptions
                lineOptions.addAll(分);
                lineOptions.width(2);
                lineOptions.color(Color.RED);
            }
            tvDistanceDuration.setText(距离+距离+,持续时间:+时间);

            //绘制折线在谷歌地图为第i个路线
            map.addPolyline(lineOptions);
        }
    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        //充气菜单;这增加了项目操作栏,如果它是present。
        。getMenuInflater()膨胀(R.menu.map,菜单);
        返回true;
    }}
 

布局sho_map.xml

 < RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    工具:上下文=>中ShowMap。
<片段
        机器人:ID =@ + ID /图
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent
        类=com.google.android.gms.maps.MapFragment/>
     <的TextView
        机器人:ID =@ + ID / tv_location
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignLeft =@ + ID /图
        机器人:layout_alignTop =@ + ID /图
        机器人:layout_marginLeft =83dp
        机器人:文本=TextView的/>

     <的TextView
         机器人:ID =@ + ID / tv_dis
         机器人:layout_width =WRAP_CONTENT
         机器人:layout_height =WRAP_CONTENT
         机器人:layout_alignParentBottom =真
         机器人:layout_alignParentLeft =真
         机器人:layout_marginBottom =15dp
         机器人:layout_marginLeft =14dp
         机器人:文本=TextView的/>

< / RelativeLayout的>
 

的Manifest.xml

 < XML版本=1.0编码=UTF-8&GT?;
<舱单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.banzina
    安卓版code =1
    机器人:VERSIONNAME =1.0>

    <用途-SDK
        安卓的minSdkVersion =15
        机器人:targetSdkVersion =15/>

    <许可
        机器人:名称=com.banzina.permission.MAPS_RECEIVE
        安卓的ProtectionLevel =签名/>

    <用途特征
        机器人:glEsVersion =0x00020000
        机器人:要求=真/>
    <使用-权限的Andr​​oid:名称=com.banzina.permission.MAPS_RECEIVE/>
    <使用-权限的Andr​​oid:名称=android.permission.INTERNET对/>
    <使用-权限的Andr​​oid:名称=android.permission.ACCESS_WIFI_STATE/>
    <使用-权限的Andr​​oid:名称=android.permission.ACCESS_NETWORK_STATE/>
    <使用-权限的Andr​​oid:名称=android.permission.WRITE_EXTERNAL_STORAG​​E/>
    <使用-权限的Andr​​oid:名称=com.google.android.providers.gsf.permission.READ_GSERVICES/>
    <使用-权限的Andr​​oid:名称=android.permission.com.google.android.providers.gsf.permission.READ_GSERVICES/>
    <使用-权限的Andr​​oid:名称=android.permission.ACCESS_COARSE_LOCATION/>
    <使用-权限的Andr​​oid:名称=android.permission.ACCESS_FINE_LOCATION/>

    <用途特征
        机器人:名称=android.hardware.location
        机器人:要求=FALSE/>
    <用途特征
        机器人:名称=android.hardware.location.network
        机器人:要求=FALSE/>
    <使用特征的android:NAME =android.hardware.location.gps/>
    <用途特征
        机器人:名称=android.hardware.wifi
        机器人:要求=FALSE/>

    <应用
        机器人:allowBackup =真
        机器人:图标=@可绘制/ ic_launcher
        机器人:标签=@字符串/ APP_NAME
        机器人:主题=@风格/ AppTheme>
        <活动
            机器人:名称=com.banzina.Map
            机器人:标签=@字符串/ APP_NAME>
            <意向滤光器>
                <作用机器人:名称=android.intent.action.MAIN/>

                <类机器人:名称=android.intent.category.LAUNCHER/>
            &所述; /意图滤光器>
        < /活性GT;

        &所述;元数据
            机器人:名称=com.google.android.maps.v2.API_KEY
            机器人:值=*********我的主要********/>


    < /用途>
< /舱单>
 

DirectionsJSONParser.java

 包com.banzina;

进口的java.util.ArrayList;
进口的java.util.HashMap;
进口的java.util.List;

进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;

进口com.google.android.gms.maps.model.LatLng;

公共类DirectionsJSONParser {
     / **收到的JSONObject并返回一个包含经纬度列表的列表* /
    公开名单<列表< HashMap的<字符串,字符串>>>解析(JSONObject的jObject){

        名单<列表< HashMap的<字符串,字符串>>>路线=新的ArrayList<列表< HashMap的<字符串,字符串>>>();
        JSONArray jRoutes = NULL;
        JSONArray jLegs = NULL;
        JSONArray jSteps = NULL;
        JSONObject的jDistance = NULL;
        JSONObject的jDuration = NULL;


        尝试 {

            jRoutes = jObject.getJSONArray(路);

            / **遍历所有路线* /
            的for(int i = 0; I< jRoutes.length();我++){
                jLegs =((的JSONObject)jRoutes.get(I))getJSONArray(腿)。
                目录路径=新的ArrayList< HashMap的<字符串,字符串>>();

                / **遍历所有的腿* /
                对于(INT J = 0; J< jLegs.length(); J ++){
                  // jSteps =((的JSONObject)jLegs.get(J))getJSONArray(步)。
                    / **获取从JSON数据*距离/
                    jDistance =((的JSONObject)jLegs.get(J))getJSONObject(距离)。
                    HashMap的<字符串,字符串> hmDistance =新的HashMap<字符串,字符串>();
                    hmDistance.put(距离,jDistance.getString(文本));

                    / **获取时间由JSON数据* /
                    jDuration =((的JSONObject)jLegs.get(J))getJSONObject(时间)。
                    HashMap的<字符串,字符串> hmDuration =新的HashMap<字符串,字符串>();
                    hmDuration.put(持续时间,jDuration.getString(文本));

                    / **添加远物体到路径* /
                    path.add(hmDistance);

                    / **添加时间对象的路径* /
                    path.add(hmDuration);

                    jSteps =((的JSONObject)jLegs.get(J))getJSONArray(步)。


                    / **遍历所有的步骤* /
                    对于(INT K = 0; K< jSteps.length(); k ++){
                        字符串折线=;
                        。折线=(字符串)(。(的JSONObject)((的JSONObject)jSteps.get(K))获得(折线))获得(分);
                        名单<经纬度>名单=去$ C $℃聚(折线);

                        / **遍历所有点* /
                        为(中间体升= 0; L&其中;则为list.size();升++){
                            HashMap的<字符串,字符串> HM =新的HashMap<字符串,字符串>();
                            hm.put(纬度,Double.toString(((经纬度)list.get(升))纬度)。);
                            hm.put(LNG,Double.toString(((经纬度)list.get(升))经度)。);
                            path.add(HM);
                        }
                    }
                    routes.add(路径);
                }
            }

        }赶上(JSONException E){
            e.printStackTrace();
        }赶上(例外五){
        }
        返回路线;
    }

    / **
    *法脱code折线点
    *礼貌:jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
    * * /
    私人列表<经纬度>德$ C $℃聚(字符串连接codeD){

        名单<经纬度>聚=新的ArrayList<经纬度>();
        INT指数= 0,len个= EN coded.length();
        INT纬度= 0,LNG = 0;

        而(指数< LEN){
            INT B,移= 0,结果为0;
            做 {
                B = EN coded.charAt(指数++) -  63;
                结果| =(B和0x1F的)LT;<转移;
                Shift + = 5;
            }而(B> = 0x20的);
            INT DLAT =((导致&安培; 1)= 0〜(结果>→1):!?(导致>→1));
            纬度+ = DLAT;

            移= 0;
            结果= 0;
            做 {
                B = EN coded.charAt(指数++) -  63;
                结果| =(B和0x1F的)LT;<转移;
                Shift + = 5;
            }而(B> = 0x20的);
            INT dlng =((导致&安培; 1)= 0〜(结果>→1):!?(导致>→1));
            LNG + = dlng;

            经纬度P =新的经纬度((((双)纬度/ 1E5)),
                                 (((双)LNG / 1E5)));
            poly.add(对);
        }
        返回聚;
    }

}
 

解决方案

有关您的应用程序,你需要访问包含地点的数据库,例子是谷歌的地方或Yelp的的实例。

这个过程是一样的,你做了解析路线。查询API通过发送一个HTTP GET请求到正确格式的URL,下载返回的数据(最可能是JSON格式),解析它,然后添加你的标记

链接到我已经mentionned这些API的文档

  

https://developers.google.com/places/documentation/    http://www.yelp.com/developers/documentation/v2/overview

I was developing an android app with google maps V2, to get nearest gas stations with status of them if they have gas or not, now i reached to get my current location and draw route between my current location and given longitude and latitude and get the distance and duration in driving mode to that location.

My question how to get nearby gas stations, is there a way to get them and get the longitude and latitude of them, because what i want to execute is to get nearest one with the smallest distance to it and have status "have gas in it" then draw route to that location.

I was thing about scenario to execute is to get all longitude and latitude and store them into a database with status of them, and when user go to any location, it get all nearest gas station then go to database to search with status and then calculate the distance then draw the route "shortest path" of nearby station, is this the suitable way to execute or i can do with another way and if so how can i do that.

please find the code i used below and also i am testing on Samsung Galaxy S Duos S7562

Map.java

package com.banzina;

public class Map extends Activity  implements LocationListener{

    GoogleMap map;
    ArrayList<LatLng> markerPoints;
    LatLng myposition;
    LatLng position2;
    float[] results = new float[1];
    TextView tvDistanceDuration;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_map);

        tvDistanceDuration = (TextView) findViewById(R.id.tv_dis);

        MapFragment fm=(MapFragment) getFragmentManager().findFragmentById(R.id.map);
        map=fm.getMap();
        map.setMyLocationEnabled(true);
        LocationManager locationManager=(LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria=new Criteria(); // object to retrieve provider
        String provider = locationManager.getBestProvider(criteria, true);
        Location location=locationManager.getLastKnownLocation(provider);
        if(location!=null){
        onLocationChanged(location);

    }
    locationManager.requestLocationUpdates(provider, 20000, 0, this);
        markerPoints = new ArrayList<LatLng>();
        map = fm.getMap();
        map.setMyLocationEnabled(true);
        map.setOnMapClickListener(new OnMapClickListener() {
    @Override
    public void onMapClick(LatLng point){
        if(markerPoints.size()>1)            {
            markerPoints.clear();
            map.clear();
        }
        markerPoints.add(point);
        MarkerOptions options = new MarkerOptions();
        options.position(point);
        if(markerPoints.size()==1)       {              options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));             
        }
        else if(markerPoints.size()==2)            {                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
        }
        map.addMarker(options);     
        position2 = new LatLng(30.08393, 31.24225);
        if(markerPoints.size() >= 2)
        {
            LatLng origin = markerPoints.get(0);
            LatLng dest = markerPoints.get(1);
              String url = getDirectionsUrl(myposition, position2);
              DownloadTask downloadTask = new DownloadTask();
              downloadTask.execute(url);
              Location.distanceBetween(myposition.latitude, myposition.longitude, position2.latitude, position2.longitude, results);
              map.addMarker(new MarkerOptions().position(position2).title("End"));

        }
    }
        });
    }

    public void distanceTo (Location dest){}
    public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results){

    }

    public void onLocationChanged(Location location) {
                double latitude = location.getLatitude();

        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        myposition = new LatLng(latitude, longitude);

        map.addMarker(new MarkerOptions().position(myposition).title("Start"));
        map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        map.animateCamera(CameraUpdateFactory.zoomTo(17));
        TextView t=(TextView) findViewById(R.id.tv_location);
        t.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );
    }

    private String getDirectionsUrl(LatLng origin,LatLng dest){
        String str_origin = "origin="+origin.latitude+","+origin.longitude;
        String str_dest = "destination="+dest.latitude+","+dest.longitude;
             String sensor = "sensor=false";
        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 = "";

            // 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(2);
                lineOptions.color(Color.RED);
            }
            tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);

            // Drawing polyline in the Google Map for the i-th route
            map.addPolyline(lineOptions);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.map, menu);
        return true;
    }}

Layout sho_map.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ShowMap" >
<fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />
     <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/map"
        android:layout_alignTop="@+id/map"
        android:layout_marginLeft="83dp"
        android:text="TextView" />

     <TextView
         android:id="@+id/tv_dis"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_alignParentLeft="true"
         android:layout_marginBottom="15dp"
         android:layout_marginLeft="14dp"
         android:text="TextView" />

</RelativeLayout>

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.banzina"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <permission
        android:name="com.banzina.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />
    <uses-permission android:name="com.banzina.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-feature
        android:name="android.hardware.location"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.location.network"
        android:required="false" />
    <uses-feature android:name="android.hardware.location.gps" />
    <uses-feature
        android:name="android.hardware.wifi"
        android:required="false" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.banzina.Map"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="*********My Key********" />


    </application>
</manifest>  

DirectionsJSONParser.java

package com.banzina;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class DirectionsJSONParser {
     /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
    public List<List<HashMap<String,String>>> parse(JSONObject jObject){

        List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;
        JSONObject jDistance = null;
        JSONObject jDuration = null;


        try {

            jRoutes = jObject.getJSONArray("routes");

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

                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){
                  //  jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");


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

                        /** Traversing all points */
                        for(int l=0;l<list.size();l++){
                            HashMap<String, String> hm = new HashMap<String, String>();
                            hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                            hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

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

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

        List<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 p = new LatLng((((double) lat / 1E5)),
                                 (((double) lng / 1E5)));
            poly.add(p);
        }
        return poly;
    }

}

解决方案

For your application you will need to access a database that contains Places, examples are Google Places or Yelp for instance.

The process is the same as what you did for parsing directions. Query the API by sending an HTTP GET request to the correctly formed URL, download the returned data (most probably in JSON format), parse it and then add your Markers.

Links to the documentation of the APIs I have mentionned

https://developers.google.com/places/documentation/ http://www.yelp.com/developers/documentation/v2/overview

这篇关于Android的谷歌地图V2拿到附近的加油站,并得到经度和站的纬度然后绘制的路线吧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆