GVKun编程网logo

android – 如何将lat lng转换为Location变量?

24

以上就是给各位分享android–如何将latlng转换为Location变量?,同时本文还将给你拓展Androidjava.lang.ClassCastException:无法将android.wi

以上就是给各位分享android – 如何将lat lng转换为Location变量?,同时本文还将给你拓展Android java.lang.ClassCastException:无法将android.widget.RelativeLayout强制转换为android.widget.EditText、Android LocationClient.getLastLocation()返回带有新时间戳的旧且不准确的位置、Android locationManager requestLocationUpdates不起作用、Android Location服务之LocationManager案例详解等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

android – 如何将lat lng转换为Location变量?

android – 如何将lat lng转换为Location变量?

我在 android中制作地图应用程序,我想在地图上获得2个位置,并查看它们之间的距离.我已经将当前位置作为“位置”变量.然而另一个地方被保存为两个变量:double lat,lng;

我检查了互联网,发现这种方法有助于:

float distance = myLocation.distanceto(temp);

问题是我所拥有的“临时”不是“位置”,而是两个不同的双打.

有没有办法将它们转换为位置?

PS.代码我试过但没有用:

Location temp = null;
temp.setLatitude(23.5678);
temp.setLongitude(34.456);
float distance = location.distanceto(temp);

问题:

Null pointer access: The variable temp can only be null at this location

解决方法

在访问其成员之前,您必须实例化Location.例如.
Location temp = new Location(LocationManager.GPS_PROVIDER);
temp.setLatitude(23.5678);
temp.setLongitude(34.456);
float distance = location.distanceto(temp);

Android java.lang.ClassCastException:无法将android.widget.RelativeLayout强制转换为android.widget.EditText

Android java.lang.ClassCastException:无法将android.widget.RelativeLayout强制转换为android.widget.EditText

单击按钮将我从一个活动带到另一个活动时,我在Android中收到以下异常(我是Android开发中的新手,因此可能不是最聪明的问题):

java.lang.classCastException: android.widget.RelativeLayout cannot be cast to android.widget.EditText

我试过几次清理项目,尝试过Android Tools中的Fix Project Properties选项,已经检查了xml中的错误,但似乎无法弄清楚.我不得不提到,在发生此异常之前,该按钮可以正常工作一段时间.

这是我的xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/editCustomerPhone"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_dark"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".CustomerInfoActivity" >

<FrameLayout
    android:id="@+id/frameLayout1"
    android:layout_width="wrap_content"
    android:layout_height="250dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:background="@drawable/ic_new_delivery" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Insert Customer Data:"
        android:textColor="@color/light_blue"
        android:textSize="20sp"
        android:text/>

</FrameLayout>

<EditText
    android:id="@+id/editCustomerName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView1"
    android:layout_alignBottom="@+id/textView1"
    android:layout_alignParentRight="true"
    android:ems="10"
    android:inputType="textPersonName"
    android:textColor="@color/light_blue" />

<Button
    android:id="@+id/submitInfoBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_alignParentBottom="true"
    android:layout_alignRight="@+id/editCustomerName"
    android:text="Submit Info"
    android:textColor="@color/light_red" 
    android:onClick="submitCustomerInfo"/>

<EditText
    android:id="@+id/editCustomerPhone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editCustomerName"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/TextView01"
    android:ems="10"
    android:inputType="phone"
    android:textColor="@color/light_red" >

    <requestFocus />
</EditText>

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/frameLayout1"
    android:text="Name:"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="@android:color/background_light"
    android:textandroid:typeface="serif" />

<TextView
    android:id="@+id/TextView02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/editCustomerPhone"
    android:layout_marginTop="14dp"
    android:text="Email:"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="@android:color/background_light"
    android:textandroid:typeface="serif" />

<EditText
    android:id="@+id/editCustomerEmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/TextView02"
    android:layout_alignBottom="@+id/TextView02"
    android:layout_alignLeft="@+id/editCustomerPhone"
    android:layout_alignParentRight="true"
    android:ems="10"
    android:inputType="textEmailAddress"
    android:textColor="@color/light_green" />

