Android - 为什么我的当前位置应用程序始终返回0纬度和0经度? [英] Android - Why is my Current Location app always return 0 Latitude and 0 Longitude?

查看:92
本文介绍了Android - 为什么我的当前位置应用程序始终返回0纬度和0经度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我调用getCurrentLocation()函数时,返回值始终是Latitude:0.0和Longitude:0.0



输出。结果与模拟器和手机上的结果相同。



我使用了实际的手机和模拟器,他们两个仍然给0和$。

这些在我的AndroidManifest.xml中。

 < manifest xmlns:android =http://schemas.android.com/apk/res/android
package =com.thesis.adrianangub.myapplication>

<使用权限android:name =android.permission.ACCESS_COARSE_LOCATION/>
< uses-permission android:name =android.permission.ACCESS_FINE_LOCATION/>
< uses-permission android:name =android.permission.INTERNET/>

$ b< application
android:allowBackup =true
android:icon =@ mipmap / ic_launcher
android:label =@ string / app_name
android:supportsRtl =true
android:theme =@ style / AppTheme>


<! - -
Google Maps API API密钥定义为字符串资源。
(请参阅文件res / values / google_maps_api.xml)。
请注意,API密钥已链接到用于签署APK的加密密钥。
您需要为每个加密密钥使用不同的API密钥,包括用于
签名的发布密钥。
您可以在src / debug /和src / release /中定义调试和发布目标的键。
- >
< meta-data
android:name =com.google.android.geo.API_KEY
android:value =@ string / google_maps_key/>

< activity
android:name =。MapsActivity
android:label =@ string / title_activity_maps>
< intent-filter>

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

< / manifest>

这些位于我的MapsActivity.java中

  package com.thesis.adrianangub.myapplication; 
公共类MapsActivity扩展FragmentActivity实现OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,GoogleMap.OnMarkerDragListener,GoogleMap.OnMapLongClickListener,View.OnClickListener
{

//我们的地图
private GoogleMap mMap;

//存储地图
私人双经度的经度和纬度;
私人双纬度;

//按钮
私人按钮buttonSave;
私人按钮buttonCurrent;
私人按钮buttonView;

// Google ApiClient
私有GoogleApiClient googleApiClient;


@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
//获取SupportMapFragment并在地图准备好使用时得到通知。
SupportMapFragment mapFragment =(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

//初始化googleapi客户端
googleApiClient =新的GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi (LocationServices.API)
.build();

//初始化视图并添加onclick监听器
buttonSave =(Button)findViewById(R.id.buttonSave);
buttonCurrent =(Button)findViewById(R.id.buttonCurrent);
buttonView =(Button)findViewById(R.id.buttonView);
buttonSave.setOnClickListener(this);
buttonCurrent.setOnClickListener(this);
buttonView.setOnClickListener(this);
}

@Override
protected void onStart(){
googleApiClient.connect();
super.onStart();
}

@Override
protected void onStop(){
googleApiClient.disconnect();
super.onStop();
}

//获取当前位置
private void getCurrentLocation(){
mMap.clear();
//创建位置对象
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED&&& ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)! = PackageManager.PERMISSION_GRANTED){
// TODO:考虑调用
// ActivityCompat#requestPermissions
//在这里请求丢失的权限,然后覆盖
// public void onRequestPermissionsResult (int requestCode,String []权限,
// int [] grantResults)
//处理用户授予权限的情况。有关更多详细信息,请参阅文档
//获取ActivityCompat#requestPermissions。
return;
}
位置位置= LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if(location!= null){
//获取经度和纬度
longitude = location.getLongitude();
latitude = location.getLatitude();

//将地图移动到位置
moveMap();



//移动地图的函数
private void moveMap(){
//显示当前纬度和经度的字符串
String msg =纬度+,+经度;

//创建一个LatLng对象来存储坐标
LatLng latLng = new LatLng(纬度,经度);

//将标记添加到地图
mMap.addMarker(new MarkerOptions()
.position(latLng)//设置位置
.draggable(true)//使标记可拖动
.title(当前位置)); //添加一个标题

//移动摄像头
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

//为相机设置动画
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

//在toast中显示当前坐标
Toast.makeText(this,msg,Toast.LENGTH_LONG).show();
}

@Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
LatLng latLng = new LatLng(-34,151);
mMap.addMarker(new MarkerOptions()。position(latLng).draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
}

@Override
public void onConnected(Bundle bundle){
getCurrentLocation();
}

@Override
public void onConnectionSuspended(int i){

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult){

}
$ b $ @覆盖
public void onMapLongClick(LatLng latLng){
//清除所有标记
mMap.clear();

//将新标记添加到当前按下的位置
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true)) ;
}

@Override
public void onMarkerDragStart(Marker marker){

}

@Override
public void onMarkerDrag(Marker marker){

}

@Override
public void onMarkerDragEnd(Marker marker){
//获取坐标
latitude = marker.getPosition()。latitude;
longitude = marker.getPosition()。longitude;

//移动地图
moveMap();
}

