public class LocateActivity は MapActivity を拡張します {
MapView mapView = null;
Geocoder geocoder = null;
Drawable drawable = null;
Geocoder gc = null;
final CountDownLatch signal = new CountDownLatch(1);
String status;
double lat;
double lng;
public ArrayAdapter<String> adapter;
public AutoCompleteTextView filltt;
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; //
ProgressDialog pDialog;
PlacesList nearPlaces;
List<Overlay> mapOverlays;
AddItemizedOverlay itemizedOverlay;
GeoPoint geoPoint;
// Map controllers
MapController mc;
double latitude;
double longitude;
OverlayItem overlayitem;
Drawable drawable_user;
Drawable drawablee;
String locnm;
GPSTracker gps;
GooglePlaces googlePlaces;
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("My locale::"+Locale.getDefault().getDisplayLanguage());
filltt = (AutoCompleteTextView)findViewById(id.autoCompleteTextView1);
mapView = (MapView) findViewById(R.id.geoMap);
mapView.setBuiltInZoomControls(true);
mapView.setClickable(true);
mapOverlays = mapView.getOverlays();
gc = new Geocoder(this);
drawable = this.getResources().getDrawable(R.drawable.pon);
adapter = new ArrayAdapter<String>(this,R.layout.item_list);
adapter.setNotifyOnChange(true);
filltt.setAdapter(adapter);
filltt.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count%3 == 1) {
adapter.clear();
GetPlaces task = new GetPlaces();
//now pass the argument in the textview to the task
task.execute(filltt.getText().toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
}
});
// map starting point
int lat = (int) (51.678383 * 1000000);
int lng = (int) (19.334822 * 1000000);
GeoPoint pt = new GeoPoint(lat, lng);
mapView.getController().setZoom(18);
mapView.getController().setCenter(pt);
final String lattt="23.0666";
final String loggg="72.6666";
Button geoBtn = (Button) findViewById(R.id.geocodeBtn);
// geoBtn.setText(Html.fromHtml("<b>Year:</b>2012,<b>Franch</b>"));
geocoder = new Geocoder(this);
geoBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
locnm = filltt.getText().toString();
if(locnm.length()==0){
Toast.makeText(LocateActivity.this, "Enter Location", Toast.LENGTH_LONG).show();
}
else
// EditText locale = (EditText) findViewById(R.id.location);
{
new LoadPlaces().execute();
String locationName = filltt.getText().toString();
Toast.makeText(LocateActivity.this, locationName, Toast.LENGTH_LONG).show();
System.out.println("location: "+locationName);
List<Address> addressList = geocoder.getFromLocationName(
locationName, 5);
System.out.println("first val: " + addressList.get(0));
System.out.println("Total Result: " + addressList.size());
if (addressList != null && addressList.size() > 0) {
int lat = (int) (addressList.get(0).getLatitude() * 1e6);
int lng = (int) (addressList.get(0).getLongitude() * 1e6);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// refresh your views here
super.onConfigurationChanged(newConfig);
}
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>>
{
@Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args)
{
Log.d("gottaGo", "doInBackground");
ArrayList<String> predictionsArr = new ArrayList<String>();
try
{
URL googlePlaces = new URL(
// URLEncoder.encode(url,"UTF-8");
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ URLEncoder.encode(args[0].toString(), "UTF-8") +"&types=geocode&language=en&sensor=true&key=AIzaSyDYnuaL0x_7xGNqrEvYkgEB20_k-b4avOI");
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
//take Google's legible JSON and turn it into one big string.
while ((line = in.readLine()) != null) {
sb.append(line);
System.out.println("Line: "+line);
}
//turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
//now get the JSON array that's inside that object
JSONArray ja = new JSONArray(predictions.getString("predictions"));
System.out.println(ja.length());
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
//add each entry to our array
predictionsArr.add(jo.getString("description"));
}
} catch (IOException e){
Log.e("YourApp", "GetPlaces : doInBackground", e);
} catch (JSONException e){
Log.e("YourApp", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
//then our post
@Override
protected void onPostExecute(ArrayList<String> result)
{
Log.d("YourApp", "onPostExecute : " + result.size());
//update the adapter
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.item_list);
adapter.setNotifyOnChange(true);
//attach the adapter to textview
filltt.setAdapter(adapter);
for (String string : result)
{
Log.d("YourApp", "onPostExecute : result = " + string);
adapter.add(string);
adapter.notifyDataSetChanged();
}
Log.d("YourApp", "onPostExecute : autoCompleteAdapter" + adapter.getCount());
}
}
class LoadPlaces extends AsyncTask<String, String, PlacesList> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LocateActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
@SuppressLint("NewApi")
protected PlacesList doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
if(gc.isPresent()){
List<Address> list = gc.getFromLocationName(locnm, 1);
Address address = list.get(0);
lat = address.getLatitude();
lng = address.getLongitude();
}
System.out.println("Lat Val: " + lat);
System.out.println("Long Val: " + lng);
String types = ""; // Listing places only cafes, restaurants
// Radius in meters - increase this value if you don't find any places
double radius = 1000; // 1000 meters
// get nearest places
nearPlaces = googlePlaces.search(lat,
lng, radius, types);
System.out.println("Places: "+nearPlaces);
// }
} catch (Exception e) {
e.printStackTrace();
}
return nearPlaces;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
protected void onPostExecute(PlacesList file_url) {
super.onPostExecute(file_url);
// dismiss the dialog after getting all products
pDialog.dismiss();
signal.countDown();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
// Get json response status
status = nearPlaces.status;
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
System.out.println("Place Name: " +p.name);
// adding HashMap to ArrayList
placesListItems.add(map);
System.out.println("ITEM: " + placesListItems.get(0));
}
}
}
else if(status.equals("ZERO_RESULTS")){
}
else if(status.equals("UNKNOWN_ERROR"))
{
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
}
else if(status.equals("REQUEST_DENIED"))
{
}
else if(status.equals("INVALID_REQUEST"))
{
}
else
{
}
}
});
try {
signal.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mapOverlays = mapView.getOverlays();
// Geopoint to place on map
geoPoint = new GeoPoint((int) (lat * 1E6),
(int) (lng * 1E6));
// Drawable marker icon
Drawable drawable_user = getResources()
.getDrawable(R.drawable.mark_red);
itemizedOverlay = new AddItemizedOverlay(drawable_user);
// Map overlay item
overlayitem = new OverlayItem(geoPoint, "Your Location",
"That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Drawable marker icon
Drawable drawable = getResources()
.getDrawable(R.drawable.mark_blue);
itemizedOverlay = new AddItemizedOverlay(drawable);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoint, place.name,
place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mapView.postInvalidate();
}
}
@Override
public boolean isLocationDisplayed() {
return false;
}
@Override
public boolean isRouteDisplayed() {
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
//moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you really want to Exit ?")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
filltt.setText("");
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//close();
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
}
注: このコードは Android 4.0 で完全に実行されますが、Android 2.3 でテストすると強制終了エラーが発生します。Service not available.. and latitude and longtitude values are 0.のようなエラーがスローされます。
その解決策は何ですか? ここから抜け出すのを手伝ってください。