无法在android中的当前位置放置标记

时间:2016-05-18 13:29:48

标签: java android google-maps

我是新的机器人,我正在尝试在我当前的位置放置一个标记,我已经编写了一个代码,它打开谷歌地图,但没有在我当前的位置放置任何标记。请帮助我,并提前谢谢 这是我的java文件的代码。

 public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.

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

}


private void setUpMapIfNeeded() {

    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) 
         getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        if (ContextCompat.checkSelfPermission(this, 
      android.Manifest.permission.ACCESS_FINE_LOCATION) ==
                PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(this,
      android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
                        PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
            // Check if we were successful in obtaining the map.
            if (mMap != null) {

                Location myLocation  = mMap.getMyLocation();
                if(myLocation!=null)
                {
                    double dLatitude = myLocation.getLatitude();
                    double dLongitude = myLocation.getLongitude();
                    Log.i("APPLICATION"," : "+dLatitude);
                    Log.i("APPLICATION", " : " + dLongitude);
                    mMap.addMarker(new MarkerOptions().position(new 
             LatLng(dLatitude, dLongitude)).title("Marker"));
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new 
              LatLng(dLatitude, dLongitude), 8));

                }
                else
                {
               Toast.makeText(this, "Unable to fetch the current  
               location", Toast.LENGTH_SHORT).show();

                }
            }
        }
     }
  }
}

1 个答案:

答案 0 :(得分:0)

使用以下代码获取经度和纬度:

GPSTracker gpsTracker = new GPSTracker(getActivity());
Float latitude  = new Float(0.0);
Float longitude = new Float(0.0);
if (gpsTracker.getIsGPSTrackingEnabled()) {
  latitude  = gpsTracker.latitude;
  longitude = gpsTracker.longitude;
} else {
  // can't get location
  // GPS or Network is not enabled
  // Ask user to enable GPS/network in settings
  gpsTracker.showSettingsAlert();
}

您需要在getMapAsync(如果在片段中)或MapView(如果在活动中)调用MapFragment,那就是根据您的结构

mapView.getMapAsync(this);

mapFragment.getMapAsync(this);