@Override
public void onClick(View v){
if(v == buttonCurrent){
getCurrentLocation();
moveMap();
}
}

}



这是我的activity_maps.xml

 < FrameLayout xmlns:android =http:// schemas。 android.com/apk/res/android
xmlns:tools =http://schemas.android.com/tools
android:layout_width =match_parent
android:layout_height = match_parent
tools:context =。MapsActivity>

< fragment xmlns:android =http://schemas.android.com/apk/res/android
xmlns:map =http://schemas.android.com / apk / res-auto
xmlns:tools =http://schemas.android.com/tools
android:id =@ + id / map
android:name =com.google.android.gms.maps.SupportMapFragment
android:layout_width =match_parent
android:layout_height =match_parent
tools:context =com.thesis.adrianangub .myapplication.MapsActivity/>

< LinearLayout
android:layout_width =match_parent
android:layout_height =match_parent
android:gravity =bottom
android:取向= 垂直 >

< LinearLayout
android:layout_width =match_parent
android:layout_height =wrap_content
android:background =#cc3b60a7
android :取向= 水平 >

< Button
android:text =Curr
android:id =@ + id / buttonCurrent
android:onClick =getCurrentLocation
android:layout_width =50dp
android:layout_height =50dp
android:layout_margin =15dp/>

< Button
android:text =Save
android:id =@ + id / buttonSave
android:layout_width =50dp
android:layout_height =50dp
android:layout_margin =15dp/>

$ b< Button
android:text =View
android:id =@ + id / buttonView
android:layout_width = 50dp
android:layout_height =50dp
android:layout_margin =15dp/>

< / LinearLayout>
< / LinearLayout>


解决方案

您必须申请棉花糖设备许可。请参阅文档



进入第一个活动时,添加以下代码:

将以下两个变量放在onCreate()方法的顶部:




  • 您可以为棉花糖添加许多权限。下面我已经在字符串数组中添加了五个权限。在此帮助下,我正在授予oncreate方法外的权限。

  • 我们在字符串数组中添加的权限是什么,它必须添加到清单。

     字符串[] perms = {android.permission.CAMERA,
    android.permission.WRITE_EXTERNAL_STORAGE ,android.permission.READ_EXTERNAL_STORAGE,
    android.permission.ACCESS_FINE_LOCATION,android.permission.ACCESS_COARSE_LOCATION};

    int permsRequestCode = 200;




