如何在GoogleMap上点击Marker(餐厅标记)时显示附近餐厅的电话号码

时间:2017-01-17 16:07:54

标签: java android google-maps

我正在创建一个应用程序。我想在点击标记时显示附近餐厅的电话号码。目前显示名称和地址。所以我想显示电话号码。请帮我如何使用以下代码获取餐厅的电话号码....

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener, LocationListener, OnItemClickListener  {

GoogleMap mMap;
SupportMapFragment mFragment;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
Marker CurrentMarker, NearbyPlace, FindMarker;
LocationRequest mLocationRequest;
Location mLastLocation;
DownloadTask placesDownloadTask;
DownloadTask placeDetailsDownloadTask;
ParserTask placesParserTask;
ParserTask placeDetailsParserTask;
final int PLACES = 0;
final int PLACES_DETAILS = 1;

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

        mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mFragment.getMapAsync(this);
    autoCompView = (AutoCompleteTextView) findViewById(R.id.editplace);
    place_autocomplete_clear_button = (ImageButton) findViewById(R.id.place_autocomplete_clear_button);
    tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);



    // Adding textchange listener
    autoCompView.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // Creating a DownloadTask to download Google Places matching "s"
            placesDownloadTask = new DownloadTask(PLACES);

            // Getting url to the Google Places Autocomplete api
            String url = getAutoCompleteUrl(s.toString());

            // Start downloading Google Places
            // This causes to execute doInBackground() of DownloadTask class

            placesDownloadTask.execute(url);


            if (!autoCompView.getText().toString().equals("")) {
                lv.setVisibility(View.VISIBLE);
                place_autocomplete_clear_button.setVisibility(View.VISIBLE);
            } else {
                lv.setVisibility(View.GONE);
                place_autocomplete_clear_button.setVisibility(View.GONE);
            }


        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });


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

    lv.setOnItemClickListener(this);


@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Toast.makeText(this, "onConnectionFailed", Toast.LENGTH_SHORT).show();

}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.getUiSettings().setMyLocationButtonEnabled(false);
    mMap.getUiSettings().setMapToolbarEnabled(false);


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);

        }
    } else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

}


protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}



@Override
public void onConnected(Bundle bundle) {



    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if(mLastLocation != null){
        latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("You are here...");
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.red_bottle));
        //markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        CurrentMarker = mMap.addMarker(markerOptions);
    }

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000); //5 seconds
    mLocationRequest.setFastestInterval(1000); //3 seconds
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();

}

@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    if (CurrentMarker != null) {
        CurrentMarker.remove();
    }



    Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
    StringBuilder builder = new StringBuilder();
    try {
        List<Address> address = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        int maxLines = address.get(0).getMaxAddressLineIndex();
        for (int i=0; i<maxLines; i++) {
            String addressStr = address.get(0).getAddressLine(i);
            builder.append(addressStr);
            builder.append(" ");
        }

         finalAddress = builder.toString(); //This is the complete address.

        //latituteField.setText(String.valueOf(lat));
        // longitudeField.setText(String.valueOf(lng));

        // TextView snippet = (TextView)findViewById(R.id.snippet) ;
        // snippet.setText(finalAddress); //This will display the final address.



    } catch (IOException e) {
        // Handle IOException
    } catch (NullPointerException e) {
        // Handle NullPointerException
    }



    try {


        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.title("You are here...");
        markerOption.snippet(finalAddress);
        //markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        markerOption.icon(BitmapDescriptorFactory.fromResource(R.drawable.red_bottle));
        CurrentMarker = mMap.addMarker(markerOption);
        Toast.makeText(this, "Location changed", Toast.LENGTH_SHORT).show();
        CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(12).build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
        //for search near by wine shop..
        loadNearByPlaces(location.getLatitude(), location.getLongitude());
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);


        }
    }catch (Exception e){


    }

}

// nearby place search..
private void loadNearByPlaces(double latitude, double longitude) {

    String type = "restaurant";
    StringBuilder googlePlacesUrl =
            new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    googlePlacesUrl.append("location=").append(latitude).append(",").append(longitude);
    googlePlacesUrl.append("&radius=").append(PROXIMITY_RADIUS);
    googlePlacesUrl.append("&types=").append(type);
    googlePlacesUrl.append("&sensor=true");
    googlePlacesUrl.append("&key=" + GOOGLE_BROWSER_API_KEY);

    JsonObjectRequest request = new JsonObjectRequest(googlePlacesUrl.toString(),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject result) {

                    Log.i(TAG, "onResponse: Result= " + result.toString());
                    parseLocationResult(result);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "onErrorResponse: Error= " + error);
                    Log.e(TAG, "onErrorResponse: Error= " + error.getMessage());
                }
            });

    AppController.getInstance().addToRequestQueue(request);
}

