0

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.のようなエラーがスローされます。
その解決策は何ですか? ここから抜け出すのを手伝ってください。

4

1 に答える 1

0
    I got the solution.

    package com.example.locatebased;

    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Hashtable;
    import org.kxml.*;
    import org.kxml.io.*;
    import org.kxml.kdom.*;
    import org.kxml.parser.*;

    import android.util.Log;

    public class Geocoding
    {
        Hashtable ht=null;
        private boolean time=true;
        private int count=0;
        private String citystreetvalue=null;

         public Geocoding()
         {
             System.out.println("Constructor call...");
             ht=new Hashtable();
         }

    //***************************** Find Address of the latitude Longitude ***********

        public String parseXml(String address)
        {       

            try
            {

                System.out.println("Address is:" + address);
                //URL mUrl = new URL("http://maps.google.com/maps/api/geocode/xml?address=tagore%20road%20rajkot&sensor=false");

                URL mUrl = new URL("http://maps.google.com/maps/api/geocode/xml?address=" + address + "&sensor=false");

                Log.e("Url",mUrl.toString());
                HttpURLConnection mConn = (HttpURLConnection) mUrl.openConnection();

                System.out.println("After address add...");
               InputStream is = mConn.getInputStream();
               Reader reader = new InputStreamReader(is);
               XmlParser parser = new XmlParser(reader);
               traverse(parser,"");


               mConn.disconnect();
               is.close();

               System.out.println("Close all connection...");
               if(ht.get("status").toString().equals("OK"))
               {
                System.out.println("result is Ok..." + ht.get("locality").toString() );
                citystreetvalue=ht.get("latitude").toString() + ","+ ht.get("longitude").toString() +","+ht.get("locality").toString();
               }
               else
               {
                System.out.println("result is not Ok...");
                citystreetvalue="InvalidLocation";
               }

            }
            catch(Exception e)
            {
                System.out.println(e.toString());
            }


            System.out.println("before returen statement...");
            return citystreetvalue;

        }    

        public void traverse(XmlParser parser, String indent ) throws Exception
        {
            System.out.println("in Traverse method....");

        boolean leave = false;
        String title = new String();
        String desc = new String();

        do
        {
        ParseEvent event = parser.read ();
        ParseEvent pe;
        switch (event.getType())
        {
         // For example, <title>
         case Xml.START_TAG:
         // see API doc of StartTag for more access methods
         // Pick up Title for display
         if ("status".equals(event.getName()))
         {
                    pe = parser.read();
                    title = pe.getText();
                    ht.put("status",title); 
         }
             if(count<2)
             {
             if ("lat".equals(event.getName()))
                {

                    pe = parser.read();
                    title = pe.getText();
                    ht.put("latitude",title);
                    count=count+1;

                }
              if ("lng".equals(event.getName()))
              {
                    pe = parser.read();
                    desc = pe.getText();
                    ht.put("longitude",desc);
                    count=count+1;

              }
             }

          if ("long_name".equals(event.getName()))
            {

                pe = parser.read();
                title = pe.getText();

            }

          if ("type".equals(event.getName()))
          {
                pe = parser.read();
                            desc = pe.getText();

                            if(desc.equals("route"))
                            {
                                System.out.println("street is:" + title);
                                ht.put("street",title);
                            }
          }  
         if("formatted_address".equals(event.getName()))
         {

                  if(time)
                  {
                            pe = parser.read();
                            title = pe.getText();
                            ht.put("address",title);
                            time=false;
                  }

         }

              ht.put(desc,title);

          traverse(parser,"") ; // recursion call for each <tag></tag>
          break;
          // For example </title?
         case Xml.END_TAG:
          leave = true;
          break;
          // For example </rss>
         case Xml.END_DOCUMENT:
          leave = true;
          break;
          // For example, the text between tags
         case Xml.TEXT:
          break;
         case Xml.WHITESPACE:
          break;
          default:
          }

          } while( !leave );

         }

    }


now add below code in mainactivity class:

geocoding=new Geocoding();

locnm=locnm.replace(" ","%20");
String citystreetvalue=geocoding.parseXml(locnm);    
System.out.println("string is:" + citystreetvalue);

if(citystreetvalue.equals("InvalidLocation"))
{
    }else
    {                               
        String citystreetval[]=Split(citystreetvalue, ",");     

            String latstreet=citystreetval[2];
            nlatitude=citystreetval[0];
            nlongitude=citystreetval[1];
    }
于 2013-02-06T06:12:57.527 に答える