经度和Android的Latiude空 [英] Longitude and Latiude null in android

查看:381
本文介绍了经度和Android的Latiude空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GPSTracker文件,但在版本的Andr​​oid M IAM歌厅上的位置,零...我找你帮忙解决这个问题...请参阅下面的

在code

片段的位置和网页视图在Google地图

 公共类ComoChegar扩展片段{
EM presaID项目;    公共ComoChegar(){
        //必需的空公共构造
    }
    @覆盖
    公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
                             捆绑savedInstanceState){
        //充气的布局该片段
       查看屏幕截图= inflater.inflate(R.layout.fragment_como_chegar,集装箱,FALSE);
        。包ID = getActivity()getIntent()getExtras()。
        字符串孝= id.getString(孝);
        如果(isOnline()){
            项目=新的EM presaID(孝);
            Autenticado(项目);
        }
        其他
        {
            android.app.AlertDialog.Builder ALERTA =新android.app.AlertDialog.Builder(getActivity());
            alerta.setMessage(VOCE ESTA SEM Acesso一个互联网POR青睐verifique SUASconfigurações,ativeØ的Wi-Fi欧修斯dadosmóveis);
            alerta.setPositiveButton(OK,NULL);
            alerta.show();
        }
        返回影视处;
    }    公共无效Autenticado(EM presaID ID)
    {
        ServerRequests服务器=新ServerRequests(getActivity());
        server.getEm preSA(ID,新GetEm presaID(){
            @覆盖
            公共无效完成(EM presaID EM preSA){
                如果(EM preSA == NULL){
                    ERRO();
                }
                其他{
                    GPSTracker GPS =新GPSTracker(getActivity());
                    清单<地址>地址;
                    双纬度= gps.getLatitude();
                    双经度= gps.getLongitude();
                    地理codeR地理codeR;
                    地理codeR =新的地缘codeR(getActivity(),Locale.getDefault());                    尝试{
                        如果(纬度== 0安培;&安培;经度== 0)
                        {
                            gps.showSettingsAlert();
                        }
                        其他{
                            地址=地理coder.getFromLocation(纬度,经度,1);
                            串地址= addresses.get(0).getAddressLine(0);
                            串城市= addresses.get(0).getLocality();
                            字符串状态= addresses.get(0).getAdminArea();
                            字符串国家= addresses.get(0).getCountryName();
                            字符串邮政code = addresses.get(0).getPostal code();
                            串knownName = addresses.get(0).getFeatureName();
                            字符串赛达=+地址+,+城市+ - +邮政code;
                            字符串chegada =+ EM presa.endereco ++ EM presa.numero +,+ EM presa.bairro + - + EM presa.cidade;
                            。的WebView地图=(的WebView)getActivity()findViewById(R.id.mapa);
                            mapa.setWebViewClient(新WebViewClient());
                            mapa.getSettings()setJavaScriptEnabled(真)。
                            串IDA = saida.replace(,+);
                            串TREM = chegada.replace(,+);
                            字符串URL =htt​​ps://www.google.com/maps/dir/+纬度+,+经度+/+ TREM +;
                            mapa.loadUrl(URL);                        }
                    }赶上(IOException异常五){
                        e.printStackTrace();
                    }                }            }
        });    }    私人无效ERRO(){
        android.support.v7.app.AlertDialog.Builder ALERTA =新android.support.v7.app.AlertDialog.Builder(getActivity());
        alerta.setMessage(埃罗AO Carregar dados做servidor);
        alerta.setPositiveButton(OK,NULL);
        alerta.show();
    }    私人布尔isOnline(){
        ConnectivityManager厘米=
                (ConnectivityManager)getActivity()getSystemService(Context.CONNECTIVITY_SERVICE)。
        NetInfo的的NetworkInfo = cm.getActiveNetworkInfo();
        返回的NetInfo = NULL&放大器;!&安培; netInfo.isConnectedOrConnecting();
    }
}

在GPSTracker类

 公共类GPSTracker扩展服务实现LocationListener的{    私人最终上下文mContext;    //标志GPS状态
    布尔isGPSEnabled = FALSE;    //标志网络状态
    布尔isNetworkEnabled = FALSE;    //标志GPS状态
    布尔canGetLocation = FALSE;    地点位置; // 位置
    双纬度; //纬度
    双经度; //经度    //最小距离改变米的更新
    私有静态最后长MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10米    //毫秒更新之间的最短时间
    私有静态最后长MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟    //声明一个位置管理
    受保护的LocationManager的LocationManager;    公共GPSTracker(上下文的背景下){
        this.mContext =背景;
        的getLocation();
    }    公共场所的getLocation(){
        尝试{
            的LocationManager =(的LocationManager)mContext
                    .getSystemService(LOCATION_SERVICE);            //获取GPS状态
            isGPSEnabled =的LocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);            //获取网络状态
            isNetworkEnabled =的LocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);            如果(isGPSEnabled&安培;!&安培;!isNetworkEnabled){
                //没有启用网络供应商
            }其他{
                this.canGetLocation = TRUE;
                //首先从网络提供商处获取位置
                如果(isNetworkEnabled){
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                    Log.d(网络,网络);
                    如果(的LocationManager!= NULL){
                        位置=的LocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        如果(位置!= NULL){
                            纬度= location.getLatitude();
                            经度= location.getLongitude();
                        }
                    }
                }
                //如果GPS功能的获得纬度/长期使用GPS服务
                如果(isGPSEnabled){
                    如果(位置== NULL){
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                        Log.d(GPS已启用,GPS功能的);
                        如果(的LocationManager!= NULL){
                            位置=的LocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            如果(位置!= NULL){
                                纬度= location.getLatitude();
                                经度= location.getLongitude();
                            }
                        }
                    }
                }
            }        }赶上(例外五){
            e.printStackTrace();
        }        返回的位置;
    }    / **
     *停止使用GPS监听器
     *调用此函数将停止在你的应用程序中使用GPS
     * * /
    公共无效stopUsingGPS(){
        如果(的LocationManager!= NULL){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }    / **
     *函数来获取纬度
     * * /
    公共双getLatitude(){
        如果(位置!= NULL){
            纬度= location.getLatitude();
        }        //返回纬度
        返回纬度;
    }    / **
     *函数来获取经度
     * * /
    公共双getLongitude(){
        如果(位置!= NULL){
            经度= location.getLongitude();
        }        //返回经度
        返回经度;
    }    / **
     *功能检查启用GPS / WIFI
     * @返回布尔
     * * /
    公共布尔canGetLocation(){
        返回this.canGetLocation;
    }    / **
     *功能,以显示设置警告对话框
     *在pressing设置按钮将劳克设置选项
     * * /
    公共无效showSettingsAlert(){
        AlertDialog.Builder alertDialog =新AlertDialog.Builder(mContext);        //设置对话框标题
        alertDialog.setTitle(ERRO);        //设置对话框留言
        alertDialog.setMessage(GPS NAO ESTA ligado Gostaria德Checar NASConfigurações?);        //在pressing设置按钮
        alertDialog.setPositiveButton(Configurações,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释它){
                意向意图=新意图(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(意向);
            }
        });        //在pressing取消按钮
        alertDialog.setNegativeButton(Cancelar,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释它){
                dialog.cancel();
            }
        });        //显示警报信息
        alertDialog.show();
    }    @覆盖
    公共无效onLocationChanged(地点){
    }    @覆盖
    公共无效onProviderDisabled(字符串提供商){
    }    @覆盖
    公共无效onProviderEnabled(字符串提供商){
    }    @覆盖
    公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
    }    @覆盖
    公众的IBinder onBind(意向为arg0){
        返回null;
    }
}


解决方案

由于您的LocationListener的尝试使用唯一的网络没有GPS得到的位置,与此code片断: locationManager.getLastKnownLocation(的LocationManager。 NETWORK_PROVIDER)
可能你得到纬度和经度值但有延迟。我有同样的问题,然后我开始使用新的/最新位置服务API及用途:
GoogleApiClient。
首先,你需要执行

  GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener的

这是你的活动,想要获取位置数据。

