简体   繁体   中英

Implementing Google Places API

I have been trying for the last couple days to find a simple tutorial on this but it seems like there is no such thing as simple with google's API.
Here is what I know so far step 1 send http message using a url that will contain long and lat and API_Key step 2 get result and prasae it step 3 use the data to get what I need. I just can't seem to figure it out. If you could provide me an example or just anything on how to implement this API it would be great! My java file

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

my xml file

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

the errors I am gettting are

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

Here is reference for all you need ..

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

And you can use same some thing like undermentioned ..

Check this simple class that implements all you need

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

That's it. You are good to go. Cheers!

here is the code for implementing google places. Following is the xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<RelativeLayout
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:padding="10dp">

    <ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="250dp" />   

</RelativeLayout>

</LinearLayout>

here is the code that has to be written in the java file

 ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();

 // KEY Strings
    public static String KEY_REFERENCE = "reference"; // id of the place
    public static String KEY_NAME = "name"; // name of the place
    public static String KEY_VICINITY = "vicinity"; // Place area name

 lv = (ListView) findViewById(R.id.list);

        // calling background Async task to load Google Places
        // After getting places from Google all the data is shown in listview
        new LoadPlaces().execute();

        class LoadPlaces extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(PlacesActivity.this);
            pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting Places JSON
         * */
        protected String doInBackground(String... args) {
            // creating Places class object
            googlePlaces = new GooglePlaces();

            try {
                // Separeate your place types by PIPE symbol "|"
                // If you want all types places make it as null
                // Check list of types supported by google
                // 
                String types; // Listing places only cafes, restaurants
                if(searchtype.equals("hotel"))
                    types = "cafe|restaurant|bakery|lodging|meal_delivery|meal_takeaway|";                                       
                // Radius in meters - increase this value if you don't find any places
                double radius = 1000; // 1000 meters 

                // get nearest places
                nearPlaces = googlePlaces.search(gps.getLatitude(),
                        gps.getLongitude(), radius, types);


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

        /**
         * After completing background task Dismiss the progress dialog
         * and show the data in UI
         * Always use runOnUiThread(new Runnable()) to update UI from background
         * thread, otherwise you will get error
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed Places into LISTVIEW
                     * */
                    // Get json response status
                    String status = nearPlaces.status;

                    // Check for all possible status
                    if(status.equals("OK")){
                        // Successfully got places details
                        if (nearPlaces.results != null) {
                            // loop through each place

                            SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
                                    .findFragmentById(R.id.map);


                            GoogleMap Mmap=mapFrag.getMap();
                            LatLng start=new LatLng(gps.getLatitude(), gps.getLongitude());
                            md.showmap(Mmap, start);
                            sm.setmarker(PlacesActivity.this, Mmap,gps.getLatitude(), gps.getLongitude(), "You", R.drawable.mark_blue);
                            for (Place p : nearPlaces.results) {
                                HashMap<String, String> map = new HashMap<String, String>();

                                // Place reference won't display in listview - it will be hidden
                                // Place reference is used to get "place full details"
                                map.put(KEY_REFERENCE, p.reference);

                                // Place name
                                map.put(KEY_NAME, p.name);



                                sm.setmarker(PlacesActivity.this, Mmap, p.geometry.location.lat, p.geometry.location.lng, p.name, R.drawable.mark_red); 

                                // adding HashMap to ArrayList
                                placesListItems.add(map);
                            }
                            // list adapter
                            ListAdapter adapter = new SimpleAdapter(PlacesActivity.this, placesListItems,
                                    R.layout.list_item,
                                    new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
                                            R.id.reference, R.id.name });

                            // Adding data into listview
                            lv.setAdapter(adapter);
                        }
                    }
                    else if(status.equals("ZERO_RESULTS")){
                        // Zero results found
                        alert.showAlertDialog(PlacesActivity.this, "Near Places",
                                "Sorry no places found. Try to change the types of places",
                                false);
                    }
                    else if(status.equals("UNKNOWN_ERROR"))
                    {
                        alert.showAlertDialog(PlacesActivity.this, "Places Error",
                                "Sorry unknown error occured.",
                                false);
                    }
                    else if(status.equals("OVER_QUERY_LIMIT"))
                    {
                        alert.showAlertDialog(PlacesActivity.this, "Places Error",
                                "Sorry query limit to google places is reached",
                                false);
                    }
                    else if(status.equals("REQUEST_DENIED"))
                    {
                        alert.showAlertDialog(PlacesActivity.this, "Places Error",
                                "Sorry error occured. Request is denied",
                                false);
                    }
                    else if(status.equals("INVALID_REQUEST"))
                    {
                        alert.showAlertDialog(PlacesActivity.this, "Places Error",
                                "Sorry error occured. Invalid Request",
                                false);
                    }
                    else
                    {
                        alert.showAlertDialog(PlacesActivity.this, "Places Error",
                                "Sorry error occured.",
                                false);
                    }
                }
            });

        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM