在谷歌地图并主张用户的当前位置,并显示它 [英] Positing user current location and show it in Google maps

查看:108
本文介绍了在谷歌地图并主张用户的当前位置,并显示它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发包含3个活动,其中之一就是地图上一个Android应用程序。我使用谷歌地图

我想要的:

  1. 当用户打开的活动(地图)它显示了用户她的位置不是坐标

  2. 用户也应该能够断定(思念)任何地方用针和我的应用程序必须存储了该引脚的坐标中的变量,所以我可以在以后使用它。

 公共类LActivity扩展MapActivity
{
    / **第一次创建活动时调用。 * /

    图形页面图形页面;
    的GeoPoint地理;
    MapController mapController;
    LocationManager locationManager;
    CustomPinpoint itemizedoverlay;


    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
        图形页面=(图形页面)findViewById(R.id.mapView);
        //创建一个地图视图
        // LinearLayout中的LinearLayout =(的LinearLayout)findViewById(R.id.main);

        mapView.setBuiltInZoomControls(真正的);
        //无论卫星或2d的
        mapView.setSatellite(真正的);
        mapController = mapView.getController();
        mapController.setZoom(14); //扩大范围1是世界观
        locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,新GeoUpdateHandler());

        可绘制绘制= this.getResources()getDrawable(R.drawable.point)。
        itemizedoverlay =新CustomPinpoint(绘制);
        createMarker();
    }

    公共类GeoUpdateHandler实现LocationListener的{

        @覆盖
        公共无效onLocationChanged(位置定位){
            INT纬度=(INT)(location.getLatitude()* 1E6);
            INT LNG =(INT)(location.getLongitude()* 1E6);
            的GeoPoint点=新的GeoPoint(纬度,经度);
            createMarker();
            mapController.animateTo(点); // mapController.setCenter(点);
        }

        @覆盖
        公共无效onProviderDisabled(字符串提供商){
        }

        @覆盖
        公共无效onProviderEnabled(字符串提供商){
        }

        @覆盖
        公共无效onStatusChanged(字符串商,INT地位,捆绑演员){
        }
    }

    私人无效createMarker(){
        的GeoPoint P = mapView.getMapCenter();
        OverlayItem overlayitem =新OverlayItem(对,,);
        itemizedoverlay.addOverlay(overlayitem);
        。调用MapView.getOverlays()加(itemizedoverlay);
    }

    @覆盖
    保护的布尔isRouteDisplayed(){
        // TODO自动生成方法存根
        返回false;
    }
}
 

这是CustomPinpoint类

 公共类CustomPinpoint扩展ItemizedOverlay< OverlayItem> {

    静态INT MAXNUM = 3;
    OverlayItem覆盖[] =新OverlayItem [MAXNUM]
    INT索引= 0;
    布尔全文= FALSE;
    CustomPinpoint itemizedoverlay;

    公共CustomPinpoint(可绘制defaultMarker){
        超(boundCenterBottom(defaultMarker));
    }

    @覆盖
    保护OverlayItem createItem中(int i)以{
        返回覆盖[I]
    }

    @覆盖
    公众诠释大小(){
        如果(全){
            返回overlays.length;
        } 其他 {
            返回指数;
        }
    }

    公共无效addOverlay(OverlayItem叠加){
        如果(指数< MAXNUM){
            覆盖[指数] =叠加;
        } 其他 {
            索引= 0;
            全= TRUE;
            覆盖[指数] =叠加;
        }
        指数++;
        填充();
    }

}
 

解决方案

我已经实现了你希望同样的事情。我为您提供样品code。在此我已经获取的位置时,还实施了ProgressDialog。

这是起点得到的位置。我叫这个AndroidLocationActivity。这是你的应用程序启动时它启动第一次活动。

 字符串提供商;
    大众双纬度,经度= 0;
    CurrentPositionTask getCurrentLocation;
    地点currentLocation;
    LocationListener的LocationListener的;
    LocationManager locationManager;
    私人时间长= 0;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);

        尝试 {
            locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
            setCriteria();
            currentLocation = AndroidLocationActivity.this.locationManager.getLastKnownLocation(供应商);

            如果(currentLocation == NULL){
                currentLocation =新的位置(供应商);
            }
            时间= currentLocation.getTime();

            如果(纬度== 0安培;&安培;经度== 0){
                纬度= currentLocation.getLatitude();
                经度= currentLocation.getLongitude();
            }
            Toast.makeText(AndroidLocationActivity.this,将String.valueOf(时间),Toast.LENGTH_LONG).show();
 

此处设置的时间,如果时间不超过1分钟比我更新不及时的位置。

 如果(时间> = 100000){
                纬度= 0;
                经度= 0;
            }
        }赶上(NullPointerException异常E){
            // TODO:处理异常
            的System.out.println(空);
            e.printStackTrace();
        }
        赶上(例外五){
            // TODO:处理异常
            e.printStackTrace();
        }

        runAsyncTask();
    }

    @覆盖
    保护无效的onDestroy(){
        // TODO自动生成方法存根
        super.onDestroy();
        locationManager.removeUpdates(LocationListener的);
    }

    公共无效setCriteria(){
        标准标准=新标准();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(假);
        criteria.setBearingRequired(假);
        criteria.setCostAllowed(真正的);
        criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
        供应商= locationManager.getBestProvider(标准,真正的);
        Toast.makeText(getApplicationContext(),提供者 - +提供商,Toast.LENGTH_SHORT).show();
        如果(供应商== NULL){
            供应商= LocationManager.GPS_PROVIDER;
        }
    }


    公共无效runAsyncTask(){
        // TODO自动生成方法存根
        如果(getCurrentLocation == NULL){
            getCurrentLocation =新CurrentPositionTask();
        }

        如果(getCurrentLocation!= NULL){
            getCurrentLocation.execute(搜索位置);
        }
    }

    公共布尔checkConnection()
    {
        //我们是否连接到网络

        ConnectivityManager conMgr =(ConnectivityManager)getSystemService(AndroidLocationActivity.CONNECTIVITY_SERVICE);
        如果(conMgr.getActiveNetworkInfo()=空&安培;!&安培; conMgr.getActiveNetworkInfo()isAvailable()&安培;&安培; conMgr.getActiveNetworkInfo()isConnected()){
            返回true;
        } 其他 {
            返回false;
        }
    }


    私有类CurrentPositionTask扩展的AsyncTask<字符串,太虚,太虚>
    {
        私人ProgressDialog对话框=新ProgressDialog(AndroidLocationActivity.this);
        私人布尔标志=真;

        公共CurrentPositionTask(){
            LocationListener的=新MyLocationListener();
        }

        @覆盖
        在preExecute保护无效(){
            // TODO自动生成方法存根
            super.on preExecute();
            尝试 {
                如果(checkConnection()){
                    Dialog.setTitle(加载);
                    Dialog.setMessage(搜索位置);
                    Dialog.show();
                    locationManager.requestLocationUpdates(提供商,0,0,LocationListener的);
                }
                其他 {
                    Toast.makeText(getApplicationContext(),互联网是不可用,Toast.LENGTH_LONG).show();
                }
            }赶上(例外五){
                // TODO:处理异常
                e.printStackTrace();
            }
        }

        @覆盖
        保护无效doInBackground(字符串... PARAMS){
            // TODO自动生成方法存根
            而(标志){
                如果(纬度= 0&安培;!&安培;!经度= 0){
                    标志= FALSE;
                }
            }
            返回null;
        }

        @覆盖
        保护无效onPostExecute(无效的结果){
            // TODO自动生成方法存根
            Toast.makeText(AndroidLocationActivity.this,地点浮筒: - +纬度+,+经度,Toast.LENGTH_LONG).show();

            super.onPostExecute(结果);
            如果(对话= NULL和放大器;!&安培; Dialog.isShowing()){
                Dialog.dismiss();
                时间= 0;
                意图homeIntent =新的意图(AndroidLocationActivity.this.getApplicationContext(),HomeMenuActivity.class);
 

设置纬度和放大器; LNG这里开始新的活动

  homeIntent.putExtra(土地增值税,纬度);
    homeIntent.putExtra(LNG,经度);
            startActivity(homeIntent);
            }
            locationManager.removeUpdates(LocationListener的);
        }
    }

    类MyLocationListener实现LocationListener的{

        @覆盖
        公共无效onLocationChanged(位置定位){
            // TODO自动生成方法存根
            如果(位置!= NULL){
                纬度= location.getLatitude();
                经度= location.getLongitude();
            }
        }

        @覆盖
        公共无效onProviderDisabled(字符串为arg0){
            // TODO自动生成方法存根
            Toast.makeText(getApplicationContext(),全球定位系统已禁用,Toast.LENGTH_SHORT).show();
        }

        @覆盖
        公共无效onProviderEnabled(字符串为arg0){
            // TODO自动生成方法存根
            Toast.makeText(getApplicationContext(),GPS功能的,Toast.LENGTH_SHORT).show();
        }

        @覆盖
        公共无效onStatusChanged(字符串为arg0,INT ARG1,捆绑ARG2){
            // TODO自动生成方法存根
        }
    }
 

这是在我的显示地图的功能。这是HomeMenuActivity

 公共静态上下文的背景下;
的onCreate(..){
    上下文= getApplicationContext(); //将在逐项叠加使用
     纬度= getIntent()getDoubleExtra(土地增值税,0); //获得纬度和放大器; LNG
     。经度= getIntent()getDoubleExtra(LNG,0);
}


公共无效showMap(){

    // TODO自动生成方法存根
    尝试 {

        的GeoPoint =新的GeoPoint((int)的(纬度* 1E6),(int)的(经度* 1E6));

        图形页面=(图形页面)findViewById(R.id.mapview);

        mapControll = mapview.getController();

        mapview.setBuiltInZoomControls(真正的);

        mapview.setStreetView(真正的);

        mapview.setTraffic(真正的);

        mapControll.setZoom(16);

        mapControll.animateTo(GeoPoint对象);



        userPic = this.getResources()getDrawable(你的PIC ....)。

        userPicOverlay =新MyItemizedOverlay(userPic);

        OverlayItem overlayItem =新OverlayItem(GeoPoint对象,,NULL);

        userPicOverlay.addOverlay(overlayItem);

        调用MapView.getOverlays()加(userPicOverlay)。
        //添加的符号会显示在地图上重绘所以现在强制重绘

        mapview.postInvalidate();

    }赶上(例外五){

        // TODO:处理异常

        e.printStackTrace();

    }

}
 

ItemizedOverlay类

 公共类MyItemizedOverlay扩展ItemizedOverlay< OverlayItem> {



    私人的ArrayList< OverlayItem> myOverlays;



    公共MyItemizedOverlay(可绘制defaultMarker){

        超(boundCenterBottom(defaultMarker));

        myOverlays =新的ArrayList< OverlayItem>();

        填充();

    }



    公共无效addOverlay(OverlayItem叠加){

        myOverlays.add(叠加);

        填充();

    }



    @覆盖

    保护OverlayItem createItem中(int i)以{

        返回myOverlays.get(ⅰ);

    }



    //删除叠加项目i

    公共无效removeItem(int i)以{

        myOverlays.remove(ⅰ);

        填充();

    }



    //返回列表中的项目present数量

    @覆盖

    公众诠释大小(){

        返回myOverlays.size();

    }





    公共无效addOverlayItem(OverlayItem overlayItem){

        myOverlays.add(overlayItem);

        填充();

    }





    公共无效addOverlayItem(INT纬度,INT LON,串题){

        尝试 {

            的GeoPoint点=新的GeoPoint(纬度,经度);

            OverlayItem overlayItem =新OverlayItem(点,标题,NULL);

            addOverlayItem(overlayItem);

        }赶上(例外五){

            // TODO:处理异常

            e.printStackTrace();

        }

    }



    @覆盖

    受保护的布尔中的onTap(INT指数){

        // TODO自动生成方法存根

        字符串标题= myOverlays.get(指数).getTitle();

        Toast.makeText(HomeMenuActivity.context,标题,Toast.LENGTH_LONG).show();

        返回super.onTap(指数);

    }

}
 

希望这将有助于.....

I am developing an android application that contains 3 activities and one of them is map. I am using google maps

what I want:

  1. When the user opens the activity (map) it shows the user her location not the coordinate.

  2. The user should also be able to posit(pining) any place by using a pin and my app must store the coordinates for this pin in a variable so i can use it later.

public class LActivity extends MapActivity 
{    
    /** Called when the activity is first created. */

    MapView mapView;
    GeoPoint geo;
    MapController mapController;
    LocationManager locationManager;
    CustomPinpoint itemizedoverlay;


    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapView);
        // create a map view
        //LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main);

        mapView.setBuiltInZoomControls(true);
        // Either satellite or 2d 
        mapView.setSatellite(true);
        mapController = mapView.getController();
        mapController.setZoom(14); // Zoon 1 is world view
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());

        Drawable drawable = this.getResources().getDrawable(R.drawable.point);
        itemizedoverlay = new CustomPinpoint(drawable);
        createMarker();
    }

    public class GeoUpdateHandler implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            int lat = (int) (location.getLatitude() * 1E6);
            int lng = (int) (location.getLongitude() * 1E6);
            GeoPoint point = new GeoPoint(lat, lng);
            createMarker();
            mapController.animateTo(point); // mapController.setCenter(point);
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

    private void createMarker() {
        GeoPoint p = mapView.getMapCenter();
        OverlayItem overlayitem = new OverlayItem(p, "", "");
        itemizedoverlay.addOverlay(overlayitem);
        mapView.getOverlays().add(itemizedoverlay);
    }

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

this is CustomPinpoint class

public class CustomPinpoint extends ItemizedOverlay<OverlayItem> {

    static int maxNum = 3;
    OverlayItem overlays[] = new OverlayItem[maxNum];
    int index = 0;
    boolean full = false;
    CustomPinpoint itemizedoverlay;

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

    @Override
    protected OverlayItem createItem(int i) {
        return overlays[i];
    }

    @Override
    public int size() {
        if (full) {
            return overlays.length;
        } else {
            return index;
        }
    }

    public void addOverlay(OverlayItem overlay) {
        if (index < maxNum) {
            overlays[index] = overlay;
        } else {
            index = 0;
            full = true;
            overlays[index] = overlay;
        }
        index++;
        populate();
    }

}

解决方案

I have implemented the same thing you want. I am providing you the sample code. In this I have also implemented the ProgressDialog when fetching the location.

This is the starting point for getting the location. I named this AndroidLocationActivity. This is the 1st activity which starts when your app starts.

String provider;
    public double latitude, longitude = 0;
    CurrentPositionTask getCurrentLocation;
    Location currentLocation;
    LocationListener locationListener;
    LocationManager locationManager;
    private long time=0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            setCriteria();
            currentLocation = AndroidLocationActivity.this.locationManager.getLastKnownLocation(provider);

            if (currentLocation == null) {
                currentLocation = new Location(provider);
            }
            time = currentLocation.getTime();

            if (latitude == 0 && longitude == 0) {
                latitude = currentLocation.getLatitude();
                longitude = currentLocation.getLongitude();    
            }
            Toast.makeText(AndroidLocationActivity.this, String.valueOf(time), Toast.LENGTH_LONG).show();