<TextView
    android:id="@+id/TextView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/TextView02"
    android:layout_below="@+id/editCustomerName"
    android:layout_marginTop="19dp"
    android:text="Phone:"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="@android:color/background_light"
    android:textandroid:typeface="serif" />
@H_301_17@

这是我在活动中引发异常的onCreate方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_customer_info);

    this.editMail = (EditText)findViewById(R.id.editCustomerEmail);
    this.editName = (EditText)findViewById(R.id.editCustomerName);
    this.editPhone = (EditText)findViewById(R.id.editCustomerPhone); // the exception points me here
}
@H_301_17@

解决方法:

您的代码说:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/editCustomerPhone"
@H_301_17@

editCustomerPhone是相对布局.

Android LocationClient.getLastLocation()返回带有新时间戳的旧且不准确的位置

Android LocationClient.getLastLocation()返回带有新时间戳的旧且不准确的位置

自从它发布以来,我一直在使用融合位置提供程序,我对它非常满意(比旧系统更好).但是当将地理围栏与LocationClient.lastKNownLocation()结合使用时,我遇到了一个特殊的问题.设置如下:

我在一些家庭位置附近丢弃了几个地理围栏(范围越来越大).当我得到越过栅栏的意图时,我从LocationClient中检索最后一个已知位置并使用它.除了我还注册了更新模式PRIORITY_BALANCED_POWER_ACCURACY的常规位置更新.

大部分时间这种方法都很好,但有时会发生这种情况:

时间000秒 – (Lat,Lon,Accuracy)=(48.127316,11.5855167,683.0)

时间120秒 – (Lat,Accuracy)=(48.1260497,11.5731745,31.823)

时间300秒 – (Lat,Accuracy)=(48.1217455,11.5641666,143.81)

时间420秒 – (Lat,Accuracy)=(48.1189942,11.559061,36.0)

时间600s – (Lat,683.0)

请注意,所有这些位置都是在getLastKnownLocation()之前检索的.这里看起来很可疑的是,第一个和最后一个位置是相同的(即使在其他属性中),更具体:

* intent at time 0: *

component: ComponentInfo{package.Class}
key [location]: Location[mProvider=fused,mTime=1373524391934,mLatitude=48.127316,mLongitude=11.5855167,mHasAltitude=false,mAltitude=0.0,mHasspeed=false,mSpeed=0.0,mHasbearing=false,mbearing=0.0,mHasAccuracy=true,mAccuracy=683.0,mExtras=Bundle[mParcelledData.dataSize=352]]

* intent at time 600: *

component: ComponentInfo{package.Class}
key [location]: Location[mProvider=fused,mTime=1373524994871,mExtras=Bundle[mParcelledData.dataSize=352]]

* note the ~600 s difference in the timestamp *

我不明白这是怎么发生的,因为两者之间的位置既较新又更准确.此外,旧位置上的新时间戳让我感到好奇……使用old API时显然发生了类似的事情,但这个新的位置提供程序只是被称为融合,所以我无法区分GPS和WPS的传感器……如果是电池塔切换问题(在关于旧API的链接问题中概述)那么为什么如果看到更近的塔,电话会连接到“远方”塔?

为什么会这样?

解决方法

第一个和最后一个点是使用细胞三角测量得到的.错误/准确性是基于单元格的位置的典型情况,看起来Google的省电逻辑决定切换到单元格即可,即使您说其最近的历史记录包括更接近的点.

Android locationManager requestLocationUpdates不起作用

Android locationManager requestLocationUpdates不起作用

我正在开发一个列出最接近用户的餐厅的应用程序.当点击刷新按钮时,它会列出用户当前位置的餐馆.我正在使用位置管理器,只有当活动进入前台(onResume)才能请求更新,以避免电池的不断使用.当应用程序进入onPause()时,位置更新被停止.当我通过终端传递更新时,它在模拟器上工作正常.

问题:
当我改变我的位置(比如开车5英里远)时,我打开我的应用程序和活动来显示最近的餐厅,需要很长时间(4-5分钟)的位置刷新,直到应用程序继续显示以前的位置的餐厅.但是,如果我实际更改我的位置并访问Google地图,然后打开我的餐厅应用程序,那么它可以立即工作.我确保GPS被打开.一旦我打开我的活动,我可以做什么来让位置管理员踢和更新位置?
先谢谢你!

