开发者

Android Canvas - Callbacks to draw a dot and reposition it based on GPS movement

开发者 https://www.devze.com 2023-03-19 09:23 出处:网络
I am new to android and i\'ve just been looking into the canvas API. I currently have an activity class called \"MyMap\" and a ViewClass called \"MapView\" (which extends view).

I am new to android and i've just been looking into the canvas API. I currently have an activity class called "MyMap" and a ViewClass called "MapView" (which extends view).

The MyMap activity sets the content view to MapView and inside MapView I am creating a canvas with a bitmap image of a Map and I am then drawing a circ开发者_StackOverflow社区le on the map based on the current GPS coordinates of the mobile. I want to know how do I perform some callback to the draw() method whenever the gps coordinates change? also will this code go in MyMap activity or in the MapView?


What you need to do is first setup a gps listener and respond to that, you can find information about that here LocationManager

It would look something like this. Keep in mind that GPS sucks battery, there are ways to do this better but here is the meat of it, more or less

Once you have that setup just do what you need to do in the onLocationChanged listener

CODE SNIPPET - NOT COMPLETE

import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;

public class gps extends Activity  {

    private LocationManager locManager = null; 

        public void onCreate(Bundle state) {
           super.onCreate(state);

           locManager = (LocationManager)App.getSystemService(Context.LOCATION_SERVICE);
        }

        LocationListener onLocationChange=new LocationListener() {
        public void onLocationChanged(Location loc) {

                  // DO SOMETHING HERE with the updated location information to change your map

            }
        }

        public onResume() {
             startGPS(1000,1); // Every second or when we move 1 meter
        }

        public onPause() {
             stopGPS(); 
        }

        private boolean startGPS(long interval, float meterTrigger)
    {

        if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
            return false; 



                            locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,interval,meterTrigger,onLocationChange);



                return true;
        }

        public void stopGPS() {
       locManager.removeUpdates(onLocationChange); 
    }

Painting the circle - you will need to determine the positioning and radius

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    float x = 0;
    float y = 0;
    float r = 0; 

    paint = new Paint(Paint.ANTI_ALIAS_FLAG); // You can cache this higher up and reuse it 
    paint.setColor(0xFFFF0000);  
    canvas.drawCircle(x, y, r, paint);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号