private void parseLocationResult(JSONObject result) {

    String  placeName = null,  vicinity = null,phone=null,phone_num=null;
    double latitude, longitude;

    try {
        jsonArray = result.getJSONArray("results");

        if (result.getString(STATUS).equalsIgnoreCase(OK)) {

            //mMap.clear();

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject place = jsonArray.getJSONObject(i);


                if (!place.isNull(NAME)) {
                    placeName = place.getString(NAME);


                }
                if (!place.isNull(VICINITY)) {
                    vicinity = place.getString(VICINITY);

                }

                if (!place.isNull(PHONE_NUMBER)) {
                    phone = place.getString(PHONE_NUMBER);

                }

                if (!place.isNull(PHONE_NUM)) {
                    phone_num = place.getString(PHONE_NUM);

                }

                latitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
                        .getDouble(LATITUDE);
                longitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
                        .getDouble(LONGITUDE);
                //reference = place.getString(REFERENCE);
                //icon = place.getString(ICON);

                MarkerOptions markerOptions = new MarkerOptions();
                LatLng latLng = new LatLng(latitude, longitude);
                markerOptions.position(latLng);
                markerOptions.title(placeName);
                //markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
                markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.bottle));

                markerOptions.snippet(vicinity);

                mMap.addMarker(markerOptions);
                NearbyPlace = mMap.addMarker(markerOptions);


                mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                    @Override
                    public void onMapClick(LatLng arg0) {

                        if(relativeLayoutdis.isShown()){
                            relativeLayoutdis.setVisibility(View.GONE);
                        }

                        if (polyline != null) {
                            polyline.remove();
                        }

                    }
                });

                if(CurrentMarker!=null) {
                    mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {




                        @Override
                        public View getInfoWindow(Marker arg0) {

                            return null;
                        }

                        @Override
                        public View getInfoContents(Marker marker) {


                            if (polyline != null) {
                                polyline.remove();
                            }


                                if (tvDistanceDuration != null) {
                                    relativeLayoutdis.setVisibility(View.VISIBLE);

                                } else {
                                    relativeLayoutdis.setVisibility(View.GONE);
                                }



                                LatLng origin = CurrentMarker.getPosition();
                                LatLng dest = marker.getPosition();

                                String url = getDirectionsUrl(origin, dest);
                                DownloadPar downloadPar = new DownloadPar();
                                // Start downloading json data from Google Directions API
                                downloadPar.execute(url);

                                View myContentsView = getLayoutInflater().inflate(R.layout.details, null);
                                TextView tvTitle = ((TextView) myContentsView.findViewById(R.id.title));
                                tvTitle.setText(marker.getTitle());
                                TextView tvSnippet = ((TextView) myContentsView.findViewById(R.id.snippet));
                                tvSnippet.setText(marker.getSnippet());
                            return myContentsView;



                        }
                    });



                }


            }

            Toast.makeText(getBaseContext(), jsonArray.length() + " Wine Store _FOUND!",
                    Toast.LENGTH_SHORT).show();
        } else if (result.getString(STATUS).equalsIgnoreCase(ZERO_RESULTS)) {
            Toast.makeText(getBaseContext(), "No Wine Shop found",
                    Toast.LENGTH_LONG).show();
        }

    } catch (JSONException e) {

        e.printStackTrace();
        Log.e(TAG, "parseLocationResult: Error=" + e.getMessage());
    }
}




private class DownloadTask extends AsyncTask<String, Void, String> {
    private int downloadType = 0;

    // Constructor
    public DownloadTask(int type) {
        this.downloadType = type;
    }

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

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        switch (downloadType) {
            case PLACES:
                // Creating ParserTask for parsing Google Places
                placesParserTask = new ParserTask(PLACES);

                // Start parsing google places json data
                // This causes to execute doInBackground() of ParserTask class
                placesParserTask.execute(result);

                break;

            case PLACES_DETAILS:
                // Creating ParserTask for parsing Google Places
                placeDetailsParserTask = new ParserTask(PLACES_DETAILS);

                // Starting Parsing the JSON string
                // This causes to execute doInBackground() of ParserTask class
                placeDetailsParserTask.execute(result);
        }
    }
}


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

    int parserType = 0;

    public ParserTask(int type) {
        this.parserType = type;
    }

    @Override
    protected List<HashMap<String, String>> doInBackground(String... jsonData) {

        JSONObject jObject;
        List<HashMap<String, String>> list = new ArrayList<>();

        try {
            jObject = new JSONObject(jsonData[0]);

            switch (parserType) {
                case PLACES:
                    PlaceJSONParser placeJsonParser = new PlaceJSONParser();
                    // Getting the parsed data as a List construct
                    list = placeJsonParser.parse(jObject);
                    break;
                case PLACES_DETAILS:
                    PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
                    // Getting the parsed data as a List construct
                    list = placeDetailsJsonParser.parse(jObject);
            }

        } catch (Exception e) {
            Log.d("Exception", e.toString());
        }
        return list;
    }

    @Override
    protected void onPostExecute(List<HashMap<String, String>> result) {

        switch (parserType) {
            case PLACES:
                String[] from = new String[]{"description"};
                int[] to = new int[]{R.id.place_name};

                // Creating a SimpleAdapter for the AutoCompleteTextView
                //SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);

                // Setting the adapter
                //atvPlaces.setAdapter(adapter);

                ListAdapter adapter = new SimpleAdapter(MainActivity.this, result,R.layout.row_item,from,to);
                // Adding data into listview
                lv.setAdapter(adapter);
                break;
            case PLACES_DETAILS:
                String location = autoCompView.getText().toString();
                if (location != null && !location.equals("")) {
                    new GeocoderTask().execute(location);


                }

                break;
        }
    }
}

