osmdroid MapView - to follow user location

By calling enableFollowLocation() of osmdroid MyLocationOverlay, the map will center on user current location and automatically scroll as user move.

osmdroid MapView - to follow user location


Modify MainActivity.java from the last article "Display user location by adding MyLocationOverlay on org.osmdroid.views.MapView". Call enableMyLocation() and enableFollowLocation() in onResume(), call disableMyLocation() and disableFollowLocation() in onPause(), and handle runOnFirstFix to animateTo user location.

package com.android_osmdroid;

import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.MyLocationOverlay;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;

public class MainActivity extends Activity {
 
 MyItemizedOverlay myItemizedOverlay = null;
 MyLocationOverlay myLocationOverlay = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final MapView mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        
        Drawable marker=getResources().getDrawable(android.R.drawable.star_big_on);
        int markerWidth = marker.getIntrinsicWidth();
        int markerHeight = marker.getIntrinsicHeight();
        marker.setBounds(0, markerHeight, markerWidth, 0);
        
        ResourceProxy resourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
        
        myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
        mapView.getOverlays().add(myItemizedOverlay);
        
        GeoPoint myPoint1 = new GeoPoint(0*1000000, 0*1000000);
        myItemizedOverlay.addItem(myPoint1, "myPoint1", "myPoint1");
        GeoPoint myPoint2 = new GeoPoint(50*1000000, 50*1000000);
        myItemizedOverlay.addItem(myPoint2, "myPoint2", "myPoint2");
        
        myLocationOverlay = new MyLocationOverlay(this, mapView);
        mapView.getOverlays().add(myLocationOverlay);
        
        myLocationOverlay.runOnFirstFix(new Runnable() {
         public void run() {
          mapView.getController().animateTo(myLocationOverlay.getMyLocation());
            } 
        });
        
    }
    
 @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  myLocationOverlay.enableMyLocation();
  myLocationOverlay.enableFollowLocation();
 } 

 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  myLocationOverlay.disableMyLocation();
  myLocationOverlay.disableFollowLocation();
 }

}


Next:
- Display Compass on osmdroid MapView


0 Response to "osmdroid MapView - to follow user location"

Posting Komentar