在android中使用纬度和经度获取位置信息

时间:2014-04-16 06:33:51

标签: android google-maps google-maps-android-api-2

我想做什么 ::

  • 我正在尝试location name使用Latitude& Longitude
  • 我已经制作了密钥并添加到了清单
  • 我已更新互联网许可&其他所需权限 也
  • 我也推动了纬度&经度仿真器

我已将项目添加到DropBox :: Anyone can refer here Download & execute


MainActivity.java

   public class MainActivity extends Activity implements OnClickListener{

        private EditText result;
        private Button btngetAddress;
        private Context context=null;
        private ProgressDialog dialog = null;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }
            context=this;

            result=(EditText)findViewById(R.id.editText_result);
            btngetAddress=(Button)findViewById(R.id.button_getAddress);
            btngetAddress.setOnClickListener(this);


        }
        @Override
        public void onClick(View arg0) {

            dialog = ProgressDialog.show(context, "","Please wait..", true);
            GetCurrentAddress currentadd=new GetCurrentAddress();
               currentadd.execute();
        }


        public  String getAddress(Context ctx, double latitude, double longitude) {
            StringBuilder result = new StringBuilder();
            try {
                Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
                if (addresses.size() > 0) {
                    Address address = addresses.get(0);

                    String locality=address.getLocality();
                    String city=address.getCountryName();
                    String region_code=address.getCountryCode();
                    String zipcode=address.getPostalCode();
                    double lat =address.getLatitude();
                    double lon= address.getLongitude();

                    result.append(locality+" ");
                    result.append(city+" "+ region_code+" ");
                    result.append(zipcode);

                }
            } catch (IOException e) {
                Log.e("tag", e.getMessage());
            }

            return result.toString();
        }

        private class GetCurrentAddress extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... urls) {
        // this lat and log we can get from current location but here we given hard coded
                double latitude=12.9183555;
                double longitude=77.6702357;

            String address= getAddress(context, latitude, longitude);
                return address;
            }

            @Override
            protected void onPostExecute(String resultString) {
                dialog.dismiss();
                result.setText(resultString);

            }
        }
    }

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button_getAddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Get Address" />

</LinearLayout>

清单::

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.addressfromlatlong"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.sunil.address.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

     <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyBzReOb6cYRWordd-G1i7sd5N92Sy_H054" />

</manifest>

更新的-登录 ::

   04-16 13:15:35.377: D/dalvikvm(92): GC_EXPLICIT freed 465K, 11% free 12191K/13575K, paused 9ms+23ms
