【问题标题】:I am able to get Geo Points( Latitude and Longitude) but could't able to locate position on Map我能够获得地理点(纬度和经度),但无法在地图上定位位置
【发布时间】:2020-06-07 18:09:56
【问题描述】:

请帮助! 如果您有帮助,请提前感谢您。 我在我的 android 项目中使用谷歌地图 API,我需要定位设备当前位置。我成功地获得了当前设备的地理点(经度和纬度),但我无法在地图中显示我当前的位置。默认地图正在显示,我可以使用 Toasts 获取地理点。

这是我尝试过的:我只是复制和粘贴所有代码。请只关注哪些是重要的。我不确定所以我都粘贴了。

为了在地图中显示地理点,我尝试了这 3 行代码,但不确定将这段代码放在哪里。

LatLng currentLocation = new LatLng(latitude,longitude);
    mMap.addMarker(new MarkerOptions().position(currentLocation).title("Marker in Current Location"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));

这是 Maps_Activity。

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
    LocationListener, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener{

private String lang,lat;
Double latitude;
Double longitude;
private Location mylocation;
private GoogleApiClient googleApiClient;
private GoogleMap mMap;
private final static int REQUEST_CHECK_SETTINGS_GPS=0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS=0x2;
@Override
public void onMapReady(GoogleMap googleMap) {
    /*
    LatLng currentLocation = new LatLng(latitude,longitude);
    mMap.addMarker(new MarkerOptions().position(currentLocation).title("Marker in Current   Location"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
    */
    mMap = googleMap;

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

    setUpGClient();
  }

 private synchronized void setUpGClient() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, 0, this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    googleApiClient.connect();
 }

 @Override
 public void onLocationChanged(Location location) {
    mylocation = location;
    if (mylocation != null) {
        latitude=mylocation.getLatitude();
        longitude=mylocation.getLongitude();
        String _lang = longitude + "";
        String _lat = latitude + "";
        Toast.makeText(this, "Longitude: " + _lang + "\nLatitude: " + _lat,          Toast.LENGTH_LONG).show();

        //Or Do whatever you want with your location
     }
 }

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

 @Override
 public void onConnectionSuspended(int i) {
    //Do whatever you need
    //You can display a message here
 }

 @Override
 public void onConnectionFailed(ConnectionResult connectionResult) {
    //You can display a message here
 }

 private void getMyLocation(){
    if(googleApiClient!=null) {
        if (googleApiClient.isConnected()) {
            int permissionLocation = ContextCompat.checkSelfPermission(MapsActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION);
            if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
                mylocation =                     LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
                LocationRequest locationRequest = new LocationRequest();
                locationRequest.setInterval(30*1000);
                locationRequest.setFastestInterval(5000);
                locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                        .addLocationRequest(locationRequest);
                builder.setAlwaysShow(true);
                LocationServices.FusedLocationApi
                        .requestLocationUpdates(googleApiClient, locationRequest, this);
                PendingResult<LocationSettingsResult> result =
                        LocationServices.SettingsApi
                                .checkLocationSettings(googleApiClient, builder.build());
                result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

                    @Override
                    public void onResult(LocationSettingsResult result) {
                        final Status status = result.getStatus();
                        switch (status.getStatusCode()) {
                            case LocationSettingsStatusCodes.SUCCESS:
                                // All location settings are satisfied.
                                // You can initialize location requests here.
                                int permissionLocation = ContextCompat
                                        .checkSelfPermission(MapsActivity.this,
                                                Manifest.permission.ACCESS_FINE_LOCATION);
                                if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
                                    mylocation = LocationServices.FusedLocationApi
                                            .getLastLocation(googleApiClient);
                                  //  mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                                    //mMap.animateCamera(CameraUpdateFactory.zoomTo(15.5f));

                                }
                                break;
                            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                // Location settings are not satisfied.
                                // But could be fixed by showing the user a dialog.
                                try {
                                    // Show the dialog by calling startResolutionForResult(),
                                    // and check the result in onActivityResult().
                                    // Ask to turn on GPS automatically
                                    status.startResolutionForResult(MapsActivity.this,
                                            REQUEST_CHECK_SETTINGS_GPS);
                                } catch (IntentSender.SendIntentException e) {
                                    // Ignore the error.
                                }
                                break;
                            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                // Location settings are not satisfied.
                                // However, we have no way
                                // to fix the
                                // settings so we won't show the dialog.
                                // finish();
                                break;
                        }
                    }
                });
            }
        }
    }
  }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case REQUEST_CHECK_SETTINGS_GPS:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    getMyLocation();
                    break;
                case Activity.RESULT_CANCELED:
                    finish();
                    break;
            }
            break;
     }
 }

 private void checkPermissions(){
    int permissionLocation = ContextCompat.checkSelfPermission(MapsActivity.this,
            android.Manifest.permission.ACCESS_FINE_LOCATION);
    List<String> listPermissionsNeeded = new ArrayList<>();
    if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this,
                    listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
        }
     }else{
        getMyLocation();

     }

 }

 @Override
 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    int permissionLocation = ContextCompat.checkSelfPermission(MapsActivity.this,
            Manifest.permission.ACCESS_FINE_LOCATION);
      if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
         getMyLocation();
      }
   }


}

【问题讨论】:

  • call mMap.addMarker(...) after assign google map mMap = googleMap;
  • 就这一行 mMap.addMarker(...) 会传入什么参数?
  • 我还在等请人帮忙
  • 在你的 onMapRead() ... mMap = googleMap; LatLng currentLocation = new LatLng(latitude,longitude); mMap.addMarker(new MarkerOptions().position(currentLocation).title("Marker in Current Location")); mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
  • 我试过它什么也没做。没有效果

标签: java android google-maps


【解决方案1】:

onLocationChanged()方法中试试这个代码:

if(REQUEST_CHECK_SETTINGS_GPS!=0) {
            LatLng latLng = new LatLng(mylocation.getLatitude(), mylocation.getLongitude());
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f));
            mMap.addMarker(new MarkerOptions().position(new LatLng(mylocation.getLatitude(), mylocation.getLongitude())).title("Current Location"));

        }

在这里mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f)); 你可以传递任何浮动值,它指的是你想要的缩放级别。你可以简单地尝试不同的值,看看什么最适合你。

试试这个,让我知道它是否有效。

【讨论】:

  • 在 onLocationChanged 方法中。我也在更新答案,所以你可能会接受。
【解决方案2】:

您可以使用 Android 版 Maps SDK 的 My Location Layer 直接获取您设备的当前位置,并将其显示在您的地图中。完整的示例代码可以在here找到。

此外,如果您已经有了 latlng 坐标,并且只需要使用标记在地图上显示您的当前位置,您可以在 onMapReady() 方法中添加以下代码:

LatLng currentLocation = new LatLng(latitude,longitude);
float zoom = 17.0f //Set a zoom level of your preference

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, zoom));
mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location").snippet("My Current Location"));

注意:不要使用CameraUpdateFactory.newLatLng(),而是使用CameraUpdateFactory.newLatLngZoom()。这对我每次都有效。只需为您的缩放级别提供一个浮点值。另外,请确保LatLng currentLocation 的值不为空。

希望这会有所帮助!

【讨论】:

猜你喜欢
  • 2023-03-22
  • 2013-10-01
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
  • 2013-06-18
  • 1970-01-01
相关资源
最近更新 更多