如何从谷歌地图Api v2获得lat和lng?

时间:2014-05-20 13:06:40

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

我今天问了这个问题,我又问了一遍,因为我不够清楚 我创建了一个返回以下值的类: lat / lng /当前位置 (街道,城市) 现在,在活动中,我需要获取当前位置的值并在简单的Toast按摩上显示它。 但是,当我到户外时,我的位置没有得到正确的值。 它记得我的最后一个位置并不是很准确。还有一件事......该应用程序已发布到市场上,并且某些设备出现了一些崩溃。我不明白这个问题。 我已经在下面列出了类代码。

第1课:

public class MapCurrentPlace implements OnMyLocationChangeListener {

public Context context;
double latitude = 0;
double longitude = 0;
String placeName = "";



public MapCurrentPlace(Context context) {
    super();
    this.context = context;
}


public double getLatitude() throws IOException {
    try {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);

        if(location != null){
            latitude = location.getLatitude();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return latitude;
}

public double getLongitude() throws IOException {
    try {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);
        if(location != null){
            longitude = location.getLongitude();    
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return longitude;
}


public String getPlaceName() throws IOException {
    try {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);

        latitude = location.getLatitude();
        longitude = location.getLongitude();

        //Get location info
        Geocoder gc = new Geocoder(context);
        if(location != null && gc !=null){
            List<Address> list = gc.getFromLocation(latitude, longitude, 1);
            if(list.size()>0){
                String city = list.get(0).getLocality();
                String street = list.get(0).getAddressLine(0);
                placeName = city+", "+street+"";        
            }


        }else{
            placeName = "";
        }


    } catch (Exception e) {
        e.printStackTrace();
        placeName = "";
    }



    return placeName;
}


@Override
public void onMyLocationChange(Location location) {
    if(location != null){
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        // After this you can call the function to be sure that the application already has a locaiton
    }
}

}

第2课(活动):

    private MapCurrentPlace place;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


try {
        place = new MapCurrentPlace(this);
        double lat = place.getLatitude();
        double lng = place.getLongitude();
        String placeLocation = place.getPlaceName();
        Toast.makeText(this, lat+" "+lng+" "+placeLocation, Toast.LENGTH_LONG).show();

} catch (Exception e) {
    // TODO: handle exception
}

    }
}

现在在我的设备上它工作正常,但当我走出去时它没有给我正确的位置

这是我的用户craches&amp; ANRs error1:

java.lang.NullPointerException
at com.bibas.workclock.tools.MapCurrentPlace.getLatitude(MapCurrentPlace.java:42)
at com.bibas.workclock.MainActivity.startTimer(MainActivity.java:269)
at com.bibas.workclock.MainActivity.onLongClick(MainActivity.java:786)
at android.view.View.performLongClick(View.java:4376)
at android.view.View$CheckForLongPress.run(View.java:17613)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5171)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564)
at dalvik.system.NativeStart.main(Native Method)

误差2:

    java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.bibas.workclock.tools.MapCurrentPlace.getPlaceName(MapCurrentPlace.java:74)
at com.bibas.workclock.MainActivity.startTimer(MainActivity.java:271)
at com.bibas.workclock.MainActivity.onLongClick(MainActivity.java:786)
at android.view.View.performLongClick(View.java:4511)
at android.view.View$CheckForLongPress.run(View.java:18758)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)

希望您能够解读我的问题谢谢:((

1 个答案:

答案 0 :(得分:0)

  • 您正在使用不再使用 locationManager Google Maps V2 ,您的课程应该实现 LocationListener 然后ovveride onLocationChanged 回调,当设备检测到比当前保存的位置更新的新位置时会触发该回调。

    public class MapCurrentPlace implements OnMyLocationChangeListener{
    
    public Context context;
    double latitude = 0;
    double longitude = 0;
    String placeName = "";
    
    
    public MapCurrentPlace(Context context) {
        super();
        this.context = context;
    }
    
    public String getPlaceName(Location location) throws IOException {
        try {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
    
            //Get location info
            Geocoder gc = new Geocoder(context);
            if(location != null && gc !=null){
                List<Address> list = gc.getFromLocation(latitude, longitude, 1);
                if(list.size()>0){
                    String city = list.get(0).getLocality();
                    String street = list.get(0).getAddressLine(0);
                    placeName = city+", "+street+"";        
                }
            }else{
                placeName = "";
            }
    
        } catch (Exception e) {
            e.printStackTrace();
            placeName = "";
        }
            //Return the place name format "city, street".
        return placeName;
    }
    
    @Override
    public void onMyLocationChange(Location location) {
    if(location != null){
           // After this you can call the function to be sure that the application already has a locaiton
     String placeName = getPlaceName(location); //  this is where you should call the method
       }
    }
    
  • 关于第一次崩溃,应该在应用上一个解决方案后修复,因为问题是当应用程序获取最后一个已知位置时,有时没有保存位置,所以参数为null并且捕获了的 NPE

  • 关于第二次崩溃,返回地点后,你写了&#39; String street = list.get(0).getAddressLine(0);&#39;在 getPlaceName()方法中,您没有检查AddressLine是否包含项目,因此您获得了空列表的第一项