0

我无法在 android 中更新我在 google map api v1 上的当前位置。只有应用程序启动时的第一个位置才会始终显示。这是我从 androidhive 获得帮助的代码。
共有三个类 AddItemizedOverlay、GPSTracker 和 AndroidGoogleMapsActivity。
AddItemizedOverlay.java(这个用于覆盖)

        package com.androidhive.googlemaps;

    import java.util.ArrayList;

    import android.content.Context;
    import android.graphics.drawable.Drawable;
    import android.util.Log;
    import android.view.MotionEvent;
    import android.widget.Toast;
    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.ItemizedOverlay;
    import com.google.android.maps.MapView;
    import com.google.android.maps.OverlayItem;

   public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {

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

   private Context context;

   public AddItemizedOverlay(Drawable defaultMarker) {
        super(boundCenterBottom(defaultMarker));
   }

   public AddItemizedOverlay(Drawable defaultMarker, Context context) {
        this(defaultMarker);
        this.context = context;
   }

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

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

   @Override
   protected boolean onTap(int index) {
      Log.e("Tap", "Tap Performed");
      return true;
   }

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

   /**
    * Getting Latitude and Longitude on Touch event
    * **/
   /*@Override
   public boolean onTouchEvent(MotionEvent event, MapView mapView) 
   {   

       if (event.getAction() == 1) {                
           GeoPoint geopoint = mapView.getProjection().fromPixels(
               (int) event.getX(),
               (int) event.getY());
           // latitude
           double lat = geopoint.getLatitudeE6() / 1E6;
           // longitude
           double lon = geopoint.getLongitudeE6() / 1E6;
           Toast.makeText(context, "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
       }                            
       return false;
   }*/ 

}

GPSTracker.java(这是获取当前的纬度和对数)

        package com.androidhive.googlemaps;

    import android.app.AlertDialog;
    import android.app.Service;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.provider.Settings;
    import android.util.Log;

    public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude
double speed;

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 10000 * 1; // 10 second

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }       
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
    double speed=location.getSpeed();
}

public double getspd() {
    double speed=location.getSpeed();
    return speed;
}
@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

@Override
public IBinder onBind(Intent arg0) {
    return null;
}}

AndroidGoogleMapsActivity.java(这是我渲染地图并调用其他两个类来获取位置和覆盖的类)

        package com.androidhive.googlemaps;

    import java.util.List;
    import java.lang.Object.*;


    import android.content.Context;
    import android.graphics.drawable.Drawable;
    import android.os.Bundle;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.os.Handler;
    import android.os.Vibrator;
    import android.location.Location;

    import com.androidhive.googlemaps.GPSTracker;
    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.MapActivity;
    import com.google.android.maps.MapController;
    import com.google.android.maps.MapView;
    import com.google.android.maps.Overlay;
    import com.google.android.maps.OverlayItem;

public class AndroidGoogleMapsActivity extends MapActivity {
GPSTracker gps;
double[] arr={24.0,0.0,24.0,50.0,24.431259282,77.155662247,24.4312773869,77.1559354131,24.4315907861,77.1560663384,24.432969441,77.1559033105,24.4345594036,77.1613486118,24.4345983795,77.1630234831,24.4349034806,77.1616558084,24.4351733778,77.1634901034,24.4356508108,77.158808477,24.4359046986,77.1588943077,24.436061943,77.1628120915,24.6377519985,77.3526723525,24.6406972305,77.3023587404,24.640731261,77.3146044449,24.640830838,77.3044040917,24.6408552293,77.3057836686,24.6559378717,77.4399105809,24.656802297,77.4460797431,26.5433058012,77.9836704178,28.4118864562,77.3072094298};
double lat=0.0;
double lon=0.0;
MapView mapView;
GeoPoint geoPoint;
double min=0.0;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
     Context context=this;
    // Displaying Zooming controls
    mapView = (MapView) findViewById(R.id.mapView);
    mapView.setBuiltInZoomControls(true);
    //TextView latituteField = (TextView) findViewById(R.id.latituteField);
    //TextView longitudeField = (TextView) findViewById(R.id.longitudeField);   
    gps = new GPSTracker(AndroidGoogleMapsActivity.this);
    // check if GPS enabled     
    if(gps.canGetLocation()){
    double latitude = gps.getLatitude();
    double longitude = gps.getLongitude();
   lat=latitude;
   lon=longitude;
    }else{
    // can't get location
    // GPS or Network is not enabled
    // Ask user to enable GPS/network in settings
    gps.showSettingsAlert();
        }
    /**
     * Changing Map Type
     * */
    // mapView.setSatellite(true); // Satellite View
    // mapView.setStreetView(true); // Street View
    // mapView.setTraffic(true); // Traffic view