将下面的方法放在onCreate ()method:

  if(canMakeSmores()){

requestPermissions(perms ,permsRequestCode);

$ b

在onCreate()方法:

  private boolean canMakeSmores(){

return(Build.VERSION。 SDK_INT> Build.VERSION_CODES.LOLLIPOP_MR1);



$ public void onRequestPermissionsResult(int permsRequestCode,String [] permissions,int [] grantResults){

switch(permsRequestCode ){

case 200:

if(grantResults.length> 0){

boolean cameraAccepted = grantResults [0] == PackageManager。许可授予;

if(cameraAccepted){

} else {
requestPermissions(perms,permsRequestCode);
}

布尔writeAccepted = grantResults [1] == PackageManager.PERMISSION_GRANTED;

if(writeAccepted){

} else {
requestPermissions(perms,permsRequestCode);
}

布尔值readAccepted = grantResults [2] == PackageManager.PERMISSION_GRANTED;

if(readAccepted){

} else {
requestPermissions(perms,permsRequestCode);
}

布尔型fineLocationAccepted = grantResults [3] == PackageManager.PERMISSION_GRANTED;

if(fineLocationAccepted){

} else {
requestPermissions(perms,permsRequestCode);
}

布尔coarseLocationAccepted = grantResults [4] == PackageManager.PERMISSION_GRANTED;

if(coarseLocationAccepted){

} else {
requestPermissions(perms,permsRequestCode);
}

}

break;



$ b

Manifest:

 < uses-permission android:name =android.permission.INTERNET/> 
<使用权限android:name =android.permission.READ_EXTERNAL_STORAGE/>
< uses-permission android:name =android.permission.WRITE_EXTERNAL_STORAGE/>
< uses-permission android:name =android.permission.ACCESS_COARSE_LOCATION/>
< uses-permission android:name =android.permission.ACCESS_FINE_LOCATION/>
<使用权限android:name =android.permission.CAMERA/>
< uses-permission android:name =android.permission.ACCESS_GPS/>
< uses-permission android:name =android.permission.ACCESS_LOCATION/>


The return value whenever i call getCurrentLocation() function is always Latitude: 0.0 and Longitude: 0.0

The Output. The result is also the same as both on the emulator and on the phone.

I used an actual phone and the emulator, both of them still give 0 and 0.

These are in my AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.thesis.adrianangub.myapplication" >

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


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >


        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

These are in my MapsActivity.java

 package com.thesis.adrianangub.myapplication;
 public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, View.OnClickListener
 {

//Our Map
private GoogleMap mMap;

//To store longitude and latitude from map
private double longitude;
private double latitude;

//Buttons
private Button buttonSave;
private Button buttonCurrent;
private Button buttonView;

//Google ApiClient
private GoogleApiClient googleApiClient;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    //Initializing googleapi client
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    //Initializing views and adding onclick listeners
    buttonSave = (Button) findViewById(R.id.buttonSave);
    buttonCurrent = (Button) findViewById(R.id.buttonCurrent);
    buttonView = (Button) findViewById(R.id.buttonView);
    buttonSave.setOnClickListener(this);
    buttonCurrent.setOnClickListener(this);
    buttonView.setOnClickListener(this);
}

@Override
protected void onStart() {
    googleApiClient.connect();
    super.onStart();
}

@Override
protected void onStop() {
    googleApiClient.disconnect();
    super.onStop();
}

//Getting current location
private void getCurrentLocation() {
    mMap.clear();
    //Creating a location object
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    if (location != null) {
        //Getting longitude and latitude
        longitude = location.getLongitude();
        latitude = location.getLatitude();

        //moving the map to location
        moveMap();
    }
}

//Function to move the map
private void moveMap() {
    //String to display current latitude and longitude
    String msg = latitude + ", "+longitude;

    //Creating a LatLng Object to store Coordinates
    LatLng latLng = new LatLng(latitude, longitude);

    //Adding marker to map
    mMap.addMarker(new MarkerOptions()
            .position(latLng) //setting position
            .draggable(true) //Making the marker draggable
            .title("Current Location")); //Adding a title

    //Moving the camera
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    //Animating the camera
    mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    //Displaying current coordinates in toast
    Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    LatLng latLng = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.setOnMarkerDragListener(this);
    mMap.setOnMapLongClickListener(this);
}

@Override
public void onConnected(Bundle bundle) {
    getCurrentLocation();
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

@Override
public void onMapLongClick(LatLng latLng) {
    //Clearing all the markers
    mMap.clear();

    //Adding a new marker to the current pressed position
    mMap.addMarker(new MarkerOptions()
            .position(latLng)
            .draggable(true));
}

@Override
public void onMarkerDragStart(Marker marker) {

}

@Override
public void onMarkerDrag(Marker marker) {

}

@Override
public void onMarkerDragEnd(Marker marker) {
    //Getting the coordinates
    latitude = marker.getPosition().latitude;
    longitude = marker.getPosition().longitude;

    //Moving the map
    moveMap();
}

@Override
public void onClick(View v) {
    if(v == buttonCurrent){
        getCurrentLocation();
        moveMap();
    }
}

}

And this is my activity_maps.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity">

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.thesis.adrianangub.myapplication.MapsActivity" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#cc3b60a7"
        android:orientation="horizontal">

        <Button
            android:text="Curr"
            android:id="@+id/buttonCurrent"
            android:onClick="getCurrentLocation"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_margin="15dp" />

        <Button
            android:text="Save"
            android:id="@+id/buttonSave"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_margin="15dp" />


        <Button
            android:text="View"
            android:id="@+id/buttonView"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_margin="15dp"/>

    </LinearLayout>
</LinearLayout>

解决方案

You have to request permission for marshmallow device. Refer this docs

While coming to the first activity, add this below code:

put this below two variables to the top of onCreate() method:

  • You can add many number of permissions for marshmallow. Below I have added the five permissions in string array. With the help of this, I am granting permission outside the oncreate method.

  • What are the permissions we are adding in string array, it have to be added in manifest.

    String[] perms = {"android.permission.CAMERA",
            "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE",
             "android.permission.ACCESS_FINE_LOCATION", "android.permission.ACCESS_COARSE_LOCATION"};     
    
    int permsRequestCode = 200;
    

Put this below method inside onCreate() method :

if(canMakeSmores()){

        requestPermissions(perms, permsRequestCode);

    }

Put these below two methods outside onCreate() method:

private boolean canMakeSmores(){

    return(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1);

}       


 public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){

    switch(permsRequestCode){

        case 200:

            if(grantResults.length > 0){

                boolean cameraAccepted = grantResults[0]==PackageManager.PERMISSION_GRANTED;

                if(cameraAccepted){

                }else {
                    requestPermissions(perms, permsRequestCode);
                }

                boolean writeAccepted = grantResults[1]==PackageManager.PERMISSION_GRANTED;

                if(writeAccepted){

                }else {
                    requestPermissions(perms, permsRequestCode);
                }

                boolean readAccepted = grantResults[2]==PackageManager.PERMISSION_GRANTED;

                if(readAccepted){

                }else {
                    requestPermissions(perms, permsRequestCode);
                }

                boolean fineLocationAccepted = grantResults[3]==PackageManager.PERMISSION_GRANTED;

                if(fineLocationAccepted){

                }else {
                    requestPermissions(perms, permsRequestCode);
                }

                boolean coarseLocationAccepted = grantResults[4]==PackageManager.PERMISSION_GRANTED;

                if(coarseLocationAccepted){

                }else {
                    requestPermissions(perms, permsRequestCode);
                }

            }

            break;

    }

}

Manifest:

 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />

这篇关于Android - 为什么我的当前位置应用程序始终返回0纬度和0经度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