java - 实现 Google Places API

标签 java android google-places-api

过去几天我一直在努力寻找一个简单的教程,但似乎没有像谷歌 API 这样简单的东西。
这是我目前所知道的 第 1 步使用将包含 long 和 lat 以及 API_Key 的 url 发送 http 消息 第 2 步得到结果并 prasae 它 第 3 步使用数据来获得我需要的东西。 我就是想不通。如果你能给我提供一个例子或任何关于如何实现这个 API 的东西,那就太好了! 我的java文件

package com.example.learnaboutme;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

public class MainActivity extends FragmentActivity {

   Context[] context = new Context[1];
   GPS[] gps = new GPS[1];
   Home home = null;
   RelativeLayout[] rel = new RelativeLayout[1];
   XMLParase xmlParase = null;
   private GoogleMap myMap;
   Polyline line;

   Location location;

   // Static LatLng
   LatLng startLatLng = new LatLng(30.707104, 76.690749);
   LatLng endLatLng = new LatLng(30.721419, 76.730017);

   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);    
      this.setContentView(R.layout.activity_main);
      final TextView text = (TextView)this.findViewById(R.id.text);
      gps[0] = new GPS();
      gps[0].start(this); 
      home = new Home();
      context[0] = this;
      rel[0] = (RelativeLayout)findViewById(R.id.rel);
      home.Initalize(rel, context);
      xmlParase = new XMLParase();
      location = gps[0].GetCoor();
      myMap = ((SupportMapFragment) getSupportFragmentManager()
              .findFragmentById(R.id.mapk)).getMap();
      try{

          final LatLng PERTH = new LatLng(-31.90, 115.86);
          Marker perth = myMap.addMarker(new MarkerOptions()
                                    .position(PERTH)
                                    .anchor((float)0.5,(float)0.5)
                                    .rotation((float)90.0));

          String urlTopass = makeURL(startLatLng.latitude,
                  startLatLng.longitude, endLatLng.latitude,
                  endLatLng.longitude);
         // new connectAsyncTask(urlTopass).execute();

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

      Timer timer = new Timer();
      final Handler handler = new Handler();
      timer.schedule(new TimerTask(){
          public void run(){
              handler.post(new Runnable(){
                  public void run()
                  { 
                      home.Check(gps);
                      String data = MainActivity.this.xmlParase.readXML("locations.xml", context[0], "Home", "address");
                      if(!data.equals("")) {
                         text.setText(data);
                      }
                  }
              });
          }
      }, 2000, 1000);
   }

   private class connectAsyncTask extends AsyncTask<Void, Void, String> {
       private ProgressDialog progressDialog;
       String url;

       connectAsyncTask(String urlPass) {
           url = urlPass;
       }

       @Override
       protected void onPreExecute() {
           // TODO Auto-generated method stub
           super.onPreExecute();
           progressDialog = new ProgressDialog(context[0]);
           progressDialog.setMessage("Fetching route, Please wait...");
           progressDialog.setIndeterminate(true);
           progressDialog.show();
       }

       @Override
       protected String doInBackground(Void... params) {
           JSONParser jParser = new JSONParser();
           String json = jParser.getJSONFromUrl(url);
           return json;
       }

       @Override
       protected void onPostExecute(String result) {
           super.onPostExecute(result);
           progressDialog.hide();
           if (result != null) {
               drawPath(result);
           }
       }
   }

   public String makeURL(double sourcelat, double sourcelog, double destlat,
           double destlog) {
       StringBuilder urlString = new StringBuilder();
       urlString.append("http://maps.googleapis.com/maps/api/directions/json");
       urlString.append("?origin=");// from
       urlString.append(Double.toString(sourcelat));
       urlString.append(",");
       urlString.append(Double.toString(sourcelog));
       urlString.append("&destination=");// to
       urlString.append(Double.toString(destlat));
       urlString.append(",");
       urlString.append(Double.toString(destlog));
       urlString.append("&sensor=false&mode=driving&alternatives=true");
       return urlString.toString();
   }

   public class JSONParser {

       InputStream is = null;
       JSONObject jObj = null;
       String json = "";

       // constructor
       public JSONParser() {
       }

       public String getJSONFromUrl(String url) {

           // Making HTTP request
           try {
               // defaultHttpClient
               DefaultHttpClient httpClient = new DefaultHttpClient();
               HttpPost httpPost = new HttpPost(url);

               HttpResponse httpResponse = httpClient.execute(httpPost);
               HttpEntity httpEntity = httpResponse.getEntity();
               is = httpEntity.getContent();

           } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
           } catch (ClientProtocolException e) {
               e.printStackTrace();
           } catch (IOException e) {
               e.printStackTrace();
           }
           try {
               BufferedReader reader = new BufferedReader(
                       new InputStreamReader(is, "iso-8859-1"), 8);
               StringBuilder sb = new StringBuilder();
               String line = null;
               while ((line = reader.readLine()) != null) {
                   sb.append(line + "\n");
               }

               json = sb.toString();
               is.close();
           } catch (Exception e) {
           }
           return json;

       }
   }

   public void drawPath(String result) {
       if (line != null) {
           myMap.clear();
       }
       myMap.addMarker(new MarkerOptions().position(endLatLng).icon(
               BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
       myMap.addMarker(new MarkerOptions().position(startLatLng).icon(
               BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
       try {
           // Tranform the string into a json object
           final JSONObject json = new JSONObject(result);
           JSONArray routeArray = json.getJSONArray("routes");
           JSONObject routes = routeArray.getJSONObject(0);
           JSONObject overviewPolylines = routes
                   .getJSONObject("overview_polyline");
           String encodedString = overviewPolylines.getString("points");
           List<LatLng> list = decodePoly(encodedString);

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

           /*for (int z = 0; z < list.size() - 1; z++) {
               LatLng src = list.get(z);
               LatLng dest = list.get(z + 1);
               line = myMap.addPolyline(new PolylineOptions()
                       .add(new LatLng(src.latitude, src.longitude),
                               new LatLng(dest.latitude, dest.longitude))
                       .width(5).color(Color.BLUE).geodesic(true));
           }*/

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

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


   public boolean onCreateOptionsMenu(Menu var1) {
      this.getMenuInflater().inflate(R.menu.main, var1);
      return true;
   }
}

我的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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:id="@+id/rel" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:id="@+id/text" />
    <fragment 
        android:id="@+id/mapk"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"/> 

</RelativeLayout>

我得到的错误是

01-10 16:47:16.283: W/ActivityThread(8390): Application com.example.learnaboutme is waiting for the debugger on port 8100...
01-10 16:47:16.303: I/System.out(8390): Sending WAIT chunk
01-10 16:47:16.503: I/System.out(8390): Debugger has connected
01-10 16:47:16.503: I/System.out(8390): waiting for debugger to settle...
01-10 16:47:16.703: I/System.out(8390): waiting for debugger to settle...
01-10 16:47:16.904: I/System.out(8390): waiting for debugger to settle...
01-10 16:47:17.104: I/System.out(8390): waiting for debugger to settle...
01-10 16:47:17.304: I/System.out(8390): waiting for debugger to settle...
01-10 16:47:17.504: I/System.out(8390): waiting for debugger to settle...
01-10 16:47:17.704: I/System.out(8390): waiting for debugger to settle...
01-10 16:47:17.905: I/System.out(8390): waiting for debugger to settle...
01-10 16:47:18.105: I/System.out(8390): waiting for debugger to settle...
01-10 16:47:18.305: I/System.out(8390): waiting for debugger to settle...
01-10 16:47:18.505: I/System.out(8390): waiting for debugger to settle...
01-10 16:47:18.706: I/System.out(8390): debugger has settled (1424)
01-10 16:51:07.610: W/dalvikvm(8390): threadid=1: thread exiting with uncaught exception (group=0x410789d8)
01-10 16:51:07.680: E/AndroidRuntime(8390): FATAL EXCEPTION: main
01-10 16:51:07.680: E/AndroidRuntime(8390): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.learnaboutme/com.example.learnaboutme.MainActivity}: android.view.InflateException: Binary XML file line #18: Error inflating class fragment
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1960)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1985)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.app.ActivityThread.access$600(ActivityThread.java:127)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1151)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.os.Looper.loop(Looper.java:137)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.app.ActivityThread.main(ActivityThread.java:4477)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at java.lang.reflect.Method.invokeNative(Native Method)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at java.lang.reflect.Method.invoke(Method.java:511)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at dalvik.system.NativeStart.main(Native Method)
01-10 16:51:07.680: E/AndroidRuntime(8390): Caused by: android.view.InflateException: Binary XML file line #18: Error inflating class fragment
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:262)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.app.Activity.setContentView(Activity.java:2071)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.example.learnaboutme.MainActivity.onCreate(MainActivity.java:61)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.app.Activity.performCreate(Activity.java:4701)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1051)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1924)
01-10 16:51:07.680: E/AndroidRuntime(8390):     ... 11 more
01-10 16:51:07.680: E/AndroidRuntime(8390): Caused by: java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value.  Expected 4030500 but found 0.  You must have the following declaration within the <application> element:     <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.google.android.gms.common.GooglePlayServicesUtil.n(Unknown Source)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable(Unknown Source)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.google.android.gms.maps.internal.q.v(Unknown Source)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.google.android.gms.maps.internal.q.u(Unknown Source)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.google.android.gms.maps.MapsInitializer.initialize(Unknown Source)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.google.android.gms.maps.SupportMapFragment$b.cE(Unknown Source)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.google.android.gms.maps.SupportMapFragment$b.a(Unknown Source)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.google.android.gms.dynamic.a.a(Unknown Source)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.google.android.gms.dynamic.a.onInflate(Unknown Source)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at com.google.android.gms.maps.SupportMapFragment.onInflate(Unknown Source)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:290)
01-10 16:51:07.680: E/AndroidRuntime(8390):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)
01-10 16:51:07.680: E/AndroidRuntime(8390):     ... 21 more

