【问题标题】:the current location does not appear on the map when i run my app to get user location当我运行我的应用程序以获取用户位置时,当前位置不会出现在地图上
【发布时间】:2018-01-20 19:30:35
【问题描述】:

我正在制作一个应用程序来在谷歌地图上显示用户位置,方法是在我运行应用程序时在他/她的当前位置放置一个标记,它只给我地图视图而不做任何其他事情,我搜索了太多但是我找不到任何可以帮助我的东西,任何人都可以指导我完成这个。 提前致谢。

MapsActivity.java

package com.example.android.getlocationtrial;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;  
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private LocationManager manager;
private LocationListener locationListener;
@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);
    //get the location service
    manager = (LocationManager) getSystemService(LOCATION_SERVICE);
    //request the location update thru location manager
    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;
    }
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            //get the latitude and longitude from the location
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            //get the location name from latitude and longitude
            Geocoder geocoder = new Geocoder(getApplicationContext());
            try {
                List<Address> addresses =
                        geocoder.getFromLocation(latitude, longitude, 1);
                String result = addresses.get(0).getSubLocality()+":";
                result += addresses.get(0).getLocality()+":";
                result += addresses.get(0).getCountryCode();
                LatLng latLng = new LatLng(latitude, longitude);
                mMap.addMarker(new MarkerOptions().position(latLng).title(result));
                mMap.setMaxZoomPreference(20);
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
    manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, locationListener);
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera

      /*
      LatLng sydney = new LatLng(-34, 151);
      mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
      mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
      */
}

@Override
protected void onPause() {
    super.onPause();
    manager.removeUpdates(locationListener);
    Log.i("onPause...","paused");
}
}

AndroidManifest.xml

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

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    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>

【问题讨论】:

    标签: android google-maps android-studio


    【解决方案1】:

    为了显示当前位置标记,您只需在地图对象上调用 setMyLocationEnabled 并传递 true 作为其参数。

    检查以下代码片段:

    private static final int LOCATION_REQUEST = 50;
    
    private String[] LOCATION_PERMS = {android.Manifest.permission.ACCESS_FINE_LOCATION };
    
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
       mMap = googleMap;
    
       // Asking for location permission to request the last user location 
       if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
    
                ActivityCompat.requestPermissions(this,
                        LOCATION_PERMS,
                        LOCATION_REQUEST);
            } else {
                ActivityCompat.requestPermissions(this,
                        LOCATION_PERMS,
                        LOCATION_REQUEST);
            }
    
        } else {
            //This will show the current user location marker
            mMap.setMyLocationEnabled(true);
    
           //Getting location updates and focus the camera with the latest location
    
           FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
           mFusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                // ...
                                userCurrentLocation = new LatLng(location.getLatitude(), location.getLongitude());
                                CameraPosition cp = CameraPosition.builder().target(userCurrentLocation).zoom(25).build();
                                mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp), 500, null);
    
                            }
                        }
                    });
         }
    }
    
     @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
    
        switch (requestCode) {
            case LOCATION_REQUEST: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay!
                    onMapReady(mMap);
    
                } else {
                    // permission denied,
                    // Ask again for the permission
                    Toast.makeText(this, R.string.location_permission_required_message, Toast.LENGTH_SHORT).show();
                    finish();
                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
    

    【讨论】:

    • 还是一样的结果,地图上没有标记@Ehab-Hamdy
    • 代码运行良好。您将获得蓝色圆圈标记,但您必须确保添加 fusedLocationClient 否则它将无法工作
    • 我在模拟器上运行程序,有问题吗?
    • 如果您在模拟器上尝试先打开谷歌地图应用程序,然后再次运行您的应用程序。
    • 还是一样的输出
    猜你喜欢
    • 2013-12-02
    • 1970-01-01
    • 2021-11-18
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    相关资源
    最近更新 更多