android中模擬器中實現GPS座標改變

來源:互聯網
上載者:User
下面的這個例子中,實現了讀取使用者的所在位置座標的功能:

public class Activity01 extends MapActivity

{

public MapController mapController;

    public MyLocationOverlay myPosition;

    public MapView myMapView;

    private static final int ZOOM_IN=Menu.FIRST;

    private static final int ZOOM_OUT=Menu.FIRST+1;

public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        //取得LocationManager執行個體

        LocationManager locationManager;

        String context=Context.LOCATION_SERVICE;

        locationManager=(LocationManager)getSystemService(context);

        myMapView=(MapView)findViewById(R.id.MapView01);

        //取得MapController執行個體,控制地圖

        mapController=myMapView.getController();

        //設定顯示模式

       // myMapView.setSatellite(true);

        myMapView.setStreetView(true);

        //設定縮放控制,這裡我們自己實現縮放菜單

        myMapView.displayZoomControls(false);  

        //設定使用MyLocationOverlay來繪圖

        mapController.setZoom(17);

        myPosition=new MyLocationOverlay();

        List<Overlay> overlays=myMapView.getOverlays();

        overlays.add(myPosition);

        //設定Criteria(服務商)的資訊

        Criteria criteria =new Criteria();

        //經度要求

        criteria.setAccuracy(Criteria.ACCURACY_FINE);

        criteria.setAltitudeRequired(false);

        criteria.setBearingRequired(false);

        criteria.setCostAllowed(false);

        criteria.setPowerRequirement(Criteria.POWER_LOW);

        //取得效果最好的criteria

        String provider=locationManager.getBestProvider(criteria, true);

        //得到座標相關的資訊

        Location location=locationManager.getLastKnownLocation(provider);

        //更新座標

        updateWithNewLocation(location);

        //註冊一個周期性的更新,3000ms更新一次

        //locationListener用來監聽定位資訊的改變

        locationManager.requestLocationUpdates(provider, 3000, 0,locationListener);

    }

    private void updateWithNewLocation(Location location)

    {

        String latLongString;

        TextView myLocationText = (TextView)findViewById(R.id.TextView01);

       

        String addressString="沒有找到地址\n";

       

        if(location!=null)

        {

        //為繪製標誌的類設定座標

            myPosition.setLocation(location);

            //取得經度和緯度

            Double geoLat=location.getLatitude()*1E6;

            Double geoLng=location.getLongitude()*1E6;

            //將其轉換為int型

            GeoPoint point=new GeoPoint(geoLat.intValue(),geoLng.intValue());

            //定位到指定座標

            mapController.animateTo(point);

            double lat=location.getLatitude();

            double lng=location.getLongitude();

            latLongString="經度:"+lat+"\n緯度:"+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="沒有找到座標.\n";

        }

        //顯示

        myLocationText.setText("你當前的座標如下:\n"+latLongString+"\n"+addressString);

    }

    private final LocationListener locationListener=new LocationListener()

    {

    //當座標改變時觸發此函數

        public void onLocationChanged(Location location)

        {

        updateWithNewLocation(location);

        }

        //Provider被disable時觸發此函數,比如GPS被關閉

        public void onProviderDisabled(String provider)

        {

        updateWithNewLocation(null);

        }

        //Provider被enable時觸發此函數,比如GPS被開啟

        public void onProviderEnabled(String provider){}

        //Provider的轉態在可用、暫時不可用和無服務三個狀態直接切換時觸發此函數

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

    };

    protected boolean isRouteDisplayed()

{

return false;

}

    //為應用程式添加菜單

    public boolean onCreateOptionsMenu(Menu menu)

{

super.onCreateOptionsMenu(menu);

menu.add(0, ZOOM_IN, Menu.NONE, "放大");

menu.add(0, ZOOM_OUT, Menu.NONE, "縮小");

return true;

}

    public boolean onOptionsItemSelected(MenuItem item)

{

super.onOptionsItemSelected(item);

switch (item.getItemId())

{

case (ZOOM_IN):

//放大

mapController.zoomIn();

return true;

case (ZOOM_OUT):

//縮小

mapController.zoomOut();

return true;

}

return true;

}

   

class MyLocationOverlay extends Overlay

{

Location mLocation;

//在更新座標時,設定該座標,一邊畫圖

public void setLocation(Location location)

{

mLocation = location;

}

@Override

public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)

{

super.draw(canvas, mapView, shadow);

Paint paint = new Paint();

Point myScreenCoords = new Point();

// 將經緯度轉換成實際螢幕座標

GeoPoint tmpGeoPoint = new GeoPoint((int)(mLocation.getLatitude()*1E6),(int)(mLocation.getLongitude()*1E6));

mapView.getProjection().toPixels(tmpGeoPoint, myScreenCoords);

paint.setStrokeWidth(1);

paint.setARGB(255, 255, 0, 0);

paint.setStyle(Paint.Style.STROKE);

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.home);

canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);

canvas.drawText("Here am I", myScreenCoords.x, myScreenCoords.y, paint);

return true;

}

}

注意的是,因為是模擬器,可以在運行程式後,模擬器開啟,但程式沒裝入時,如下設定:

在eclipse下,windows-->open perspective-->DDMS-->Emulator control-->Manual下手動設定經緯度,並按send按鈕。

也可以如下設定:

首先開啟模擬器,然後運行cmd,輸入telnet localhost 5554(註:5554是模擬器在原生連接埠,有可能不一樣哈,具體連接埠號碼,模擬器左上方有顯示的),這樣會出現

Android Console: type 'help' for a list of commands

OK的字樣。

如果是使用WIN7的朋友,控制台可能會提示telnet無效什麼的,那是因為WIN7下預設是不出現telnet的,需要手動開啟。具體為:[1]控制台-->程式-->開啟或關閉Windows功能,然後將Telnet伺服器和Telnet用戶端勾選上。[2]然後在管理工具-->服務中手動啟動Telnet

(2)使用geo命令類比發送GPS訊號:

geo fix 經度 緯度

(3)這時就會發現在模擬器的狀態列上多了一個GPS的標誌

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.