package com.mortley.android.restaurantsaver;

public class NearbyRestaurantActivity extends ListActivity implements OnClickListener,LocationListener{
    private Button refreshButton,searchRestaurants; 
    ImageButton goToSearch;
    private double[] lastKNownLocation;
    private EditText locationEditText;
    private LocationManager locManager;
    private LocationListener locListener;
    private boolean gps_enabled = false;
    private boolean network_enabled = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nearbyrestaurants);
        refreshButton = (Button)findViewById(R.id.reloadButton);
        refreshButton.setonClickListener(this);

        searchRestaurants = (Button)findViewById(R.id.searchButton);
        searchRestaurants.setonClickListener(this);
        goToSearch = (ImageButton)findViewById(R.id.GolocationButton);
        goToSearch.setonClickListener(this);
        locationEditText = (EditText)findViewById(R.id.addresstextBox);
        locationEditText.setVisibility(View.GONE);
        goToSearch.setVisibility(View.GONE);

        locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);//??


        locManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,1000,100,this);

        //checks network connectivity
        boolean checkConnection = isNetworkAvailable();
        if(!checkConnection){
            Toast.makeText(getApplicationContext(),"Check your Network Connectivity",Toast.LENGTH_LONG).show();
        }

        if(checkConnection){
            //sets current location parameters for the user
            lastKNownLocation = RestaurantHelper.getLastKNownLocation(this);
            //Log.v("NearbyRestaurantActivity","This"+this);

            RestaurantApplication application = (RestaurantApplication) this.getApplication();
            RestaurantAdapter restaurantAdapter = new RestaurantAdapter(this,R.layout.restaurantrow,R.id.label,new ArrayList<RestaurantReference>());
            restaurantAdapter.setLastKNownLocation(lastKNownLocation);  


            //set a global variable for the RestaurantAdapter in the RestaurantApplication class.
            application.setRestaurantAdapter(restaurantAdapter);
            //Set the adapter first and then update it when the RestaurantHttpAsyncTask makes a web service call.
            setlistadapter(restaurantAdapter);
            //Make a webservice call in a different thread passing Keyword for URL as a string array.
            RestaurantHttpAsyncTask m_progresstask;
            String[] keywords = {"","american","asian","italian","mexican"};
            //String[] keywords = {"indian"};
            m_progresstask = new RestaurantHttpAsyncTask(NearbyRestaurantActivity.this,keywords);
            m_progresstask.setRestaurantAdapter(restaurantAdapter);
            m_progresstask.execute();
        }
    }

    @Override
    public void onClick(View v) {   
        //Refresh button helps to refresh the restaurant list on location change. Again it makes a call to the webservice using Async Task
        if(v.getId() == refreshButton.getId() ){


            try {
                gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            } catch (Exception ex) {
                ex.printstacktrace();
            }
            try {
                network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            } catch (Exception ex) {
                ex.printstacktrace();
            }

            // don't start listeners if no provider is enabled
            if (!gps_enabled && !network_enabled) {
                Toast.makeText(getApplicationContext(),"Sorry,Location is not determined. Please enable your Network Providers.",Toast.LENGTH_LONG).show();


            }

            //check network connectivity before refresh
            boolean checkConnection = isNetworkAvailable();
            if(!checkConnection){
                Toast.makeText(getApplicationContext(),Toast.LENGTH_LONG).show();
            }
            if(checkConnection){

                RestaurantApplication application = (RestaurantApplication) this.getApplication();
                RestaurantAdapter restaurantAdapter = new RestaurantAdapter(this,new ArrayList<RestaurantReference>());
                restaurantAdapter.setLastKNownLocation(lastKNownLocation);  
                //set a global variable for the RestaurantAdapter in the RestaurantApplication class.
                application.setRestaurantAdapter(restaurantAdapter);
                //Set the adapter first and then update it when the RestaurantHttpAsyncTask makes a web service call.
                setlistadapter(restaurantAdapter);
                //Make a webservice call in a different thread passing Keyword for URL as a string array.
                RestaurantHttpAsyncTask m_progresstask,m_progresstask1;
                String[] keywords = {"","mexican","chinese","indian"};
                //String[] keywords = {"Chinese"};
                m_progresstask = new RestaurantHttpAsyncTask(NearbyRestaurantActivity.this,keywords);
                m_progresstask.setRestaurantAdapter(restaurantAdapter);
                m_progresstask.execute();
            }
        }

        if(v.getId() == goToSearch.getId() ){

            Activity child = this;
            while(child.getParent() != null){
                child = child.getParent();
            }
            TabGroup1Activity parent = (TabGroup1Activity)getParent();


            InputMethodManager imm = (InputMethodManager)getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(locationEditText.getwindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

            //changes ** restaurantAdapter to RestaurantAdapter1 to test & application to application1  
            RestaurantApplication application1 = (RestaurantApplication) this.getApplication();
            RestaurantAdapter restaurantAdapter1 = new RestaurantAdapter(this,new ArrayList<RestaurantReference>());
            restaurantAdapter1.setLastKNownLocation(lastKNownLocation);  
            //set a global variable for the RestaurantAdapter in the RestaurantApplication class.
            application1.setRestaurantAdapter(restaurantAdapter1);
            //Set the adapter first and then update it when the RestaurantHttpAsyncTask makes a web service call.
            setlistadapter(restaurantAdapter1);
            //Make a webservice call in a different thread passing Keyword for URL as a string array.
            RestaurantHttpAsyncTaskTextSearch m_progresstask,m_progresstask1;
            String keywords = locationEditText.getText().toString();
            if(keywords.equals("")){
                keywords = "Pizza in Palo Alto";
            }
            keywords = keywords.replaceAll(" ","%20");
            keywords = keywords.replaceAll(",","%20");
            m_progresstask = new RestaurantHttpAsyncTaskTextSearch (NearbyRestaurantActivity.this,keywords);
            m_progresstask.setRestaurantAdapter(restaurantAdapter1);
            m_progresstask.execute();

            locationEditText.setVisibility(View.GONE);
            goToSearch.setVisibility(View.GONE);
        }
        if(v.getId() == searchRestaurants.getId() ){
            if(goToSearch.isShown() == true){
                goToSearch.setVisibility(View.GONE);
                locationEditText.setVisibility(View.GONE);
            }
            else if(goToSearch.isShown() == false){
                //check network connectivity before refresh
                boolean checkConnection = isNetworkAvailable();
                if(!checkConnection){
                    Toast.makeText(getApplicationContext(),Toast.LENGTH_LONG).show();
                }
                if(checkConnection){
                    goToSearch.setVisibility(View.VISIBLE);
                    locationEditText.setVisibility(View.VISIBLE);

                }
            }
        }

    }
    //Method to check network connectivity
    public boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
        = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting()) {
            //Log.d("network","Network available:true");
            return true;
        } else {
            //Log.d("network","Network available:false");
            return false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,50,this); 
        //Log.v("NearbyRestaurantActivity","In OnResume()");
    }

    @Override
    protected void onPause() {
        super.onPause();
        locManager.removeUpdates(this); 
        //Log.v("NearbyRestaurantActivity","In onPause()");

    }

    @Override
    public void onLocationChanged(Location location) {
        // Todo Auto-generated method stub

    }

    @Override
    public void onProviderdisabled(String provider) {
        // Todo Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // Todo Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider,int status,Bundle extras) {
        // Todo Auto-generated method stub

    }
}






