How can I add a search bar in Google map using MapView object of Android?
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mapmain);
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONT开发者_如何转开发ENT));
mapView.displayZoomControls(true);
}
Assuming you have an EditText called: mapSearchBox
mapSearchBox = (EditText) findViewById(R.id.search);
mapSearchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
actionId == EditorInfo.IME_ACTION_GO ||
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
// hide virtual keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mapSearchBox.getWindowToken(), 0);
new SearchClicked(mapSearchBox.getText().toString()).execute();
mapSearchBox.setText("", TextView.BufferType.EDITABLE);
return true;
}
return false;
}
});
Then you need the 'SearchClicked' class to handle the request:
private class SearchClicked extends AsyncTask<Void, Void, Boolean> {
private String toSearch;
private Address address;
public SearchClicked(String toSearch) {
this.toSearch = toSearch;
}
@Override
protected Boolean doInBackground(Void... voids) {
try {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.UK);
List<Address> results = geocoder.getFromLocationName(toSearch, 1);
if (results.size() == 0) {
return false;
}
address = results.get(0);
// Now do something with this GeoPoint:
GeoPoint p = new GeoPoint((int) (address.getLatitude() * 1E6), (int) (address.getLongitude() * 1E6))
} catch (Exception e) {
Log.e("", "Something went wrong: ", e);
return false;
}
return true;
}
}
精彩评论