定义

 私人GoogleApiClient mGoogleApiClient;mGoogleApiClient =新GoogleApiClient.Builder(本)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(本)
                .addOnConnectionFailedListener(本)
                。建立();

如果您还没有添加

 <使用许可权`机器人:名字=android.permission.ACCESS_FINE_LOCATION/>`

到清单文件中,添加。

有关进一步的文档:<一href=\"https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient\" rel=\"nofollow\">https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient

I have a GPSTracker file but in the android M iam geting a zero on the locations... i ask for your help to solve this problem...see the code below

Fragment with the location and a webview to google maps

    public class ComoChegar extends Fragment {
EmpresaID item;

    public ComoChegar() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
       View tela = inflater.inflate(R.layout.fragment_como_chegar, container, false);
        Bundle id = getActivity().getIntent().getExtras();
        String Filial = id.getString("filial");
        if (isOnline()) {
            item = new EmpresaID(Filial);
            Autenticado(item);
        }
        else
        {
            android.app.AlertDialog.Builder alerta = new android.app.AlertDialog.Builder(getActivity());
            alerta.setMessage("Você está sem Acesso a Internet por favor verifique suas configurações, ative o wi-fi ou seus dados móveis");
            alerta.setPositiveButton("OK", null);
            alerta.show();
        }
        return  tela;
    }

    public  void Autenticado(EmpresaID id)
    {
        ServerRequests server = new ServerRequests(getActivity());
        server.getEmpresa(id, new GetEmpresaID() {
            @Override
            public void done(EmpresaID empresa) {
                if(empresa == null) {
                    Erro();
                }
                else {
                    GPSTracker gps = new GPSTracker(getActivity());
                    List<Address> addresses;
                    double latitude  = gps.getLatitude();
                    double longitude = gps.getLongitude();
                    Geocoder geocoder;
                    geocoder = new Geocoder(getActivity(), Locale.getDefault());

                    try {
                        if(latitude == 0 && longitude == 0)
                        {
                            gps.showSettingsAlert();
                        }
                        else {
                            addresses = geocoder.getFromLocation(latitude, longitude, 1);
                            String address = addresses.get(0).getAddressLine(0);
                            String city = addresses.get(0).getLocality();
                            String state = addresses.get(0).getAdminArea();
                            String country = addresses.get(0).getCountryName();
                            String postalCode = addresses.get(0).getPostalCode();
                            String knownName = addresses.get(0).getFeatureName();
                            String saida = "" + address + "," + city + "-" + postalCode;
                            String chegada = "" + empresa.endereco + " " + empresa.numero + "," + empresa.bairro + "-" + empresa.cidade;
                            WebView mapa = (WebView) getActivity().findViewById(R.id.mapa);
                            mapa.setWebViewClient(new WebViewClient());
                            mapa.getSettings().setJavaScriptEnabled(true);
                            String ida = saida.replace(" ", "+");
                            String trem = chegada.replace(" ", "+");
                            String Url = "https://www.google.com/maps/dir/" + latitude + "," + longitude + "/" + trem + "";
                            mapa.loadUrl(Url);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }

            }
        });

    }

    private void Erro() {
        android.support.v7.app.AlertDialog.Builder alerta = new android.support.v7.app.AlertDialog.Builder(getActivity());
        alerta.setMessage("Erro ao Carregar dados do servidor");
        alerta.setPositiveButton("OK", null);
        alerta.show();
    }

    private boolean isOnline() {
        ConnectivityManager cm =
                (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }


}

the GPSTracker class

    public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("Erro");

        // Setting Dialog Message
        alertDialog.setMessage("GPS não está ligado. Gostaria de Checar nas Configurações?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Configurações", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

解决方案

Since your LocationListener tries to get location using only Network not GPS, with this code snippet: locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) probably you are getting latitude and longitude values but with a delay. I had the same problem then I begin to use new/latest Location service API and use: GoogleApiClient. First you need to implement

GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener

from you activity that want to fetch the location data.

Define

private GoogleApiClient mGoogleApiClient;

mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

If you haven't add

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

to the manifest file, add that.

For further documentation : https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient

这篇关于经度和Android的Latiude空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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