public class RestaurantHelper {

public static double[] getLastKNownLocation(Activity activity){
    double lat = 0.0;
    double lon = 0.0;
    LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);    
    Location location = lm.getLastKNownLocation(LocationManager.NETWORK_PROVIDER);  

    if(location == null){
        lat = 0.0;
        lon = 0.0;
    }
    else{
        //Log.v("Latitude",Double.toString(location.getLatitude()));
        //Log.v("Longitude",Double.toString(location.getLongitude()));

        lat = location.getLatitude();
        lon = location.getLongitude();
    }
    return new double[]{lat,lon};
}
}

解决方法

您没有快速获取更新的位置信息的主要原因是您依赖于RestaurantHelper.getLastKNownLocation()方法中的NETWORK_PROVIDER,但在onCreate()中注册了GPS_PROVIDER的LocationListener.

所以,这个代码在RestaurantHelper.getLastKNownLocation()中:

Location location = lm.getLastKNownLocation(LocationManager.NETWORK_PROVIDER);

应该改为:

Location location = lm.getLastKNownLocation(LocationManager.GPS_PROVIDER);

在理论上,这应该给你最新的GPS位置,当你注册听众时应该刷新它.相反,您也可以更改为监听onCreate()中的NETWORK_PROVIDER,并将RestaurantHelper.getLastKNownLocation()保持原样.这取决于您的准确性要求 – 如果您希望高精度位置将最近的位置返回到最近的建筑物级别(例如5-30米),则应使用GPS_PROVIDER.但是,如果您可以以更准确的方式生活,NETWORK_PROVIDER通常会返回一个比GPS更快的新位置,特别是如果您在室内,有时如果从WiFi导出,这可能相当准确.

