我想在Android应用程序中跟踪我当前的位置

时间:2011-03-10 06:10:59

标签: android android-mapview

在这里,我创建了一个跟踪当前位置的项目。 但我编码时出了问题...我不确切知道如何使用OVERLAY类以及何时调用它。

我已发布我的代码..请帮帮我

package com.techno.gps;

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

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.Projection;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class gps extends MapActivity{

    MapController mapController;
     Location location;
     MyPositionOverlay positionOverlay;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

     // Get a reference to the MapView
        MapView myMapView = (MapView)findViewById(R.id.mapView);
        // Get the Map View’s controller
        mapController = myMapView.getController();
        // Configure the map display options
        myMapView.setSatellite(true);
        myMapView.setStreetView(true);
        myMapView.displayZoomControls(false);
        // Zoom in
        mapController.setZoom(17);
        //add postionoverlay
        positionOverlay = new MyPositionOverlay();
        List<Overlay> overlays = myMapView.getOverlays();
        overlays.add(positionOverlay);

        LocationManager locationManager;
        String context = Context.LOCATION_SERVICE;
        locationManager = (LocationManager)getSystemService(context);

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        String provider = locationManager.getBestProvider(criteria, true);
        location = locationManager.getLastKnownLocation(provider);
        updateWithNewLocation(location);
        locationManager.requestLocationUpdates(provider, 2000, 10,locationListener);

    }

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

    private void updateWithNewLocation(Location location)
    {
        String latLongString;
        TextView myLocationText;
        myLocationText = (TextView)findViewById(R.id.myLocationText);

        String addressString = "No address found";
        if (location != null) {
        // Update the map location.
        positionOverlay.setLocation(location);
        Double geoLat = location.getLatitude()*1E6;
        Double geoLng = location.getLongitude()*1E6;
        GeoPoint point = new GeoPoint(geoLat.intValue(),
        geoLng.intValue());
        mapController.animateTo(point);
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        latLongString = "Lat: "+ lat + " Long:" + lng;
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        Geocoder gc = new Geocoder(this, Locale.getDefault());
        try 
        {
                List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
                StringBuilder sb = new StringBuilder();
                if (addresses.size() > 0) 
                {
                    Address address = addresses.get(0);
                    for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                    {
                        sb.append(address.getAddressLine(i)).append("\n");
                    }
                    sb.append(address.getLocality()).append("\n");
                    sb.append(address.getPostalCode()).append("\n");
                    sb.append(address.getCountryName());
                }
                addressString = sb.toString();
                }
                catch (IOException e) 
                {

                }

        }
            else 
            {
                latLongString = "No location found";
            }
            myLocationText.setText("Your Current Position is:\n" +latLongString + "\n" + addressString);


        }

        private final LocationListener locationListener = new LocationListener() 
        {
                public void onLocationChanged(Location location) {
                updateWithNewLocation(location);
        }
        public void onProviderDisabled(String provider)
        {
            updateWithNewLocation(null);
        }
        public void onProviderEnabled(String provider)
        {

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

        }
    };

    public class MyPositionOverlay extends Overlay 
    {
        Location location;
        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) 
        {
            Projection projection = mapView.getProjection();
            if (shadow == false) {
            // Get the current location
            Double latitude = location.getLatitude()*1E6;
            Double longitude = location.getLongitude()*1E6;
            GeoPoint geoPoint;
            geoPoint = new GeoPoint(latitude.intValue(),longitude.intValue());
            // Convert the location to screen pixels
            int mRadius=5;
            Point point = new Point();
            projection.toPixels(geoPoint, point);
            RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
            point.x + mRadius, point.y + mRadius);
            // Setup the paint
            Paint paint = new Paint();
            paint.setARGB(250, 255, 0, 0);
            paint.setAntiAlias(true);
            paint.setFakeBoldText(true);
            Paint backPaint = new Paint();
            backPaint.setARGB(175, 50, 50, 50);
            backPaint.setAntiAlias(true);
            RectF backRect = new RectF(point.x + 2 + mRadius,
            point.y - 3*mRadius,
            point.x + 65, point.y + mRadius);
            // Draw the marker
            canvas.drawOval(oval, paint);
            canvas.drawRoundRect(backRect, 5, 5, backPaint);
            canvas.drawText("Here I Am", point.x + 2*mRadius, point.y, paint);
            }
            super.draw(canvas, mapView, shadow);
        }
        @Override
        public boolean onTap(GeoPoint point, MapView mapView) 
        {
            // Return true if screen tap is handled by this overlay
            return false;
        }

        public Location getLocation() {
        return location;
        }
        public void setLocation(Location location) {
        this.location = location;
        }

   }

}

感谢...

2 个答案:

答案 0 :(得分:2)

很遗憾你不知道自己的代码。你应该尝试自己写。复制粘贴始终不起作用。

回答你的问题。 Overlay是可绘制对象,可以在MapView上方的不同图层上显示在地图的顶部。

这是将该绘图添加到MapView的代码的一部分。

    positionOverlay = new MyPositionOverlay();
    List<Overlay> overlays = myMapView.getOverlays();
    overlays.add(positionOverlay);

您正在OnCreate()中执行此操作。哪个没有意义,因为你还没有定位。

  1. 在updateWithNewLocation()
  2. 中获得pos-fix时添加叠加层
  3. 要强制调用draw,请使用MapView.invalidate()

答案 1 :(得分:1)

我有相同的示例代码,2.2安卓,工作,但不要卓越覆盖,我的位置,否则,使用debuggin你可以看到代码正常工作。真奇怪。

我认为代码是正确的,因为在onCreate中,代码已初始化,然后在updateWithNewLocation中,覆盖图将使用positionOverlay.setLocation(location);更新