如何通过片段中的地址位置实现Google Map搜索

时间:2016-05-30 06:54:53

标签: java android google-maps android-fragments

我正在尝试创建一个应用。我想在片段中的谷歌地图上添加地址搜索使用以下代码 -

public class Search extends Fragment implements OnItemClickListener{

private final String  TAG = this.getClass().getSimpleName();

MainActivity main=null;
PlacesTask placesTask = null ;
DownloadTask downloadTask=null;
LatLng latLng;
GoogleMap mMap;
Marker CurrentMarker,FindMarker;

AutoCompleteTextView autoCompView=null;
Button findbtn = null;
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";

//------------ make your specific key ------------
private static final String API_KEY = "**************************************";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.search, container,false);
    autoCompView = (AutoCompleteTextView) view.findViewById(R.id.editplace);

    autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item));
    autoCompView.setOnItemClickListener(this);

    findbtn  =(Button) view.findViewById(R.id.findbtn);
    findbtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String location = autoCompView.getText().toString();
            if(location!=null && !location.equals("")){
                  new GeocoderTask().execute(location); 
            Log.e(TAG, "login button is clicked");


                }

        }
    });



    return view;

   }

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(getActivity());
        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(getActivity(), "No Location found", Toast.LENGTH_SHORT).show();
        }

        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());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Find Location");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker=mMap.addMarker(markerOptions);


        CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(14).build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        double mLatitude=address.getLatitude();
        double mLongitude=address.getLongitude();
        StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        sb.append("location="+mLatitude+","+mLongitude);
        sb.append("&radius=5000");
        sb.append("&types=" + "liquor_store");
        sb.append("&sensor=true");
        sb.append("&key=********************************");
        Log.d("Map", "<><>api: " + sb.toString());

        //query places with find location
        placesTask.execute(sb.toString());

        //for direction Route
        LatLng origin = CurrentMarker.getPosition();
       LatLng dest = FindMarker.getPosition();

        String url = getDirectionsUrl(origin, dest);


        // Start downloading json data from Google Directions API
        downloadTask.execute(url);
        Toast.makeText(getActivity(), " Location found", Toast.LENGTH_SHORT).show();


        }

    }       

 }

@Override
public void onResume() {

   super.onResume();


    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                if(getFragmentManager().getBackStackEntryCount() > 0) {
                  getFragmentManager().popBackStack();
                }

                return true;

            }

            return false;
        }
    });
}
@Override
public void onDestroyView() {
    super.onDestroyView();
    getActivity().getActionBar().setTitle("IQWINER");


}

@Override
public void onItemClick(AdapterView adapterView, View view, int position,
        long id) {
    // TODO Auto-generated method stub
    String str = (String) adapterView.getItemAtPosition(position);
    Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();

}

public static ArrayList<String> autocomplete(String input) {
    ArrayList<String> resultList = null;

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?key=" + API_KEY);
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));

        URL url = new URL(sb.toString());

        System.out.println("URL: "+url);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        //Log.e(LOG_TAG, "Error processing Places API URL", e);
        return resultList;
    } catch (IOException e) {
        //Log.e(LOG_TAG, "Error connecting to Places API", e);
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {

        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results
        resultList = new ArrayList<String>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {

            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
        }
    } catch (JSONException e) {
        //Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
}

class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String> implements Filterable {
    private ArrayList<String> resultList;

    public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }



    @Override
    public int getCount() {
        return resultList.size();
    }

    @Override
    public String getItem(int index) {
        return resultList.get(index);
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    // Retrieve the autocomplete results.
                    resultList = autocomplete(constraint.toString());

                    // Assign the data to the FilterResults
                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        };
        return filter;
    }
  }
}

[在此输入错误说明] [2]

如何通过片段中的Google地图上的地址位置实现搜索。请告诉我..

enter error description here

1 个答案:

答案 0 :(得分:0)

你可以用另一种方式来做。

您可以生成api密钥以及Google maps&amp; Google将api放置在您的开发人员控制台中(单击带圆圈的链接并启用api)

shown here

您可以使用AutoCompleteView onclick监听器或任何其他愿望的监听器来调用下面的api

private int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;// declare this globally

//Call this on your listener method
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                                .build(getActivity());
                startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);

这将打开Goog​​le地方搜索屏幕,您可以获得如下结果

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == getActivity().RESULT_OK) {
            Place place = PlaceAutocomplete.getPlace(getActivity(), data);
            mSearchPlace = place;
            mSearchText.setText(String.valueOf(place.getName()));
// You will get Lat,Long values here where you can use it to move your map or reverse geo code it.
            LatLng latLng = new LatLng(place.getLatLng().latitude, place.getLatLng().longitude); 
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));

        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(getActivity(), data);
        } else if (resultCode == getActivity().RESULT_CANCELED) {
            // The user canceled the operation.
        }
    }
}

希望这有帮助。