04-16 13:15:35.517: D/PackageManager(92): generateServicesMap(android.accounts.AccountAuthenticator): 2 services unchanged
04-16 13:15:35.708: D/PackageManager(92): generateServicesMap(android.content.SyncAdapter): 4 services unchanged
04-16 13:15:35.727: D/BackupManagerService(92): Received broadcast Intent { act=android.intent.action.PACKAGE_REMOVED dat=package:com.example.addressfromlatlong flg=0x10000010 (has extras) }
04-16 13:15:35.757: D/StrictMode(92): StrictMode policy violation; ~duration=201 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=151 violation=2
04-16 13:15:35.757: D/StrictMode(92):   at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:1074)
04-16 13:15:35.757: D/StrictMode(92):   at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1557)
04-16 13:15:35.757: D/StrictMode(92):   at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1449)
04-16 13:15:35.757: D/StrictMode(92):   at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1405)
04-16 13:15:35.757: D/StrictMode(92):   at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1485)
04-16 13:15:35.757: D/StrictMode(92):   at android.accounts.AccountManagerService.purgeOldGrants(AccountManagerService.java:224)
04-16 13:15:35.757: D/StrictMode(92):   at android.accounts.AccountManagerService.access$000(AccountManagerService.java:76)
04-16 13:15:35.757: D/StrictMode(92):   at android.accounts.AccountManagerService$1.onReceive(AccountManagerService.java:213)
04-16 13:15:35.757: D/StrictMode(92):   at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
04-16 13:15:35.757: D/StrictMode(92):   at android.os.Handler.handleCallback(Handler.java:605)
04-16 13:15:35.757: D/StrictMode(92):   at android.os.Handler.dispatchMessage(Handler.java:92)
04-16 13:15:35.757: D/StrictMode(92):   at android.os.Looper.loop(Looper.java:137)
04-16 13:15:35.757: D/StrictMode(92):   at com.android.server.ServerThread.run(SystemServer.java:744)
04-16 13:15:35.788: I/AccountTypeManager(278): Loaded meta-data for 1 account types, 0 accounts in 178ms(wall) 16ms(cpu)
04-16 13:15:35.837: D/PackageManager(92): generateServicesMap(android.accounts.AccountAuthenticator): 2 services unchanged
04-16 13:15:35.858: D/PackageManager(92): generateServicesMap(android.content.SyncAdapter): 4 services unchanged
04-16 13:15:36.317: D/BackupManagerService(92): Received broadcast Intent { act=android.intent.action.PACKAGE_ADDED dat=package:com.example.addressfromlatlong flg=0x10000010 (has extras) }
04-16 13:15:36.317: V/BackupManagerService(92): updatePackageParticipantsLocked: com.example.addressfromlatlong
04-16 13:15:36.477: I/AccountTypeManager(278): Loaded meta-data for 1 account types, 0 accounts in 407ms(wall) 12ms(cpu)
04-16 13:15:37.078: W/RecognitionManagerService(92): no available voice recognition services found
04-16 13:15:38.247: D/StrictMode(92): StrictMode policy violation; ~duration=1107 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=151 violation=2
04-16 13:15:38.247: D/StrictMode(92):   at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:1074)
04-16 13:15:38.247: D/StrictMode(92):   at libcore.io.BlockGuardOs.open(BlockGuardOs.java:94)
04-16 13:15:38.247: D/StrictMode(92):   at libcore.io.IoBridge.open(IoBridge.java:390)
04-16 13:15:38.247: D/StrictMode(92):   at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
04-16 13:15:38.247: D/StrictMode(92):   at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
04-16 13:15:38.247: D/StrictMode(92):   at com.android.internal.os.AtomicFile.startWrite(AtomicFile.java:59)
04-16 13:15:38.247: D/StrictMode(92):   at com.android.server.AppWidgetService.saveStateLocked(AppWidgetService.java:1181)
04-16 13:15:38.247: D/StrictMode(92):   at com.android.server.AppWidgetService$2.onReceive(AppWidgetService.java:1452)
04-16 13:15:38.247: D/StrictMode(92):   at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
04-16 13:15:38.247: D/StrictMode(92):   at android.os.Handler.handleCallback(Handler.java:605)
04-16 13:15:38.247: D/StrictMode(92):   at android.os.Handler.dispatchMessage(Handler.java:92)
04-16 13:15:38.247: D/StrictMode(92):   at android.os.Looper.loop(Looper.java:137)
04-16 13:15:38.247: D/StrictMode(92):   at com.android.server.ServerThread.run(SystemServer.java:744)
04-16 13:15:38.317: D/StrictMode(92): StrictMode policy violation; ~duration=1073 ms: android.os.StrictMode$StrictModeDiskWriteViolation: policy=151 violation=1
04-16 13:15:38.317: D/StrictMode(92):   at android.os.StrictMode$AndroidBlockGuardPolicy.onWriteToDisk(StrictMode.java:1048)
04-16 13:15:38.317: D/StrictMode(92):   at libcore.io.BlockGuardOs.write(BlockGuardOs.java:178)
04-16 13:15:38.317: D/StrictMode(92):   at libcore.io.IoBridge.write(IoBridge.java:447)
04-16 13:15:38.317: D/StrictMode(92):   at java.io.FileOutputStream.write(FileOutputStream.java:187)
04-16 13:15:38.317: D/StrictMode(92):   at com.android.internal.util.FastXmlSerializer.flushBytes(FastXmlSerializer.java:212)
04-16 13:15:38.317: D/StrictMode(92):   at com.android.internal.util.FastXmlSerializer.flush(FastXmlSerializer.java:233)
04-16 13:15:38.317: D/StrictMode(92):   at com.android.internal.util.FastXmlSerializer.endDocument(FastXmlSerializer.java:183)
04-16 13:15:38.317: D/StrictMode(92):   at com.android.server.AppWidgetService.writeStateToFileLocked(AppWidgetService.java:1240)
04-16 13:15:38.317: D/StrictMode(92):   at com.android.server.AppWidgetService.saveStateLocked(AppWidgetService.java:1182)
04-16 13:15:38.317: D/StrictMode(92):   at com.android.server.AppWidgetService$2.onReceive(AppWidgetService.java:1452)
04-16 13:15:38.317: D/StrictMode(92):   at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
04-16 13:15:38.317: D/StrictMode(92):   at android.os.Handler.handleCallback(Handler.java:605)
04-16 13:15:38.317: D/StrictMode(92):   at android.os.Handler.dispatchMessage(Handler.java:92)
04-16 13:15:38.317: D/StrictMode(92):   at android.os.Looper.loop(Looper.java:137)
04-16 13:15:38.317: D/StrictMode(92):   at com.android.server.ServerThread.run(SystemServer.java:744)
04-16 13:15:38.317: D/StrictMode(92): StrictMode policy violation; ~duration=1065 ms: android.os.StrictMode$StrictModeDiskWriteViolation: policy=151 violation=1
04-16 13:15:38.317: D/StrictMode(92):   at android.os.StrictMode$AndroidBlockGuardPolicy.onWriteToDisk(StrictMode.java:1048)
04-16 13:15:38.317: D/StrictMode(92):   at libcore.io.BlockGuardOs.fsync(BlockGuardOs.java:84)
04-16 13:15:38.317: D/StrictMode(92):   at java.io.FileDescriptor.sync(FileDescriptor.java:71)
04-16 13:15:38.317: D/StrictMode(92):   at android.os.FileUtils.sync(FileUtils.java:111)
04-16 13:15:38.317: D/StrictMode(92):   at com.android.internal.os.AtomicFile.finishWrite(AtomicFile.java:80)
04-16 13:15:38.317: D/StrictMode(92):   at com.android.server.AppWidgetService.saveStateLocked(AppWidgetService.java:1183)
04-16 13:15:38.317: D/StrictMode(92):   at com.android.server.AppWidgetService$2.onReceive(AppWidgetService.java:1452)
04-16 13:15:38.317: D/StrictMode(92):   at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
04-16 13:15:38.317: D/StrictMode(92):   at android.os.Handler.handleCallback(Handler.java:605)
04-16 13:15:38.317: D/StrictMode(92):   at android.os.Handler.dispatchMessage(Handler.java:92)
04-16 13:15:38.317: D/StrictMode(92):   at android.os.Looper.loop(Looper.java:137)
04-16 13:15:38.317: D/StrictMode(92):   at com.android.server.ServerThread.run(SystemServer.java:744)
04-16 13:15:38.338: D/BackupManagerService(92): Received broadcast Intent { act=android.intent.action.PACKAGE_REPLACED dat=package:com.example.addressfromlatlong flg=0x10000010 (has extras) }
04-16 13:15:38.338: V/BackupManagerService(92): updatePackageParticipantsLocked: com.example.addressfromlatlong
04-16 13:15:39.437: D/dalvikvm(92): GC_CONCURRENT freed 471K, 10% free 12310K/13575K, paused 12ms+133ms
04-16 13:15:41.133: D/dalvikvm(278): GC_CONCURRENT freed 363K, 5% free 10129K/10631K, paused 2134ms+56ms
04-16 13:15:43.257: D/dalvikvm(1022): GC_FOR_ALLOC freed 1421K, 28% free 14502K/19975K, paused 133ms
04-16 13:15:44.617: D/dalvikvm(92): GC_EXPLICIT freed 216K, 11% free 12185K/13575K, paused 1612ms+76ms
04-16 13:15:44.687: D/AndroidRuntime(1073): Shutting down VM
04-16 13:15:44.727: I/AndroidRuntime(1073): NOTE: attach of thread 'Binder Thread #3' failed
04-16 13:15:44.757: D/dalvikvm(1073): GC_CONCURRENT freed 101K, 78% free 454K/2048K, paused 3ms+4ms
04-16 13:15:44.777: D/jdwp(1073): Got wake-up signal, bailing out of select
04-16 13:15:44.787: D/dalvikvm(1073): Debugger has detached; object registry had 1 entries
04-16 13:15:45.847: D/AndroidRuntime(1094): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
04-16 13:15:45.857: D/AndroidRuntime(1094): CheckJNI is ON
04-16 13:15:47.667: D/AndroidRuntime(1094): Calling main entry com.android.commands.am.Am
04-16 13:15:47.758: I/ActivityManager(92): START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.addressfromlatlong/com.sunil.address.MainActivity} from pid 1094
04-16 13:15:47.797: W/WindowManager(92): Failure taking screenshot for (180x300) to layer 21010
04-16 13:15:47.887: D/AndroidRuntime(1094): Shutting down VM
04-16 13:15:47.947: I/AndroidRuntime(1094): NOTE: attach of thread 'Binder Thread #3' failed
04-16 13:15:47.987: D/dalvikvm(1094): GC_CONCURRENT freed 102K, 77% free 483K/2048K, paused 2ms+43ms
04-16 13:15:47.987: D/jdwp(1094): Got wake-up signal, bailing out of select
04-16 13:15:47.987: D/dalvikvm(1094): Debugger has detached; object registry had 1 entries
04-16 13:15:48.047: D/dalvikvm(1105): Not late-enabling CheckJNI (already on)
04-16 13:15:48.087: I/ActivityManager(92): Start proc com.example.addressfromlatlong for activity com.example.addressfromlatlong/com.sunil.address.MainActivity: pid=1105 uid=10047 gids={3003, 1015}
04-16 13:15:48.117: I/WindowManager(92): createSurface Window{41510cd0 Starting com.example.addressfromlatlong paused=false}: DRAW NOW PENDING
04-16 13:15:48.747: W/NetworkManagementSocketTagger(92): setKernelCountSet(10047, 1) failed with errno -2
04-16 13:15:50.117: I/WindowManager(92): createSurface Window{41600328 com.example.addressfromlatlong/com.sunil.address.MainActivity paused=false}: DRAW NOW PENDING
04-16 13:15:50.277: D/gralloc_goldfish(1105): Emulator without GPU emulation detected.
04-16 13:15:50.487: I/ActivityManager(92): Displayed com.example.addressfromlatlong/com.sunil.address.MainActivity: +2s601ms
04-16 13:15:51.018: W/NetworkManagementSocketTagger(92): setKernelCountSet(10005, 0) failed with errno -2
04-16 13:15:54.527: I/WindowManager(92): createSurface Window{416690e8 com.example.addressfromlatlong/com.sunil.address.MainActivity paused=false}: DRAW NOW PENDING
04-16 13:15:55.458: W/InputManagerService(92): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@4150df50

我仍然无法获得所需信息 如何解决此问题

3 个答案:

答案 0 :(得分:0)

参考https://stackoverflow.com/a/6922448/2771869

LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);

Location locations = locationManager.getLastKnownLocation(provider);
List<String>  providerList = locationManager.getAllProviders();
if(null!=locations && null!=providerList && providerList.size()>0){                 
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());                 
try {
    List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
    if(null!=listAddresses&&listAddresses.size()>0){
        String _Location = listAddresses.get(0).getAddressLine(0);
    }
} catch (IOException e) {
    e.printStackTrace();
}

}

答案 1 :(得分:0)

你的代码对我来说似乎很好。

将以下代码放在活动中setContentView()的正下方。

 if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

如果在保存应用程序后出现错误,则只需将鼠标悬停在错误上并添加@SuppressLint(&#34; NewApi&#34;)(Eclipse将为您提供鼠标悬停选项)。例如,您将收到错误的单词&#34; build&#34;。如果有效,请告诉我。

答案 2 :(得分:0)

我确信有一个例外:

catch (Exception e)
{
   Log.e("tag", e.getMessage());
}

这将在您的logcat中打印:tag : Service not available。要解决此问题,请遵循thisthis

转到位置设置并启用:

  1. 使用无线网络
  2. 使用GPS卫星