@Override
public void onItemClick (AdapterView < ? > adapterView, View view,int i, long l){
    //ListView lv = (ListView) adapterView;
    SimpleAdapter adapter = (SimpleAdapter) adapterView.getAdapter();

    HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(i);

    // Creating a DownloadTask to download Places details of the selected place
    placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);

    // Getting url to the Google Places details api
    String url = getPlaceDetailsUrl(hm.get("reference"));

    // Start downloading Google Place Details
    // This causes to execute doInBackground() of DownloadTask class
    placeDetailsDownloadTask.execute(url);

    InputMethodManager inputManager = (InputMethodManager)
            getSystemService(Context.INPUT_METHOD_SERVICE);

    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
            InputMethodManager.HIDE_NOT_ALWAYS);

     str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
    Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
    autoCompView.setText(str);

    lv.setVisibility(View.GONE);


}


//  nearby place for referecnce..
private String getPlaceDetailsUrl(String ref) {
    // Obtain browser key from https://code.google.com/apis/console
    String key = "key=AIzaSyC47V7li_j9_M_HyYEW8D5Z2nyFYX7DkuI";

    // reference of place
    String reference = "reference=" + ref;

    // Sensor enabled
    String sensor = "sensor=false";

    // Building the parameters to the web service
    String parameters = reference + "&" + sensor + "&" + key;

    // Output format
    String output = "json";

    // Building the url to the web service
    String url = "https://maps.googleapis.com/maps/api/place/details/" + output + "?" + parameters;

    return url;
}


//  serch for address...


private String getAutoCompleteUrl(String place) {
    // Obtain browser key from https://code.google.com/apis/console
    String key = "key=**********************************";

    // place to be be searched
    String input = "input=" + place;

    // place type to be searched
    String types = "types=geocode|establishment";

    // Sensor enabled
    String sensor = "sensor=false";

    // Building the parameters to the web service
    String parameters = input + "&" + types + "&" + sensor + "&" + key;

    // Output format
    String output = "json";

    // Building the url to the web service
    String url = "https://maps.googleapis.com/maps/api/place/autocomplete/" + output + "?" + parameters;

    url = url.replaceAll(" ", "%20");
    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;
}


// enter address to search location...

private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {

    @Override
    protected List<Address> doInBackground(String... locationName) {
        // TODO Auto-generated method stub

        Geocoder geocoder = new Geocoder(getBaseContext());
        List<Address> addresses = null;

        try {
            // Getting a maximum of 3 Address that matches the input text
            addresses = geocoder.getFromLocationName(locationName[0], 3);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return addresses;
    }


    protected void onPostExecute(List<Address> addresses) {
        /*if(addresses==null || addresses.size()==0){
            Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
            return;
        }*/
        if(addresses==null){

            Snackbar snackbar = Snackbar.make(autoCompView, "No Internet Access", Snackbar.LENGTH_LONG)
                    .setAction("Action", null);
            View sbView = snackbar.getView();
            sbView.setBackgroundColor(ContextCompat.getColor(getBaseContext(),R.color.colorPrimary));
            snackbar.show();

            return;
        }

        if(addresses.size()==0){
            Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
            return;
        }


        for(int i=0;i<addresses.size();i++){
            Address address =  (Address)addresses.get(i);
            latLng = new LatLng(address.getLatitude(), address.getLongitude());
            String addressText = String.format("%s, %s",
                    address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                    address.getCountryName());
            mMap.clear();



            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("Searched Location...");
            markerOptions.snippet(str);
            //markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.red_bottle));
            FindMarker = mMap.addMarker(markerOptions);

            CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(12).build();
            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            loadNearByPlaces(address.getLatitude(), address.getLongitude());

            //direction

            if(CurrentMarker !=null) {
                LatLng origin =CurrentMarker.getPosition();
                LatLng dest = FindMarker.getPosition();

                String url = getDirectionsUrl(origin, dest);

                DownloadPar downloadPar = new DownloadPar();

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

            }



        }

    }

}



}

}

当我点击谷歌地图上的标记时,请帮助如何获取附近地区(餐厅)的电话并显示。

谢谢..