好的家伙我正在建造一个出租车应用程序。这显然是位置感知。我想要的是,我想在按钮上点击地图上放置一个搜索按钮,它应该显示一个搜索栏或搜索框,当用户输入一个地址进行搜索时,它应该显示一个自动完成的建议。有了一个下拉菜单,他也可以选择像Uber这样的地点或谷歌地图所做的选择。 这是我所做的代码。 我已经实现了用标记显示用户的当前位置,并在标记片段中显示了它的当前地址。
我的地图活动
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationListener,GoogleMap.OnMarkerClickListener,LoaderManager.LoaderCallbacks<Cursor>,GoogleMap.OnInfoWindowClickListener, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerDragListener {
private GoogleApiClient mGoogleApiClient;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
public LocationRequest mLocationRequest;
public LocationRequest LocationDrop;
// TextView currentloc;
String filterAddress = "";
String DropoffAdress = "";
String DraggedDroppOff= "";
String dragendaddress = "";
ArrayList<LatLng> markerPoints;
TextView tvDistanceDuration;
// TextView dropOffaddress;
double currentLatitude;
double currentLongitude;
double draglat;
double draglng;
Button ButtonRequestAcaB;
Button BtnSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
BtnSearch = (Button) findViewById(R.id.btnCab);
ButtonRequestAcaB = (Button) findViewById(R.id.btnCab);
tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);
// Initializing
markerPoints = new ArrayList<LatLng>();
// tvLocInfo = (TextView) findViewById(R.id.locinfo);
mMap.setOnMapLongClickListener(this);
mMap.setOnMarkerDragListener(this);
mMap.setOnMarkerClickListener(this);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
/*
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = fragment.getMap();
*/
}
});
BtnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = fragment.getMap();
handleIntent(getIntent());
}
});
// LocationDrop = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10 * 1000).setFastestInterval(1 * 1000);
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
ButtonRequestAcaB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (markerPoints.size() == 1) {
// markerPoints.clear();
// mMap.clear();
markerPoints.add(new LatLng(currentLatitude, currentLongitude));
}
// Adding new item to the ArrayList
// Checks, whether start and end locations are captured
if (markerPoints.size() >= 2){
markerPoints.add(new LatLng(draglat,draglng));
LatLng pickup = markerPoints.get(0);
LatLng dropOff = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(pickup, dropOff);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
Log.e("My URL IS", url);
}
}
});
// handleIntent(getIntent());
}
// code for searching
private void handleIntent(Intent intent){
if(intent.getAction().equals(Intent.ACTION_SEARCH)){
doSearch(intent.getStringExtra(SearchManager.QUERY));
}else if(intent.getAction().equals(Intent.ACTION_VIEW)){
getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
private void doSearch(String query){
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(0, data, this);
}
private void getPlace(String query){
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(1, data, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()){
case R.id.action_search:
onSearchRequested();
break;
}
return super.onMenuItemSelected(featureId, item);
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle query) {
CursorLoader cLoader = null;
if(arg0==0)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{ query.getString("query") }, null);
else if(arg0==1)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{ query.getString("query") }, null);
return cLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
showLocations(c);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
}
private void showLocations(Cursor c){
MarkerOptions markerOptions = null;
LatLng position = null;
mMap.clear();
while(c.moveToNext()){
markerOptions = new MarkerOptions();
position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
markerOptions.position(position);
markerOptions.title(c.getString(0));
mMap.addMarker(markerOptions);
}
if(position!=null){
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
mMap.animateCamera(cameraPosition);
}
}
/*
This is some thing I am trying to do..to get the search going..
This is
PlaceDetailsJSONParser
public class PlaceDetailsJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
Double lat = Double.valueOf(0);
Double lng = Double.valueOf(0);
String formattedAddress = "";
HashMap<String, String> hm = new HashMap<String, String>();
List<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
try {
lat = (Double)jObject.getJSONObject("result").getJSONObject("geometry").getJSONObject("location").get("lat");
lng = (Double)jObject.getJSONObject("result").getJSONObject("geometry").getJSONObject("location").get("lng");
formattedAddress = (String) jObject.getJSONObject("result").get("formatted_address");
} catch (JSONException e) {
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
hm.put("lat", Double.toString(lat));
hm.put("lng", Double.toString(lng));
hm.put("formatted_address",formattedAddress);
list.add(hm);
return list;
}
}
-----------------------
Place JSON PARSER
public class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("predictions");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject)jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){
HashMap<String, String> place = new HashMap<String, String>();
String id="";
String reference="";
String description="";
try{
description = jPlace.getString("description");
id = jPlace.getString("id");
reference = jPlace.getString("reference");
place.put("description" , description);
Log.e("description", description);
Log.e("id", id);
Log.e("reference", reference);
}catch(JSONException e){
e.printStackTrace();
}
return place;
}
}
-----
Place PRovider
public class PlaceProvider extends ContentProvider {
public static final String AUTHORITY = " com.example";
public static final Uri SEARCH_URI = Uri.parse("content://"+AUTHORITY+"/search");
public static final Uri DETAILS_URI = Uri.parse("content://" + AUTHORITY + "/details");
private static final int SEARCH = 1;
private static final int SUGGESTIONS = 2;
private static final int DETAILS = 3;
String mKey = API KEY;
// Defines a set of uris allowed with this content provider
private static final UriMatcher mUriMatcher = buildUriMatcher();
private static UriMatcher buildUriMatcher(){
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// URI for "Go" button
uriMatcher.addURI(AUTHORITY, "search", SEARCH );
// URI for suggestions in Search Dialog
uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY,SUGGESTIONS);
// URI for Details
uriMatcher.addURI(AUTHORITY, "details",DETAILS);
return uriMatcher;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder){
Cursor c = null;
PlaceJSONParser parser = new PlaceJSONParser();
PlaceDetailsJSONParser detailsParser = new PlaceDetailsJSONParser();
String jsonString = "";
String jsonPlaceDetails = "";
List<HashMap<String, String>> list = null;
List<HashMap<String, String>> detailsList = null;
MatrixCursor mCursor = null;
switch(mUriMatcher.match(uri)){
case SEARCH:
// Defining a cursor object with columns description, lat and lng
mCursor = new MatrixCursor(new String[] { "description","lat","lng" });
// Create a parser object to parse places in JSON format
parser = new PlaceJSONParser();
// Create a parser object to parse place details in JSON format
detailsParser = new PlaceDetailsJSONParser();
// Get Places from Google Places API
jsonString = getPlaces(selectionArgs);
try {
// Parse the places ( JSON => List )
list = parser.parse(new JSONObject(jsonString));
// Finding latitude and longitude for each places using Google Places Details API
for(int i=0;i<list.size();i++){
HashMap<String, String> hMap = (HashMap<String, String>) list.get(i);
detailsParser =new PlaceDetailsJSONParser();
// Get Place details
jsonPlaceDetails = getPlaceDetails(hMap.get("reference"));
// Parse the details ( JSON => List )
detailsList = detailsParser.parse(new JSONObject(jsonPlaceDetails));
// Creating cursor object with places
for(int j=0;j<detailsList.size();j++){
HashMap<String, String> hMapDetails = detailsList.get(j);
// Adding place details to cursor
mCursor.addRow(new String[]{ hMap.get("description") , hMapDetails.get("lat") , hMapDetails.get("lng") });
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c = mCursor;
break;
case SUGGESTIONS :
// Defining a cursor object with columns id, SUGGEST_COLUMN_TEXT_1, SUGGEST_COLUMN_INTENT_EXTRA_DATA
mCursor = new MatrixCursor(new String[] { "_id", SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA } );
// Creating a parser object to parse places in JSON format
parser = new PlaceJSONParser();
// Get Places from Google Places API
jsonString = getPlaces(selectionArgs);
try {
// Parse the places ( JSON => List )
list = parser.parse(new JSONObject(jsonString));
// Creating cursor object with places
for(int i=0;i<list.size();i++){
HashMap<String, String> hMap = (HashMap<String, String>) list.get(i);
// Adding place details to cursor
mCursor.addRow(new String[] { Integer.toString(i), hMap.get("description"), hMap.get("reference") });
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c = mCursor;
break;
case DETAILS :
// Defining a cursor object with columns description, lat and lng
mCursor = new MatrixCursor(new String[] { "description","lat","lng" });
detailsParser = new PlaceDetailsJSONParser();
jsonPlaceDetails = getPlaceDetails(selectionArgs[0]);
try {
detailsList = detailsParser.parse(new JSONObject(jsonPlaceDetails));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int j=0;j<detailsList.size();j++){
HashMap<String, String> hMapDetails = detailsList.get(j);
mCursor.addRow(new String[]{ hMapDetails.get("formatted_address") , hMapDetails.get("lat") , hMapDetails.get("lng") });
}
c = mCursor;
break;
}
return c;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean onCreate() {
// TODO Auto-generated method stub
return false;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
/** 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.e("Exception url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private String getPlaceDetailsUrl(String ref){
// reference of place
String reference = "reference="+ref;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = reference+"&"+sensor+"&"+mKey;
// 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;
}
private String getPlacesUrl(String qry){
try {
qry = "input=" + URLEncoder.encode(qry, "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// Sensor enabled
String sensor = "sensor=false";
// place type to be searched
String types = "types=geocode";
// Building the parameters to the web service
String parameters = qry+"&"+types+"&"+sensor+"&"+mKey;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;
return url;
}
private String getPlaces(String[] params){
// For storing data from web service
String data = "";
String url = getPlacesUrl(params[0]);
try{
// Fetching the data from web service in background
data = downloadUrl(url);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
private String getPlaceDetails(String reference){
String data = "";
String url = getPlaceDetailsUrl(reference);
try {
data = downloadUrl(url);
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
enter code here