如何在Android中的谷歌mapview获取当前位置

时间:2012-10-19 05:14:27

标签: android google-maps android-mapview

在我的代码中,我不明白我在代码中的错误。我没有在地图视图中获得带针点图像的当前位置。如何获得Latitude&纬度和传递Geo点。然后传递值OverlayItem ..

public class HelloGoogleMaps2 extends MapActivity implements LocationListener{

 private LocationManager locationManager;
 private String provider;
 int lat;
 int lng;
 MyLocationOverlay  myLocOverlay;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MapView mapView = (MapView) findViewById(R.id.mapview);    
    mapView.setBuiltInZoomControls(true);

    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(provider);

    Log.d("provider  ","Provider  "+provider);
    Log.d("provider  ","Provider  "+provider);
    Log.d("provider  ","Provider  "+provider);
    Log.d("location","Location "+location);

    Log.d("location","Location "+location);        

    Log.d("location","Location "+location);
    // Initialize the location fields
    if (location != null) {
      System.out.println("Provider " + provider + " has been selected.");
      onLocationChanged(location);
    } else {
      //latituteField.setText("Location not available");
     // longitudeField.setText("Location not available");
    }


    List<Overlay> mapOverlays = mapView.getOverlays();

    myLocOverlay = new MyLocationOverlay(this, mapView);
    mapOverlays.add(myLocOverlay);
    myLocOverlay.enableMyLocation();
    GeoPoint point = new GeoPoint(lat, lng);
   //        mc.setCenter(point);
    //        mapView.invalidate();

    Drawable drawable = this.getResources().getDrawable(R.drawable.ic_launcher);
    HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);

      GeoPoint point = new GeoPoint(lat,lng);
OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");


itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}


@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}

 protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
      }

      /* Remove the locationlistener updates when Activity is paused */
      //
      protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
      }

      //
      public void onLocationChanged(Location location) {
         lat = (int) (location.getLatitude()* 1E6);
         lng = (int) (location.getLongitude()* 1E6);
       // latituteField.setText(String.valueOf(lat));
       // longitudeField.setText(String.valueOf(lng));
      }

      //
      public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

      }

      //
      public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
            Toast.LENGTH_SHORT).show();

      }

      //
      public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
            Toast.LENGTH_SHORT).show();
      }

}

3 个答案:

答案 0 :(得分:2)

请参阅此链接,并按照相同的步骤提供结果:googlemaps for current location

答案 1 :(得分:2)

正确的代码是这样,但也添加uses-permissio,Internet,ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION和WRITE_EXTERNAL_STORAGE .user-library。

  public class GoogleMapActivity extends  MapActivity implements LocationListener {
  private final static String TAG = GoogleMapActivity.class.getSimpleName();
private MyItemizedOverlay itemizedOverlay;

double lat;
double lng;
private String provider;
private LocationManager locationManager;

private MapView mapview;

Drawable drawable;



boolean sat = true;
boolean dra = true;

private MapController controller;

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

    // fetch the map view from the layout
    mapview = (MapView) findViewById(R.id.mapview);

    // make available zoom controls
    mapview.setBuiltInZoomControls(false);

    // Use the location manager through GPS

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);

    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        lat = (double) (location.getLatitude());
        lng = (double) (location.getLongitude());

        Log.i(TAG, "Lattitude:" + lat);
        Log.i(TAG, "Longitude:" + lng);
        Toast.makeText(
                this,
                "Current location:\nLatitude: " + lat + "\n"
                        + "Longitude: " + lng, Toast.LENGTH_LONG).show();
        // create geo point
        GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

        // get the MapController object
        controller = mapview.getController();

        // animate to the desired point
        controller.animateTo(point);

        // set the map zoom to 13
        // zoom 1 is top world view
        controller.setZoom(13);

        // invalidate the map in order to show changes
        mapview.invalidate();

        drawable = this.getResources().getDrawable(R.drawable.ic_launcher);
        OverlayItem overlayItem = new OverlayItem(point, "", "");
        itemizedOverlay = new MyItemizedOverlay(drawable, this);
        itemizedOverlay.addOverlay(overlayItem);
        mapview.getOverlays().add(itemizedOverlay);
        mapview.invalidate();
    } else {

        System.out.println("Location not avilable");
    }

    // when the current location is found – stop listening for updates
    // (preserves battery)
    locationManager.removeUpdates(this);

}

@Override
protected boolean isRouteDisplayed() {
    return false;

}

@Override
protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(provider, 400, 1, this);
}

/* Remove the locationlistener updates when Activity is paused */
@Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
}

public void onProviderDisabled(String provider) {
    Toast.makeText(this, "Disabled provider " + provider,
            Toast.LENGTH_SHORT).show();
}

public void onProviderEnabled(String provider) {
    Toast.makeText(this, "Enabled new provider " + provider,
            Toast.LENGTH_SHORT).show();
}

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

}

public void onLocationChanged(Location location) {

}

public MapView getMapView() {
    return this.mapview;
}


    }

`//这是另一个项目叠加

    public class MyItemizedOverlay  extends ItemizedOverlay<OverlayItem>
     {



   private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();


    public MyItemizedOverlay(Drawable defaultMarker, Context ctx){ 
        super(boundCenterBottom(defaultMarker));

    }

    public void addOverlay(OverlayItem overlay) {
        mOverlays.add(overlay);
        populate();
    }

    public void clear() {
        mOverlays.clear();
        populate();
    }

    @Override
    protected OverlayItem createItem(int i) {
        return mOverlays.get(i);
    }

    @Override
    public int size() {
        return mOverlays.size();
    }

    @Override
    protected boolean onTap(int index) {
        return true;
    }

}

答案 2 :(得分:0)

我建议MyLocationOverlay

用于在地图上绘制用户当前位置(和精度)的覆盖图,和/或罗盘 - 玫瑰插图。子句可以覆盖dispatchTap()来处理当前位置的点击 您可能希望调用enableMyLocation()和/或enableCompass(),可能来自Activity的Activity.onResume()方法,以启用此叠加层的功能。请记住在Activity的Activity.onPause()方法中调用相应的disableMyLocation()和/或disableCompass()以在后台关闭更新。
可选地,构造函数也可以使用MapController并使用它来通过在地图离开时平移地图来保持“我的位置”点可见,并在更改位置或方向时使用View to View.postInvalidate()。
可以在runOnFirstFix(java.lang.Runnable)中提供Runnables,以便在我们修复后立即运行。 (例如,这可以使地图居中并放大以显示位置。)

您可以在MyLocationOverlay here

上找到一个很好的教程