gpt4 book ai didi

java - 如何通过fragment中的地址位置实现Google map 搜索

转载 作者:太空宇宙 更新时间:2023-11-04 12:34:10 25 4
gpt4 key购买 nike

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

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]

如何在fragment中实现按Google map 上的地址位置搜索。请告诉我..

enter error description here

最佳答案

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

您可以在开发者控制台中生成 API key 以及 Google map 和 Google Places 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);

这将打开 Google 地点搜索屏幕,您可以获得如下结果

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

希望这有帮助。

关于java - 如何通过fragment中的地址位置实现Google map 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37519367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com