最佳答案

这是您需要的所有引用..

https://developers.google.com/places/documentation/ https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/MapFragment

你可以使用同样的东西,比如下面提到的..

检查这个实现了所有你需要的简单类

public class MainActivity extends FragmentActivity implements OnClickListener {

    private GoogleMap myMap;
    Polyline line;
    Context context;

    Location location;
    boolean check_provider_enabled = false;

    // Static LatLng
    LatLng startLatLng = new LatLng(30.707104, 76.690749);
    LatLng endLatLng = new LatLng(30.721419, 76.730017);

    public void onCreate(Bundle bd) {
        super.onCreate(bd);
        setContentView(R.layout.activity_main);
        context = MainActivity.this;



        // GoogleMap myMap
        myMap = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map)).getMap();

        /*
        // Construct a CameraPosition focusing on Mountain View and animate the camera to that position.
        CameraPosition cameraPosition = new CameraPosition.Builder()
            //.target(endLatLng)      // Sets the center of the map to Mountain View
            .zoom(17)                   // Sets the zoom
            .bearing(90)                // Sets the orientation of the camera to east
            .tilt(30)                   // Sets the tilt of the camera to 30 degrees
            .build();                   // Creates a CameraPosition from the builder
        myMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));*/

        myMap.setMyLocationEnabled(true);
        myMap.moveCamera(CameraUpdateFactory.newLatLng(startLatLng));
        myMap.animateCamera(CameraUpdateFactory.zoomTo(12));

        myMap.getUiSettings().setZoomControlsEnabled(false);







        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
        location = service.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        // check if enabled and if not send user to the GSP settings
        // Better solution would be to display a dialog and suggesting to 
        // go to the settings
        if (!enabled) {
          /*Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
          startActivity(intent);*/
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
            Toast.makeText(getApplicationContext(), "Enable GPS servcies to use this app.", Toast.LENGTH_LONG).show();
        } else{



            try{

                final LatLng PERTH = new LatLng(-31.90, 115.86);
                Marker perth = myMap.addMarker(new MarkerOptions()
                                          .position(PERTH)
                                          .anchor((float)0.5,(float)0.5)
                                          .rotation((float)90.0));

                String urlTopass = makeURL(startLatLng.latitude,
                        startLatLng.longitude, endLatLng.latitude,
                        endLatLng.longitude);
               // new connectAsyncTask(urlTopass).execute();

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

        }

       /* if (myMap!=null){
            Marker hamburg = myMap.addMarker(new MarkerOptions().position(startLatLng)
                .title("Hamburg"));
            Marker kiel = myMap.addMarker(new MarkerOptions()
                .position(endLatLng)
                .title("Vivek")
                .snippet("VIVEK's ANDROID HACKER")
                .icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.one)));
          }*/



        // Now auto clicking the button
       // btntemp.performClick();
    }