另一种方法是通过在onCreate()中通过两个requestLocationUpdates()行注册来监听GPS_PROVIDER和NETWORK_PROVIDER,然后检查从lm.getLastKNownLocation(LocationManager.GPS_PROVIDER)的位置上查看最近的时间戳.和lm.getLastKNownLocation(LocationManager.NETWORK_PROVIDER);并使用最近更新的那个.

我还建议您进行以下更改,使您的代码在大量Android设备上可靠:

>在侦听GPS或NETWORK位置更新时,将requestLocationUpdates()mindistance参数指定为0 – mindistance参数具有由原始设备制造商解释的方式不可靠和不可预测的历史,直到Android 4.1.
>切换到新的Fused Location Provider – 当调用getLastKNownLocation()方法比Android框架的位置API更为可靠,并且在不同的设备之间更一致.请注意,这依赖于Google Play服务SDK(仅适用于Android 2.2及更高版本).

Android Location服务之LocationManager案例详解

Android Location服务之LocationManager案例详解

上次介绍了位置服务中的Geocoder,这次就来介绍一下LocationManager。LocationManager系统服务是位置服务的核心组件,它提供了一系列方法来处理与位置相关的问题,包括查询上一个已知位置、注册和注销来自某个LocationProvider的周期性的位置更新、注册和注销接近某个坐标时对一个已定义的Intent的触发等。今天我们就一起探讨一下LocationManager的简单应用。

在进入正题之前,朋友们需要了解与LocationManager相关的两个知识点:

provider:LocationManager获取位置信息的途径,常用的有两种:GPS和NETWORK。GPS定位更精确,缺点是只能在户外使用,耗电严重,并且返回用户位置信息的速度远不能满足用户需求。NETWORK通过基站和Wi-Fi信号来获取位置信息,室内室外均可用,速度更快,耗电更少。为了获取用户位置信息,我们可以使用其中一个,也可以同时使用两个。

LocationListener:位置监听器接口,定义了常见的provider状态变化和位置的变化的方法,我们需要实现此接口,完成自己的处理逻辑,然后让LocationManager注册此监听器,完成对各种状态的监听。

既然上面讲到位置服务的核心是LocationManager,那么我们如何取得一个LocationManager呢?像其他系统服务一样,通过以下方式即可得到一个LocationManager实例:

LocationManager locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

对象实例是获取到了,可是怎么应用呢?下面就通过一个示例具体演示一下。

我们新建一个location项目。因为示例是基于地图服务的,所以创建时别忘了Build Target要选中Google APIs这一项。

然后修改/res/layout/main.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
	<com.google.android.maps.MapView
		android:id="@+id/mapView"
		android:layout_width="fill_parent"
    	android:layout_height="fill_parent"
		android:clickable="true"
		android:apiKey="your apiKey goes here"/>
	<Button
		android:id="@+id/removeUpdates"
		android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:text="removeUpdates"/>
</FrameLayout>

然后我们来看以下MainActivity.java文件,代码如下:

package com.scott.location;
 
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
 
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;
 
public class MainActivity extends MapActivity {
	
    private MapView mapView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.getController().setZoom(17);
        