Here set the time if time is not more than 1minute than i am not updating the location.

            if (time >= 100000) {
                latitude = 0;
                longitude = 0;
            }
        } catch (NullPointerException e) {
            // TODO: handle exception
            System.out.println("Null");
            e.printStackTrace();
        } 
        catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        runAsyncTask();    
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        locationManager.removeUpdates(locationListener);
    }

    public void setCriteria() {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
        provider = locationManager.getBestProvider(criteria, true);
        Toast.makeText(getApplicationContext(), "Provider - " + provider, Toast.LENGTH_SHORT).show();
        if (provider == null) {
            provider = LocationManager.GPS_PROVIDER;
        }
    }    


    public void runAsyncTask() {
        // TODO Auto-generated method stub
        if (getCurrentLocation == null) {
            getCurrentLocation = new CurrentPositionTask();    
        }

        if (getCurrentLocation != null) {
            getCurrentLocation.execute("Searching for Location");    
        }
    }

    public boolean checkConnection()
    {
        //ARE WE CONNECTED TO THE NET

        ConnectivityManager conMgr = (ConnectivityManager) getSystemService (AndroidLocationActivity.CONNECTIVITY_SERVICE);
        if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable()&& conMgr.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    } 


    private class CurrentPositionTask extends AsyncTask<String, Void, Void>
    {
        private ProgressDialog Dialog = new ProgressDialog(AndroidLocationActivity.this);
        private boolean flag = true;

        public CurrentPositionTask() {
            locationListener = new MyLocationListener();
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            try {
                if (checkConnection()) {
                    Dialog.setTitle("Loading");
                    Dialog.setMessage("Searching for Location");
                    Dialog.show();
                    locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
                }
                else {
                    Toast.makeText(getApplicationContext(), "Internet is Not Available", Toast.LENGTH_LONG).show();
                }    
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub
            while (flag) {
                if (latitude !=0 && longitude != 0) {
                    flag=false;
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            Toast.makeText(AndroidLocationActivity.this, "Location Floats:- " + latitude + "," + longitude, Toast.LENGTH_LONG).show();

            super.onPostExecute(result);
            if (Dialog != null && Dialog.isShowing()) {
                Dialog.dismiss();
                time=0;
                Intent homeIntent = new Intent(AndroidLocationActivity.this.getApplicationContext(), HomeMenuActivity.class);

set the lat & lng here and start new activity

            homeIntent.putExtra("lat", latitude);
    homeIntent.putExtra("lng", longitude);
            startActivity(homeIntent);
            }
            locationManager.removeUpdates(locationListener);
        }
    }

    class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();    
            }
        }

        @Override
        public void onProviderDisabled(String arg0) {
            // TODO Auto-generated method stub
            Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onProviderEnabled(String arg0) {
            // TODO Auto-generated method stub
            Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            // TODO Auto-generated method stub
        }
    } 

This is the function in which i am displaying the Map. This is the HomeMenuActivity

public static Context context;
onCreate(..) {
    context = getApplicationContext(); // it will be used in Itemized Overlay
     latitude = getIntent().getDoubleExtra("lat", 0);//get the lat & lng
     longitude = getIntent().getDoubleExtra("lng", 0);
}


public void showMap() {

    // TODO Auto-generated method stub
    try {

        geoPoint = new GeoPoint((int)(latitude * 1E6),(int)(longitude * 1E6));

        mapview = (MapView)findViewById(R.id.mapview);

        mapControll= mapview.getController();

        mapview.setBuiltInZoomControls(true);

        mapview.setStreetView(true);

        mapview.setTraffic(true);

        mapControll.setZoom(16);

        mapControll.animateTo(geoPoint);



        userPic = this.getResources().getDrawable(your pic....);

        userPicOverlay = new MyItemizedOverlay(userPic);

        OverlayItem overlayItem = new OverlayItem(geoPoint, "", null);

        userPicOverlay.addOverlay(overlayItem);

        mapview.getOverlays().add(userPicOverlay);
        //Added symbols will be displayed when map is redrawn so force redraw now

        mapview.postInvalidate();

    } catch (Exception e) {

        // TODO: handle exception

        e.printStackTrace();

    }

}

ItemizedOverlay Class

public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {



    private ArrayList<OverlayItem> myOverlays ;



    public MyItemizedOverlay(Drawable defaultMarker) {

        super(boundCenterBottom(defaultMarker));

        myOverlays = new ArrayList<OverlayItem>();

        populate();

    }



    public void addOverlay(OverlayItem overlay){

        myOverlays.add(overlay);

        populate();

    }



    @Override

    protected OverlayItem createItem(int i) {

        return myOverlays.get(i);

    }



    // Removes overlay item i

    public void removeItem(int i){

        myOverlays.remove(i);

        populate();

    }



    // Returns present number of items in list

    @Override

    public int size() {

        return myOverlays.size();

    }





    public void addOverlayItem(OverlayItem overlayItem) {

        myOverlays.add(overlayItem);

        populate();

    }





    public void addOverlayItem(int lat, int lon, String title) {

        try {

            GeoPoint point = new GeoPoint(lat, lon);

            OverlayItem overlayItem = new OverlayItem(point, title, null);

            addOverlayItem(overlayItem);    

        } catch (Exception e) {

            // TODO: handle exception

            e.printStackTrace();

        }

    }



    @Override

    protected boolean onTap(int index) {

        // TODO Auto-generated method stub

        String title = myOverlays.get(index).getTitle();

        Toast.makeText(HomeMenuActivity.context, title, Toast.LENGTH_LONG).show();

        return super.onTap(index);

    }

}

Hope this will help.....

这篇关于在谷歌地图并主张用户的当前位置,并显示它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