/*
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.btn_pass_home_call_temp:
            String urlTopass = makeURL(startLatLng.latitude,
                    startLatLng.longitude, endLatLng.latitude,
                    endLatLng.longitude);
            new connectAsyncTask(urlTopass).execute();
            break;

        default:
            break;
        }

    }*/

    private class connectAsyncTask extends AsyncTask<Void, Void, String> {
        private ProgressDialog progressDialog;
        String url;

        connectAsyncTask(String urlPass) {
            url = urlPass;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            progressDialog = new ProgressDialog(context);
            progressDialog.setMessage("Fetching route, Please wait...");
            progressDialog.setIndeterminate(true);
            progressDialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {
            JSONParser jParser = new JSONParser();
            String json = jParser.getJSONFromUrl(url);
            return json;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressDialog.hide();
            if (result != null) {
                drawPath(result);
            }
        }
    }

    public String makeURL(double sourcelat, double sourcelog, double destlat,
            double destlog) {
        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.googleapis.com/maps/api/directions/json");
        urlString.append("?origin=");// from
        urlString.append(Double.toString(sourcelat));
        urlString.append(",");
        urlString.append(Double.toString(sourcelog));
        urlString.append("&destination=");// to
        urlString.append(Double.toString(destlat));
        urlString.append(",");
        urlString.append(Double.toString(destlog));
        urlString.append("&sensor=false&mode=driving&alternatives=true");
        return urlString.toString();
    }

    public class JSONParser {

        InputStream is = null;
        JSONObject jObj = null;
        String json = "";

        // constructor
        public JSONParser() {
        }

        public String getJSONFromUrl(String url) {

            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }

                json = sb.toString();
                is.close();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
            return json;

        }
    }

    public void drawPath(String result) {
        if (line != null) {
            myMap.clear();
        }
        myMap.addMarker(new MarkerOptions().position(endLatLng).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
        myMap.addMarker(new MarkerOptions().position(startLatLng).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
        try {
            // Tranform the string into a json object
            final JSONObject json = new JSONObject(result);
            JSONArray routeArray = json.getJSONArray("routes");
            JSONObject routes = routeArray.getJSONObject(0);
            JSONObject overviewPolylines = routes
                    .getJSONObject("overview_polyline");
            String encodedString = overviewPolylines.getString("points");
            List<LatLng> list = decodePoly(encodedString);

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

            /*for (int z = 0; z < list.size() - 1; z++) {
                LatLng src = list.get(z);
                LatLng dest = list.get(z + 1);
                line = myMap.addPolyline(new PolylineOptions()
                        .add(new LatLng(src.latitude, src.longitude),
                                new LatLng(dest.latitude, dest.longitude))
                        .width(5).color(Color.BLUE).geodesic(true));
            }*/

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

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

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

    }

    /*@Override
    public void onMarkerDrag(Marker marker) {

       //add the marker's latlng in a arraylist of LatLng and pass it to the loop
        for (int i = 0; i < arraylistoflatlng.size(); i++) {
             myMap.addPolyline(new PolylineOptions()
            .addAll(arraylistoflatlng)
            .width(5)
            .color(Color.RED));
        }
        }*/
}

就是这样。你已准备好出发。 干杯!

关于java - 实现 Google Places API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21034636/

相关文章:

java - java将String(FF FF FF FF FF FF FF FF FF)转换为int数组

java - 如何通过包含 namespace 信息来创建 XML 元素?

android - 失败:生成失败,发生异常。在volley\bintray.gradle中

javascript - Android、Javascript、Rhino、JSON

javascript - 打开/关闭表单字段的自动完成功能

java - 如何减少以下程序的执行时间

java - 如何使用变量声明新的 JComboBox

android - onSomeEventListener 崩溃

swift - iOS : GMSPlacePickerViewController Country Restriction

android - 有入口和大门的地方