    /**
     * showing location by Latitude and Longitude
     * */        
    MapController mc = mapView.getController();
    //double lat = Double.parseDouble("24.435702");
    //double lon = Double.parseDouble("77.160931");
    geoPoint = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6));
    mc.animateTo(geoPoint);
    mc.setZoom(20);



    /**
     * Placing Marker
     * */
    List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.yellow);
    AddItemizedOverlay itemizedOverlay = 
         new AddItemizedOverlay(drawable, this);


    OverlayItem overlayitem = new OverlayItem(geoPoint, "Hello", "Sample Overlay item");

    itemizedOverlay.addOverlay(overlayitem);
    mapOverlays.add(itemizedOverlay);
    mapView.invalidate();
    //List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable1 = this.getResources().getDrawable(R.drawable.mark_red);
    AddItemizedOverlay itemizedOverlay1 = 
         new AddItemizedOverlay(drawable1, this);
    for(int i=0;i<21;i++)
    {
        GeoPoint geoPoint1 = new GeoPoint((int)(arr[2*i] * 1E6), (int)(arr[(2*i)+1] * 1E6));
        //Location.distanceBetween(lat, lon, arr[2*i], arr[(2*i)+1], results);
        Location locationA = new Location("point A");

        locationA.setLatitude(lat);
        locationA.setLongitude(lon);

        Location locationB = new Location("point B");

        locationB.setLatitude(arr[2*i]);
        locationB.setLongitude(arr[(2*i)+1]);

        double distance = locationA.distanceTo(locationB);
        if(i==0)
            min=distance;
        else if(distance<min)
            min=distance;
        //Toast.makeText(context,"Result " + distance + ", Result"+arr[(2*i)+1], Toast.LENGTH_SHORT).show();
        OverlayItem overlayitem1 = new OverlayItem(geoPoint1, "Pothole", "It's a pothole");

        itemizedOverlay1.addOverlay(overlayitem1);
        mapOverlays.add(itemizedOverlay1);
    }
    Location location = new Location("point present");
    double speed=-1.0;
    if(location.hasSpeed())
    {
        speed = (location.getSpeed());
    }
    else
    {
        Toast.makeText(context,"No speed boss", Toast.LENGTH_SHORT).show();   
    }
    //double speed=location.getSpeed();
    Toast.makeText(context,"Lat: " + lat + ", Lon: "+lon + "Min distance"+min+" Speed="+speed, Toast.LENGTH_SHORT).show();  
  mapView.postInvalidate();
  Vibrator v = (Vibrator) getSystemService(context.VIBRATOR_SERVICE);
  double slimit=27.7778;
  double hlimit=166.6665;

  if(min>slimit&&min<hlimit)
  {
      Toast.makeText(context,"Pothole " + min + " meters ahead.", Toast.LENGTH_SHORT).show();
      v.vibrate(3000);
  }
  /*for(int j=0;j<1000000;j++)
  {
      if((j%50000)==0)
      {
          GPSTracker gps1=new GPSTracker(AndroidGoogleMapsActivity.this);;
          lat=gps1.getLatitude();
          lon=gps1.getLongitude();
          geoPoint = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6));
          mapView.invalidate();
          mapView.postInvalidate();
          //mapView.getController().scrollBy(1, 1);
          //mapView.getController().scrollBy(-1, -1);
          Toast.makeText(context,"Lat: " + lat + ", Lon: "+lon+" ,j=:"+j, Toast.LENGTH_SHORT).show(); 
      }
  }*/

}

@Override
protected boolean isRouteDisplayed() {
    return false;
}
   }

AndroidGoogleMapsActivity.java 仅显示应用打开时的位置,它不显示每 1 秒后更新的位置(最短更新时间)。请帮助它是我最后一年项目的一部分。提前致谢。

4

1 回答 1

0

您在onLocationChanged中获得位置更新,在您的代码中,您只捕捉速度。

public void onLocationChanged(Location location) {
    double speed=location.getSpeed();
   // update code for getting location (la & ln )
}
于 2013-05-02T16:28:08.270 回答