2013年10月11日 星期五

for android:最小的取得經緯度函數

import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import com.neotech.goingtvmall.frontend.R.id;
import com.neotech.goingtvmall.frontend.SubStoreTypeListActivity.MyAdapter;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;

public class GeolocationFunc {


public static String getAddress(Location location,Context ctxOfActivity)throws Exception{
        Geocoder geocoder;
        geocoder = new Geocoder(ctxOfActivity, Locale.getDefault());
List<Address> addresses=
geocoder.getFromLocation(location.getLatitude(),
                location.getLongitude(), 1);
//geocoder.getFromLocation(currentlocation.getLatitude(),currentlocation.getLongitude(), 1);
StringBuffer sb=new StringBuffer();
for(Address address : addresses){
   String addressLine = address.getAddressLine(0);
       String city = address.getAddressLine(1);
       String country = address.getAddressLine(2);
       Log.v("addr",addressLine+" "+city+" "+country);
       if(city==null)city="";
       if(country==null)country="";
       sb.append(addressLine+" "+city+" "+country+"附近");
}
return sb.toString();
}

public static Location getBestLocation(Context ctxt) {
   Location gpslocation = getLocationByProvider(
       LocationManager.GPS_PROVIDER, ctxt);
   Location networkLocation = getLocationByProvider(
       LocationManager.NETWORK_PROVIDER, ctxt);
   Location fetchedlocation = null;
   // if we have only one location available, the choice is easy
   if (gpslocation != null) {
       Log.i("New Location Receiver", "GPS Location available.");
       fetchedlocation = gpslocation;
   } else {
       Log.i("New Location Receiver",
           "No GPS Location available. Fetching Network location lat="
               + networkLocation.getLatitude() + " lon ="
               + networkLocation.getLongitude());
       fetchedlocation = networkLocation;
   }
   return fetchedlocation;
}

/**
* get the last known location from a specific provider (network/gps)
*/
private static Location getLocationByProvider(String provider, Context ctxt) {
   Location location = null;
   // if (!isProviderSupported(provider)) {
   // return null;
   // }
   LocationManager locationManager = (LocationManager) ctxt
           .getSystemService(Context.LOCATION_SERVICE);
   try {
       if (locationManager.isProviderEnabled(provider)) {
           location = locationManager.getLastKnownLocation(provider);
       }
   } catch (IllegalArgumentException e) {
       Log.i("New Location Receiver", "Cannot access Provider " + provider);
   }
   return location;
}
}

沒有留言:

張貼留言