        final LocationManager locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        //获取缓存中的位置信息
        Location location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
        	markCurrLocation(location);
        }
        
        final MyLocationListener listener = new MyLocationListener();
        //注册位置更新监听(最小时间间隔为5秒,最小距离间隔为5米)
        locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, listener);
        
        Button removeUpdates = (Button) findViewById(R.id.removeUpdates);
        removeUpdates.setOnClickListener(new View.OnClickListener() {
        	@Override
        	public void onClick(View v) {
        		//停止监听
        		locMgr.removeUpdates(listener);
        	}
        });
    }
    
    /**
     * 标记当前位置
     * @param location
     */
    private void markCurrLocation(Location location) {
    	mapView.removeAllViews();	//清除地图上所有标记视图
    	GeoPoint point = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
		mapView.getController().animateTo(point);
		final MapView.LayoutParams params = new MapView.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, point, LayoutParams.BOTTOM_CENTER);
		final ImageView marker = new ImageView(MainActivity.this);
		marker.setImageResource(R.drawable.marker);
		marker.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), "hello, location manager!", Toast.LENGTH_SHORT).show();
			}
		});
		mapView.addView(marker, params);
	}
 
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	private final class MyLocationListener implements LocationListener {
 
		@Override
		public void onLocationChanged(Location location) {
			markCurrLocation(location);
		}
 
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			//Provider状态在可用、暂不可用、无服务三个状态之间直接切换时触发此函数
		}
 
		@Override
		public void onProviderEnabled(String provider) {
			//Provider被enable时触发此函数,比如GPS被打开
		}
 
		@Override
		public void onProviderDisabled(String provider) {
			//Provider被disable时触发此函数,比如GPS被关闭
		}
		
	}
}

因为用到了地图服务,所以需要在AndroidManifest.xml中的application标签之间加入google map library声明:

<uses-library android:name="com.google.android.maps" />

然后加入位置服务所需的权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

这里朋友们需要注意:如果使用GPS_PROVIDER或者同时使用GPS_PROVIDER和NETWORK_PROVIDER,则只需声明ACCESS_FINE_LOCATION权限,它对于上述两个provider都是有效的;而ACCESS_COARSE_LOCATION权限只针对NETWORK_PROVIDER。

如果是在模拟器里调试的话,我们可以用以下两种方法设置一个模拟的坐标值:geo命令和DDMS。

先来说一下geo命令,它需要telnet到本机的5554端口,然后在命令行下输入geo fix命令,参数可附带经度、纬度和海拔(可选)。

具体操作如图:

如果朋友用的系统是windows7的话,会遇到一些小小的麻烦,因为windows7默认是没有装Telnet服务,所以我们需要手动安装一下,点击“开始->控制面板->程序->程序和功能”,然后再弹出的窗口左侧点击“打开或关闭Windows功能”,会弹出一下界面,选中“Telnet客户端”和“Telnet服务端”即可。如图:

不过,使用geo命令还是挺麻烦的,ADT提供了一个设置模拟坐标的界面,打开“Emulator Control”视图,即可看到一下界面:

如果设置了模拟坐标后,在模拟器的状态栏就会出现一个雷达图形的标志,如图:

到此这篇关于Android Location服务之LocationManager案例详解的文章就介绍到这了,更多相关Android Location服务之LocationManager内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

您可能感兴趣的文章:
  • Android LocationManager获取经度与纬度等地理信息
  • Android 模拟地图定位功能的实现
  • 一分钟快速定位Android启动耗时问题
  • Android如何实现模拟定位
  • Android Studio使用Profiler来完成内存泄漏的定位
  • 解决Android原生定位的坑
  • Android原生定位服务LocationManager

今天关于android – 如何将lat lng转换为Location变量?的讲解已经结束,谢谢您的阅读,如果想了解更多关于Android java.lang.ClassCastException:无法将android.widget.RelativeLayout强制转换为android.widget.EditText、Android LocationClient.getLastLocation()返回带有新时间戳的旧且不准确的位置、Android locationManager requestLocationUpdates不起作用、Android Location服务之LocationManager案例详解的相关知识,请在本站搜索。

本文标签: