Android - 如何获取当前位置(经度和纬度)?

时间:2011-05-23 10:25:14

标签: android geolocation latitude-longitude geocode google-latitude

我使用以下代码获取当前位置(纬度和经度),但我没有获得当前位置(纬度和经度)。

任何人都知道为什么?

package com.ram.currentlocation;

import android.app.Activity;    
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class Location_Gps extends Activity
{

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      /* Use the LocationManager class to obtain GPS locations */
      LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

      LocationListener mlocListener = new MyLocationListener();
      mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
    }

    /* Class My Location Listener */
    public class MyLocationListener implements LocationListener
    {

      @Override
      public void onLocationChanged(Location loc)
      {

        loc.getLatitude();
        loc.getLongitude();

        String Text = "My current location is: " +
        "Latitud = " + loc.getLatitude() +
        "Longitud = " + loc.getLongitude();

        Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onProviderDisabled(String provider)
      {
        Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
      }

      @Override
      public void onProviderEnabled(String provider)
      {
        Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onStatusChanged(String provider, int status, Bundle extras)
      {

      }
    }
}

P.S。:我在manifest文件中使用以下权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_CORSE_LOCATION"/>

4 个答案:

答案 0 :(得分:25)

您的清单文件中有错误。正确的是:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

答案 1 :(得分:5)

您必须将位置修复发送到模拟器,因为模拟器是您需要提供位置修复的软件。

如果您正在使用eclipse,请转到

Window -> Show view -> Other

选择Android标签并搜索模拟器控件 在您看到仿真器控制窗口导航到位置控件之后 正如你在下面的图片中看到的那样

sending loc fix

发送loc修复后,您可以使用

Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

其中lmLocationManager对象,因此90%的工作已完成;)

干杯!

答案 2 :(得分:3)

在你的Android清单中你设置了权限吗?

android.permission.ACCESS_FINE_LOCATION

只有获得(0,0)co-ords你可能正在使用模拟器。如果您正在使用eclipse,请转到模拟器控件,然后在底部将伪造的数据发送到设备

答案 3 :(得分:1)

您没有使用正确的权限。正确的是:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

顺便说一句,您的需求只能通过以下方式实现:

<using-permission android:name="ACCESS_FINE_LOCATION" />

所以不需要ACCESS_COARSE_LOCATION

相关问题